proxy_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package service
  2. import (
  3. "net/url"
  4. "testing"
  5. )
  6. func TestProxyURL(t *testing.T) {
  7. t.Parallel()
  8. tests := []struct {
  9. name string
  10. proxy Proxy
  11. want string
  12. }{
  13. {
  14. name: "without auth",
  15. proxy: Proxy{
  16. Protocol: "http",
  17. Host: "proxy.example.com",
  18. Port: 8080,
  19. },
  20. want: "http://proxy.example.com:8080",
  21. },
  22. {
  23. name: "with auth",
  24. proxy: Proxy{
  25. Protocol: "socks5",
  26. Host: "socks.example.com",
  27. Port: 1080,
  28. Username: "user",
  29. Password: "pass",
  30. },
  31. want: "socks5://user:pass@socks.example.com:1080",
  32. },
  33. {
  34. name: "username only",
  35. proxy: Proxy{
  36. Protocol: "http",
  37. Host: "proxy.example.com",
  38. Port: 8080,
  39. Username: "user-only",
  40. },
  41. want: "http://user-only@proxy.example.com:8080",
  42. },
  43. {
  44. name: "password only",
  45. proxy: Proxy{
  46. Protocol: "http",
  47. Host: "proxy.example.com",
  48. Port: 8080,
  49. Password: "pass-only",
  50. },
  51. want: "http://:pass-only@proxy.example.com:8080",
  52. },
  53. {
  54. name: "with special characters in credentials",
  55. proxy: Proxy{
  56. Protocol: "http",
  57. Host: "proxy.example.com",
  58. Port: 3128,
  59. Username: "first last@corp",
  60. Password: "p@ ss:#word",
  61. },
  62. want: "http://first%20last%40corp:p%40%20ss%3A%23word@proxy.example.com:3128",
  63. },
  64. }
  65. for _, tc := range tests {
  66. tc := tc
  67. t.Run(tc.name, func(t *testing.T) {
  68. t.Parallel()
  69. if got := tc.proxy.URL(); got != tc.want {
  70. t.Fatalf("Proxy.URL() mismatch: got=%q want=%q", got, tc.want)
  71. }
  72. })
  73. }
  74. }
  75. func TestProxyURL_SpecialCharactersRoundTrip(t *testing.T) {
  76. t.Parallel()
  77. proxy := Proxy{
  78. Protocol: "http",
  79. Host: "proxy.example.com",
  80. Port: 3128,
  81. Username: "first last@corp",
  82. Password: "p@ ss:#word",
  83. }
  84. parsed, err := url.Parse(proxy.URL())
  85. if err != nil {
  86. t.Fatalf("parse proxy URL failed: %v", err)
  87. }
  88. if got := parsed.User.Username(); got != proxy.Username {
  89. t.Fatalf("username mismatch after parse: got=%q want=%q", got, proxy.Username)
  90. }
  91. pass, ok := parsed.User.Password()
  92. if !ok {
  93. t.Fatal("password missing after parse")
  94. }
  95. if pass != proxy.Password {
  96. t.Fatalf("password mismatch after parse: got=%q want=%q", pass, proxy.Password)
  97. }
  98. }