-
Notifications
You must be signed in to change notification settings - Fork 1
/
timeout_test.go
79 lines (59 loc) · 1.59 KB
/
timeout_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
package timeout
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/stretchr/testify/suite"
)
type TimeoutSuite struct {
suite.Suite
server *httptest.Server
}
func (s *TimeoutSuite) SetupSuite() {
mux := http.NewServeMux()
mux.Handle("/hello", http.HandlerFunc(helloHandler))
mux.Handle("/timeout", http.HandlerFunc(timeoutHandler))
s.server = httptest.NewServer(Handler(mux, time.Second,
DefaultTimeoutHandler))
}
func (s *TimeoutSuite) TestTimeout() {
req, err := http.NewRequest(http.MethodGet, s.server.URL+"/timeout", nil)
s.Nil(err)
res, err := sendRequest(req)
s.Nil(err)
s.Equal(http.StatusGatewayTimeout, res.StatusCode)
s.Equal([]byte("Service timeout"), getResRawBody(res))
}
func (s *TimeoutSuite) TestNotTimeout() {
req, err := http.NewRequest(http.MethodGet, s.server.URL+"/hello", nil)
s.Nil(err)
res, err := sendRequest(req)
s.Nil(err)
s.Equal(http.StatusOK, res.StatusCode)
s.Equal([]byte("Hello World"), getResRawBody(res))
}
func TestTimeout(t *testing.T) {
suite.Run(t, new(TimeoutSuite))
}
func helloHandler(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(http.StatusOK)
res.Write([]byte("Hello World"))
}
func timeoutHandler(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(http.StatusOK)
res.Write([]byte("Hello World"))
<-time.After(2 * time.Second)
}
func sendRequest(req *http.Request) (*http.Response, error) {
cli := &http.Client{}
return cli.Do(req)
}
func getResRawBody(res *http.Response) []byte {
bytes, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err)
}
return bytes
}