service_test.go 2.2 KB

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