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 Aug 3, 2021
1 parent 6ebb945 commit afaa809
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 5 deletions.
16 changes: 15 additions & 1 deletion context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,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
Expand Down Expand Up @@ -2152,3 +2152,17 @@ func TestContextWithFallbackValueFromRequestContext(t *testing.T) {
})
}
}

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())
}
6 changes: 3 additions & 3 deletions gin.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ func New() *Engine {
}
engine.RouterGroup.engine = engine
engine.pool.New = func() interface{} {
return engine.allocateContext()
return engine.allocateContext(engine.maxParams)
}
return engine
}
Expand All @@ -199,8 +199,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}
}

Expand Down
10 changes: 9 additions & 1 deletion test_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit afaa809

Please sign in to comment.