diff options
Diffstat (limited to 'app')
| -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) + }) }) }) } |
