per_host_test.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package proxy
  5. import (
  6. "context"
  7. "errors"
  8. "net"
  9. "reflect"
  10. "testing"
  11. )
  12. type recordingProxy struct {
  13. addrs []string
  14. }
  15. func (r *recordingProxy) Dial(network, addr string) (net.Conn, error) {
  16. r.addrs = append(r.addrs, addr)
  17. return nil, errors.New("recordingProxy")
  18. }
  19. func TestPerHost(t *testing.T) {
  20. expectedDef := []string{
  21. "example.com:123",
  22. "1.2.3.4:123",
  23. "[1001::]:123",
  24. }
  25. expectedBypass := []string{
  26. "localhost:123",
  27. "zone:123",
  28. "foo.zone:123",
  29. "127.0.0.1:123",
  30. "10.1.2.3:123",
  31. "[1000::]:123",
  32. }
  33. t.Run("Dial", func(t *testing.T) {
  34. var def, bypass recordingProxy
  35. perHost := NewPerHost(&def, &bypass)
  36. perHost.AddFromString("localhost,*.zone,127.0.0.1,10.0.0.1/8,1000::/16")
  37. for _, addr := range expectedDef {
  38. perHost.Dial("tcp", addr)
  39. }
  40. for _, addr := range expectedBypass {
  41. perHost.Dial("tcp", addr)
  42. }
  43. if !reflect.DeepEqual(expectedDef, def.addrs) {
  44. t.Errorf("Hosts which went to the default proxy didn't match. Got %v, want %v", def.addrs, expectedDef)
  45. }
  46. if !reflect.DeepEqual(expectedBypass, bypass.addrs) {
  47. t.Errorf("Hosts which went to the bypass proxy didn't match. Got %v, want %v", bypass.addrs, expectedBypass)
  48. }
  49. })
  50. t.Run("DialContext", func(t *testing.T) {
  51. var def, bypass recordingProxy
  52. perHost := NewPerHost(&def, &bypass)
  53. perHost.AddFromString("localhost,*.zone,127.0.0.1,10.0.0.1/8,1000::/16")
  54. for _, addr := range expectedDef {
  55. perHost.DialContext(context.Background(), "tcp", addr)
  56. }
  57. for _, addr := range expectedBypass {
  58. perHost.DialContext(context.Background(), "tcp", addr)
  59. }
  60. if !reflect.DeepEqual(expectedDef, def.addrs) {
  61. t.Errorf("Hosts which went to the default proxy didn't match. Got %v, want %v", def.addrs, expectedDef)
  62. }
  63. if !reflect.DeepEqual(expectedBypass, bypass.addrs) {
  64. t.Errorf("Hosts which went to the bypass proxy didn't match. Got %v, want %v", bypass.addrs, expectedBypass)
  65. }
  66. })
  67. }