...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package kivikd
16
17 import (
18 "bytes"
19 "context"
20 "net/http"
21 "net/http/httptest"
22 "regexp"
23 "testing"
24
25 "github.com/go-kivik/kivik/v4/x/kivikd/auth"
26 "github.com/go-kivik/kivik/v4/x/kivikd/authdb"
27 "github.com/go-kivik/kivik/v4/x/kivikd/logger"
28 )
29
30 func TestLogger(t *testing.T) {
31 buf := &bytes.Buffer{}
32 l := logger.New(buf)
33 mw := loggerMiddleware(l)
34 req := httptest.NewRequest("GET", "/foo", nil)
35 session := &auth.Session{User: &authdb.UserContext{Name: "bob"}}
36 ctx := context.WithValue(req.Context(), SessionKey, &session)
37 req = req.WithContext(ctx)
38 w := httptest.NewRecorder()
39 handler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
40 w.WriteHeader(http.StatusUnauthorized)
41 _, _ = w.Write([]byte("Go away!"))
42 })
43 mw(handler).ServeHTTP(w, req)
44 expectedRE := regexp.MustCompile(`^192\.0\.2\.1 bob \[\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d.+] ` +
45 `\([\d.]+[µn]s\) "GET /foo HTTP/1.1" 401 8 "" ""`)
46 if !expectedRE.Match(buf.Bytes()) {
47 t.Errorf("Log does not match. Got:\n%s\n", buf.String())
48 }
49 }
50
51 func TestLoggerNoAuth(t *testing.T) {
52 buf := &bytes.Buffer{}
53 l := logger.New(buf)
54 mw := loggerMiddleware(l)
55 req := httptest.NewRequest("GET", "/foo", nil)
56 session := &auth.Session{}
57 ctx := context.WithValue(req.Context(), SessionKey, &session)
58 req = req.WithContext(ctx)
59 w := httptest.NewRecorder()
60 handler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
61 w.WriteHeader(http.StatusUnauthorized)
62 _, _ = w.Write([]byte("Go away!"))
63 })
64 mw(handler).ServeHTTP(w, req)
65 expectedRE := regexp.MustCompile(`^192\.0\.2\.1 \[\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d.+] ` +
66 `\([\d.]+[µn]s\) "GET /foo HTTP/1.1" 401 8 "" ""`)
67 if !expectedRE.Match(buf.Bytes()) {
68 t.Errorf("Log does not match. Got:\n%s\n", buf.String())
69 }
70 }
71
View as plain text