error_test.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package rest
  2. import (
  3. "errors"
  4. "io"
  5. "net/http/httptest"
  6. "testing"
  7. )
  8. func TestErrorWriteJSON(t *testing.T) {
  9. type TestCase struct {
  10. Input Error
  11. C int
  12. Output string
  13. Err error
  14. }
  15. testCases := []TestCase{
  16. // Empty error
  17. {Input: Err, C: 200, Output: `{"message":""}`},
  18. // Standard errors
  19. {Input: ErrPermanentRedirect, C: 308, Output: `{"message":"Permanent Redirect"}`},
  20. {Input: ErrNotFound, C: 404, Output: `{"message":"Not Found"}`},
  21. {Input: ErrInternalServerError, C: 500, Output: `{"message":"Internal Server Error"}`},
  22. // Error with changed message
  23. {Input: ErrBadRequest.WithMessage("Invalid Recipe"), C: 400, Output: `{"message":"Invalid Recipe"}`},
  24. // Error with data
  25. {
  26. Input: ErrGatewayTimeout.WithData(map[string]any{"service": "RecipeDatabase"}),
  27. C: 504,
  28. Output: `{"message":"Gateway Timeout","data":{"service":"RecipeDatabase"}}`,
  29. },
  30. // Error with value
  31. {
  32. Input: ErrGatewayTimeout.WithValue("service", "RecipeDatabase"),
  33. C: 504,
  34. Output: `{"message":"Gateway Timeout","data":{"service":"RecipeDatabase"}}`,
  35. },
  36. // Error with error
  37. {
  38. Input: ErrInternalServerError.WithError(errors.New("recipe is too delicious")),
  39. C: 500,
  40. Output: `{"message":"Internal Server Error","data":{"error":"recipe is too delicious"}}`,
  41. },
  42. }
  43. for i, tc := range testCases {
  44. t.Logf("(%d) Testing %v", i, tc.Input)
  45. rec := httptest.NewRecorder()
  46. err := tc.Input.WriteJSON(rec)
  47. if err != tc.Err {
  48. t.Errorf("Expected error %v, got %v", tc.Err, err)
  49. }
  50. if err != nil {
  51. continue
  52. }
  53. res := rec.Result()
  54. if res.StatusCode != tc.C {
  55. t.Errorf("Expected status code %d, got %d", tc.C, res.StatusCode)
  56. }
  57. body, err := io.ReadAll(res.Body)
  58. if err != nil {
  59. t.Errorf("Unexpected error reading response body: %v", err)
  60. continue
  61. }
  62. if string(body) != tc.Output {
  63. t.Errorf("Expected body %q, got %q", tc.Output, string(body))
  64. }
  65. }
  66. }