1
1
package middleware
2
2
3
3
import (
4
+ "bytes"
5
+ "net/http"
4
6
"net/http/httptest"
5
7
"testing"
6
8
)
@@ -22,3 +24,63 @@ func TestHttp2FancyWriterRemembersWroteHeaderWhenFlushed(t *testing.T) {
22
24
t .Fatal ("want Flush to have set wroteHeader=true" )
23
25
}
24
26
}
27
+
28
+ func TestBasicWritesTeesWritesWithoutDiscard (t * testing.T ) {
29
+ // explicitly create the struct instead of NewRecorder to control the value of Code
30
+ original := & httptest.ResponseRecorder {
31
+ HeaderMap : make (http.Header ),
32
+ Body : new (bytes.Buffer ),
33
+ }
34
+ wrap := & basicWriter {ResponseWriter : original }
35
+
36
+ var buf bytes.Buffer
37
+ wrap .Tee (& buf )
38
+
39
+ _ , err := wrap .Write ([]byte ("hello world" ))
40
+ assertNoError (t , err )
41
+
42
+ assertEqual (t , 200 , original .Code )
43
+ assertEqual (t , []byte ("hello world" ), original .Body .Bytes ())
44
+ assertEqual (t , []byte ("hello world" ), buf .Bytes ())
45
+ assertEqual (t , 11 , wrap .BytesWritten ())
46
+ }
47
+
48
+ func TestBasicWriterDiscardsWritesToOriginalResponseWriter (t * testing.T ) {
49
+ t .Run ("With Tee" , func (t * testing.T ) {
50
+ // explicitly create the struct instead of NewRecorder to control the value of Code
51
+ original := & httptest.ResponseRecorder {
52
+ HeaderMap : make (http.Header ),
53
+ Body : new (bytes.Buffer ),
54
+ }
55
+ wrap := & basicWriter {ResponseWriter : original }
56
+
57
+ var buf bytes.Buffer
58
+ wrap .Tee (& buf )
59
+ wrap .Discard ()
60
+
61
+ _ , err := wrap .Write ([]byte ("hello world" ))
62
+ assertNoError (t , err )
63
+
64
+ assertEqual (t , 0 , original .Code ) // wrapper shouldn't call WriteHeader implicitly
65
+ assertEqual (t , 0 , original .Body .Len ())
66
+ assertEqual (t , []byte ("hello world" ), buf .Bytes ())
67
+ assertEqual (t , 11 , wrap .BytesWritten ())
68
+ })
69
+
70
+ t .Run ("Without Tee" , func (t * testing.T ) {
71
+ // explicitly create the struct instead of NewRecorder to control the value of Code
72
+ original := & httptest.ResponseRecorder {
73
+ HeaderMap : make (http.Header ),
74
+ Body : new (bytes.Buffer ),
75
+ }
76
+ wrap := & basicWriter {ResponseWriter : original }
77
+ wrap .Discard ()
78
+
79
+ _ , err := wrap .Write ([]byte ("hello world" ))
80
+ assertNoError (t , err )
81
+
82
+ assertEqual (t , 0 , original .Code ) // wrapper shouldn't call WriteHeader implicitly
83
+ assertEqual (t , 0 , original .Body .Len ())
84
+ assertEqual (t , 11 , wrap .BytesWritten ())
85
+ })
86
+ }
0 commit comments