This repository has been archived by the owner on Nov 22, 2018. It is now read-only.
forked from nicolasazrak/caddy-cache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
response_test.go
111 lines (87 loc) · 1.95 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
package cache
import "testing"
import "github.com/stretchr/testify/require"
import "net/http/httptest"
import "io/ioutil"
import "io"
type TestStorage struct {
recorder *httptest.ResponseRecorder
closed bool
flushed bool
cleaned bool
}
func NewTestStorage() *TestStorage {
return &TestStorage{
recorder: httptest.NewRecorder(),
}
}
func (ts *TestStorage) Write(p []byte) (int, error) {
return ts.recorder.Write(p)
}
func (ts *TestStorage) Close() error {
ts.closed = true
return nil
}
func (ts *TestStorage) Flush() error {
ts.flushed = true
return nil
}
func (ts *TestStorage) Clean() error {
ts.cleaned = true
return nil
}
func (ts *TestStorage) GetReader() (io.ReadCloser, error) {
return ts.recorder.Result().Body, nil
}
func (ts *TestStorage) ReadAll() []byte {
r, _ := ts.GetReader()
c, _ := ioutil.ReadAll(r)
return c
}
////////////////////////////
func TestResponseSendHeaders(t *testing.T) {
r := NewResponse()
go func() {
r.Header().Add("Content-Type", "application/json")
r.WriteHeader(200)
}()
r.WaitHeaders()
require.Equal(t, r.Header().Get("Content-Type"), "application/json")
}
func TestResponseWaitStorage(t *testing.T) {
r := NewResponse()
routineStarted := make(chan struct{}, 1)
writtenChan := make(chan struct{}, 1)
originalContent := []byte("abc")
go func() {
routineStarted <- struct{}{}
r.Write(originalContent)
writtenChan <- struct{}{}
}()
r.WaitHeaders()
<-routineStarted
require.Len(t, writtenChan, 0)
storage := NewTestStorage()
r.SetBody(storage)
<-writtenChan
require.Equal(t, originalContent, storage.ReadAll())
}
func TestCloseResponse(t *testing.T) {
r := NewResponse()
go func() {
r.WriteHeader(200)
}()
r.WaitHeaders()
storage := NewTestStorage()
r.SetBody(storage)
r.Close()
require.True(t, storage.closed)
}
func TestResponseClean(t *testing.T) {
r := NewResponse()
r.Close()
storage := NewTestStorage()
r.SetBody(storage)
r.Clean()
require.True(t, storage.cleaned)
}