-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathgzip_error_handling_test.go
More file actions
345 lines (287 loc) · 11 KB
/
Copy pathgzip_error_handling_test.go
File metadata and controls
345 lines (287 loc) · 11 KB
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
package main
import (
"bytes"
"compress/gzip"
"fmt"
"net/http"
"net/http/httptest"
"time"
"github.com/gofiber/fiber/v3"
"github.com/valyala/fasthttp"
)
// Tests for error handling in gzip decompression and general error propagation
// TestGzipHandling tests proper handling of gzipped responses
func (suite *Tests) TestGzipHandling() {
// Create a test server that returns gzipped content
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Set the Content-Encoding header to indicate gzipped content
w.Header().Set("Content-Encoding", "gzip")
// Create a gzipped response
var buf bytes.Buffer
gzipWriter := gzip.NewWriter(&buf)
payload := `{"data":{"test":"gzipped response"}}`
_, _ = gzipWriter.Write([]byte(payload))
_ = gzipWriter.Close()
// Send the gzipped data
w.WriteHeader(http.StatusOK)
_, _ = w.Write(buf.Bytes())
}))
defer server.Close()
// Store original client and restore after test
originalClient := cfg.Client.FastProxyClient
defer func() {
cfg.Client.FastProxyClient = originalClient
}()
// Configure client for test
cfg.Client.ClientTimeout = 5
cfg.Client.FastProxyClient = createFasthttpClient(cfg)
// Configure server URL
cfg.Server.HostGraphQL = server.URL
// Create request context
reqCtx := &fasthttp.RequestCtx{}
reqCtx.Request.SetRequestURI("/graphql")
reqCtx.Request.Header.SetMethod("POST")
reqCtx.Request.Header.Set("Content-Type", "application/json")
reqCtx.Request.SetBody([]byte(`{"query": "query { test }"}`))
// Create fiber context
ctx := suite.app.AcquireCtx(reqCtx)
defer suite.app.ReleaseCtx(ctx)
// Call the proxy function
err := proxyTheRequest(ctx, cfg.Server.HostGraphQL)
// Verify success
suite.Nil(err, "proxyTheRequest should succeed with gzipped content")
suite.Equal(fiber.StatusOK, ctx.Response().StatusCode(), "Response status should be 200 OK")
// Verify the content was properly decompressed
responseBody := string(ctx.Response().Body())
suite.Contains(responseBody, "gzipped response", "Response should contain the decompressed content")
// Verify the Content-Encoding header was removed
suite.Equal("", string(ctx.Response().Header.Peek("Content-Encoding")),
"Content-Encoding header should be removed after decompression")
}
// TestInvalidGzipHandling tests handling of responses with invalid gzip data
func (suite *Tests) TestInvalidGzipHandling() {
// Create a test server that returns invalid gzipped content
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Set the Content-Encoding header to indicate gzipped content
w.Header().Set("Content-Encoding", "gzip")
// Send invalid gzip data
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("This is not valid gzip data"))
}))
defer server.Close()
// Store original client and restore after test
originalClient := cfg.Client.FastProxyClient
defer func() {
cfg.Client.FastProxyClient = originalClient
}()
// Configure client for test
cfg.Client.ClientTimeout = 5
cfg.Client.FastProxyClient = createFasthttpClient(cfg)
// Configure server URL
cfg.Server.HostGraphQL = server.URL
// Create request context
reqCtx := &fasthttp.RequestCtx{}
reqCtx.Request.SetRequestURI("/graphql")
reqCtx.Request.Header.SetMethod("POST")
reqCtx.Request.Header.Set("Content-Type", "application/json")
reqCtx.Request.SetBody([]byte(`{"query": "query { test }"}`))
// Create fiber context
ctx := suite.app.AcquireCtx(reqCtx)
defer suite.app.ReleaseCtx(ctx)
// Call the proxy function
err := proxyTheRequest(ctx, cfg.Server.HostGraphQL)
// Verify error handling
suite.NotNil(err, "proxyTheRequest should return error with invalid gzip data")
suite.Contains(err.Error(), "gzip", "Error should mention gzip decompression issue")
}
// TestErrorPropagation tests that various errors are properly propagated
func (suite *Tests) TestErrorPropagation() {
tests := []struct {
name string
serverHandler func(w http.ResponseWriter, r *http.Request)
expectedError string
}{
{
name: "5xx_error",
serverHandler: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(`{"errors":[{"message":"Internal server error"}]}`))
},
expectedError: "received non-200 response",
},
{
name: "malformed_json_response",
serverHandler: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{malformed json`))
},
expectedError: "", // No error expected, as we don't validate JSON format
},
{
name: "empty_response",
serverHandler: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
// Empty response body
},
expectedError: "", // No error expected, empty responses are valid
},
}
for _, tt := range tests {
suite.Run(tt.name, func() {
// Create a test server with the current test handler
server := httptest.NewServer(http.HandlerFunc(tt.serverHandler))
defer server.Close()
// Store original client and restore after test
originalClient := cfg.Client.FastProxyClient
defer func() {
cfg.Client.FastProxyClient = originalClient
}()
// Configure client for test
cfg.Client.ClientTimeout = 5
cfg.Client.FastProxyClient = createFasthttpClient(cfg)
// Configure server URL
cfg.Server.HostGraphQL = server.URL
// Create request context
reqCtx := &fasthttp.RequestCtx{}
reqCtx.Request.SetRequestURI("/graphql")
reqCtx.Request.Header.SetMethod("POST")
reqCtx.Request.Header.Set("Content-Type", "application/json")
reqCtx.Request.SetBody([]byte(`{"query": "query { test }"}`))
// Create fiber context
ctx := suite.app.AcquireCtx(reqCtx)
defer suite.app.ReleaseCtx(ctx)
// Call the proxy function
err := proxyTheRequest(ctx, cfg.Server.HostGraphQL)
// Verify error handling based on test case
if tt.expectedError != "" {
suite.NotNil(err, "proxyTheRequest should return error")
suite.Contains(err.Error(), tt.expectedError,
"Error should contain expected message")
} else {
suite.Nil(err, "proxyTheRequest should not return error")
}
})
}
}
// TestMiddlewareErrorPropagation tests error propagation through the middleware chain
func (suite *Tests) TestMiddlewareErrorPropagation() {
// Setup a basic middleware chain that mimics the production setup
testMiddleware := func(c fiber.Ctx) error {
// Access request path to check proper error propagation
path := c.Path()
if path == "/error-path" {
return fmt.Errorf("middleware error")
}
return c.Next()
}
app := fiber.New()
app.Use(testMiddleware)
// Setup the handler that would receive the request after middleware
app.Post("/graphql", func(c fiber.Ctx) error {
// This should not be called if middleware returns error
return c.Status(fiber.StatusOK).JSON(fiber.Map{"data": "success"})
})
// Test successful path
req := httptest.NewRequest("POST", "/graphql", nil)
resp, err := app.Test(req)
suite.Nil(err, "App test should not error")
suite.Equal(fiber.StatusOK, resp.StatusCode, "Status should be 200 OK")
// Test error path
req = httptest.NewRequest("POST", "/error-path", nil)
resp, err = app.Test(req)
suite.Nil(err, "App test should not error")
suite.NotEqual(fiber.StatusOK, resp.StatusCode, "Status should not be 200 OK")
// Check that error status was properly propagated
suite.Equal(fiber.StatusInternalServerError, resp.StatusCode,
"Error status should be 500 Internal Server Error")
}
// TestTimeout tests the proper handling of timeouts
func (suite *Tests) TestTimeout() {
// Skip this timing-sensitive test as it's prone to race conditions under race detection
suite.T().Skip("Skipping timing-sensitive timeout test due to race conditions under race detection")
// Create a test server that simulates a timeout
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Sleep longer than the client timeout
time.Sleep(3 * time.Second)
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"data":{"test":"response"}}`))
}))
defer server.Close()
// Store original client and restore after test
originalClient := cfg.Client.FastProxyClient
originalTimeout := cfg.Client.ClientTimeout
defer func() {
cfg.Client.FastProxyClient = originalClient
cfg.Client.ClientTimeout = originalTimeout
}()
// Configure client with a short timeout
cfg.Client.ClientTimeout = 1 // 1 second
cfg.Client.FastProxyClient = createFasthttpClient(cfg)
// Configure server URL
cfg.Server.HostGraphQL = server.URL
// Create request context
reqCtx := &fasthttp.RequestCtx{}
reqCtx.Request.SetRequestURI("/graphql")
reqCtx.Request.Header.SetMethod("POST")
reqCtx.Request.Header.Set("Content-Type", "application/json")
reqCtx.Request.SetBody([]byte(`{"query": "query { test }"}`))
// Create fiber context
ctx := suite.app.AcquireCtx(reqCtx)
defer suite.app.ReleaseCtx(ctx)
// Call the proxy function
err := proxyTheRequest(ctx, cfg.Server.HostGraphQL)
// Verify timeout error handling
suite.NotNil(err, "proxyTheRequest should return error on timeout")
if err != nil {
suite.Contains(err.Error(), "timeout", "Error should mention timeout")
}
}
// TestLargeResponseHandling tests handling of large responses
func (suite *Tests) TestLargeResponseHandling() {
// Create a test server that returns a large response
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Generate a large response (1MB)
largeResponse := make([]byte, 1024*1024)
for i := 0; i < len(largeResponse); i++ {
largeResponse[i] = byte(i % 256)
}
// Set headers and send response
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(largeResponse)
}))
defer server.Close()
// Store original client and restore after test
originalClient := cfg.Client.FastProxyClient
defer func() {
cfg.Client.FastProxyClient = originalClient
}()
// Configure client for test
cfg.Client.ClientTimeout = 10 // Longer timeout for large response
cfg.Client.FastProxyClient = createFasthttpClient(cfg)
// Configure server URL
cfg.Server.HostGraphQL = server.URL
// Create request context
reqCtx := &fasthttp.RequestCtx{}
reqCtx.Request.SetRequestURI("/graphql")
reqCtx.Request.Header.SetMethod("POST")
reqCtx.Request.Header.Set("Content-Type", "application/json")
reqCtx.Request.SetBody([]byte(`{"query": "query { test }"}`))
// Create fiber context
ctx := suite.app.AcquireCtx(reqCtx)
defer suite.app.ReleaseCtx(ctx)
// Call the proxy function
err := proxyTheRequest(ctx, cfg.Server.HostGraphQL)
// Verify large response handling
suite.Nil(err, "proxyTheRequest should handle large responses")
suite.Equal(fiber.StatusOK, ctx.Response().StatusCode(), "Status should be 200 OK")
suite.Equal(1024*1024, len(ctx.Response().Body()), "Response body should match expected size")
}
// Helper function to create gzipped data
func createGzippedData(data []byte) []byte {
var buf bytes.Buffer
gw := gzip.NewWriter(&buf)
_, _ = gw.Write(data)
_ = gw.Close()
return buf.Bytes()
}