1package log
2
3import (
4 "net/http"
5 "net/http/httptest"
6 "strings"
7 "testing"
8)
9
10func TestHTTPRoundTripLogger(t *testing.T) {
11 // Create a test server that returns a 500 error
12 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
13 w.Header().Set("Content-Type", "application/json")
14 w.Header().Set("X-Custom-Header", "test-value")
15 w.WriteHeader(http.StatusInternalServerError)
16 w.Write([]byte(`{"error": "Internal server error", "code": 500}`))
17 }))
18 defer server.Close()
19
20 // Create HTTP client with logging
21 client := NewHTTPClient()
22
23 // Make a request
24 req, err := http.NewRequestWithContext(
25 t.Context(),
26 http.MethodPost,
27 server.URL,
28 strings.NewReader(`{"test": "data"}`),
29 )
30 if err != nil {
31 t.Fatal(err)
32 }
33 req.Header.Set("Content-Type", "application/json")
34 req.Header.Set("Authorization", "Bearer secret-token")
35
36 resp, err := client.Do(req)
37 if err != nil {
38 t.Fatal(err)
39 }
40 defer resp.Body.Close()
41
42 // Verify response
43 if resp.StatusCode != http.StatusInternalServerError {
44 t.Errorf("Expected status code 500, got %d", resp.StatusCode)
45 }
46}
47
48func TestFormatHeaders(t *testing.T) {
49 headers := http.Header{
50 "Content-Type": []string{"application/json"},
51 "Authorization": []string{"Bearer secret-token"},
52 "X-API-Key": []string{"api-key-123"},
53 "User-Agent": []string{"test-agent"},
54 }
55
56 formatted := formatHeaders(headers)
57
58 // Check that sensitive headers are redacted
59 if formatted["Authorization"][0] != "[REDACTED]" {
60 t.Error("Authorization header should be redacted")
61 }
62 if formatted["X-API-Key"][0] != "[REDACTED]" {
63 t.Error("X-API-Key header should be redacted")
64 }
65
66 // Check that non-sensitive headers are preserved
67 if formatted["Content-Type"][0] != "application/json" {
68 t.Error("Content-Type header should be preserved")
69 }
70 if formatted["User-Agent"][0] != "test-agent" {
71 t.Error("User-Agent header should be preserved")
72 }
73}