forked from jlelse/GoBlog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpClient_test.go
77 lines (69 loc) · 1.67 KB
/
httpClient_test.go
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
package main
import (
"context"
"io"
"net/http"
"net/http/httptest"
"sync"
"testing"
"github.com/stretchr/testify/require"
)
type fakeHttpClient struct {
mu sync.Mutex
handler http.Handler
*http.Client
req *http.Request
res *http.Response
}
func newFakeHttpClient() *fakeHttpClient {
fc := &fakeHttpClient{}
fc.Client = newHandlerClient(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
fc.mu.Lock()
defer fc.mu.Unlock()
fc.req = r
if fc.handler != nil {
rec := httptest.NewRecorder()
fc.handler.ServeHTTP(rec, r)
res := rec.Result()
fc.res = res
// Copy the headers from the response recorder
for k, v := range rec.Header() {
rw.Header()[k] = v
}
// Copy result status code and body
rw.WriteHeader(rec.Code)
_, _ = io.Copy(rw, rec.Body)
// Close response body
_ = res.Body.Close()
}
}))
return fc
}
func (c *fakeHttpClient) clean() {
c.mu.Lock()
c.req = nil
c.res = nil
c.handler = nil
c.mu.Unlock()
}
func (c *fakeHttpClient) setHandler(handler http.Handler) {
c.clean()
c.mu.Lock()
c.handler = handler
c.mu.Unlock()
}
func (c *fakeHttpClient) setFakeResponse(statusCode int, body string) {
c.setHandler(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
rw.WriteHeader(statusCode)
_, _ = rw.Write([]byte(body))
}))
}
func Test_fakeHttpClient(t *testing.T) {
fc := newFakeHttpClient()
fc.setFakeResponse(http.StatusNotFound, "Not found")
req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://localhost:8080/", nil)
resp, err := fc.Client.Do(req)
require.NoError(t, err)
require.Equal(t, http.StatusNotFound, resp.StatusCode)
_ = resp.Body.Close()
}