git.iko.soy/typeable/oauth2-proxy
on request-rules help sign in
typeable/oauth2-proxy/logging_handler_test.go
65 lines 2.2 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 }{
24 {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{}},
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{}},
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{"/ping"}},
27 {logger.DefaultRequestLoggingFormat, "", "/foo/bar", []string{"/foo/bar"}},
28 {logger.DefaultRequestLoggingFormat, "", "/ping", []string{}},
29 {logger.DefaultRequestLoggingFormat, "", "/ping", []string{"/ping"}},
30 {logger.DefaultRequestLoggingFormat, "", "/ping", []string{"/ping"}},
31 {logger.DefaultRequestLoggingFormat, "", "/ping", []string{"/foo/bar", "/ping"}},
32 {"{{.RequestMethod}}", "GET\n", "/foo/bar", []string{}},
33 {"{{.RequestMethod}}", "GET\n", "/foo/bar", []string{"/ping"}},
34 {"{{.RequestMethod}}", "GET\n", "/ping", []string{}},
35 {"{{.RequestMethod}}", "", "/ping", []string{"/ping"}},
36 }
38 for _, test := range tests {
39 buf := bytes.NewBuffer(nil)
40 handler := func(w http.ResponseWriter, req *http.Request) {
41 _, ok := w.(http.Hijacker)
42 if !ok {
43 t.Error("http.Hijacker is not available")
44 }
46 w.Write([]byte("test"))
47 }
49 logger.SetOutput(buf)
50 logger.SetReqTemplate(test.Format)
51 logger.SetExcludePaths(test.ExcludePaths)
52 h := LoggingHandler(http.HandlerFunc(handler))
54 r, _ := http.NewRequest("GET", test.Path, nil)
55 r.RemoteAddr = "127.0.0.1"
56 r.Host = "test-server"
58 h.ServeHTTP(httptest.NewRecorder(), r)
60 actual := buf.String()
61 if !strings.Contains(actual, test.ExpectedLogMessage) {
62 t.Errorf("Log message was\n%s\ninstead of matching \n%s", actual, test.ExpectedLogMessage)
63 }
64 }