| Total Lines | 42 | 
| Duplicated Lines | 0 % | 
| Changes | 0 | ||
| 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(responseCodes []int, responses [][]byte, requests *[]http.Request) *httptest.Server { | ||
| 24 | index := 0 | ||
| 25 | 	return httptest.NewServer(http.HandlerFunc(func(responseWriter http.ResponseWriter, req *http.Request) { | ||
| 26 | clonedRequest := req.Clone(context.Background()) | ||
| 27 | |||
| 28 | // clone body | ||
| 29 | body, err := io.ReadAll(req.Body) | ||
| 30 | 		if err != nil { | ||
| 31 | panic(err) | ||
| 32 | } | ||
| 33 | req.Body = io.NopCloser(bytes.NewReader(body)) | ||
| 34 | clonedRequest.Body = io.NopCloser(bytes.NewReader(body)) | ||
| 35 | |||
| 36 | *requests = append(*requests, *clonedRequest) | ||
| 37 | |||
| 38 | responseWriter.WriteHeader(responseCodes[index]) | ||
| 39 | _, err = responseWriter.Write(responses[index]) | ||
| 40 | index++ | ||
| 41 | 		if err != nil { | ||
| 42 | panic(err) | ||
| 43 | } | ||
| 46 |