-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebtest.go
More file actions
68 lines (56 loc) · 1.61 KB
/
webtest.go
File metadata and controls
68 lines (56 loc) · 1.61 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
// This package is a modified version of the webtest package available at
// https://github.com/cespare/webtest, and is under the same license as the
// original package. This version has a reusable http.Client that allows the
// tested handler to set and remove secure cookies as needed.
package webtest
import (
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"net/url"
"path/filepath"
"testing"
)
// newHttpTester creates a server and client for testing the given handler.
func newHttpTester(t *testing.T, h http.Handler) (*httptest.Server, *http.Client, *url.URL) {
server := httptest.NewTLSServer(h)
jar, err := cookiejar.New(nil)
if err != nil {
t.Fatal("could not newHttpTester:", err)
}
client := server.Client()
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
client.Jar = jar
url, err := url.Parse(server.URL)
if err != nil {
t.Fatal("could not newHttpTester:", err)
}
return server, client, url
}
// TestHandler runs the test script files matched by glob against the given
// handler.
func TestHandler(t *testing.T, glob string, h http.Handler) {
server, client, url := newHttpTester(t, h)
defer server.Close()
files, err := filepath.Glob(glob)
if err != nil {
t.Fatal("could not test:", err)
}
if len(files) == 0 {
t.Fatalf("could not test: no files match %#q", glob)
}
for _, file := range files {
script, err := newScript(file)
if err != nil {
t.Fatal(err)
}
for _, c := range script.cases {
err := c.runHandler(url, client, h)
if err != nil {
t.Fatal("expected no error, received", err)
}
}
}
}