Repository navigation
Expand file tree
/
Copy pathquery_http_test.go
More file actions
94 lines (84 loc) · 2.42 KB
/
Copy pathquery_http_test.go
File metadata and controls
94 lines (84 loc) · 2.42 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
package htmlquery
import (
"bytes"
"compress/gzip"
"compress/zlib"
"io"
"net/http"
"testing"
)
type trackedResponseBody struct {
io.Reader
closes int
}
func (b *trackedResponseBody) Close() error {
b.closes++
return nil
}
type responseTransport func(*http.Request) (*http.Response, error)
func (f responseTransport) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}
type failedResponseReader struct{}
func (failedResponseReader) Read([]byte) (int, error) {
return 0, io.ErrClosedPipe
}
func TestLoadURLWithClientClosesResponseBody(t *testing.T) {
const document = "<html><head><title>example</title></head><body>page</body></html>"
var gz, def bytes.Buffer
gw := gzip.NewWriter(&gz)
if _, err := io.WriteString(gw, document); err != nil {
t.Fatal(err)
}
if err := gw.Close(); err != nil {
t.Fatal(err)
}
dw := zlib.NewWriter(&def)
if _, err := io.WriteString(dw, document); err != nil {
t.Fatal(err)
}
if err := dw.Close(); err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name, encoding string
reader io.Reader
wantErr bool
}{
{"plain", "", bytes.NewBufferString(document), false},
{"gzip", "gzip", bytes.NewReader(gz.Bytes()), false},
{"deflate", "deflate", bytes.NewReader(def.Bytes()), false},
{"invalid gzip", "gzip", bytes.NewBufferString("invalid"), true},
{"invalid deflate", "deflate", bytes.NewBufferString("invalid"), true},
{"unsupported encoding", "br", bytes.NewBufferString(document), true},
{"read failure", "", failedResponseReader{}, true},
} {
t.Run(tc.name, func(t *testing.T) {
body := &trackedResponseBody{Reader: tc.reader}
client := &http.Client{Transport: responseTransport(func(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{
"Content-Encoding": []string{tc.encoding},
"Content-Type": []string{"text/html; charset=utf-8"},
},
Body: body,
Request: req,
}, nil
})}
node, err := LoadURLWithClient("https://example.invalid/page", client)
if (err != nil) != tc.wantErr {
t.Fatalf("error = %v, want error %t", err, tc.wantErr)
}
if err == nil {
title := FindOne(node, "//title")
if title == nil || InnerText(title) != "example" {
t.Fatal("parsed document changed")
}
}
if body.closes != 1 {
t.Errorf("response body Close calls = %d, want 1", body.closes)
}
})
}
}