| Total Lines | 53 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | package helpers |
||
| 2 | |||
| 3 | import ( |
||
| 4 | "bytes" |
||
| 5 | "context" |
||
| 6 | "io/ioutil" |
||
| 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 | // MakeTestServerWithMultipleResponses creates an api server for testing with multiple responses |
||
| 23 | func MakeTestServerWithMultipleResponses(responseCode int, responses [][]byte) *httptest.Server { |
||
| 24 | count := 0 |
||
| 25 | return httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { |
||
| 26 | res.WriteHeader(responseCode) |
||
| 27 | _, err := res.Write(responses[count]) |
||
| 28 | if err != nil { |
||
| 29 | panic(err) |
||
| 30 | } |
||
| 31 | count++ |
||
| 32 | })) |
||
| 33 | } |
||
| 34 | |||
| 35 | // MakeRequestCapturingTestServer creates an api server that captures the request object |
||
| 36 | func MakeRequestCapturingTestServer(responseCode int, response []byte, request *http.Request) *httptest.Server { |
||
| 37 | return httptest.NewServer(http.HandlerFunc(func(responseWriter http.ResponseWriter, req *http.Request) { |
||
| 38 | clonedRequest := req.Clone(context.Background()) |
||
| 39 | |||
| 40 | // clone body |
||
| 41 | body, err := ioutil.ReadAll(req.Body) |
||
| 42 | if err != nil { |
||
| 43 | panic(err) |
||
| 44 | } |
||
| 45 | req.Body = ioutil.NopCloser(bytes.NewReader(body)) |
||
| 46 | clonedRequest.Body = ioutil.NopCloser(bytes.NewReader(body)) |
||
| 47 | |||
| 48 | *request = *clonedRequest |
||
| 49 | |||
| 50 | responseWriter.WriteHeader(responseCode) |
||
| 51 | _, err = responseWriter.Write(response) |
||
| 52 | if err != nil { |
||
| 53 | panic(err) |
||
| 54 | } |
||
| 57 |