-
Notifications
You must be signed in to change notification settings - Fork 1
/
yams.go
178 lines (147 loc) · 3.4 KB
/
yams.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
package yams
import (
"bytes"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
"reflect"
"regexp"
"time"
)
type server struct {
ops chan op
mockServer *httptest.Server
}
type Mock struct {
Method string
URL string
ReqHeaders http.Header
ReqBody []byte
RespStatus int
RespHeaders http.Header
RespBody []byte
Wait time.Duration
Times int
}
type op struct {
code string
argument Mock
response chan Mock
}
const add = "add"
const find = "find"
const flush = "flush"
const count = "count"
// Yet Another Mockup Server
func New(port int) (*server, error) {
s := &server{ops: make(chan op)}
go s.runMocks()
listener, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
if err != nil {
return nil, err
}
s.mockServer = httptest.NewUnstartedServer(s)
s.mockServer.Listener.Close()
s.mockServer.Listener = listener
s.mockServer.Start()
return s, nil
}
func (s *server) runMocks() {
mocks := make(map[string]Mock)
for operation := range s.ops {
switch operation.code {
case add:
m := mocks[operation.argument.key()]
if m.key() == operation.argument.key() {
m.Times++
} else {
m = operation.argument
}
mocks[m.key()] = m
case find:
for _, m := range mocks {
if ok, err := regexp.MatchString(m.key(), operation.argument.key()); ok && err == nil {
operation.response <- m
m.Times--
mocks[m.key()] = m
}
}
close(operation.response)
case flush:
mocks = make(map[string]Mock)
}
}
}
func (s *server) ServeHTTP(response http.ResponseWriter, request *http.Request) {
operation := op{find, Mock{Method: request.Method, URL: request.URL.String()}, make(chan Mock)}
s.ops <- operation
mock := <-operation.response
err := mock.match(request)
if err != nil {
response.WriteHeader(http.StatusNotFound)
response.Write([]byte(err.Error()))
return
}
if mock.Times <= 0 {
response.WriteHeader(http.StatusBadRequest)
response.Write([]byte(fmt.Sprintf("no more calls were expected for (%s)", mock.key())))
return
}
time.Sleep(mock.Wait)
mock.write(response)
}
func (s *server) Add(mocks ...Mock) error {
for _, m := range mocks {
if m.Times == 0 {
m.Times = 1
}
s.ops <- op{add, m, nil}
}
return nil
}
func (s *server) Close() {
if s == nil {
return
}
close(s.ops)
s.mockServer.Close()
}
func (m Mock) key() string {
return fmt.Sprintf("%s_%s", m.Method, m.URL)
}
func (m Mock) match(req *http.Request) error {
if m.Method != req.Method {
return fmt.Errorf("no match for %s %s", req.Method, req.URL.String())
}
if ok, err := regexp.MatchString(m.key(), req.URL.String()); ok && err == nil {
return fmt.Errorf("no match for %s %s", req.Method, req.URL.String())
}
defer req.Body.Close()
body, err := ioutil.ReadAll(req.Body)
if err != nil {
return err
}
if !bytes.Equal(m.ReqBody, body) {
return fmt.Errorf("no match for %s %s [body mismatch]", req.Method, req.URL.String())
}
if len(m.ReqHeaders) > 0 {
for name, values := range m.ReqHeaders {
if !reflect.DeepEqual(req.Header[name], values) {
return fmt.Errorf("no match for %s %s [headers mismatch]", req.Method, req.URL.String())
}
}
}
return nil
}
func (m Mock) write(response http.ResponseWriter) error {
response.WriteHeader(m.RespStatus)
for k, v := range m.RespHeaders {
for _, vv := range v {
response.Header().Add(k, vv)
}
}
response.Write(m.RespBody)
return nil
}