-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathhttpmock_test.go
More file actions
105 lines (81 loc) · 2.26 KB
/
httpmock_test.go
File metadata and controls
105 lines (81 loc) · 2.26 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
104
105
package httpmock
import (
"fmt"
"io"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
func TestBasicRequestResponse(t *testing.T) {
downstream := NewMockHandler(t)
downstream.On("Handle", "GET", "/object/12345", mock.Anything).Return(Response{
Body: []byte(`{"status": "ok"}`),
})
s := NewServer(downstream)
defer s.Close()
req, err := http.NewRequest("GET", fmt.Sprintf("%s/object/12345", s.URL()), nil)
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, []byte(`{"status": "ok"}`), body)
downstream.AssertExpectations(t)
}
func TestBasicRequestResponseWithHeaders(t *testing.T) {
headerKey := "HTTPMOCK-TEST"
headerVal := "its here"
downstream := NewMockHandlerWithHeaders(t)
downstream.On(
"HandleWithHeaders",
"GET",
"/object/12345",
HeaderMatcher(headerKey, headerVal),
mock.Anything,
).
Return(Response{
Body: []byte(`{"status": "ok"}`),
})
s := NewServer(downstream)
defer s.Close()
req, err := http.NewRequest("GET", fmt.Sprintf("%s/object/12345", s.URL()), nil)
require.NoError(t, err)
req.Header.Set(headerKey, headerVal)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, []byte(`{"status": "ok"}`), body)
downstream.AssertExpectations(t)
}
func TestMultiHeaderMatcher(t *testing.T) {
headerKey := "HTTPMOCK-TEST"
headerVal := "its here"
headerKey2 := "HTTPMOCK-TEST-2"
headerVal2 := "its here too!"
downstream := NewMockHandlerWithHeaders(t)
downstream.On(
"HandleWithHeaders",
"GET",
"/object/12345",
MultiHeaderMatcher(http.Header{
headerKey: []string{headerVal},
headerKey2: []string{headerVal2},
}),
mock.Anything,
).
Return(Response{
Body: []byte(`{"status": "ok"}`),
})
s := NewServer(downstream)
defer s.Close()
req, err := http.NewRequest("GET", fmt.Sprintf("%s/object/12345", s.URL()), nil)
require.NoError(t, err)
req.Header.Set(headerKey, headerVal)
req.Header.Set(headerKey2, headerVal2)
_, err = http.DefaultClient.Do(req)
require.NoError(t, err)
downstream.AssertExpectations(t)
}