-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstub.go
102 lines (85 loc) · 1.77 KB
/
stub.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
package stub
import (
"encoding/json"
"net/http"
"net/url"
)
type Stub struct {
con *Connect
matchers []Matcher
result Response
}
func (s *Stub) match(r *Request) bool {
for _, m := range s.matchers {
if !m.Match(r) {
return false
}
}
return true
}
type Response struct {
Status int
Body []byte
Header http.Header
}
type Matcher interface {
Match(r *Request) bool
}
type Request struct {
Body []byte
Method string
Header http.Header
URL *url.URL
}
func (s *Stub) Return(resp Response) ReleaseStub {
s.result = resp
s.con.addStub <- s
return ReleaseStub{s}
}
func (s *Stub) ReturnJSON(code int, payload interface{}) ReleaseStub {
b, _ := json.Marshal(payload)
s.result = Response{
Status: code,
Body: b,
}
s.con.addStub <- s
return ReleaseStub{s}
}
func (s *Stub) MethodPost() *Stub {
s.matchers = append(s.matchers, methodMatcher(http.MethodPost))
return s
}
func (s *Stub) MethodGet() *Stub {
s.matchers = append(s.matchers, methodMatcher(http.MethodGet))
return s
}
func (s *Stub) MethodPatch() *Stub {
s.matchers = append(s.matchers, methodMatcher(http.MethodPatch))
return s
}
func (s *Stub) MethodDelete() *Stub {
s.matchers = append(s.matchers, methodMatcher(http.MethodDelete))
return s
}
func (s *Stub) MethodPut() *Stub {
s.matchers = append(s.matchers, methodMatcher(http.MethodPut))
return s
}
func (s *Stub) Header(k, v string) *Stub {
s.matchers = append(s.matchers, headerMatcher{k, v})
return s
}
func (s *Stub) Path(p string) *Stub {
s.matchers = append(s.matchers, pathMatcher(p))
return s
}
func (s *Stub) Body(m func(body []byte) bool) *Stub {
s.matchers = append(s.matchers, bodyMatcher(m))
return s
}
type ReleaseStub struct {
s *Stub
}
func (rs ReleaseStub) Remove() {
rs.s.con.removeStub <- rs.s
}