withcoderesponsewriter_test.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package response
  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", http.NoBody)
  10. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  11. cw := NewWithCodeResponseWriter(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. }
  27. func TestWithCodeResponseWriter_Hijack(t *testing.T) {
  28. resp := httptest.NewRecorder()
  29. writer := NewWithCodeResponseWriter(NewWithCodeResponseWriter(resp))
  30. assert.NotPanics(t, func() {
  31. writer.Hijack()
  32. })
  33. writer = &WithCodeResponseWriter{
  34. Writer: mockedHijackable{resp},
  35. }
  36. assert.NotPanics(t, func() {
  37. writer.Hijack()
  38. })
  39. }