gunziphandler_test.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package handler
  2. import (
  3. "bytes"
  4. "io/ioutil"
  5. "net/http"
  6. "net/http/httptest"
  7. "strings"
  8. "sync"
  9. "testing"
  10. "git.i2edu.net/i2/go-zero/core/codec"
  11. "git.i2edu.net/i2/go-zero/rest/httpx"
  12. "github.com/stretchr/testify/assert"
  13. )
  14. func TestGunzipHandler(t *testing.T) {
  15. const message = "hello world"
  16. var wg sync.WaitGroup
  17. wg.Add(1)
  18. handler := GunzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  19. body, err := ioutil.ReadAll(r.Body)
  20. assert.Nil(t, err)
  21. assert.Equal(t, string(body), message)
  22. wg.Done()
  23. }))
  24. req := httptest.NewRequest(http.MethodPost, "http://localhost",
  25. bytes.NewReader(codec.Gzip([]byte(message))))
  26. req.Header.Set(httpx.ContentEncoding, gzipEncoding)
  27. resp := httptest.NewRecorder()
  28. handler.ServeHTTP(resp, req)
  29. assert.Equal(t, http.StatusOK, resp.Code)
  30. wg.Wait()
  31. }
  32. func TestGunzipHandler_NoGzip(t *testing.T) {
  33. const message = "hello world"
  34. var wg sync.WaitGroup
  35. wg.Add(1)
  36. handler := GunzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  37. body, err := ioutil.ReadAll(r.Body)
  38. assert.Nil(t, err)
  39. assert.Equal(t, string(body), message)
  40. wg.Done()
  41. }))
  42. req := httptest.NewRequest(http.MethodPost, "http://localhost",
  43. strings.NewReader(message))
  44. resp := httptest.NewRecorder()
  45. handler.ServeHTTP(resp, req)
  46. assert.Equal(t, http.StatusOK, resp.Code)
  47. wg.Wait()
  48. }
  49. func TestGunzipHandler_NoGzipButTelling(t *testing.T) {
  50. const message = "hello world"
  51. handler := GunzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
  52. req := httptest.NewRequest(http.MethodPost, "http://localhost",
  53. strings.NewReader(message))
  54. req.Header.Set(httpx.ContentEncoding, gzipEncoding)
  55. resp := httptest.NewRecorder()
  56. handler.ServeHTTP(resp, req)
  57. assert.Equal(t, http.StatusBadRequest, resp.Code)
  58. }