-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathchaos_test.go
More file actions
399 lines (339 loc) · 10.2 KB
/
chaos_test.go
File metadata and controls
399 lines (339 loc) · 10.2 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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
// Copyright 2025 The Rivaas Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build !integration
package app
import (
"fmt"
"log/slog"
"math/rand/v2"
"net/http"
"net/http/httptest"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
// TestChaos_ConcurrentRouteRegistration tests registering routes concurrently
// to find race conditions in route registration.
// Note: Route registration during serving is not a supported pattern.
// Routes should be registered before serving begins.
func TestChaos_ConcurrentRouteRegistration(t *testing.T) {
t.Parallel()
app := MustNew(
WithServiceName("test"),
WithServiceVersion("1.0.0"),
)
const numRoutes = 100
const numRequests = 1000
var wg sync.WaitGroup
var registrationErrors atomic.Int64
var requestErrors atomic.Int64
// Phase 1: Register routes concurrently (before serving)
for i := range numRoutes {
wg.Add(1)
go func(id int) {
defer wg.Done()
defer func() {
if r := recover(); r != nil {
registrationErrors.Add(1)
}
}()
path := fmt.Sprintf("/route%d", id%10)
app.GET(path, func(c *Context) {
if err := c.Stringf(http.StatusOK, "route-%d", id); err != nil {
slog.ErrorContext(c.RequestContext(), "failed to write response", "err", err)
}
})
}(i)
}
// Wait for all route registration to complete
wg.Wait()
// Phase 2: Make requests concurrently (after all routes registered)
for i := range numRequests {
wg.Add(1)
go func(_ int) {
defer wg.Done()
// #nosec G404 -- test code, not security-sensitive
routeID := rand.IntN(10) // Only 10 unique routes (0-9)
path := fmt.Sprintf("/route%d", routeID)
req := httptest.NewRequest(http.MethodGet, path, nil)
w := httptest.NewRecorder()
func() {
defer func() {
if r := recover(); r != nil {
requestErrors.Add(1)
}
}()
app.Router().ServeHTTP(w, req)
}()
}(i)
}
wg.Wait()
assert.Equal(t, int64(0), registrationErrors.Load(), "no panics during registration")
assert.Equal(t, int64(0), requestErrors.Load(), "no panics during requests")
}
// TestChaos_StressTestHighConcurrency tests the app under extreme
// concurrency conditions to find performance issues and race conditions.
func TestChaos_StressTestHighConcurrency(t *testing.T) {
t.Parallel()
app := MustNew(
WithServiceName("test"),
WithServiceVersion("1.0.0"),
)
var requestCount atomic.Int64
var errorCount atomic.Int64
app.GET("/stress", func(c *Context) {
requestCount.Add(1)
// Simulate variable work
// #nosec G404 -- test code, not security-sensitive
time.Sleep(time.Duration(rand.IntN(5)) * time.Millisecond)
if err := c.String(http.StatusOK, "ok"); err != nil {
slog.ErrorContext(c.RequestContext(), "failed to write response", "err", err)
}
})
const concurrency = 500
const requestsPerGoroutine = 10
var wg sync.WaitGroup
start := time.Now()
for range concurrency {
wg.Go(func() {
for range requestsPerGoroutine {
req := httptest.NewRequest(http.MethodGet, "/stress", nil)
w := httptest.NewRecorder()
app.Router().ServeHTTP(w, req)
if w.Code != http.StatusOK {
errorCount.Add(1)
}
}
})
}
wg.Wait()
duration := time.Since(start)
totalRequests := int64(concurrency * requestsPerGoroutine)
assert.Equal(t, totalRequests, requestCount.Load(), "all requests should be processed")
assert.Equal(t, int64(0), errorCount.Load(), "no errors should occur")
t.Logf("Processed %d requests in %v (%.0f req/s)",
totalRequests, duration, float64(totalRequests)/duration.Seconds())
}
// TestChaos_RandomRoutePatterns tests with random route patterns to
// ensure the router handles edge cases correctly.
func TestChaos_RandomRoutePatterns(t *testing.T) {
t.Parallel()
app := MustNew(
WithServiceName("test"),
WithServiceVersion("1.0.0"),
)
const numRoutes = 200
var wg sync.WaitGroup
var panicCount atomic.Int64
// Generate random route patterns
routes := make([]string, 0, numRoutes)
for i := range numRoutes {
// Generate various route patterns
var route string
switch i % 5 {
case 0:
route = fmt.Sprintf("/api/v%d/resource", i%10)
case 1:
route = "/users/:id/posts/:post_id"
case 2:
route = fmt.Sprintf("/static%d", i)
case 3:
route = fmt.Sprintf("/deep/nested/path/%d", i)
default:
route = fmt.Sprintf("/wildcard/*path%d", i)
}
routes = append(routes, route)
}
// Register routes concurrently
for i, route := range routes {
wg.Add(1)
go func(id int, path string) {
defer wg.Done()
func() {
defer func() {
if r := recover(); r != nil {
panicCount.Add(1)
}
}()
app.GET(path, func(c *Context) {
//nolint:errcheck // chaos test handler, we don't care about the error here
_ = c.Stringf(http.StatusOK, "route-%d", id)
})
}()
}(i, route)
}
wg.Wait()
assert.Equal(t, int64(0), panicCount.Load(), "no panics during route registration")
// Test that routes work
for _, route := range routes[:10] { // Test first 10
req := httptest.NewRequest(http.MethodGet, route, nil)
w := httptest.NewRecorder()
app.Router().ServeHTTP(w, req)
// Routes might return 404 if pattern doesn't match, but shouldn't panic
assert.NotEqual(t, http.StatusInternalServerError, w.Code,
"route should not return 500")
}
}
// TestChaos_MiddlewareChainStress tests middleware chains under stress
// to ensure correct execution order and no race conditions.
func TestChaos_MiddlewareChainStress(t *testing.T) {
t.Parallel()
app := MustNew(
WithServiceName("test"),
WithServiceVersion("1.0.0"),
)
const numMiddleware = 10
var executionOrder sync.Map // Use sync.Map for concurrent access
var counter atomic.Int64
// Add many middleware
for i := range numMiddleware {
app.Use(func(c *Context) {
order := counter.Add(1)
executionOrder.Store(order, i)
c.Next()
})
}
app.GET("/test", func(c *Context) {
order := counter.Add(1)
executionOrder.Store(order, -1) // -1 indicates handler
if err := c.String(http.StatusOK, "ok"); err != nil {
slog.ErrorContext(c.RequestContext(), "failed to write response", "err", err)
}
})
const concurrency = 100
var wg sync.WaitGroup
for range concurrency {
wg.Go(func() {
req := httptest.NewRequest(http.MethodGet, "/test", nil)
w := httptest.NewRecorder()
app.Router().ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
})
}
wg.Wait()
// Verify execution order for last request
// (order verification is complex with concurrent requests, so we just check no panics)
assert.Positive(t, counter.Load(), "middleware should have executed")
}
// TestChaos_ContextPoolExhaustion tests that context pooling works correctly
// even under extreme load where contexts might be exhausted.
func TestChaos_ContextPoolExhaustion(t *testing.T) {
t.Parallel()
app := MustNew(
WithServiceName("test"),
WithServiceVersion("1.0.0"),
)
// Handler that holds context briefly
app.GET("/slow", func(c *Context) {
time.Sleep(5 * time.Millisecond)
if err := c.String(http.StatusOK, "ok"); err != nil {
slog.ErrorContext(c.RequestContext(), "failed to write response", "err", err)
}
})
const burstSize = 1000
var wg sync.WaitGroup
var successCount atomic.Int64
// Burst of requests that might exhaust context pool
for range burstSize {
wg.Go(func() {
req := httptest.NewRequest(http.MethodGet, "/slow", nil)
w := httptest.NewRecorder()
app.Router().ServeHTTP(w, req)
if w.Code == http.StatusOK {
successCount.Add(1)
}
})
}
wg.Wait()
// All requests should succeed even if context pool is exhausted
// (pool should allocate new contexts as needed)
assert.Equal(t, int64(burstSize), successCount.Load(),
"all requests should succeed even under pool exhaustion")
}
// TestChaos_MixedOperations tests a mix of operations in phases:
// Phase 1: concurrent route registration and middleware addition
// Phase 2: concurrent request handling
// Note: Route registration during serving is not a supported pattern.
func TestChaos_MixedOperations(t *testing.T) {
t.Parallel()
app := MustNew(
WithServiceName("test"),
WithServiceVersion("1.0.0"),
)
var wg sync.WaitGroup
var registrationErrors atomic.Int64
var requestErrors atomic.Int64
// Pre-register some routes
app.GET("/existing", func(c *Context) {
if err := c.String(http.StatusOK, "existing"); err != nil {
slog.ErrorContext(c.RequestContext(), "failed to write response", "err", err)
}
})
const operations = 50
// Phase 1: Register routes and middleware concurrently (before serving)
// Register new routes
for i := range operations {
wg.Add(1)
go func(id int) {
defer wg.Done()
func() {
defer func() {
if r := recover(); r != nil {
registrationErrors.Add(1)
}
}()
app.GET(fmt.Sprintf("/new%d", id), func(c *Context) {
if err := c.Stringf(http.StatusOK, "new-%d", id); err != nil {
slog.ErrorContext(c.RequestContext(), "failed to write response", "err", err)
}
})
}()
}(i)
}
// Add middleware concurrently (also before serving)
for range operations {
wg.Go(func() {
func() {
defer func() {
if r := recover(); r != nil {
registrationErrors.Add(1)
}
}()
app.Use(func(c *Context) {
c.Next()
})
}()
})
}
// Wait for all registration to complete
wg.Wait()
// Phase 2: Handle requests concurrently (after all routes registered)
for range operations * 2 {
wg.Go(func() {
defer func() {
if r := recover(); r != nil {
requestErrors.Add(1)
}
}()
req := httptest.NewRequest(http.MethodGet, "/existing", nil)
w := httptest.NewRecorder()
app.Router().ServeHTTP(w, req)
})
}
wg.Wait()
assert.Equal(t, int64(0), registrationErrors.Load(), "no panics during registration")
assert.Equal(t, int64(0), requestErrors.Load(), "no panics during requests")
}