|
1 | 1 | package helper |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "context" |
4 | 5 | "errors" |
5 | 6 | "net" |
| 7 | + "strings" |
6 | 8 | "testing" |
7 | 9 | ) |
8 | 10 |
|
@@ -46,7 +48,7 @@ func TestIsIpGoodBot(t *testing.T) { |
46 | 48 | clientIP: "1.2.3.4", |
47 | 49 | goodBots: []string{"google.com"}, |
48 | 50 | lookupAddrReturn: []string{ |
49 | | - "host.example.com.", |
| 51 | + "crawl.google.com.", |
50 | 52 | }, |
51 | 53 | lookupAddrErr: nil, |
52 | 54 | lookupIPReturn: []net.IP{ |
@@ -97,25 +99,42 @@ func TestIsIpGoodBot(t *testing.T) { |
97 | 99 | lookupIPErr: nil, |
98 | 100 | expected: true, |
99 | 101 | }, |
| 102 | + { |
| 103 | + name: "Client IP is not the first forward result", |
| 104 | + clientIP: "1.2.3.4", |
| 105 | + goodBots: []string{"example.com"}, |
| 106 | + lookupAddrReturn: []string{ |
| 107 | + "crawler.example.com.", |
| 108 | + }, |
| 109 | + lookupIPReturn: []net.IP{ |
| 110 | + net.ParseIP("5.6.7.8"), |
| 111 | + net.ParseIP("1.2.3.4"), |
| 112 | + }, |
| 113 | + expected: true, |
| 114 | + }, |
100 | 115 | } |
101 | 116 |
|
102 | 117 | for _, tc := range tests { |
103 | | - lookupAddrFunc = func(ip string) ([]string, error) { |
| 118 | + lookupAddrFunc = func(_ context.Context, ip string) ([]string, error) { |
104 | 119 | if ip != tc.clientIP { |
105 | 120 | t.Errorf("Expected lookupAddr to be called with %q; got %q", tc.clientIP, ip) |
106 | 121 | } |
107 | 122 | return tc.lookupAddrReturn, tc.lookupAddrErr |
108 | 123 | } |
109 | 124 |
|
110 | | - lookupIPFunc = func(host string) ([]net.IP, error) { |
111 | | - if len(tc.lookupAddrReturn) == 0 || host != tc.lookupAddrReturn[0] { |
112 | | - t.Errorf("Expected lookupIP to be called with %q; got %q", tc.lookupAddrReturn[0], host) |
| 125 | + lookupIPFunc = func(_ context.Context, network, host string) ([]net.IP, error) { |
| 126 | + if network != "ip" { |
| 127 | + t.Errorf("Expected lookupIP network %q; got %q", "ip", network) |
| 128 | + } |
| 129 | + expectedHost := strings.TrimSuffix(tc.lookupAddrReturn[0], ".") |
| 130 | + if host != expectedHost { |
| 131 | + t.Errorf("Expected lookupIP to be called with %q; got %q", expectedHost, host) |
113 | 132 | } |
114 | 133 | return tc.lookupIPReturn, tc.lookupIPErr |
115 | 134 | } |
116 | 135 |
|
117 | 136 | t.Run(tc.name, func(t *testing.T) { |
118 | | - result := IsIpGoodBot(tc.clientIP, tc.goodBots) |
| 137 | + result := IsIpGoodBot(context.Background(), tc.clientIP, tc.goodBots) |
119 | 138 | if result != tc.expected { |
120 | 139 | t.Errorf("IsIpGoodBot(%q) = %v; expected %v", tc.clientIP, result, tc.expected) |
121 | 140 | } |
|
0 commit comments