-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathmockserver.go
More file actions
77 lines (70 loc) · 2.06 KB
/
mockserver.go
File metadata and controls
77 lines (70 loc) · 2.06 KB
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
package testutil
import (
"encoding/json"
"net/http"
"net/http/httptest"
"sync"
"testing"
)
// MockResponse represents a single response that the MockServer will return for a request.
// If `Handler` is set, it will be used to handle the request and the other fields will be ignored.
// If `ToJsonBody` is set, it will be marshaled to JSON and returned as the response body with content-type application/json.
// If `StatusCode` is set, it will be used as the response status code. Otherwise, http.StatusOK will be used.
type MockResponse struct {
StatusCode int
Description string
ToJsonBody any
Handler http.HandlerFunc
}
var _ http.Handler = (*MockServer)(nil)
type MockServer struct {
mu sync.Mutex
nextResponse int
responses []MockResponse
Server *httptest.Server
t *testing.T
}
// NewMockServer creates a new simple mock server that returns `responses` in order for each request.
// Use the `Reset` method to reset the response order and set new responses.
func NewMockServer(t *testing.T, responses ...MockResponse) *MockServer {
mock := &MockServer{
nextResponse: 0,
responses: responses,
t: t,
}
mock.Server = httptest.NewServer(mock)
return mock
}
func (m *MockServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
m.mu.Lock()
defer m.mu.Unlock()
if m.nextResponse >= len(m.responses) {
m.t.Fatalf("No more responses left in the mock server for request: %v", r)
}
next := m.responses[m.nextResponse]
m.nextResponse++
if next.Handler != nil {
next.Handler(w, r)
return
}
status := next.StatusCode
if status == 0 {
status = http.StatusOK
}
if next.ToJsonBody != nil {
bs, err := json.Marshal(next.ToJsonBody)
if err != nil {
m.t.Fatalf("Error marshaling response body: %v", err)
}
w.Header().Set("content-type", "application/json")
w.WriteHeader(status)
w.Write(bs) //nolint:errcheck //test will fail when this happens
}
w.WriteHeader(status)
}
func (m *MockServer) Reset(responses ...MockResponse) {
m.mu.Lock()
defer m.mu.Unlock()
m.nextResponse = 0
m.responses = responses
}