-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathhttp_test.go
More file actions
103 lines (91 loc) · 2.35 KB
/
http_test.go
File metadata and controls
103 lines (91 loc) · 2.35 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
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
package mockutil
import (
"fmt"
"io"
"math/rand"
"net/http"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestHandler(t *testing.T) {
server := NewServer(t, []Request{
{
Method: "GET", Path: "/",
Status: 200,
JSON: struct {
Data string `json:"data"`
}{
Data: "Hello",
},
},
{
Method: "GET", Path: "/",
Status: 400,
JSONRaw: `{"error": "failed"}`,
},
{
Method: "GET", Path: "/",
Status: 503,
},
{
Method: "GET",
Want: func(t *testing.T, r *http.Request) {
require.True(t, strings.HasPrefix(r.RequestURI, "/random?key="))
},
Status: 200,
},
{
Method: "GET", Path: "/",
Status: 200,
TextRaw: "hello",
},
})
// Request 1
resp, err := http.Get(server.URL)
require.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode)
assert.Equal(t, "application/json", resp.Header.Get("Content-Type"))
assert.JSONEq(t, `{"data":"Hello"}`, readBody(t, resp))
// Request 2
resp, err = http.Get(server.URL)
require.NoError(t, err)
assert.Equal(t, 400, resp.StatusCode)
assert.Equal(t, "application/json", resp.Header.Get("Content-Type"))
assert.JSONEq(t, `{"error": "failed"}`, readBody(t, resp))
// Request 3
resp, err = http.Get(server.URL)
require.NoError(t, err)
assert.Equal(t, 503, resp.StatusCode)
assert.Empty(t, resp.Header.Get("Content-Type"))
assert.Empty(t, readBody(t, resp))
// Request 4
resp, err = http.Get(fmt.Sprintf("%s/random?key=%d", server.URL, rand.Int63()))
require.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode)
assert.Empty(t, resp.Header.Get("Content-Type"))
assert.Empty(t, readBody(t, resp))
// Request 5
resp, err = http.Get(server.URL)
require.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode)
assert.Equal(t, "text/plain", resp.Header.Get("Content-Type"))
assert.Equal(t, "hello", readBody(t, resp))
// Extra request 6
server.Expect([]Request{
{Method: "GET", Path: "/", Status: 200},
})
resp, err = http.Get(server.URL)
require.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode)
assert.Empty(t, resp.Header.Get("Content-Type"))
assert.Empty(t, readBody(t, resp))
}
func readBody(t *testing.T, resp *http.Response) string {
t.Helper()
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
return strings.TrimSuffix(string(body), "\n")
}