-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_test.go
More file actions
60 lines (45 loc) · 1.14 KB
/
Copy pathserver_test.go
File metadata and controls
60 lines (45 loc) · 1.14 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
package httpmock
import (
"context"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
)
func Test_Server(t *testing.T) {
t.Parallel()
require := require.New(t)
s := Server(t)
New(s.URL).
Get("/").
Reply(200).
JSON(map[string]any{
"i": 2,
})
resp, body := SendRequestAndGetResponse(t, http.MethodGet, s, "/", nil, map[string]string{})
require.Equal(200, resp.StatusCode)
require.JSONEq(`{"i": 2}`, string(body))
}
func SendRequestAndGetResponse(t *testing.T, method string, server *httptest.Server, path string, body io.Reader, header map[string]string) (*http.Response, []byte) {
t.Helper()
req, err := http.NewRequestWithContext(context.Background(), method, server.URL+path, body)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", "application/json")
for k, v := range header {
req.Header.Set(k, v)
}
client := server.Client()
resp, err := client.Do(req)
if err != nil {
t.Fatalf("error making http call: %v", err)
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("unable to read response: %v", err)
}
return resp, b
}