json_test.go52 lines, 1.5 KB
| 1 | package httpx_test |
| 2 | |
| 3 | import ( |
| 4 | "net/http" |
| 5 | "net/http/httptest" |
| 6 | "strings" |
| 7 | "testing" |
| 8 | |
| 9 | "github.com/fiston-user/payments/internal/platform/httpx" |
| 10 | ) |
| 11 | |
| 12 | func TestDecodeJSON(t *testing.T) { |
| 13 | tests := []struct { |
| 14 | name string |
| 15 | body string |
| 16 | status int |
| 17 | want string |
| 18 | }{ |
| 19 | {"valid", `{"amount": 500}`, 200, ""}, |
| 20 | {"empty", ``, 400, "body must not be empty"}, |
| 21 | {"malformed", `{"amount": 5`, 400, "malformed JSON"}, |
| 22 | {"wrong type", `{"amount": "500"}`, 400, `field "amount" must be of type int64`}, |
| 23 | {"unknown field", `{"amount": 500, "amout": 5}`, 400, `unknown field "amout"`}, |
| 24 | {"two values", `{"amount": 1}{"amount": 2}`, 400, "body must contain a single JSON value"}, |
| 25 | {"too large", `{"amount": 1, "pad": "` + strings.Repeat("x", 2<<20) + `"}`, 413, "body must be at most 1048576 bytes"}, |
| 26 | } |
| 27 | for _, tt := range tests { |
| 28 | t.Run(tt.name, func(t *testing.T) { |
| 29 | h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 30 | var in struct { |
| 31 | Amount int64 `json:"amount"` |
| 32 | } |
| 33 | if err := httpx.DecodeJSON(w, r, &in); err != nil { |
| 34 | httpx.Error(w, r, err) |
| 35 | return |
| 36 | } |
| 37 | httpx.WriteJSON(w, r, http.StatusOK, in) |
| 38 | }) |
| 39 | rr := httptest.NewRecorder() |
| 40 | h.ServeHTTP(rr, httptest.NewRequest("POST", "/", strings.NewReader(tt.body))) |
| 41 | |
| 42 | if rr.Code != tt.status { |
| 43 | t.Fatalf("status = %d, want %d: %s", rr.Code, tt.status, rr.Body) |
| 44 | } |
| 45 | if tt.status != 200 { |
| 46 | if got := decodeError(t, rr).Error.Message; got != tt.want { |
| 47 | t.Errorf("message = %q, want %q", got, tt.want) |
| 48 | } |
| 49 | } |
| 50 | }) |
| 51 | } |
| 52 | } |