body_test.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package rest
  2. import (
  3. "errors"
  4. "net/http"
  5. "net/http/httptest"
  6. "strings"
  7. "testing"
  8. )
  9. func TestReadRequestJSON(t *testing.T) {
  10. type TestInput struct {
  11. Title string `json:"title"`
  12. Serves int `json:"serves"`
  13. Author string `json:"author,omitempty"`
  14. }
  15. type TestCase struct {
  16. Req *http.Request
  17. Input TestInput
  18. Err error
  19. }
  20. testCases := []TestCase{
  21. {
  22. Req: httptest.NewRequest("POST", "/recipes", nil),
  23. Err: errors.New("unexpected end of JSON input"),
  24. },
  25. {
  26. Req: httptest.NewRequest("POST", "/recipes", strings.NewReader(`{"title":"Gnocchi","serves":2}`)),
  27. Input: TestInput{Title: "Gnocchi", Serves: 2},
  28. },
  29. {
  30. Req: httptest.NewRequest("POST", "/recipes", strings.NewReader(`{"title":"Spaghetti","serves":4,"author":"Mom"}`)),
  31. Input: TestInput{Title: "Spaghetti", Serves: 4, Author: "Mom"},
  32. },
  33. }
  34. for i, tc := range testCases {
  35. t.Logf("(%d) Testing request body against %+v", i, tc.Input)
  36. input := TestInput{}
  37. err := ReadRequestJSON(tc.Req, &input)
  38. if err != nil {
  39. if tc.Err != nil {
  40. // Compare error strings, as json.SyntaxError isn't directly comparable
  41. if err.Error() != tc.Err.Error() {
  42. t.Errorf("Expected error %v, got %v", tc.Err, err)
  43. }
  44. } else {
  45. t.Errorf("Expected error %v, got %v", tc.Err, err)
  46. }
  47. continue
  48. }
  49. if input != tc.Input {
  50. t.Errorf("Expected %v, got %v", tc.Input, input)
  51. }
  52. }
  53. }