forked from zerodha/fastglue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mock_test.go
77 lines (63 loc) · 2.17 KB
/
mock_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 fastglue
import (
"io/ioutil"
"net/http"
"testing"
"github.com/valyala/fasthttp"
)
func TestMockServer(t *testing.T) {
m := NewMockServer()
// Register mock upstream handlers.
m.Handle(fasthttp.MethodGet, "/test", MockResponse{Body: []byte("hello world")})
m.Handle(fasthttp.MethodGet, "/test2", MockResponse{
StatusCode: fasthttp.StatusInternalServerError,
Body: []byte("{\"data\": \"ouch\"}")})
// Create a fake request context and use it with the real handler.
req := m.NewFastglueReq()
req.RequestCtx.SetUserValue("mock_url", m.URL()+"/test")
mr := m.Do(handleMockRequest, req, t)
mr.AssertStatus(fasthttp.StatusOK)
mr.AssertBody([]byte("hello world"))
req = m.NewFastglueReq()
req.RequestCtx.SetUserValue("mock_url", m.URL()+"/test2")
mr = m.Do(handleMockRequest, req, t)
mr.AssertStatus(fasthttp.StatusInternalServerError)
mr.AssertJSON([]byte("{ \"data\": \"ouch\" }"))
}
func TestMockServerReset(t *testing.T) {
m := NewMockServer()
t.Run("test1", func(t *testing.T) {
m.Handle(fasthttp.MethodGet, "/test", MockResponse{Body: []byte("hello world from test1")})
req := m.NewFastglueReq()
req.RequestCtx.SetUserValue("mock_url", m.URL()+"/test")
mr := m.Do(handleMockRequest, req, t)
mr.AssertStatus(fasthttp.StatusOK)
mr.AssertBody([]byte("hello world from test1"))
})
t.Run("test2", func(t *testing.T) {
m.Reset()
m.Handle(fasthttp.MethodGet, "/test", MockResponse{Body: []byte("hello world from test2")})
req := m.NewFastglueReq()
req.RequestCtx.SetUserValue("mock_url", m.URL()+"/test")
mr := m.Do(handleMockRequest, req, t)
mr.AssertStatus(fasthttp.StatusOK)
mr.AssertBody([]byte("hello world from test2"))
})
}
// handleMockRequest is a dummy HTTP handler that sends a request
// to the mock server URL and writes that response.
func handleMockRequest(r *Request) error {
var (
mockURL = r.RequestCtx.UserValue("mock_url").(string)
)
resp, err := http.Get(mockURL)
if err != nil {
r.SendErrorEnvelope(fasthttp.StatusInternalServerError,
err.Error(), nil, "error")
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
r.RequestCtx.SetStatusCode(resp.StatusCode)
r.RequestCtx.Write(body)
return nil
}