diff options
| author | mo khan <mo@mokhan.ca> | 2025-06-13 15:41:41 -0600 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2025-06-13 15:41:41 -0600 |
| commit | 508de573199aacf7579ef4bcd6090b6e8b777277 (patch) | |
| tree | e50d7e87c847734eeba122c241fa525767965d38 | |
| parent | 5808687bd25022655cfe89b8350937f50035c550 (diff) | |
test: add test to reproduce the double header write issue
| -rw-r--r-- | app/controllers/sparkles/controller_test.go | 37 |
1 files changed, 36 insertions, 1 deletions
diff --git a/app/controllers/sparkles/controller_test.go b/app/controllers/sparkles/controller_test.go index 0619b99..37e1a82 100644 --- a/app/controllers/sparkles/controller_test.go +++ b/app/controllers/sparkles/controller_test.go @@ -1,7 +1,9 @@ package sparkles import ( + "errors" "net/http" + "net/http/httptest" "testing" "github.com/stretchr/testify/assert" @@ -13,6 +15,22 @@ import ( "gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/domain" ) +type FailingResponseWriter struct { + *testing.T + *httptest.ResponseRecorder + headerWritten bool +} + +func (f *FailingResponseWriter) WriteHeader(statusCode int) { + require.False(f.T, f.headerWritten) + f.headerWritten = true + f.ResponseRecorder.WriteHeader(statusCode) +} + +func (f *FailingResponseWriter) Write([]byte) (int, error) { + return 0, errors.New("write failed") +} + func TestSparkles(t *testing.T) { t.Run("GET /sparkles", func(t *testing.T) { sparkle, _ := domain.NewSparkle("@tanuki for helping me") @@ -47,7 +65,6 @@ func TestSparkles(t *testing.T) { currentUser := domain.NewUser(domain.WithID[*domain.User](domain.ID("1"))) t.Run("saves a new sparkle", func(t *testing.T) { - repository := db.NewRepository[*domain.Sparkle]() mux := http.NewServeMux() controller := New(repository) @@ -84,6 +101,24 @@ func TestSparkles(t *testing.T) { assert.Equal(t, currentUser, item.Author) }) }) + + t.Run("prevents double WriteHeader when serialization fails", func(t *testing.T) { + repository := db.NewRepository[*domain.Sparkle]() + controller := New(repository) + + currentUser := domain.NewUser(domain.WithID[*domain.User](domain.ID("1"))) + sparkle, _ := domain.NewSparkle("@user for testing") + + request, response := test.RequestResponse( + "POST", + "/sparkles", + test.WithAcceptHeader(serde.JSON), + test.WithContentType(sparkle, serde.JSON), + test.WithContextKeyValue(t.Context(), cfg.CurrentUser, currentUser), + ) + + controller.Create(&FailingResponseWriter{T: t, ResponseRecorder: response}, request) + }) }) }) } |
