-
Notifications
You must be signed in to change notification settings - Fork 0
/
expectation.go
105 lines (85 loc) · 2.34 KB
/
expectation.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
package clientmock
import (
"fmt"
"io/ioutil"
"net/http"
)
// Expectation is an interface for an expectation check for the request that will be made
type Expectation interface {
// Check will give the expectation the incoming request to be validated
Check(req *http.Request)
// Met will check if the check has passed
Met() bool
// Message is the msg passed to error.New if the expectation wasn't met
Message() string
}
// ExpectedMethod will verify that the request method matches the expected method
type ExpectedMethod struct {
method string
met bool
msg string
}
// Check will verify the *http.Request method matches the expected method
func (m *ExpectedMethod) Check(req *http.Request) {
if m.method == req.Method {
m.met = true
}
m.msg = fmt.Sprintf("expected method %s got %s", m.method, req.Method)
}
// Met returns if methods matched
func (m *ExpectedMethod) Met() bool {
return m.met
}
// Message returns the error message or "" if none
func (m *ExpectedMethod) Message() string {
return m.msg
}
// ExpectedBody verifies that the request body matches the expected body
type ExpectedBody struct {
body string
met bool
msg string
}
// Check will verify the body in the request matches the expected body
func (e *ExpectedBody) Check(req *http.Request) {
data, _ := ioutil.ReadAll(req.Body)
if string(data) != e.body {
e.msg = fmt.Sprintf("bodies don't match expected [%s] got [%s]", e.body, string(data))
return
}
e.met = true
}
// Met returns whether or not the expectation has been met
func (e *ExpectedBody) Met() bool {
return e.met
}
// Message returns the error message or "" if none
func (e *ExpectedBody) Message() string {
return e.msg
}
// ExpectedHeader will verify the sent header matches the expected header
type ExpectedHeader struct {
h http.Header
met bool
msg string
}
// Check will verify the headers match the expected
func (e *ExpectedHeader) Check(req *http.Request) {
e.met = true
for key := range e.h {
exp := e.h.Get(key)
got := req.Header.Get(key)
if exp != "" && exp != got {
e.met = false
e.msg += fmt.Sprintf("Expected %s got %s for %s\n", exp, got, key)
}
}
}
// Met returns whether or not the expectations were met
func (e *ExpectedHeader) Met() bool {
return e.met
}
// Message returns the error message or "" if none
func (e *ExpectedHeader) Message() string {
return e.msg
}