git.iko.soy/typeable/oauth2-proxy
on c0fb7e8 help sign in
typeable/oauth2-proxy/logging_handler_test.go
69 lines 2.4 kB history raw
1package main
3import (
4 "bytes"
5 "fmt"
6 "net/http"
7 "net/http/httptest"
8 "strings"
9 "testing"
10 "time"
12 "github.com/oauth2-proxy/oauth2-proxy/pkg/logger"
15func TestLoggingHandler_ServeHTTP(t *testing.T) {
16 ts := time.Now()
18 tests := []struct {
19 Format,
20 ExpectedLogMessage,
21 Path string
22 ExcludePaths []string
23 SilencePingLogging bool
24 }{
25 {logger.DefaultRequestLoggingFormat, fmt.Sprintf("127.0.0.1 - - [%s] test-server GET - \"/foo/bar\" HTTP/1.1 \"\" 200 4 0.000\n", logger.FormatTimestamp(ts)), "/foo/bar", []string{}, false},
26 {logger.DefaultRequestLoggingFormat, fmt.Sprintf("127.0.0.1 - - [%s] test-server GET - \"/foo/bar\" HTTP/1.1 \"\" 200 4 0.000\n", logger.FormatTimestamp(ts)), "/foo/bar", []string{}, true},
27 {logger.DefaultRequestLoggingFormat, fmt.Sprintf("127.0.0.1 - - [%s] test-server GET - \"/foo/bar\" HTTP/1.1 \"\" 200 4 0.000\n", logger.FormatTimestamp(ts)), "/foo/bar", []string{"/ping"}, false},
28 {logger.DefaultRequestLoggingFormat, "", "/foo/bar", []string{"/foo/bar"}, false},
29 {logger.DefaultRequestLoggingFormat, "", "/ping", []string{}, true},
30 {logger.DefaultRequestLoggingFormat, "", "/ping", []string{"/ping"}, false},
31 {logger.DefaultRequestLoggingFormat, "", "/ping", []string{"/ping"}, true},
32 {logger.DefaultRequestLoggingFormat, "", "/ping", []string{"/foo/bar", "/ping"}, false},
33 {"{{.RequestMethod}}", "GET\n", "/foo/bar", []string{}, true},
34 {"{{.RequestMethod}}", "GET\n", "/foo/bar", []string{"/ping"}, false},
35 {"{{.RequestMethod}}", "GET\n", "/ping", []string{}, false},
36 {"{{.RequestMethod}}", "", "/ping", []string{"/ping"}, true},
37 }
39 for _, test := range tests {
40 buf := bytes.NewBuffer(nil)
41 handler := func(w http.ResponseWriter, req *http.Request) {
42 _, ok := w.(http.Hijacker)
43 if !ok {
44 t.Error("http.Hijacker is not available")
45 }
47 w.Write([]byte("test"))
48 }
50 logger.SetOutput(buf)
51 logger.SetReqTemplate(test.Format)
52 if test.SilencePingLogging {
53 test.ExcludePaths = append(test.ExcludePaths, "/ping")
54 }
55 logger.SetExcludePaths(test.ExcludePaths)
56 h := LoggingHandler(http.HandlerFunc(handler))
58 r, _ := http.NewRequest("GET", test.Path, nil)
59 r.RemoteAddr = "127.0.0.1"
60 r.Host = "test-server"
62 h.ServeHTTP(httptest.NewRecorder(), r)
64 actual := buf.String()
65 if !strings.Contains(actual, test.ExpectedLogMessage) {
66 t.Errorf("Log message was\n%s\ninstead of matching \n%s", actual, test.ExpectedLogMessage)
67 }
68 }