http_test.go 1.9 KB

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