withcoderesponsewriter_test.go 880 B

123456789101112131415161718192021222324252627282930313233
  1. package security
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "testing"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. func TestWithCodeResponseWriter(t *testing.T) {
  9. req := httptest.NewRequest(http.MethodGet, "http://localhost", nil)
  10. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  11. cw := &WithCodeResponseWriter{Writer: w}
  12. cw.Header().Set("X-Test", "test")
  13. cw.WriteHeader(http.StatusServiceUnavailable)
  14. assert.Equal(t, cw.Code, http.StatusServiceUnavailable)
  15. _, err := cw.Write([]byte("content"))
  16. assert.Nil(t, err)
  17. flusher, ok := http.ResponseWriter(cw).(http.Flusher)
  18. assert.True(t, ok)
  19. flusher.Flush()
  20. })
  21. resp := httptest.NewRecorder()
  22. handler.ServeHTTP(resp, req)
  23. assert.Equal(t, http.StatusServiceUnavailable, resp.Code)
  24. assert.Equal(t, "test", resp.Header().Get("X-Test"))
  25. assert.Equal(t, "content", resp.Body.String())
  26. }