forked from richyen/walker
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhelpers.go
More file actions
319 lines (276 loc) · 7.48 KB
/
helpers.go
File metadata and controls
319 lines (276 loc) · 7.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
package walker
import (
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"path"
"path/filepath"
"runtime"
"strings"
"time"
"code.google.com/p/log4go"
)
// LoadTestConfig loads the given test config yaml file. The given path is
// assumed to be relative to the `walker/test/` directory, the location of this
// file. This will panic if it cannot read the requested config file. If you
// expect an error or are testing ReadConfigFile, use `GetTestFileDir()`
// instead.
func LoadTestConfig(filename string) {
testdir := GetTestFileDir()
err := ReadConfigFile(path.Join(testdir, filename))
if err != nil {
panic(err.Error())
}
}
// GetTestFileDir returns the directory where shared test files are stored, for
// example test config files. It will panic if it could not get the path from
// the runtime.
func GetTestFileDir() string {
_, p, _, ok := runtime.Caller(0)
if !ok {
panic("Failed to get location of test source file")
}
if !filepath.IsAbs(p) {
log4go.Warn("Tried to use runtime.Caller to get the test file "+
"directory, but the path is incorrect: %v\nMost likely this means the "+
"-cover flag was used with `go test`, which does not return a usable "+
"path when testing the walker package. Returning './test' as the test "+
"directory; if CWD != the root walker directory, tests will fail.", p)
return "test"
}
return path.Join(path.Dir(p), "test")
}
// fakeDial makes connections to localhost, no matter what addr was given.
func fakeDial(network, addr string) (net.Conn, error) {
_, port, _ := net.SplitHostPort(addr)
return net.Dial(network, net.JoinHostPort("localhost", port))
}
// getFakeTransport gets a http.RoundTripper that uses fakeDial
func getFakeTransport() http.RoundTripper {
return &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: fakeDial,
TLSHandshakeTimeout: 10 * time.Second,
}
}
//
// RecordingTransport counts how many times the Dial routine is called
//
type recordingTransport struct {
http.Transport
Name string
Record []string
}
func (self *recordingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
self.Record = append(self.Record, req.URL.String())
return self.Transport.RoundTrip(req)
}
func (self *recordingTransport) String() string {
return fmt.Sprintf("recordingTransport named %v: %v", self.Name, self.Record)
}
func getRecordingTransport(name string) *recordingTransport {
r := &recordingTransport{
Transport: http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSHandshakeTimeout: 10 * time.Second,
Dial: fakeDial,
},
Name: name,
}
return r
}
//
// CancelTrackingTransport isa http.Transport that tracks which requests where canceled.
//
type cancelTrackingTransport struct {
http.Transport
Canceled map[string]int
}
func (ctt *cancelTrackingTransport) CancelRequest(req *http.Request) {
key := req.URL.String()
count := 0
if c, cok := ctt.Canceled[key]; cok {
count = c
}
ctt.Canceled[key] = count + 1
ctt.Transport.CancelRequest(req)
}
//
// wontConnectDial has a Dial routine that will never connect
//
type wontConnectDial struct {
quit chan struct{}
}
// Close allows usert to close the wontConnectDial
func (wcd *wontConnectDial) Close() error {
close(wcd.quit)
return nil
}
// Dial function won't return until quit is closed.
func (wcd *wontConnectDial) Dial(network, addr string) (net.Conn, error) {
<-wcd.quit
return nil, fmt.Errorf("I'll never connect!!")
}
func getWontConnectTransport() (*cancelTrackingTransport, io.Closer) {
dialer := &wontConnectDial{make(chan struct{})}
trans := &cancelTrackingTransport{
Transport: http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: dialer.Dial,
TLSHandshakeTimeout: 10 * time.Second,
},
Canceled: make(map[string]int),
}
return trans, dialer
}
//
// Spoof an Addr interface. Used by stallingConn
//
type emptyAddr struct{}
func (ea *emptyAddr) Network() string {
return ""
}
func (ea *emptyAddr) String() string {
return ""
}
//
// stallingConn will stall during any read or write
//
type stallingConn struct {
closed bool
quit chan struct{}
}
func (sc *stallingConn) Read(b []byte) (int, error) {
<-sc.quit
return 0, fmt.Errorf("Staling Read")
}
func (sc *stallingConn) Write(b []byte) (int, error) {
<-sc.quit
return 0, fmt.Errorf("Staling Write")
}
func (sc *stallingConn) Close() error {
select {
case <-sc.quit:
default:
close(sc.quit)
}
return nil
}
func (sc *stallingConn) LocalAddr() net.Addr {
return &emptyAddr{}
}
func (sc *stallingConn) RemoteAddr() net.Addr {
return &emptyAddr{}
}
func (sc *stallingConn) SetDeadline(t time.Time) error {
return nil
}
func (sc *stallingConn) SetReadDeadline(t time.Time) error {
return nil
}
func (sc *stallingConn) SetWriteDeadline(t time.Time) error {
return nil
}
//
// stallCloser tracks a bundle of stallingConn's
//
type stallCloser struct {
stalls map[*stallingConn]bool
}
func (sc *stallCloser) Close() error {
for conn := range sc.stalls {
conn.Close()
}
return nil
}
func (sc *stallCloser) newConn() *stallingConn {
x := &stallingConn{quit: make(chan struct{})}
sc.stalls[x] = true
return x
}
func (sc *stallCloser) Dial(network, addr string) (net.Conn, error) {
return sc.newConn(), nil
}
func getStallingReadTransport() (*cancelTrackingTransport, io.Closer) {
dialer := &stallCloser{make(map[*stallingConn]bool)}
trans := &cancelTrackingTransport{
Transport: http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: dialer.Dial,
TLSHandshakeTimeout: 10 * time.Second,
},
Canceled: make(map[string]int),
}
return trans, dialer
}
// MustParse is a helper for calling ParseURL when we kow the string is
// a safe URL. It will panic if it fails.
func MustParse(ref string) *URL {
u, err := ParseURL(ref)
if err != nil {
panic("Failed to parse URL: " + ref)
}
return u
}
func response404() *http.Response {
return &http.Response{
Status: "404",
StatusCode: 404,
Proto: "HTTP/1.0",
ProtoMajor: 1,
ProtoMinor: 0,
Header: http.Header{"Content-Type": []string{"text/html"}},
Body: ioutil.NopCloser(strings.NewReader("")),
ContentLength: -1,
}
}
func response307(link string) *http.Response {
return &http.Response{
Status: "307",
StatusCode: 307,
Proto: "HTTP/1.0",
ProtoMajor: 1,
ProtoMinor: 0,
Header: http.Header{"Location": []string{link}, "Content-Type": []string{"text/html"}},
Body: ioutil.NopCloser(strings.NewReader("")),
ContentLength: -1,
}
}
func response200() *http.Response {
return &http.Response{
Status: "200 OK",
StatusCode: 200,
Proto: "HTTP/1.0",
ProtoMajor: 1,
ProtoMinor: 0,
Header: http.Header{"Content-Type": []string{"text/html"}},
Body: ioutil.NopCloser(strings.NewReader(
`<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>No Links</title>
</head>
<div id="menu">
</div>
</html>`)),
ContentLength: -1,
}
}
// mapRoundTrip maps input links --> http.Response. See TestRedirects for example.
type mapRoundTrip struct {
Responses map[string]*http.Response
}
func (mrt *mapRoundTrip) RoundTrip(req *http.Request) (*http.Response, error) {
res, resOk := mrt.Responses[req.URL.String()]
if !resOk {
return response404(), nil
}
return res, nil
}
// This allows the mapRoundTrip to be canceled. Which is needed to prevent
// errant robots.txt GET's to break TestRedirects.
func (self *mapRoundTrip) CancelRequest(req *http.Request) {
}