helpers.MakeTestServer   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 6
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
dl 0
loc 6
rs 10
c 0
b 0
f 0
nop 2
1
package helpers
2
3
import (
4
	"bytes"
5
	"context"
6
	"io"
7
	"net/http"
8
	"net/http/httptest"
9
)
10
11
// MakeTestServer creates an api server for testing
12
func MakeTestServer(responseCode int, body []byte) *httptest.Server {
13
	return httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
14
		res.WriteHeader(responseCode)
15
		_, err := res.Write(body)
16
		if err != nil {
17
			panic(err)
18
		}
19
	}))
20
}
21
22
// MakeRequestCapturingTestServer creates an api server that captures the request object
23
func MakeRequestCapturingTestServer(responseCode int, responses [][]byte, requests *[]*http.Request) *httptest.Server {
24
	index := 0
25
	return httptest.NewServer(http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) {
26
		clonedRequest := request.Clone(context.Background())
27
28
		// clone body
29
		body, err := io.ReadAll(request.Body)
30
		if err != nil {
31
			panic(err)
32
		}
33
		request.Body = io.NopCloser(bytes.NewReader(body))
34
		clonedRequest.Body = io.NopCloser(bytes.NewReader(body))
35
36
		*requests = append(*requests, clonedRequest)
37
38
		responseWriter.WriteHeader(responseCode)
39
		_, err = responseWriter.Write(responses[index])
40
		if err != nil {
41
			panic(err)
42
		}
43
		index++
44
	}))
45
}
46