middleware_test.go116 lines, 3.4 KB
| 1 | package httpx_test |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/json" |
| 6 | "log/slog" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "slices" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | |
| 13 | "github.com/fiston-user/payments/internal/platform/httpx" |
| 14 | "github.com/fiston-user/payments/internal/platform/logging" |
| 15 | ) |
| 16 | |
| 17 | func TestRequestID(t *testing.T) { |
| 18 | tests := []struct { |
| 19 | name, header string |
| 20 | keep bool |
| 21 | }{ |
| 22 | {"generated when missing", "", false}, |
| 23 | {"kept when valid", "checkout-7f3a", true}, |
| 24 | {"replaced when invalid", "bad id\nlevel=ERROR", false}, |
| 25 | } |
| 26 | for _, tt := range tests { |
| 27 | t.Run(tt.name, func(t *testing.T) { |
| 28 | var seen string |
| 29 | h := httpx.RequestID(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 30 | seen = httpx.RequestIDFrom(r.Context()) |
| 31 | })) |
| 32 | req := httptest.NewRequest("GET", "/", nil) |
| 33 | req.Header.Set(httpx.RequestIDHeader, tt.header) |
| 34 | rr := httptest.NewRecorder() |
| 35 | h.ServeHTTP(rr, req) |
| 36 | |
| 37 | got := rr.Header().Get(httpx.RequestIDHeader) |
| 38 | if got == "" || got != seen { |
| 39 | t.Fatalf("response ID %q, handler saw %q: want the same, non-empty ID", got, seen) |
| 40 | } |
| 41 | if (got == tt.header) != tt.keep { |
| 42 | t.Errorf("ID = %q for header %q, keep = %v", got, tt.header, tt.keep) |
| 43 | } |
| 44 | }) |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | // newLogger returns a JSON logger that writes into buf, so tests can read it. |
| 49 | func newLogger(buf *bytes.Buffer) *slog.Logger { |
| 50 | return logging.New(buf, logging.Options{Service: "test", Format: "json"}) |
| 51 | } |
| 52 | |
| 53 | func TestAccessLog(t *testing.T) { |
| 54 | var buf bytes.Buffer |
| 55 | h := httpx.Chain(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 56 | w.WriteHeader(http.StatusTeapot) |
| 57 | w.Write([]byte("short and stout")) |
| 58 | }), httpx.RequestID, httpx.AccessLog(newLogger(&buf))) |
| 59 | |
| 60 | req := httptest.NewRequest("GET", "/teapot", nil) |
| 61 | req.Header.Set(httpx.RequestIDHeader, "req-1") |
| 62 | h.ServeHTTP(httptest.NewRecorder(), req) |
| 63 | |
| 64 | var line map[string]any |
| 65 | if err := json.Unmarshal(buf.Bytes(), &line); err != nil { |
| 66 | t.Fatalf("want one JSON log line, got %q: %v", buf.String(), err) |
| 67 | } |
| 68 | want := map[string]any{ |
| 69 | "msg": "request", "service": "test", "request_id": "req-1", |
| 70 | "method": "GET", "path": "/teapot", "status": 418.0, "bytes": 15.0, |
| 71 | } |
| 72 | for k, v := range want { |
| 73 | if line[k] != v { |
| 74 | t.Errorf("log %s = %v, want %v", k, line[k], v) |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | func TestRecover(t *testing.T) { |
| 80 | var buf bytes.Buffer |
| 81 | h := httpx.Chain(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 82 | panic("something broke") |
| 83 | }), httpx.RequestID, httpx.Recover(newLogger(&buf))) |
| 84 | |
| 85 | rr := httptest.NewRecorder() |
| 86 | h.ServeHTTP(rr, httptest.NewRequest("GET", "/", nil)) |
| 87 | |
| 88 | if rr.Code != http.StatusInternalServerError { |
| 89 | t.Errorf("status = %d, want 500", rr.Code) |
| 90 | } |
| 91 | body := decodeError(t, rr) |
| 92 | if body.Error.Code != "internal" || body.Error.RequestID == "" { |
| 93 | t.Errorf("got code %q and request ID %q", body.Error.Code, body.Error.RequestID) |
| 94 | } |
| 95 | if !strings.Contains(buf.String(), "something broke") { |
| 96 | t.Errorf("panic not logged: %s", buf.String()) |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | func TestChainOrder(t *testing.T) { |
| 101 | var order []string |
| 102 | mark := func(name string) httpx.Middleware { |
| 103 | return func(next http.Handler) http.Handler { |
| 104 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 105 | order = append(order, name) |
| 106 | next.ServeHTTP(w, r) |
| 107 | }) |
| 108 | } |
| 109 | } |
| 110 | h := httpx.Chain(http.NotFoundHandler(), mark("first"), mark("second"), mark("third")) |
| 111 | h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/", nil)) |
| 112 | |
| 113 | if want := []string{"first", "second", "third"}; !slices.Equal(order, want) { |
| 114 | t.Errorf("order = %v, want %v", order, want) |
| 115 | } |
| 116 | } |