Skip to content

Commit 9db2b15

Browse files
committed
fix missing route params for CreateTestContext (#2778)
1 parent 6ebb945 commit 9db2b15

File tree

3 files changed

+27
-5
lines changed

3 files changed

+27
-5
lines changed

context_test.go

+15-1
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ func TestSaveUploadedCreateFailed(t *testing.T) {
158158

159159
func TestContextReset(t *testing.T) {
160160
router := New()
161-
c := router.allocateContext()
161+
c := router.allocateContext(0)
162162
assert.Equal(t, c.engine, router)
163163

164164
c.index = 2
@@ -2152,3 +2152,17 @@ func TestContextWithFallbackValueFromRequestContext(t *testing.T) {
21522152
})
21532153
}
21542154
}
2155+
2156+
func TestCreateTestContextWithRouteParams(t *testing.T) {
2157+
w := httptest.NewRecorder()
2158+
engine := New()
2159+
engine.GET("/:action/:name", func(ctx *Context) {
2160+
ctx.String(http.StatusOK, "%s %s", ctx.Param("action"), ctx.Param("name"))
2161+
})
2162+
c := CreateTestContextOnly(w, engine)
2163+
c.Request, _ = http.NewRequest(http.MethodGet, "/hello/gin", nil)
2164+
engine.HandleContext(c)
2165+
2166+
assert.Equal(t, http.StatusOK, w.Code)
2167+
assert.Equal(t, "hello gin", w.Body.String())
2168+
}

gin.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ func New() *Engine {
186186
}
187187
engine.RouterGroup.engine = engine
188188
engine.pool.New = func() interface{} {
189-
return engine.allocateContext()
189+
return engine.allocateContext(engine.maxParams)
190190
}
191191
return engine
192192
}
@@ -199,8 +199,8 @@ func Default() *Engine {
199199
return engine
200200
}
201201

202-
func (engine *Engine) allocateContext() *Context {
203-
v := make(Params, 0, engine.maxParams)
202+
func (engine *Engine) allocateContext(maxParams uint16) *Context {
203+
v := make(Params, 0, maxParams)
204204
return &Context{engine: engine, params: &v}
205205
}
206206

test_helpers.go

+9-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,15 @@ import "net/http"
99
// CreateTestContext returns a fresh engine and context for testing purposes
1010
func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine) {
1111
r = New()
12-
c = r.allocateContext()
12+
c = r.allocateContext(0)
13+
c.reset()
14+
c.writermem.reset(w)
15+
return
16+
}
17+
18+
// CreateTestContextOnly returns a fresh context base on the engine for testing purposes
19+
func CreateTestContextOnly(w http.ResponseWriter, r *Engine) (c *Context) {
20+
c = r.allocateContext(r.maxParams)
1321
c.reset()
1422
c.writermem.reset(w)
1523
return

0 commit comments

Comments
 (0)