forked from h2non/baloo
/
body.go
81 lines (72 loc) · 1.92 KB
/
body.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
package assert
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"regexp"
"strconv"
)
func readBody(res *http.Response) ([]byte, error) {
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return []byte{}, err
}
// Re-fill body reader stream after reading it
res.Body = ioutil.NopCloser(bytes.NewBuffer(body))
return body, err
}
// BodyMatchString asserts a response body matching a string expression.
// Regular expressions can be used as value to perform the specific assertions.
func BodyMatchString(pattern string) Func {
return func(res *http.Response, req *http.Request) error {
body, err := readBody(res)
if err != nil {
return err
}
if match, _ := regexp.MatchString(pattern, string(body)); !match {
return fmt.Errorf("body mismatch: pattern not found '%s'", pattern)
}
return nil
}
}
// BodyEquals asserts as strict equality comparison the
// response body with a given string string.
func BodyEquals(value string) Func {
return func(res *http.Response, req *http.Request) error {
body, err := readBody(res)
if err != nil {
return err
}
bodyStr := string(body)
err = fmt.Errorf("bodies mismatch:\n\thave: %#v\n\twant: %#v", bodyStr, value)
// Remove line feed sequence
if len(bodyStr) > 0 && bodyStr[len(bodyStr)-1] == '\n' {
bodyStr = bodyStr[:len(bodyStr)-1]
}
// Perform the comparison
if len(bodyStr) != len(value) || value != bodyStr {
return err
}
return nil
}
}
// BodyLength asserts a response body length.
func BodyLength(length int) Func {
return func(res *http.Response, req *http.Request) error {
cl, err := strconv.Atoi(res.Header.Get("Content-Length"))
// Infer length from body buffer
if err != nil || cl == 0 {
body, err := readBody(res)
if err != nil {
return err
}
cl = len(body)
}
// Match body length
if cl != length {
return fmt.Errorf("body length mismatch: '%d' should be equal to '%d'", cl, length)
}
return nil
}
}