~bigbes/huntsman

ref: 783841b91eafd678cb3895cfcc8dfd89f290ece7 huntsman/internal/server/middleware/logging_test.go -rw-r--r-- 1.8 KiB
783841b9 — Eugene Blikh Initial commit: multi-provider search router 6 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package middleware

import (
	"bytes"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func TestLoggingEmitsLineWithStatusAndPath(t *testing.T) {
	var buf bytes.Buffer
	logger := slog.New(slog.NewTextHandler(&buf, nil))
	h := Logging(logger)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(201)
		_, _ = w.Write([]byte("hello"))
	}))

	rr := httptest.NewRecorder()
	h.ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), "POST", "/widgets", http.NoBody))

	logged := buf.String()
	for _, want := range []string{"http request", "method=POST", "path=/widgets", "status=201", "size=5"} {
		if !strings.Contains(logged, want) {
			t.Errorf("log line missing %q\nfull line: %s", want, logged)
		}
	}
}

func TestLoggingDefaultsStatusTo200(t *testing.T) {
	var buf bytes.Buffer
	logger := slog.New(slog.NewTextHandler(&buf, nil))
	h := Logging(logger)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		// No explicit WriteHeader: should default to 200 in our log line.
		_, _ = w.Write([]byte("ok"))
	}))

	rr := httptest.NewRecorder()
	h.ServeHTTP(rr, httptest.NewRequestWithContext(t.Context(), "GET", "/", http.NoBody))

	if !strings.Contains(buf.String(), "status=200") {
		t.Errorf("expected status=200 in log, got %q", buf.String())
	}
}

func TestLoggingIncludesRequestID(t *testing.T) {
	var buf bytes.Buffer
	logger := slog.New(slog.NewTextHandler(&buf, nil))
	h := RequestID(Logging(logger)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusOK)
	})))

	req := httptest.NewRequestWithContext(t.Context(), "GET", "/", http.NoBody)
	req.Header.Set("X-Request-ID", "abc-123")
	rr := httptest.NewRecorder()
	h.ServeHTTP(rr, req)

	if !strings.Contains(buf.String(), "request_id=abc-123") {
		t.Errorf("expected request_id in log, got %q", buf.String())
	}
}