-
Notifications
You must be signed in to change notification settings - Fork 7
/
crawler_test.go
109 lines (86 loc) · 2.42 KB
/
crawler_test.go
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
package adstxt
import (
"io"
"net/http"
"net/http/httptest"
"testing"
"time"
)
// TestSendAndParseRquest test send HTTP request to remote host to Get Ads.txt file
func TestSendAndParseRquest(t *testing.T) {
// expected response
const expected = "greenadexchange.com,XF7342,DIRECT"
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, expected)
w.Header().Set("Content-Type", "text/plain")
}))
defer ts.Close()
// request mock
req, _ := NewRequest(ts.URL)
// test send request
c := newCrawler()
res, err := c.sendRequest(req)
if err != nil {
t.Error(err)
}
defer res.Body.Close()
body, err := c.readBody(req, res)
if err != nil {
t.Error(err)
}
if string(body) != expected {
t.Errorf("Expected response body [%s] to be \"%s\"", string(body), expected)
}
}
// TestHandleRedirect test crawler handle HTTP redirect response: extract new redirect destination from HTTP response
func TestHandleRedirect(t *testing.T) {
const redirect = "http://gotest.com/ads.txt"
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Location", redirect)
w.WriteHeader(http.StatusMovedPermanently)
}))
defer ts.Close()
// request mock
req, _ := NewRequest(ts.URL)
// test send request
c := newCrawler()
res, err := c.sendRequest(req)
if err != nil {
t.Error(err)
}
defer res.Body.Close()
// parse redirect location
r, err := c.handleRedirect(req, res)
if err != nil {
t.Error(err)
}
if r != redirect {
t.Errorf("Expected redirect destination to be [%s] and not [%s]", redirect, r)
}
}
// TestParseExpires test parse Ads.txt file expires from HTTP response Header
func TestParseExpires(t *testing.T) {
// expected response
var cache = time.Now().AddDate(60, 0, 0)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Expires", cache.Format(http.TimeFormat))
w.WriteHeader(http.StatusOK)
}))
defer ts.Close()
// request mock
req, _ := NewRequest(ts.URL)
// test send request
c := newCrawler()
res, err := c.sendRequest(req)
if err != nil {
t.Error(err)
}
defer res.Body.Close()
expires, err := c.parseExpires(res)
if err != nil {
t.Error(err)
}
if expires.Format(http.TimeFormat) != cache.Format(http.TimeFormat) {
t.Errorf("After Expected expires [%s] to be [%s]", expires.Format(http.TimeFormat), cache.Format(http.TimeFormat))
}
}