github.com/Andyfoo/golang/x/net@v0.0.0-20190901054642-57c1bf301704/proxy/per_host_test.go (about)

     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  
     5  package proxy
     6  
     7  import (
     8  	"context"
     9  	"errors"
    10  	"net"
    11  	"reflect"
    12  	"testing"
    13  )
    14  
    15  type recordingProxy struct {
    16  	addrs []string
    17  }
    18  
    19  func (r *recordingProxy) Dial(network, addr string) (net.Conn, error) {
    20  	r.addrs = append(r.addrs, addr)
    21  	return nil, errors.New("recordingProxy")
    22  }
    23  
    24  func TestPerHost(t *testing.T) {
    25  	expectedDef := []string{
    26  		"example.com:123",
    27  		"1.2.3.4:123",
    28  		"[1001::]:123",
    29  	}
    30  	expectedBypass := []string{
    31  		"localhost:123",
    32  		"zone:123",
    33  		"foo.zone:123",
    34  		"127.0.0.1:123",
    35  		"10.1.2.3:123",
    36  		"[1000::]:123",
    37  	}
    38  
    39  	t.Run("Dial", func(t *testing.T) {
    40  		var def, bypass recordingProxy
    41  		perHost := NewPerHost(&def, &bypass)
    42  		perHost.AddFromString("localhost,*.zone,127.0.0.1,10.0.0.1/8,1000::/16")
    43  		for _, addr := range expectedDef {
    44  			perHost.Dial("tcp", addr)
    45  		}
    46  		for _, addr := range expectedBypass {
    47  			perHost.Dial("tcp", addr)
    48  		}
    49  
    50  		if !reflect.DeepEqual(expectedDef, def.addrs) {
    51  			t.Errorf("Hosts which went to the default proxy didn't match. Got %v, want %v", def.addrs, expectedDef)
    52  		}
    53  		if !reflect.DeepEqual(expectedBypass, bypass.addrs) {
    54  			t.Errorf("Hosts which went to the bypass proxy didn't match. Got %v, want %v", bypass.addrs, expectedBypass)
    55  		}
    56  	})
    57  
    58  	t.Run("DialContext", func(t *testing.T) {
    59  		var def, bypass recordingProxy
    60  		perHost := NewPerHost(&def, &bypass)
    61  		perHost.AddFromString("localhost,*.zone,127.0.0.1,10.0.0.1/8,1000::/16")
    62  		for _, addr := range expectedDef {
    63  			perHost.DialContext(context.Background(), "tcp", addr)
    64  		}
    65  		for _, addr := range expectedBypass {
    66  			perHost.DialContext(context.Background(), "tcp", addr)
    67  		}
    68  
    69  		if !reflect.DeepEqual(expectedDef, def.addrs) {
    70  			t.Errorf("Hosts which went to the default proxy didn't match. Got %v, want %v", def.addrs, expectedDef)
    71  		}
    72  		if !reflect.DeepEqual(expectedBypass, bypass.addrs) {
    73  			t.Errorf("Hosts which went to the bypass proxy didn't match. Got %v, want %v", bypass.addrs, expectedBypass)
    74  		}
    75  	})
    76  }