errors_test.go69 lines, 2.3 KB
| 1 | package httpx_test |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "net/http/httptest" |
| 8 | "testing" |
| 9 | |
| 10 | "github.com/fiston-user/payments/internal/platform/apperr" |
| 11 | "github.com/fiston-user/payments/internal/platform/httpx" |
| 12 | ) |
| 13 | |
| 14 | // errorResponse mirrors the JSON error body, the way a client would see it. |
| 15 | type errorResponse struct { |
| 16 | Error struct { |
| 17 | Code string `json:"code"` |
| 18 | Message string `json:"message"` |
| 19 | RequestID string `json:"request_id"` |
| 20 | Fields map[string]string `json:"fields"` |
| 21 | } `json:"error"` |
| 22 | } |
| 23 | |
| 24 | func decodeError(t *testing.T, rr *httptest.ResponseRecorder) errorResponse { |
| 25 | t.Helper() |
| 26 | if ct := rr.Header().Get("Content-Type"); ct != "application/json" { |
| 27 | t.Errorf("Content-Type = %q, want application/json", ct) |
| 28 | } |
| 29 | var body errorResponse |
| 30 | if err := json.Unmarshal(rr.Body.Bytes(), &body); err != nil { |
| 31 | t.Fatalf("decode error body %q: %v", rr.Body, err) |
| 32 | } |
| 33 | return body |
| 34 | } |
| 35 | |
| 36 | func TestError(t *testing.T) { |
| 37 | invalid := &apperr.ValidationError{} |
| 38 | invalid.Add("amount", "must be positive") |
| 39 | broke := apperr.NewRule("insufficient_funds", "insufficient funds") |
| 40 | |
| 41 | tests := []struct { |
| 42 | name string |
| 43 | err error |
| 44 | status int |
| 45 | code string |
| 46 | message string |
| 47 | }{ |
| 48 | {"not found", fmt.Errorf("account 42: %w", apperr.ErrNotFound), 404, "not_found", "account 42: not found"}, |
| 49 | {"conflict", fmt.Errorf("wallet exists: %w", apperr.ErrConflict), 409, "conflict", "wallet exists: conflict"}, |
| 50 | {"unauthenticated", fmt.Errorf("%w: bad token", apperr.ErrUnauthenticated), 401, "unauthenticated", "unauthenticated: bad token"}, |
| 51 | {"validation", invalid.Err(), 422, "invalid_input", "invalid input: amount"}, |
| 52 | {"rule", fmt.Errorf("wallet 42: %w", broke), 422, "insufficient_funds", "wallet 42: insufficient funds"}, |
| 53 | {"internal", errors.New("dial tcp 10.0.0.7:5432: refused"), 500, "internal", "internal server error"}, |
| 54 | } |
| 55 | for _, tt := range tests { |
| 56 | t.Run(tt.name, func(t *testing.T) { |
| 57 | rr := httptest.NewRecorder() |
| 58 | httpx.Error(rr, httptest.NewRequest("GET", "/", nil), tt.err) |
| 59 | |
| 60 | if rr.Code != tt.status { |
| 61 | t.Errorf("status = %d, want %d", rr.Code, tt.status) |
| 62 | } |
| 63 | body := decodeError(t, rr) |
| 64 | if body.Error.Code != tt.code || body.Error.Message != tt.message { |
| 65 | t.Errorf("got %q %q, want %q %q", body.Error.Code, body.Error.Message, tt.code, tt.message) |
| 66 | } |
| 67 | }) |
| 68 | } |
| 69 | } |