/
mockwebserver_test.go
109 lines (89 loc) · 2.36 KB
/
mockwebserver_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
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
106
107
108
109
package mockwebserver_test
import (
"fmt"
"io/ioutil"
"net/http"
"testing"
"time"
"github.com/bmizerany/assert"
"github.com/segmentio/mockwebserver"
)
func TestMockWebServer(t *testing.T) {
s := mockwebserver.New()
url := s.Start()
defer s.Stop()
s.Enqueue(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "https://giphy.com/gifs/sloth-WVLZLE4yGCQFi", http.StatusInternalServerError)
})
s.Enqueue(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "This is the response you are looking for.")
})
{
resp, err := http.Get(url)
assert.Equal(t, nil, err)
assert.Equal(t, http.StatusInternalServerError, resp.StatusCode)
assertBodyEqual(t, resp, "https://giphy.com/gifs/sloth-WVLZLE4yGCQFi\n")
request := s.TakeRequest()
assert.Equal(t, "/", request.URL.String())
}
{
resp, err := http.Get(url + "/foo")
assert.Equal(t, nil, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
assertBodyEqual(t, resp, "This is the response you are looking for.\n")
request := s.TakeRequestWithTimeout(1 * time.Second)
assert.Equal(t, "/foo", request.URL.String())
}
}
func TestNoRegisteredHandlers(t *testing.T) {
s := mockwebserver.New()
url := s.Start()
defer s.Stop()
resp, err := http.Get(url)
assert.Equal(t, nil, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
assertBodyEqual(t, resp, "")
request := s.TakeRequest()
assert.Equal(t, "/", request.URL.String())
}
func TestNoRecordedResponsesWithTimeout(t *testing.T) {
s := mockwebserver.New()
s.Start()
defer s.Stop()
request := s.TakeRequestWithTimeout(1 * time.Second)
if request != nil {
t.Errorf("request != nil")
}
}
func ExampleMockWebServer() {
// Start the server.
s := mockwebserver.New()
url := s.Start()
defer s.Stop()
// Enqeue a response
s.Enqueue(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello World!")
})
// Excercise your HTTP code.
resp, _ := http.Get(url)
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
// Inspect the request.
req := s.TakeRequest()
fmt.Println(req.Method)
fmt.Println(req.URL)
// Output:
// Hello World!
//
// GET
// /
}
func assertBodyEqual(t *testing.T, resp *http.Response, exp string) {
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Errorf("%s", err.Error())
}
assert.Equal(t, exp, string(body))
}