Repository navigation
Expand file tree
/
Copy pathmain_test.go
More file actions
457 lines (389 loc) · 10.4 KB
/
Copy pathmain_test.go
File metadata and controls
457 lines (389 loc) · 10.4 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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
package main
import (
"bytes"
"context"
"flag"
"io"
"os"
"strings"
"sync"
"testing"
"time"
"github.com/ja1code/quicrawl/internal/service"
)
// Helper function to reset flag.CommandLine for testing
func resetFlags() {
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
}
func TestMain_ServerMode(t *testing.T) {
// Save original args and restore after test
oldArgs := os.Args
defer func() { os.Args = oldArgs }()
// Test server mode
os.Args = []string{"quicrawl", "-mode=server", "-port=0"} // Use port 0 for auto-assignment
resetFlags()
// Capture output
var buf bytes.Buffer
oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
// Run main in a goroutine with timeout
done := make(chan bool, 1)
go func() {
defer func() {
if r := recover(); r != nil {
// Server might panic on shutdown, which is expected in tests
done <- true
}
}()
// We can't easily test the full server startup without it blocking,
// so we'll test the flag parsing and service creation parts
var (
mode = flag.String("mode", "cli", "Mode to run in: 'server' or 'cli'")
port = flag.Int("port", 8080, "Port for HTTP server (only used in server mode)")
)
flag.Parse()
// Create service instance (this part we can test)
svc := service.New()
if svc == nil {
t.Error("failed to create service")
}
if *mode != "server" {
t.Errorf("expected mode 'server', got %s", *mode)
}
if *port != 0 {
t.Errorf("expected port 0, got %d", *port)
}
done <- true
}()
// Wait for test completion with timeout
select {
case <-done:
// Test completed successfully
case <-time.After(1 * time.Second):
t.Error("test timed out")
}
// Restore stdout
w.Close()
os.Stdout = oldStdout
io.Copy(&buf, r)
}
func TestMain_CLIMode(t *testing.T) {
// Save original args and restore after test
oldArgs := os.Args
defer func() { os.Args = oldArgs }()
// Test CLI mode with help command
os.Args = []string{"quicrawl", "-mode=cli"}
resetFlags()
// We can test the flag parsing part
var (
mode = flag.String("mode", "cli", "Mode to run in: 'server' or 'cli'")
port = flag.Int("port", 8080, "Port for HTTP server (only used in server mode)")
)
flag.Parse()
// Create service instance
svc := service.New()
if svc == nil {
t.Fatal("failed to create service")
}
if *mode != "cli" {
t.Errorf("expected mode 'cli', got %s", *mode)
}
if *port != 8080 {
t.Errorf("expected default port 8080, got %d", *port)
}
}
func TestMain_InvalidMode(t *testing.T) {
// Save original args and restore after test
oldArgs := os.Args
defer func() { os.Args = oldArgs }()
os.Args = []string{"quicrawl", "-mode=invalid"}
resetFlags()
var (
mode = flag.String("mode", "cli", "Mode to run in: 'server' or 'cli'")
)
flag.Parse()
// Create service instance
svc := service.New()
if svc == nil {
t.Fatal("failed to create service")
}
// Test the switch logic
switch *mode {
case "server":
t.Error("should not reach server case")
case "cli":
t.Error("should not reach cli case")
default:
// This is the expected path for invalid mode
if *mode != "invalid" {
t.Errorf("expected mode 'invalid', got %s", *mode)
}
}
}
func TestRunServer_Function(t *testing.T) {
// Create a service instance
svc := service.New()
// Test that runServer function can be called without panicking
// We can't easily test the full server startup, but we can test the setup
defer func() {
if r := recover(); r != nil {
// If there's a panic, it might be due to port binding issues in tests
// which is acceptable for this test
}
}()
// We'll test this by creating the server components manually
// since the actual runServer function would block
server := createTestServer(svc, 0)
if server == nil {
t.Error("failed to create test server")
}
}
func TestRunCLI_Function(t *testing.T) {
// Create a service instance
svc := service.New()
// Test CLI creation and basic functionality
// We can't easily test the full CLI execution without args,
// but we can test the setup
cli := createTestCLI(svc)
if cli == nil {
t.Error("failed to create test CLI")
}
}
// Helper functions to simulate the main function components
func createTestServer(svc *service.Service, port int) interface{} {
// This simulates the server creation part of runServer
// without actually starting the server
if svc == nil {
return nil
}
return "mock server" // Return something to indicate success
}
func createTestCLI(svc *service.Service) interface{} {
// This simulates the CLI creation part of runCLI
if svc == nil {
return nil
}
return "mock cli" // Return something to indicate success
}
// Integration test that tests the main components working together
func TestMain_Integration(t *testing.T) {
// Test service creation (core component)
svc := service.New()
if svc == nil {
t.Fatal("failed to create service")
}
// Test that service methods work
ctx := context.Background()
// Test ProcessRequest
result, err := svc.ProcessRequest(ctx, "integration test")
if err != nil {
t.Errorf("ProcessRequest failed: %v", err)
}
if !strings.Contains(result, "integration test") {
t.Error("ProcessRequest result should contain input")
}
// Test GetStatus
status := svc.GetStatus(ctx)
if status == nil {
t.Error("GetStatus returned nil")
}
if status["status"] != "running" {
t.Error("service should be running")
}
// Test HealthCheck
if err := svc.HealthCheck(ctx); err != nil {
t.Errorf("HealthCheck failed: %v", err)
}
}
// Test concurrent access to service (simulating server load)
func TestMain_ConcurrentAccess(t *testing.T) {
svc := service.New()
if svc == nil {
t.Fatal("failed to create service")
}
ctx := context.Background()
var wg sync.WaitGroup
errors := make(chan error, 10)
// Run multiple concurrent requests
for i := 0; i < 10; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
// Test ProcessRequest
result, err := svc.ProcessRequest(ctx, "concurrent test")
if err != nil {
errors <- err
return
}
if !strings.Contains(result, "concurrent test") {
errors <- err
return
}
// Test GetStatus
status := svc.GetStatus(ctx)
if status == nil {
errors <- err
return
}
// Test HealthCheck
if err := svc.HealthCheck(ctx); err != nil {
errors <- err
return
}
}(i)
}
wg.Wait()
close(errors)
// Check for any errors
for err := range errors {
if err != nil {
t.Errorf("concurrent access error: %v", err)
}
}
}
// Test flag parsing edge cases
func TestMain_FlagParsing(t *testing.T) {
tests := []struct {
name string
args []string
expectedMode string
expectedPort int
}{
{
name: "default values",
args: []string{"quicrawl"},
expectedMode: "cli",
expectedPort: 8080,
},
{
name: "server mode with custom port",
args: []string{"quicrawl", "-mode=server", "-port=9090"},
expectedMode: "server",
expectedPort: 9090,
},
{
name: "cli mode explicit",
args: []string{"quicrawl", "-mode=cli"},
expectedMode: "cli",
expectedPort: 8080,
},
{
name: "server mode with default port",
args: []string{"quicrawl", "-mode=server"},
expectedMode: "server",
expectedPort: 8080,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Save and restore original args
oldArgs := os.Args
defer func() { os.Args = oldArgs }()
os.Args = tt.args
resetFlags()
var (
mode = flag.String("mode", "cli", "Mode to run in: 'server' or 'cli'")
port = flag.Int("port", 8080, "Port for HTTP server (only used in server mode)")
)
flag.Parse()
if *mode != tt.expectedMode {
t.Errorf("expected mode %s, got %s", tt.expectedMode, *mode)
}
if *port != tt.expectedPort {
t.Errorf("expected port %d, got %d", tt.expectedPort, *port)
}
})
}
}
// Test service initialization under different conditions
func TestMain_ServiceInitialization(t *testing.T) {
// Test multiple service instances
services := make([]*service.Service, 5)
for i := 0; i < 5; i++ {
services[i] = service.New()
if services[i] == nil {
t.Errorf("failed to create service instance %d", i)
}
}
// Test that each service is independent
ctx := context.Background()
for i, svc := range services {
result, err := svc.ProcessRequest(ctx, "test")
if err != nil {
t.Errorf("service %d ProcessRequest failed: %v", i, err)
}
if result == "" {
t.Errorf("service %d returned empty result", i)
}
}
}
// Benchmark main function components
func BenchmarkMain_ServiceCreation(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
svc := service.New()
if svc == nil {
b.Fatal("failed to create service")
}
}
}
func BenchmarkMain_FlagParsing(b *testing.B) {
// Save original args
oldArgs := os.Args
defer func() { os.Args = oldArgs }()
b.ResetTimer()
for i := 0; i < b.N; i++ {
os.Args = []string{"quicrawl", "-mode=server", "-port=8080"}
resetFlags()
var (
mode = flag.String("mode", "cli", "Mode to run in: 'server' or 'cli'")
port = flag.Int("port", 8080, "Port for HTTP server (only used in server mode)")
)
flag.Parse()
// Use the values to prevent optimization
_ = *mode
_ = *port
}
}
// Test environment variable handling (if any)
func TestMain_Environment(t *testing.T) {
// Test with different environment conditions
// This is a placeholder for any environment-specific testing
svc := service.New()
if svc == nil {
t.Fatal("service creation failed in test environment")
}
// Test basic functionality in test environment
ctx := context.Background()
if err := svc.HealthCheck(ctx); err != nil {
t.Errorf("health check failed in test environment: %v", err)
}
status := svc.GetStatus(ctx)
if status["status"] != "running" {
t.Error("service should be running in test environment")
}
}
// Test resource cleanup
func TestMain_ResourceCleanup(t *testing.T) {
// Test that resources are properly cleaned up
svc := service.New()
if svc == nil {
t.Fatal("failed to create service")
}
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
// Perform some operations
_, err := svc.ProcessRequest(ctx, "cleanup test")
if err != nil {
t.Errorf("ProcessRequest failed: %v", err)
}
// Cancel context and ensure graceful handling
cancel()
// Try to use cancelled context
_, err = svc.ProcessRequest(ctx, "should fail")
if err == nil {
// This might not fail depending on implementation,
// but we test that it doesn't panic
}
}