-
Notifications
You must be signed in to change notification settings - Fork 18
/
response_test.go
135 lines (109 loc) · 2.34 KB
/
response_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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package httpcache
import (
"io"
"io/ioutil"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/suite"
)
type TestBackend struct {
recorder *httptest.ResponseRecorder
closed bool
flushed bool
cleaned bool
}
func NewTestBackend() *TestBackend {
return &TestBackend{
recorder: httptest.NewRecorder(),
}
}
func (t *TestBackend) Length() int {
return t.recorder.Body.Len()
}
func (t *TestBackend) Write(p []byte) (int, error) {
return t.recorder.Write(p)
}
func (t *TestBackend) Flush() error {
t.flushed = true
return nil
}
func (t *TestBackend) Clean() error {
t.cleaned = true
return nil
}
func (t *TestBackend) Close() error {
t.closed = true
return nil
}
func (t *TestBackend) GetReader() (io.ReadCloser, error) {
return t.recorder.Result().Body, nil
}
type ResponseTestSuite struct {
suite.Suite
}
func (suite *ResponseTestSuite) TestResponseSendHeaders() {
r := NewResponse()
go func() {
r.Header().Add("Content-Type", "application/json")
r.WriteHeader(200)
}()
r.WaitHeaders()
suite.Equal(r.Header().Get("Content-Type"), "application/json")
}
func (suite *ResponseTestSuite) TestResponseWaitBackend() {
r := NewResponse()
requestEntered := make(chan struct{}, 1)
writtenChan := make(chan struct{}, 1)
originalContent := []byte("hello")
go func() {
requestEntered <- struct{}{}
r.Write(originalContent)
writtenChan <- struct{}{}
}()
r.WaitHeaders()
<-requestEntered
suite.Len(writtenChan, 0)
backend := NewTestBackend()
r.SetBody(backend)
<-writtenChan
r.Close()
reader, err := r.GetReader()
if err != nil {
suite.Error(err)
}
content, err := ioutil.ReadAll(reader)
if err != nil {
suite.Error(err)
}
suite.Equal(originalContent, content)
}
func (suite *ResponseTestSuite) TestCloseResponse() {
r := NewResponse()
go func() {
r.WriteHeader(200)
}()
r.WaitHeaders()
backend := NewTestBackend()
r.SetBody(backend)
r.Close()
r.Flush()
suite.True(backend.closed)
}
func (suite *ResponseTestSuite) TestCleanResponse() {
r := NewResponse()
backend := NewTestBackend()
r.SetBody(backend)
r.Close()
r.Clean()
suite.True(backend.cleaned)
}
func (suite *ResponseTestSuite) TestSetNilBody() {
r := NewResponse()
r.SetBody(nil)
n, err := r.Write([]byte(`hello`))
suite.Equal(0, n)
suite.Error(err)
}
func TestResponseTestSuite(t *testing.T) {
suite.Run(t, new(ResponseTestSuite))
}