package http_test import ( "log/slog" "net/http" "net/http/httptest" "net/url" "testing" "go.sudomsg.com/kit/logging" httpHandler "go.sudomsg.com/kit/logging/http" "go.sudomsg.com/kit/logging/test" ) func TestNew(t *testing.T) { t.Parallel() tests := []struct { name string method string url string status int handler http.HandlerFunc }{ { name: "No Status", method: http.MethodGet, url: "http://example.com/", status: http.StatusOK, handler: func(w http.ResponseWriter, r *http.Request) { w.Write([]byte{}) }, }, { name: "NotFound", method: http.MethodGet, url: "http://example.com/", status: http.StatusNotFound, handler: http.NotFound, }, { name: "Query", method: http.MethodGet, url: "http://example.com/a?b", status: http.StatusNotFound, handler: http.NotFound, }, { name: "Flush", method: http.MethodGet, url: "http://example.com/", status: http.StatusOK, handler: func(w http.ResponseWriter, r *http.Request) { rc := http.NewResponseController(w) w.Write([]byte{}) rc.Flush() }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() log := test.NewMockLogHandler(t) logger := slog.New(log) handler := httpHandler.New(tt.handler) r := httptest.NewRequest(tt.method, tt.url, nil) r = r.WithContext(logging.WithLogger(r.Context(), logger)) w := httptest.NewRecorder() handler.ServeHTTP(w, r) records := log.Records() if len(records) != 1 { t.Fatalf("expected 1 log record, got %d", len(records)) } record := records[0] attrs := map[string]slog.Value{} record.Attrs(func(a slog.Attr) bool { attrs[a.Key] = a.Value return true }) method := attrs["method"] if got := method.String(); got != tt.method { t.Fatalf("expected %v log record, got %v", tt.method, got) } status := attrs["status"] if got := int(status.Int64()); got != tt.status { t.Fatalf("expected %v log record, got %v", tt.status, got) } url, err := url.Parse(tt.url) if err != nil { t.Fatalf("Unexpected error: %v", err) } host := attrs["host"] if got := host.String(); got != url.Host { t.Fatalf("expected %v log record, got %v", url.Host, got) } path := attrs["path"] if got := path.String(); got != url.RequestURI() { t.Fatalf("expected %v log record, got %v", url.RequestURI(), got) } }) } }