-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
268 lines (205 loc) · 5.78 KB
/
server.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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package httpmock
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"github.com/stretchr/testify/require"
"go.nhat.io/httpmock/format"
"go.nhat.io/httpmock/planner"
"go.nhat.io/httpmock/test"
"go.nhat.io/httpmock/value"
)
// Server is a Mock server.
type Server struct {
// Requests are the matched expectations.
Requests []planner.Expectation
// Test server.
server *httptest.Server
planner planner.Planner
// test is An optional variable that holds the test struct, to be used when an
// invalid MockServer call was made.
test test.T
mu sync.Mutex
// defaultRequestOptions contains a list of default options what will be applied to every new requests.
defaultRequestOptions []func(e Expectation)
// defaultResponseHeader contains a list of default headers that will be sent to client.
defaultResponseHeader map[string]string
}
// NewServer creates a new server.
func NewServer() *Server {
s := Server{
test: test.NoOpT(),
planner: planner.Sequence(),
}
s.server = httptest.NewServer(&s)
return &s
}
// WithPlanner sets the planner.
func (s *Server) WithPlanner(p planner.Planner) *Server {
s.mu.Lock()
defer s.mu.Unlock()
if !s.planner.IsEmpty() {
panic(errors.New("could not change planner: planner is not empty")) // nolint: goerr113
}
s.planner = p
return s
}
// WithTest sets the *testing.T of the server.
func (s *Server) WithTest(t test.T) *Server {
s.mu.Lock()
defer s.mu.Unlock()
s.test = t
return s
}
// WithDefaultRequestOptions sets the default request options of the server.
func (s *Server) WithDefaultRequestOptions(opt func(e Expectation)) *Server {
s.mu.Lock()
defer s.mu.Unlock()
s.defaultRequestOptions = append(s.defaultRequestOptions, opt)
return s
}
// WithDefaultResponseHeaders sets the default response headers of the server.
func (s *Server) WithDefaultResponseHeaders(headers map[string]string) *Server {
s.mu.Lock()
defer s.mu.Unlock()
s.defaultResponseHeader = headers
return s
}
// URL returns the current URL of the httptest.Server.
func (s *Server) URL() string {
return s.server.URL
}
// Close closes mocked server.
func (s *Server) Close() {
s.server.Close()
}
// Expect adds a new expected request.
//
// Server.Expect(httpmock.MethodGet, "/path").
func (s *Server) Expect(method string, requestURI any) Expectation {
expect := newRequestExpectation(method, requestURI)
expect.Once()
for _, o := range s.defaultRequestOptions {
o(expect)
}
s.mu.Lock()
defer s.mu.Unlock()
s.planner.Expect(expect)
return expect
}
// ExpectGet adds a new expected http.MethodGet request.
//
// Server.ExpectGet("/path")
func (s *Server) ExpectGet(requestURI any) Expectation {
return s.Expect(MethodGet, requestURI)
}
// ExpectHead adds a new expected http.MethodHead request.
//
// Server.ExpectHead("/path")
func (s *Server) ExpectHead(requestURI any) Expectation {
return s.Expect(MethodHead, requestURI)
}
// ExpectPost adds a new expected http.MethodPost request.
//
// Server.ExpectPost("/path")
func (s *Server) ExpectPost(requestURI any) Expectation {
return s.Expect(MethodPost, requestURI)
}
// ExpectPut adds a new expected http.MethodPut request.
//
// Server.ExpectPut("/path")
func (s *Server) ExpectPut(requestURI any) Expectation {
return s.Expect(MethodPut, requestURI)
}
// ExpectPatch adds a new expected http.MethodPatch request.
//
// Server.ExpectPatch("/path")
func (s *Server) ExpectPatch(requestURI any) Expectation {
return s.Expect(MethodPatch, requestURI)
}
// ExpectDelete adds a new expected http.MethodDelete request.
//
// Server.ExpectDelete("/path")
func (s *Server) ExpectDelete(requestURI any) Expectation {
return s.Expect(MethodDelete, requestURI)
}
// ExpectationsWereMet checks whether all queued expectations were met in order.
// If any of them was not met - an error is returned.
func (s *Server) ExpectationsWereMet() error {
s.mu.Lock()
defer s.mu.Unlock()
if s.planner.IsEmpty() {
return nil
}
var (
sb strings.Builder
count int
)
sb.WriteString("there are remaining expectations that were not met:\n")
for _, expected := range s.planner.Remain() {
repeat := expected.RemainTimes()
calls := expected.FulfilledTimes()
if repeat < 1 && calls > 0 {
continue
}
sb.WriteString("- ")
format.ExpectedRequestTimes(&sb,
expected.Method(),
expected.URIMatcher(),
expected.HeaderMatcher(),
expected.BodyMatcher(),
int(calls),
int(repeat), //nolint: gosec
)
count++
}
if count == 0 {
return nil
}
// nolint:goerr113
return errors.New(sb.String())
}
// ServeHTTP serves the request.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
defer s.mu.Unlock()
if s.planner.IsEmpty() {
body, err := value.GetBody(r)
if err == nil && len(body) > 0 {
s.failResponsef(w, "unexpected request received: %s %s, body:\n%s", r.Method, r.RequestURI, string(body))
} else {
s.failResponsef(w, "unexpected request received: %s %s", r.Method, r.RequestURI)
}
return
}
expected, err := s.planner.Plan(r)
if err != nil {
s.failResponsef(w, err.Error()) //nolint: govet
return
}
// Log the request.
expected.Fulfilled()
s.Requests = append(s.Requests, expected)
if h, ok := expected.(ExpectationHandler); ok {
err = h.Handle(w, r, s.defaultResponseHeader)
require.NoError(s.test, err)
return
}
s.failResponsef(w, "could not handle request: %s %s", r.Method, r.RequestURI)
}
func (s *Server) failResponsef(w http.ResponseWriter, format string, args ...any) {
body := fmt.Sprintf(format, args...)
s.test.Errorf(body)
err := FailResponse(w, body) //nolint: govet
require.NoError(s.test, err, "could not write response: %q", body)
}
// ResetExpectations resets all the expectations.
func (s *Server) ResetExpectations() {
s.mu.Lock()
defer s.mu.Unlock()
s.Requests = nil
s.planner.Reset()
}