From 97601544e3582676c417fcc79bf842c5e1d9468e Mon Sep 17 00:00:00 2001 From: RoCry Date: Sun, 3 Oct 2021 19:32:22 +0800 Subject: [PATCH] fix missing route params for CreateTestContext (#2778) --- context_test.go | 16 +++++++++++++++- gin.go | 6 +++--- test_helpers.go | 10 +++++++++- 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/context_test.go b/context_test.go index ad16fbb1c6..671e161fd3 100644 --- a/context_test.go +++ b/context_test.go @@ -144,7 +144,7 @@ func TestSaveUploadedCreateFailed(t *testing.T) { func TestContextReset(t *testing.T) { router := New() - c := router.allocateContext() + c := router.allocateContext(0) assert.Equal(t, c.engine, router) c.index = 2 @@ -2147,3 +2147,17 @@ func TestContextAddParam(t *testing.T) { assert.Equal(t, ok, true) assert.Equal(t, value, v) } + +func TestCreateTestContextWithRouteParams(t *testing.T) { + w := httptest.NewRecorder() + engine := New() + engine.GET("/:action/:name", func(ctx *Context) { + ctx.String(http.StatusOK, "%s %s", ctx.Param("action"), ctx.Param("name")) + }) + c := CreateTestContextOnly(w, engine) + c.Request, _ = http.NewRequest(http.MethodGet, "/hello/gin", nil) + engine.HandleContext(c) + + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, "hello gin", w.Body.String()) +} diff --git a/gin.go b/gin.go index 02a1062c31..2d75fdcdfa 100644 --- a/gin.go +++ b/gin.go @@ -187,7 +187,7 @@ func New() *Engine { } engine.RouterGroup.engine = engine engine.pool.New = func() interface{} { - return engine.allocateContext() + return engine.allocateContext(engine.maxParams) } return engine } @@ -200,8 +200,8 @@ func Default() *Engine { return engine } -func (engine *Engine) allocateContext() *Context { - v := make(Params, 0, engine.maxParams) +func (engine *Engine) allocateContext(maxParams uint16) *Context { + v := make(Params, 0, maxParams) return &Context{engine: engine, params: &v} } diff --git a/test_helpers.go b/test_helpers.go index 3a7a5ddf69..4e94c3c44e 100644 --- a/test_helpers.go +++ b/test_helpers.go @@ -9,7 +9,15 @@ import "net/http" // CreateTestContext returns a fresh engine and context for testing purposes func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine) { r = New() - c = r.allocateContext() + c = r.allocateContext(0) + c.reset() + c.writermem.reset(w) + return +} + +// CreateTestContextOnly returns a fresh context base on the engine for testing purposes +func CreateTestContextOnly(w http.ResponseWriter, r *Engine) (c *Context) { + c = r.allocateContext(r.maxParams) c.reset() c.writermem.reset(w) return