Merge b045f4c1b2f218e9e54e8495a10939a9dfbafd55 into 0f09c3a9b4626d9fe9979cf4d0521d6ae32ab646

This commit is contained in:
Ruben Pari 2026-10-12 17:38:53 +02:00 committed by GitHub
commit 927af95152
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 25 additions and 0 deletions

View File

@ -3613,6 +3613,21 @@ func TestCreateTestContextWithRouteParams(t *testing.T) {
assert.Equal(t, "hello gin", w.Body.String())
}
func TestCreateTestContextStatusRequiresFlush(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
// Status() buffers the code but does not flush to the ResponseWriter
c.Status(http.StatusCreated)
assert.Equal(t, http.StatusCreated, c.Writer.Status())
assert.Equal(t, http.StatusOK, w.Code, "status not yet flushed to recorder")
// After WriteHeaderNow, the recorder observes the status code
c.Writer.WriteHeaderNow()
assert.Equal(t, http.StatusCreated, w.Code)
}
type interceptedWriter struct {
ResponseWriter
b *bytes.Buffer

View File

@ -14,6 +14,13 @@ import (
// This is useful for tests that need to set up a new Gin engine instance
// along with a context, for example, to test middleware that doesn't depend on
// specific routes. The ResponseWriter `w` is used to initialize the context's writer.
//
// Unlike Engine.ServeHTTP, CreateTestContext does not flush the response at the
// end of the handler. The status code set by Context.Status is buffered until
// the response body is written (Context.Writer.Write/WriteString) or
// Context.Writer.WriteHeaderNow is called. To observe the status code in the
// ResponseWriter after a handler that only calls Context.Status, call
// c.Writer.WriteHeaderNow() explicitly.
func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine) {
r = New()
c = r.allocateContext(0)
@ -27,6 +34,9 @@ func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine) {
// Gin engine instance and need a new context for it.
// The ResponseWriter `w` is used to initialize the context's writer.
// The context is allocated with the `maxParams` setting from the provided engine.
//
// Unlike Engine.ServeHTTP, CreateTestContextOnly does not flush the response at the
// end of the handler. See CreateTestContext for details on observing the status code.
func CreateTestContextOnly(w http.ResponseWriter, r *Engine) (c *Context) {
c = r.allocateContext(r.maxParams)
c.reset()