Skip to content

Commit a3e8818

Browse files
authored
test(http): logging middleware verifications
Signed-off-by: Marc Nuri <[email protected]>
1 parent 775fa21 commit a3e8818

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

pkg/http/http_test.go

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,13 @@ import (
44
"bufio"
55
"bytes"
66
"context"
7+
"flag"
78
"fmt"
89
"net"
910
"net/http"
1011
"os"
1112
"path/filepath"
13+
"regexp"
1214
"strings"
1315
"testing"
1416
"time"
@@ -47,7 +49,10 @@ func (c *httpContext) beforeEach() {
4749
_ = os.Setenv("KUBECONFIG", kubeConfig)
4850
// Capture logging
4951
c.klogState = klog.CaptureState()
50-
klog.SetLogger(textlogger.NewLogger(textlogger.NewConfig(textlogger.Verbosity(1), textlogger.Output(&c.logBuffer))))
52+
flags := flag.NewFlagSet("test", flag.ContinueOnError)
53+
klog.InitFlags(flags)
54+
_ = flags.Set("v", "5")
55+
klog.SetLogger(textlogger.NewLogger(textlogger.NewConfig(textlogger.Verbosity(5), textlogger.Output(&c.logBuffer))))
5156
// Start server in random port
5257
ln, err := net.Listen("tcp", "0.0.0.0:0")
5358
if err != nil {
@@ -247,3 +252,29 @@ func TestWellKnownOAuthProtectedResource(t *testing.T) {
247252
})
248253
})
249254
}
255+
256+
func TestMiddlewareLogging(t *testing.T) {
257+
testCase(t, func(ctx *httpContext) {
258+
_, _ = http.Get(fmt.Sprintf("http://%s/.well-known/oauth-protected-resource", ctx.httpAddress))
259+
t.Run("Logs HTTP requests and responses", func(t *testing.T) {
260+
if !strings.Contains(ctx.logBuffer.String(), "GET /.well-known/oauth-protected-resource 200") {
261+
t.Errorf("Expected log entry for GET /.well-known/oauth-protected-resource, got: %s", ctx.logBuffer.String())
262+
}
263+
})
264+
t.Run("Logs HTTP request duration", func(t *testing.T) {
265+
expected := `"GET /.well-known/oauth-protected-resource 200 (.+)"`
266+
m := regexp.MustCompile(expected).FindStringSubmatch(ctx.logBuffer.String())
267+
if len(m) != 2 {
268+
t.Fatalf("Expected log entry to contain duration, got %s", ctx.logBuffer.String())
269+
}
270+
duration, err := time.ParseDuration(m[1])
271+
if err != nil {
272+
t.Fatalf("Failed to parse duration from log entry: %v", err)
273+
}
274+
if duration < 0 {
275+
t.Errorf("Expected duration to be non-negative, got %v", duration)
276+
}
277+
})
278+
})
279+
280+
}

0 commit comments

Comments
 (0)