Skip to content

Commit 4920eb3

Browse files
committed
Import code
1 parent 75bc5de commit 4920eb3

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

webtest.go

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package webtest
2+
3+
import (
4+
"fmt"
5+
"io"
6+
"io/ioutil"
7+
"net/http"
8+
"strings"
9+
)
10+
11+
type RequestTestCase struct {
12+
Method string
13+
URL string
14+
Body io.Reader
15+
Header http.Header
16+
ResponseStatus int
17+
ResponseBody io.Reader
18+
}
19+
20+
type RequestTestSuite []RequestTestCase
21+
22+
func (ts RequestTestSuite) Execute(c *http.Client, errFn func(err error)) {
23+
for i, tc := range ts {
24+
if tc.Method == "" || tc.URL == "" {
25+
panic("httpTestCase requires Method and URL to be set")
26+
}
27+
28+
if tc.ResponseStatus == 0 {
29+
tc.ResponseStatus = http.StatusOK
30+
}
31+
32+
req, err := http.NewRequest(tc.Method, tc.URL, tc.Body)
33+
if err != nil {
34+
panic(err)
35+
}
36+
37+
if tc.Header != nil {
38+
req.Header = tc.Header
39+
}
40+
41+
res, err := c.Do(req)
42+
if err != nil {
43+
panic(err)
44+
}
45+
46+
if res.StatusCode != tc.ResponseStatus {
47+
errFn(fmt.Errorf("Expected test case #%d (%s %s) to respond with %d but got %d", i, tc.Method, tc.URL, tc.ResponseStatus, res.StatusCode))
48+
}
49+
50+
if tc.ResponseBody != nil {
51+
eb, err := ioutil.ReadAll(tc.ResponseBody)
52+
if err != nil {
53+
panic(err)
54+
}
55+
56+
ab, err := ioutil.ReadAll(res.Body)
57+
if err != nil {
58+
panic(err)
59+
}
60+
61+
if strings.TrimSpace(string(ab)) != strings.TrimSpace(string(eb)) {
62+
errFn(fmt.Errorf("Expected test case #%d (%s %s) response to be:\n%s\nbut got:\n%s", i, tc.Method, tc.URL, eb, ab))
63+
}
64+
}
65+
}
66+
}

0 commit comments

Comments
 (0)