helpers_test.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package httpclient
  2. import (
  3. "net/http"
  4. "net/url"
  5. "testing"
  6. )
  7. func TestRequestAuthority(t *testing.T) {
  8. testCases := []struct {
  9. name string
  10. url string
  11. expect string
  12. }{
  13. {name: "https default port", url: "https://example.com/foo", expect: "example.com:443"},
  14. {name: "http default port", url: "http://example.com/foo", expect: "example.com:80"},
  15. {name: "https explicit port", url: "https://example.com:8443/foo", expect: "example.com:8443"},
  16. {name: "https uppercase host", url: "https://EXAMPLE.COM/foo", expect: "example.com:443"},
  17. {name: "https ipv6 default port", url: "https://[2001:db8::1]/foo", expect: "[2001:db8::1]:443"},
  18. {name: "https ipv6 explicit port", url: "https://[2001:db8::1]:8443/foo", expect: "[2001:db8::1]:8443"},
  19. {name: "https ipv4", url: "https://192.0.2.1/foo", expect: "192.0.2.1:443"},
  20. }
  21. for _, testCase := range testCases {
  22. t.Run(testCase.name, func(t *testing.T) {
  23. parsed, err := url.Parse(testCase.url)
  24. if err != nil {
  25. t.Fatalf("parse url: %v", err)
  26. }
  27. got := requestAuthority(&http.Request{URL: parsed})
  28. if got != testCase.expect {
  29. t.Fatalf("got %q, want %q", got, testCase.expect)
  30. }
  31. })
  32. }
  33. t.Run("nil request", func(t *testing.T) {
  34. if got := requestAuthority(nil); got != "" {
  35. t.Fatalf("got %q, want empty", got)
  36. }
  37. })
  38. t.Run("nil URL", func(t *testing.T) {
  39. if got := requestAuthority(&http.Request{}); got != "" {
  40. t.Fatalf("got %q, want empty", got)
  41. }
  42. })
  43. t.Run("empty host", func(t *testing.T) {
  44. if got := requestAuthority(&http.Request{URL: &url.URL{Scheme: "https"}}); got != "" {
  45. t.Fatalf("got %q, want empty", got)
  46. }
  47. })
  48. }