Skip to content

Commit

Permalink
fix missing route params for CreateTestContext (gin-gonic#2778)
Browse files Browse the repository at this point in the history
  • Loading branch information
RoCry committed Jul 14, 2022
1 parent b57163a commit 76b015a
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
14 changes: 14 additions & 0 deletions context_test.go
Expand Up @@ -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())
}
2 changes: 1 addition & 1 deletion gin.go
Expand Up @@ -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()
}
Expand Down
8 changes: 8 additions & 0 deletions test_helpers.go
Expand Up @@ -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
}

0 comments on commit 76b015a

Please sign in to comment.