github.com/go-kivik/kivik/v4@v4.3.2/x/kivikd/logger_test.go (about) 1 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 2 // use this file except in compliance with the License. You may obtain a copy of 3 // the License at 4 // 5 // http://www.apache.org/licenses/LICENSE-2.0 6 // 7 // Unless required by applicable law or agreed to in writing, software 8 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 9 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 // License for the specific language governing permissions and limitations under 11 // the License. 12 13 //go:build !js 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 }