summaryrefslogtreecommitdiffstats
path: root/logging/http/http_test.go
blob: 832b49e19899ad7aff70eced9f4a01c17d25a2e2 (plain) (blame)
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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)
			}
		})
	}
}