From 76b015a1e408f636e3e740cde88e2e1e226c14d9 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 | 14 ++++++++++++++ gin.go | 2 +- test_helpers.go | 8 ++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/context_test.go b/context_test.go index d09b0ae1ea..301ab137c1 100644 --- a/context_test.go +++ b/context_test.go @@ -2354,3 +2354,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 f9324299b7..0d22ee5782 100644 --- a/gin.go +++ b/gin.go @@ -201,7 +201,7 @@ func New() *Engine { trustedProxies: []string{"0.0.0.0/0", "::/0"}, trustedCIDRs: defaultTrustedCIDRs, } - engine.RouterGroup.engine = engine + engine.RouterGroup.engine = engine) engine.pool.New = func() any { return engine.allocateContext() } diff --git a/test_helpers.go b/test_helpers.go index b3be93b4ee..2a38872926 100644 --- a/test_helpers.go +++ b/test_helpers.go @@ -14,3 +14,11 @@ func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine) { 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() + c.reset() + c.writermem.reset(w) + return +}