-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathwrap_writer_test.go
86 lines (70 loc) · 2.4 KB
/
wrap_writer_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
package middleware
import (
"bytes"
"net/http"
"net/http/httptest"
"testing"
)
func TestHttpFancyWriterRemembersWroteHeaderWhenFlushed(t *testing.T) {
f := &httpFancyWriter{basicWriter: basicWriter{ResponseWriter: httptest.NewRecorder()}}
f.Flush()
if !f.wroteHeader {
t.Fatal("want Flush to have set wroteHeader=true")
}
}
func TestHttp2FancyWriterRemembersWroteHeaderWhenFlushed(t *testing.T) {
f := &http2FancyWriter{basicWriter{ResponseWriter: httptest.NewRecorder()}}
f.Flush()
if !f.wroteHeader {
t.Fatal("want Flush to have set wroteHeader=true")
}
}
func TestBasicWritesTeesWritesWithoutDiscard(t *testing.T) {
// explicitly create the struct instead of NewRecorder to control the value of Code
original := &httptest.ResponseRecorder{
HeaderMap: make(http.Header),
Body: new(bytes.Buffer),
}
wrap := &basicWriter{ResponseWriter: original}
var buf bytes.Buffer
wrap.Tee(&buf)
_, err := wrap.Write([]byte("hello world"))
assertNoError(t, err)
assertEqual(t, 200, original.Code)
assertEqual(t, []byte("hello world"), original.Body.Bytes())
assertEqual(t, []byte("hello world"), buf.Bytes())
assertEqual(t, 11, wrap.BytesWritten())
}
func TestBasicWriterDiscardsWritesToOriginalResponseWriter(t *testing.T) {
t.Run("With Tee", func(t *testing.T) {
// explicitly create the struct instead of NewRecorder to control the value of Code
original := &httptest.ResponseRecorder{
HeaderMap: make(http.Header),
Body: new(bytes.Buffer),
}
wrap := &basicWriter{ResponseWriter: original}
var buf bytes.Buffer
wrap.Tee(&buf)
wrap.Discard()
_, err := wrap.Write([]byte("hello world"))
assertNoError(t, err)
assertEqual(t, 0, original.Code) // wrapper shouldn't call WriteHeader implicitly
assertEqual(t, 0, original.Body.Len())
assertEqual(t, []byte("hello world"), buf.Bytes())
assertEqual(t, 11, wrap.BytesWritten())
})
t.Run("Without Tee", func(t *testing.T) {
// explicitly create the struct instead of NewRecorder to control the value of Code
original := &httptest.ResponseRecorder{
HeaderMap: make(http.Header),
Body: new(bytes.Buffer),
}
wrap := &basicWriter{ResponseWriter: original}
wrap.Discard()
_, err := wrap.Write([]byte("hello world"))
assertNoError(t, err)
assertEqual(t, 0, original.Code) // wrapper shouldn't call WriteHeader implicitly
assertEqual(t, 0, original.Body.Len())
assertEqual(t, 11, wrap.BytesWritten())
})
}