responses_test.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package httpx
  2. import (
  3. "net/http"
  4. "strings"
  5. "testing"
  6. "github.com/stretchr/testify/assert"
  7. "github.com/tal-tech/go-zero/core/logx"
  8. )
  9. type message struct {
  10. Name string `json:"name"`
  11. }
  12. func init() {
  13. logx.Disable()
  14. }
  15. func TestOkJson(t *testing.T) {
  16. w := tracedResponseWriter{
  17. headers: make(map[string][]string),
  18. }
  19. msg := message{Name: "anyone"}
  20. OkJson(&w, msg)
  21. assert.Equal(t, http.StatusOK, w.code)
  22. assert.Equal(t, "{\"name\":\"anyone\"}", w.builder.String())
  23. }
  24. func TestWriteJsonTimeout(t *testing.T) {
  25. // only log it and ignore
  26. w := tracedResponseWriter{
  27. headers: make(map[string][]string),
  28. timeout: true,
  29. }
  30. msg := message{Name: "anyone"}
  31. WriteJson(&w, http.StatusOK, msg)
  32. assert.Equal(t, http.StatusOK, w.code)
  33. }
  34. func TestWriteJsonLessWritten(t *testing.T) {
  35. w := tracedResponseWriter{
  36. headers: make(map[string][]string),
  37. lessWritten: true,
  38. }
  39. msg := message{Name: "anyone"}
  40. WriteJson(&w, http.StatusOK, msg)
  41. assert.Equal(t, http.StatusOK, w.code)
  42. }
  43. type tracedResponseWriter struct {
  44. headers map[string][]string
  45. builder strings.Builder
  46. code int
  47. lessWritten bool
  48. timeout bool
  49. }
  50. func (w *tracedResponseWriter) Header() http.Header {
  51. return w.headers
  52. }
  53. func (w *tracedResponseWriter) Write(bytes []byte) (n int, err error) {
  54. if w.timeout {
  55. return 0, http.ErrHandlerTimeout
  56. }
  57. n, err = w.builder.Write(bytes)
  58. if w.lessWritten {
  59. n -= 1
  60. }
  61. return
  62. }
  63. func (w *tracedResponseWriter) WriteHeader(code int) {
  64. w.code = code
  65. }