service_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package httpc
  2. import (
  3. "context"
  4. "net/http"
  5. "net/http/httptest"
  6. "testing"
  7. "github.com/stretchr/testify/assert"
  8. "github.com/wuntsong-org/go-zero-plus/rest/internal/header"
  9. )
  10. func TestNamedService_DoRequest(t *testing.T) {
  11. svr := httptest.NewServer(http.RedirectHandler("/foo", http.StatusMovedPermanently))
  12. defer svr.Close()
  13. req, err := http.NewRequest(http.MethodGet, svr.URL, nil)
  14. assert.Nil(t, err)
  15. service := NewService("foo")
  16. _, err = service.DoRequest(req)
  17. // too many redirects
  18. assert.NotNil(t, err)
  19. }
  20. func TestNamedService_DoRequestGet(t *testing.T) {
  21. svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  22. w.Header().Set("foo", r.Header.Get("foo"))
  23. }))
  24. defer svr.Close()
  25. service := NewService("foo", func(r *http.Request) *http.Request {
  26. r.Header.Set("foo", "bar")
  27. return r
  28. })
  29. req, err := http.NewRequest(http.MethodGet, svr.URL, nil)
  30. assert.Nil(t, err)
  31. resp, err := service.DoRequest(req)
  32. assert.Nil(t, err)
  33. assert.Equal(t, http.StatusOK, resp.StatusCode)
  34. assert.Equal(t, "bar", resp.Header.Get("foo"))
  35. }
  36. func TestNamedService_DoRequestPost(t *testing.T) {
  37. svr := httptest.NewServer(http.NotFoundHandler())
  38. defer svr.Close()
  39. service := NewService("foo")
  40. req, err := http.NewRequest(http.MethodPost, svr.URL, nil)
  41. assert.Nil(t, err)
  42. req.Header.Set(header.ContentType, header.JsonContentType)
  43. resp, err := service.DoRequest(req)
  44. assert.Nil(t, err)
  45. assert.Equal(t, http.StatusNotFound, resp.StatusCode)
  46. }
  47. func TestNamedService_Do(t *testing.T) {
  48. type Data struct {
  49. Key string `path:"key"`
  50. Value int `form:"value"`
  51. Header string `header:"X-Header"`
  52. Body string `json:"body"`
  53. }
  54. svr := httptest.NewServer(http.NotFoundHandler())
  55. defer svr.Close()
  56. service := NewService("foo")
  57. data := Data{
  58. Key: "foo",
  59. Value: 10,
  60. Header: "my-header",
  61. Body: "my body",
  62. }
  63. resp, err := service.Do(context.Background(), http.MethodPost, svr.URL+"/nodes/:key", data)
  64. assert.Nil(t, err)
  65. assert.Equal(t, http.StatusNotFound, resp.StatusCode)
  66. }
  67. func TestNamedService_DoBadRequest(t *testing.T) {
  68. val := struct {
  69. Value string `json:"value,options=[a,b]"`
  70. }{
  71. Value: "c",
  72. }
  73. service := NewService("foo")
  74. _, err := service.Do(context.Background(), http.MethodPost, "/nodes/:key", val)
  75. assert.NotNil(t, err)
  76. }