~ewintr/go-kit

go-kit/test/httpmock.go -rw-r--r-- 3.9 KiB View raw
36275689Erik Winter renamed http_mock a month ago
                                                                                
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
package test

import (
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"strings"
)

// MockResponse represents a response for the mock server to serve
type MockResponse struct {
	StatusCode int
	Headers    http.Header
	Body       []byte
}

type MockServerProcedure struct {
	URI        string
	HTTPMethod string
	Response   MockResponse
}

// MockRecorder provides a way to record request information from every
// successful request.
type MockRecorder interface {
	Record(r *http.Request)
}

// recordedRequest represents recorded structured information about each request
type recordedRequest struct {
	hits     int
	requests []*http.Request
	bodies   [][]byte
}

// MockAssertion represents a common assertion for requests
type MockAssertion struct {
	indexes map[string]int    // indexation for key
	recs    []recordedRequest // request catalog
}

// Record records request hit information
func (m *MockAssertion) Record(r *http.Request) {
	k := m.index(r.RequestURI, r.Method)

	b, _ := ioutil.ReadAll(r.Body)
	if len(b) == 0 {
		b = nil
	}

	if k < 0 {
		m.newIndex(r.RequestURI, r.Method)
		m.recs = append(m.recs, recordedRequest{
			hits:     1,
			requests: []*http.Request{r},
			bodies:   [][]byte{b},
		})
		return
	}

	m.recs[k].hits++
	m.recs[k].requests = append(m.recs[k].requests, r)
	m.recs[k].bodies = append(m.recs[k].bodies, b)
}

// Hits returns the number of hits for a uri and method
func (m *MockAssertion) Hits(uri, method string) int {
	k := m.index(uri, method)
	if k < 0 {
		return 0
	}

	return m.recs[k].hits
}

// Headers returns a slice of request headers
func (m *MockAssertion) Headers(uri, method string) []http.Header {
	k := m.index(uri, method)
	if k < 0 {
		return nil
	}

	headers := make([]http.Header, len(m.recs[k].requests))
	for i, r := range m.recs[k].requests {

		// remove default headers
		if _, ok := r.Header["Content-Length"]; ok {
			r.Header.Del("Content-Length")
		}

		if v, ok := r.Header["User-Agent"]; ok {
			if _, yes := equals([]string{"Go-http-client/1.1"}, v); yes {
				r.Header.Del("User-Agent")
			}
		}

		if v, ok := r.Header["Accept-Encoding"]; ok {
			if _, yes := equals([]string{"gzip"}, v); yes {
				r.Header.Del("Accept-Encoding")
			}
		}

		if len(r.Header) == 0 {
			continue
		}

		headers[i] = r.Header
	}
	return headers
}

// Body returns request body
func (m *MockAssertion) Body(uri, method string) [][]byte {
	k := m.index(uri, method)
	if k < 0 {
		return nil
	}

	return m.recs[k].bodies
}

// Reset sets all unexpected properties to their zero value
func (m *MockAssertion) Reset() error {
	m.indexes = make(map[string]int)
	m.recs = make([]recordedRequest, 0)
	return nil
}

// index indexes a key composed of the uri and method and returns the position
// for this key in a list if it was indexed before.
func (m *MockAssertion) index(uri, method string) int {
	if isZero(m.indexes) {
		m.indexes = make(map[string]int)
	}

	k := strings.ToLower(uri + method)

	if i, ok := m.indexes[k]; ok {
		return i
	}

	return -1
}

func (m *MockAssertion) newIndex(uri, method string) int {
	k := strings.ToLower(uri + method)
	m.indexes[k] = len(m.indexes)
	return m.indexes[k]
}

// NewMockServer return a mock HTTP server to test requests
func NewMockServer(rec MockRecorder, procedures ...MockServerProcedure) *httptest.Server {
	var handler http.Handler

	handler = http.HandlerFunc(
		func(w http.ResponseWriter, r *http.Request) {

			for _, proc := range procedures {

				if proc.URI == r.URL.RequestURI() && proc.HTTPMethod == r.Method {

					headers := w.Header()
					for hkey, hvalue := range proc.Response.Headers {
						headers[hkey] = hvalue
					}

					code := proc.Response.StatusCode
					if code == 0 {
						code = http.StatusOK
					}

					w.WriteHeader(code)
					w.Write(proc.Response.Body)

					if rec != nil {
						rec.Record(r)
					}
					return
				}
			}

			w.WriteHeader(http.StatusNotFound)
			return
		})

	return httptest.NewServer(handler)
}