http_responses.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package testhelper
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "net/http"
  6. "net/http/httptest"
  7. "net/url"
  8. "reflect"
  9. "testing"
  10. )
  11. var (
  12. // Mux is a multiplexer that can be used to register handlers.
  13. Mux *http.ServeMux
  14. // Server is an in-memory HTTP server for testing.
  15. Server *httptest.Server
  16. )
  17. // SetupHTTP prepares the Mux and Server.
  18. func SetupHTTP() {
  19. Mux = http.NewServeMux()
  20. Server = httptest.NewServer(Mux)
  21. }
  22. // TeardownHTTP releases HTTP-related resources.
  23. func TeardownHTTP() {
  24. Server.Close()
  25. }
  26. // Endpoint returns a fake endpoint that will actually target the Mux.
  27. func Endpoint() string {
  28. return Server.URL + "/"
  29. }
  30. // TestFormValues ensures that all the URL parameters given to the http.Request are the same as values.
  31. func TestFormValues(t *testing.T, r *http.Request, values map[string]string) {
  32. want := url.Values{}
  33. for k, v := range values {
  34. want.Add(k, v)
  35. }
  36. r.ParseForm()
  37. if !reflect.DeepEqual(want, r.Form) {
  38. t.Errorf("Request parameters = %v, want %v", r.Form, want)
  39. }
  40. }
  41. // TestMethod checks that the Request has the expected method (e.g. GET, POST).
  42. func TestMethod(t *testing.T, r *http.Request, expected string) {
  43. if expected != r.Method {
  44. t.Errorf("Request method = %v, expected %v", r.Method, expected)
  45. }
  46. }
  47. // TestHeader checks that the header on the http.Request matches the expected value.
  48. func TestHeader(t *testing.T, r *http.Request, header string, expected string) {
  49. if actual := r.Header.Get(header); expected != actual {
  50. t.Errorf("Header %s = %s, expected %s", header, actual, expected)
  51. }
  52. }
  53. // TestBody verifies that the request body matches an expected body.
  54. func TestBody(t *testing.T, r *http.Request, expected string) {
  55. b, err := ioutil.ReadAll(r.Body)
  56. if err != nil {
  57. t.Errorf("Unable to read body: %v", err)
  58. }
  59. str := string(b)
  60. if expected != str {
  61. t.Errorf("Body = %s, expected %s", str, expected)
  62. }
  63. }
  64. // TestJSONRequest verifies that the JSON payload of a request matches an expected structure, without asserting things about
  65. // whitespace or ordering.
  66. func TestJSONRequest(t *testing.T, r *http.Request, expected string) {
  67. b, err := ioutil.ReadAll(r.Body)
  68. if err != nil {
  69. t.Errorf("Unable to read request body: %v", err)
  70. }
  71. var actualJSON interface{}
  72. err = json.Unmarshal(b, &actualJSON)
  73. if err != nil {
  74. t.Errorf("Unable to parse request body as JSON: %v", err)
  75. }
  76. CheckJSONEquals(t, expected, actualJSON)
  77. }