-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathit_test.go
867 lines (761 loc) · 20.8 KB
/
it_test.go
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
package it_test
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync"
"sync/atomic"
"syscall"
"testing"
"time"
"github.com/theHamdiz/it"
"golang.org/x/crypto/bcrypt"
)
// TestRecoverPanicAndContinue tests panic recovery
func TestRecoverPanicAndContinue(t *testing.T) {
defer it.RecoverPanicAndContinue()()
recovered := false
func() {
defer func() {
if r := recover(); r != nil {
recovered = true
}
}()
panic("test panic")
}()
if !recovered {
t.Error("Expected panic to be recovered")
}
}
// TestMust tests the Must function
func TestMust(t *testing.T) {
// Test successful case
result := it.Must(func() (string, error) {
return "success", nil
})
if result != "success" {
t.Errorf("Expected 'success', got %s", result)
}
// Test panic case
defer func() {
if r := recover(); r == nil {
t.Error("Expected Must to panic on error")
}
}()
it.Must(func() (string, error) {
return "", errors.New("test error")
})
}
// TestShould tests the Should function
func TestShould(t *testing.T) {
// Test successful case
result := it.Should(func() (string, error) {
return "success", nil
})
if result != "success" {
t.Errorf("Expected 'success', got %s", result)
}
// Test error case (should not panic)
result = it.Should(func() (string, error) {
return "default", errors.New("test error")
})
if result != "default" {
t.Errorf("Expected 'default', got %s", result)
}
}
// TestCould tests the Could function, I mean right?
func TestCould(t *testing.T) {
// For the indecisive
count := 0
maybeDoWork := it.Could(func() (string, error) {
count++
return "meh", nil
})
// Call it whenever you feel like it
result1 := maybeDoWork()
result2 := maybeDoWork()
result3 := maybeDoWork()
// Make sure we were lazy enough
if count != 1 {
t.Errorf("did work %d times, expected once", count)
}
// Check if all results are consistently mediocre
if result1 != result2 || result2 != result3 {
t.Error("got different results somehow")
}
// Test with errors because life is pain
failures := 0
maybeFail := it.Could(func() (int, error) {
failures++
return 42, errors.New("nope")
})
// Even failures should be consistent
r1 := maybeFail()
r2 := maybeFail()
if failures != 1 {
t.Error("failed more than necessary")
}
if r1 != r2 {
t.Error("failed differently somehow")
}
}
// TestSafeGo tests goroutine safety
func TestSafeGo(t *testing.T) {
wg := sync.WaitGroup{}
wg.Add(1)
executed := false
it.SafeGo(func() {
defer wg.Done()
executed = true
})
wg.Wait()
if !executed {
t.Error("SafeGo didn't execute the function")
}
}
// TestSafeGoWithContext tests context-aware goroutine safety
func TestSafeGoWithContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
wg := sync.WaitGroup{}
wg.Add(1)
executed := false
it.SafeGoWithContext(ctx, func(ctx context.Context) {
defer wg.Done()
executed = true
})
wg.Wait()
if !executed {
t.Error("SafeGoWithContext didn't execute the function")
}
}
// TestLogging tests various logging functions
func TestLogging(t *testing.T) {
// Redirect logs to a temporary file for testing
tmpFile, err := os.CreateTemp("", "log_test")
if err != nil {
t.Fatal(err)
}
defer func(name string) {
err := os.Remove(name)
if err != nil {
t.Errorf("Failed to remove temp file %s: %v", name, err)
}
}(tmpFile.Name())
it.SetLogOutput(tmpFile)
tests := []struct {
name string
logFunc func(string)
message string
}{
{"Info", it.Info, "info message"},
{"Warn", it.Warn, "warning message"},
{"Error", it.Error, "error message"},
{"Debug", it.Debug, "debug message"},
{"Trace", it.Trace, "trace message"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.logFunc(tt.message)
// Here you could read the temp file and verify the log message
})
}
}
// TestRetry tests retry functionality
func TestRetry(t *testing.T) {
attempts := 0
err := it.Retry(3, time.Millisecond, func() error {
attempts++
if attempts < 3 {
return errors.New("not yet")
}
return nil
})
if err != nil {
t.Error("Expected retry to succeed")
}
if attempts != 3 {
t.Errorf("Expected 3 attempts, got %d", attempts)
}
}
type mockServer struct {
shutdownCalled bool
shutdownError error
mu sync.Mutex
}
func (m *mockServer) Shutdown(ctx context.Context) error {
m.mu.Lock()
defer m.mu.Unlock()
m.shutdownCalled = true
return m.shutdownError
}
func (m *mockServer) WasShutdownCalled() bool {
m.mu.Lock()
defer m.mu.Unlock()
return m.shutdownCalled
}
// Improved test with multiple scenarios
func TestGracefulShutdown(t *testing.T) {
testCases := []struct {
name string
timeout time.Duration
shutdownError error
action func()
setupTest func()
validateTest func(*testing.T, *mockServer, bool)
}{
{
name: "successful shutdown",
timeout: time.Second,
setupTest: func() {
// Small delay to ensure shutdown manager is ready
time.Sleep(100 * time.Millisecond)
_ = syscall.Kill(syscall.Getpid(), syscall.SIGTERM)
},
validateTest: func(t *testing.T, server *mockServer, success bool) {
if !success {
t.Error("Graceful shutdown reported failure")
}
if !server.WasShutdownCalled() {
t.Error("Server shutdown was not called")
}
},
},
{
name: "shutdown with error",
timeout: time.Second,
shutdownError: errors.New("planned shutdown error"),
setupTest: func() {
time.Sleep(100 * time.Millisecond)
_ = syscall.Kill(syscall.Getpid(), syscall.SIGTERM)
},
validateTest: func(t *testing.T, server *mockServer, success bool) {
if success {
t.Error("Graceful shutdown should have reported failure")
}
if !server.WasShutdownCalled() {
t.Error("Server shutdown was not called")
}
},
},
{
name: "shutdown with action",
timeout: time.Second,
action: func() {
},
setupTest: func() {
time.Sleep(100 * time.Millisecond)
_ = syscall.Kill(syscall.Getpid(), syscall.SIGTERM)
},
validateTest: func(t *testing.T, server *mockServer, success bool) {
if !success {
t.Error("Graceful shutdown reported failure")
}
if !server.WasShutdownCalled() {
t.Error("Server shutdown was not called")
}
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// Create a new server for each test
server := &mockServer{shutdownError: tc.shutdownError}
done := make(chan bool)
ctx, cancel := context.WithTimeout(context.Background(), tc.timeout)
defer cancel()
// Start graceful shutdown in a goroutine
go func() {
it.GracefulShutdown(ctx, server, tc.timeout, done, tc.action)
}()
// Setup test conditions
if tc.setupTest != nil {
tc.setupTest()
}
// Wait for completion with timeout
var success bool
select {
case success = <-done:
// Shutdown completed
case <-time.After(tc.timeout * 2):
t.Fatal("Test timed out waiting for shutdown")
}
// Validate test results
if tc.validateTest != nil {
tc.validateTest(t, server, success)
}
})
}
}
// TestWaitFor tests the WaitFor function
func TestWaitFor(t *testing.T) {
// Test successful wait
success := it.WaitFor(time.Millisecond*100, func() bool {
return true
})
if !success {
t.Error("WaitFor should return true for immediate condition")
}
// Test timeout
start := time.Now()
success = it.WaitFor(time.Millisecond*100, func() bool {
return false
})
duration := time.Since(start)
if success {
t.Error("WaitFor should return false on timeout")
}
if duration < time.Millisecond*100 {
t.Error("WaitFor didn't wait for the full timeout duration")
}
}
// TestGenerateSecret tests secret generation
func TestGenerateSecret(t *testing.T) {
for secretLength := 4; secretLength <= 16; secretLength++ {
seenSecrets := make(map[string]struct{})
// Technically, duplicate secrets could be produced even
// if working properly, but it's relatively unlikely.
for i := 0; i < 10; i++ {
secret := it.GenerateSecret(secretLength)
expectedLength := secretLength * 2
if len(secret) != expectedLength {
t.Errorf("Secret length mismatch. Should be %d, got %d", expectedLength, len(secret))
}
if _, ok := seenSecrets[secret]; ok {
t.Errorf("Duplicate secret generated: %s", secret)
}
seenSecrets[secret] = struct{}{}
}
}
}
// TestHashPassword ensures that HashPassword returns a valid bcrypt hash.
func TestHashPassword(t *testing.T) {
password := "mySecretPassword123"
cost := 12
hashed, err := it.HashPassword(password, cost)
if err != nil {
t.Fatalf("HashPassword returned an error (surprise!): %v", err)
}
if len(hashed) == 0 {
t.Fatal("Expected a non-empty hashed password; did you forget to hash it?")
}
// Check that the resulting hash is valid by using bcrypt's CompareHashAndPassword.
if err := bcrypt.CompareHashAndPassword(hashed, []byte(password)); err != nil {
t.Errorf("bcrypt comparison failed: %v", err)
}
}
// TestVerifyPassword_Correct verifies that VerifyPassword accepts the correct password.
func TestVerifyPassword_Correct(t *testing.T) {
password := "mySecretPassword123"
cost := 12
hashed, err := it.HashPassword(password, cost)
if err != nil {
t.Fatalf("HashPassword returned an error (not again!): %v", err)
}
// The correct password should pass verification.
if err := it.VerifyPassword(hashed, password); err != nil {
t.Errorf("VerifyPassword failed for a correct password: %v", err)
}
}
// TestVerifyPassword_Incorrect ensures that VerifyPassword rejects an incorrect password.
func TestVerifyPassword_Incorrect(t *testing.T) {
password := "mySecretPassword123"
wrongPassword := "wrongPassword"
cost := 12
hashed, err := it.HashPassword(password, cost)
if err != nil {
t.Fatalf("HashPassword returned an error (seriously?): %v", err)
}
// The wrong password should not verify.
if err := it.VerifyPassword(hashed, wrongPassword); err == nil {
t.Error("VerifyPassword accepted an incorrect password (we thought you cared about security)")
}
}
// TestHashProducesDifferentHashes verifies that the same password produces different hashes
// each time due to the random salt. Because if they're equal, then something is very wrong.
func TestHashProducesDifferentHashes(t *testing.T) {
password := "mySecretPassword123"
cost := 12
hashed1, err := it.HashPassword(password, cost)
if err != nil {
t.Fatalf("First HashPassword call failed: %v", err)
}
hashed2, err := it.HashPassword(password, cost)
if err != nil {
t.Fatalf("Second HashPassword call failed: %v", err)
}
if string(hashed1) == string(hashed2) {
t.Error("Two hashes for the same password should not be equal (thanks, salt!)")
}
}
// TestStructuredLogging tests structured logging functionality
func TestStructuredLogging(t *testing.T) {
tmpFile, err := os.CreateTemp("", "structured_log_test")
if err != nil {
t.Fatal(err)
}
defer func(name string) {
err := os.Remove(name)
if err != nil {
t.Errorf("Failed to remove temp file %s: %v", name, err)
}
}(tmpFile.Name())
it.SetLogOutput(tmpFile)
testCases := []struct {
name string
logFunc func(string, map[string]any)
message string
data map[string]any
}{
{
name: "StructuredInfo",
logFunc: it.StructuredInfo,
message: "test info",
data: map[string]any{
"key": "value",
"num": 123,
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
tc.logFunc(tc.message, tc.data)
// Add verification of log output if needed
})
}
}
// TestRetryExponentialWithContext tests exponential backoff retry with context
func TestRetryExponentialWithContext(t *testing.T) {
testCases := []struct {
name string
attempts int
initialDelay time.Duration
operation func(int *int) error
expectedError string
minDuration time.Duration
maxDuration time.Duration
expectedAttempts int
setupContext func(context.Context, context.CancelFunc) // Added setup function
}{
{
name: "basic retry with failure",
attempts: 3,
initialDelay: time.Millisecond * 10,
operation: func(attempts *int) error {
*attempts++
return errors.New("persistent error")
},
expectedError: "persistent error",
minDuration: time.Millisecond * 30,
maxDuration: time.Millisecond * 50,
expectedAttempts: 3,
setupContext: nil, // No special setup needed
},
{
name: "success on second attempt",
attempts: 3,
initialDelay: time.Millisecond * 10,
operation: func(attempts *int) error {
*attempts++
if *attempts < 2 {
return errors.New("temporary error")
}
return nil
},
expectedError: "",
minDuration: time.Millisecond * 10,
maxDuration: time.Millisecond * 30,
expectedAttempts: 2,
setupContext: nil,
},
{
name: "context cancellation",
attempts: 3,
initialDelay: time.Millisecond * 10,
operation: func(attempts *int) error {
*attempts++
time.Sleep(time.Millisecond * 5) // Small delay to ensure context cancellation
return errors.New("should be cancelled")
},
expectedError: context.Canceled.Error(),
minDuration: time.Millisecond * 0,
maxDuration: time.Millisecond * 20,
expectedAttempts: 1,
setupContext: func(ctx context.Context, cancel context.CancelFunc) {
// Cancel after a short delay to allow first attempt
go func() {
time.Sleep(time.Millisecond)
cancel()
}()
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
attempts := 0
start := time.Now()
ctx, cancel := context.WithTimeout(context.Background(), tc.maxDuration)
defer cancel()
if tc.setupContext != nil {
tc.setupContext(ctx, cancel)
}
err := it.RetryExponentialWithContext(ctx, tc.attempts, tc.initialDelay, func() error {
return tc.operation(&attempts)
})
duration := time.Since(start)
// Check error
if tc.expectedError == "" {
if err != nil {
t.Errorf("Expected no error, got: %v", err)
}
} else {
if err == nil || !strings.Contains(err.Error(), tc.expectedError) {
t.Errorf("Expected error containing '%s', got: %v", tc.expectedError, err)
}
}
// Check attempts
if attempts != tc.expectedAttempts {
t.Errorf("Expected %d attempts, got %d", tc.expectedAttempts, attempts)
}
// Check duration with some tolerance
if duration < tc.minDuration {
t.Errorf("Retries happened too quickly. Expected minimum %v, got %v", tc.minDuration, duration)
}
if duration > tc.maxDuration {
t.Errorf("Retries took too long. Expected maximum %v, got %v", tc.maxDuration, duration)
}
})
}
}
// TestTimeParallel tests parallel execution timing
func TestTimeParallel(t *testing.T) {
durations := it.TimeParallel("parallel_test",
func() { time.Sleep(time.Millisecond * 50) },
func() { time.Sleep(time.Millisecond * 100) },
func() { time.Sleep(time.Millisecond * 75) },
)
if len(durations) != 3 {
t.Errorf("Expected 3 durations, got %d", len(durations))
}
// Verify that durations are reasonable
for i, d := range durations {
if d < time.Millisecond*50 {
t.Errorf("Duration %d too short: %v", i, d)
}
}
}
// TestRateLimiterWithHTTPRequests tests rate limiting with HTTP requests
func TestRateLimiterWithHTTPRequests(t *testing.T) {
// Create a test server
requestCount := int32(0)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt32(&requestCount, 1)
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
// Create a rate-limited HTTP client
makeRequest := func() error {
resp, err := http.Get(server.URL)
if err != nil {
return err
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
t.Errorf("Failed to close response body: %v", err)
}
}(resp.Body)
return nil
}
rateLimitedRequest := it.RateLimiter(time.Millisecond*100, makeRequest).(func() error)
// Make several requests
start := time.Now()
for i := 0; i < 5; i++ {
err := rateLimitedRequest()
if err != nil {
t.Errorf("Request %d failed: %v", i, err)
}
}
duration := time.Since(start)
if duration < time.Millisecond*400 {
t.Error("Requests were not rate limited properly")
}
}
// TestTimeFunctionWithCallback tests timing with callback
func TestTimeFunctionWithCallback(t *testing.T) {
var measured time.Duration
callback := func(duration time.Duration) {
measured = duration
}
result := it.TimeFunctionWithCallback(
"test_function",
func() string {
time.Sleep(time.Millisecond * 50)
return "done"
},
callback,
)
if result != "done" {
t.Error("Function didn't return expected result")
}
if measured < time.Millisecond*50 {
t.Error("Measured duration too short")
}
}
// TestConfigurationChanges tests configuration modifications
func TestConfigurationChanges(t *testing.T) {
// Test color output configuration
it.EnableColoredOutput(true)
config := it.GetCurrentConfig()
if !config.ColorsEnabled() {
t.Error("Color output not enabled")
}
// Test shutdown timeout configuration
timeout := time.Second * 5
it.SetShutdownTimeout(timeout)
config = it.GetCurrentConfig()
if config.ShutdownTimeout != timeout {
t.Error("Shutdown timeout not set correctly")
}
}
// TestEnvironmentVariables tests environment variable handling
func TestEnvironmentVariables(t *testing.T) {
// Save original env vars
originalLogLevel := os.Getenv("LOG_LEVEL")
originalLogFile := os.Getenv("LOG_FILE")
defer func() {
_ = os.Setenv("LOG_LEVEL", originalLogLevel)
_ = os.Setenv("LOG_FILE", originalLogFile)
}()
// Test LOG_LEVEL
_ = os.Setenv("LOG_LEVEL", "DEBUG")
it.InitFromEnv()
// Add verification of log level change
// Test LOG_FILE
tmpFile, err := os.CreateTemp("", "log_test")
if err != nil {
t.Fatal(err)
}
defer func(name string) {
err := os.Remove(name)
if err != nil {
t.Errorf("Failed to remove temp file %s: %v", name, err)
}
}(tmpFile.Name())
_ = os.Setenv("LOG_FILE", tmpFile.Name())
it.InitFromEnv()
// Add verification of log file change
}
// TestLogOnce ensures messages are logged only once
func TestLogOnce(t *testing.T) {
tmpFile, err := os.CreateTemp("", "log_once_test")
if err != nil {
t.Fatal(err)
}
defer func(name string) {
err := os.Remove(name)
if err != nil {
t.Errorf("Failed to remove temp file %s: %v", name, err)
}
}(tmpFile.Name())
it.SetLogOutput(tmpFile)
message := "this should appear once"
for i := 0; i < 3; i++ {
it.LogOnce(message)
}
// Read log file and verify message appears only once
content, err := os.ReadFile(tmpFile.Name())
if err != nil {
t.Fatal(err)
}
occurrences := 0
for _, line := range strings.Split(string(content), "\n") {
if strings.Contains(line, message) {
occurrences++
}
}
if occurrences != 1 {
t.Errorf("Expected message to appear once, got %d occurrences", occurrences)
}
}
// TestAuditLogging tests audit log functionality
func TestAuditLogging(t *testing.T) {
tmpFile, err := os.CreateTemp("", "audit_log_test")
if err != nil {
t.Fatal(err)
}
defer func(name string) {
err := os.Remove(name)
if err != nil {
t.Errorf("Failed to remove temp file %s: %v", name, err)
}
}(tmpFile.Name())
it.SetLogOutput(tmpFile)
auditMessage := "sensitive operation performed"
it.Audit(auditMessage)
// Verify audit log format and content
content, err := os.ReadFile(tmpFile.Name())
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(content), "AUDIT") || !strings.Contains(string(content), auditMessage) {
t.Error("Audit log entry not formatted correctly")
}
}
// TestTimeBlock measures block execution time
func TestTimeBlock(t *testing.T) {
done := it.TimeBlock("test_block")
time.Sleep(time.Millisecond * 50)
done()
// Note: This test might need adjustment based on how TimeBlock logs its output
}
// TestConcurrentLogging tests thread-safety of logging
func TestConcurrentLogging(t *testing.T) {
tmpFile, err := os.CreateTemp("", "concurrent_log_test")
if err != nil {
t.Fatal(err)
}
defer func(name string) {
err := os.Remove(name)
if err != nil {
t.Errorf("Failed to remove temp file %s: %v", name, err)
}
}(tmpFile.Name())
it.SetLogOutput(tmpFile)
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
it.Infof("Concurrent log %d", id)
}(i)
}
wg.Wait()
}
// BenchmarkRateLimiter benchmarks rate limiting performance
func BenchmarkRateLimiter(b *testing.B) {
operation := func() error {
return nil
}
rateLimitedOp := it.RateLimiter(time.Microsecond, operation).(func() error)
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = rateLimitedOp()
}
}
// BenchmarkStructuredLogging benchmarks structured logging performance
func BenchmarkStructuredLogging(b *testing.B) {
data := map[string]any{
"key1": "value1",
"key2": 123,
"key3": true,
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
it.StructuredInfo("benchmark message", data)
}
}