@@ -3,10 +3,12 @@ package middleware
3
3
import (
4
4
"bytes"
5
5
"compress/gzip"
6
+ "errors"
6
7
"io/ioutil"
7
8
"net/http"
8
9
"net/http/httptest"
9
10
"strings"
11
+ "sync"
10
12
"testing"
11
13
12
14
"github.com/labstack/echo/v4"
@@ -43,6 +45,35 @@ func TestDecompress(t *testing.T) {
43
45
assert .Equal (body , string (b ))
44
46
}
45
47
48
+ func TestDecompressDefaultConfig (t * testing.T ) {
49
+ e := echo .New ()
50
+ req := httptest .NewRequest (http .MethodPost , "/" , strings .NewReader ("test" ))
51
+ rec := httptest .NewRecorder ()
52
+ c := e .NewContext (req , rec )
53
+
54
+ h := DecompressWithConfig (DecompressConfig {})(func (c echo.Context ) error {
55
+ c .Response ().Write ([]byte ("test" )) // For Content-Type sniffing
56
+ return nil
57
+ })
58
+ h (c )
59
+
60
+ assert := assert .New (t )
61
+ assert .Equal ("test" , rec .Body .String ())
62
+
63
+ // Decompress
64
+ body := `{"name": "echo"}`
65
+ gz , _ := gzipString (body )
66
+ req = httptest .NewRequest (http .MethodPost , "/" , strings .NewReader (string (gz )))
67
+ req .Header .Set (echo .HeaderContentEncoding , GZIPEncoding )
68
+ rec = httptest .NewRecorder ()
69
+ c = e .NewContext (req , rec )
70
+ h (c )
71
+ assert .Equal (GZIPEncoding , req .Header .Get (echo .HeaderContentEncoding ))
72
+ b , err := ioutil .ReadAll (req .Body )
73
+ assert .NoError (err )
74
+ assert .Equal (body , string (b ))
75
+ }
76
+
46
77
func TestCompressRequestWithoutDecompressMiddleware (t * testing.T ) {
47
78
e := echo .New ()
48
79
body := `{"name":"echo"}`
@@ -108,6 +139,36 @@ func TestDecompressSkipper(t *testing.T) {
108
139
assert .Equal (t , body , string (reqBody ))
109
140
}
110
141
142
+ type TestDecompressPoolWithError struct {
143
+ }
144
+
145
+ func (d * TestDecompressPoolWithError ) gzipDecompressPool () sync.Pool {
146
+ return sync.Pool {
147
+ New : func () interface {} {
148
+ return errors .New ("pool error" )
149
+ },
150
+ }
151
+ }
152
+
153
+ func TestDecompressPoolError (t * testing.T ) {
154
+ e := echo .New ()
155
+ e .Use (DecompressWithConfig (DecompressConfig {
156
+ Skipper : DefaultSkipper ,
157
+ GzipDecompressPool : & TestDecompressPoolWithError {},
158
+ }))
159
+ body := `{"name": "echo"}`
160
+ req := httptest .NewRequest (http .MethodPost , "/echo" , strings .NewReader (body ))
161
+ req .Header .Set (echo .HeaderContentEncoding , GZIPEncoding )
162
+ rec := httptest .NewRecorder ()
163
+ c := e .NewContext (req , rec )
164
+ e .ServeHTTP (rec , req )
165
+ assert .Equal (t , GZIPEncoding , req .Header .Get (echo .HeaderContentEncoding ))
166
+ reqBody , err := ioutil .ReadAll (c .Request ().Body )
167
+ assert .NoError (t , err )
168
+ assert .Equal (t , body , string (reqBody ))
169
+ assert .Equal (t , rec .Code , http .StatusInternalServerError )
170
+ }
171
+
111
172
func BenchmarkDecompress (b * testing.B ) {
112
173
e := echo .New ()
113
174
body := `{"name": "echo"}`
0 commit comments