-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrace_test.go
More file actions
88 lines (74 loc) · 2.31 KB
/
race_test.go
File metadata and controls
88 lines (74 loc) · 2.31 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
// Package fleet provides a distributed peer-to-peer communication framework.
package fleet
import (
"context"
"fmt"
"sync"
"testing"
"time"
)
// TestForRaceConditions runs a series of concurrent operations to help detect
// race conditions in the codebase. This should be used with the -race flag.
// Example: go test -race github.com/KarpelesLab/fleet -run TestForRaceConditions
func TestForRaceConditions(t *testing.T) {
// Create a test agent
a := New(WithName("test-agent-1"), WithDivision("test-division"))
if a == nil {
t.Fatalf("Failed to create agent")
}
defer a.Close()
// Test concurrent lock operations
testConcurrentLocks(t, a)
}
// testConcurrentLocks tests for race conditions in lock handling
func testConcurrentLocks(t *testing.T, a *Agent) {
const numLocks = 5
const numGoroutines = 3
var wg sync.WaitGroup
// Run tests for both local and global locks to test both code paths
for i := 0; i < numGoroutines; i++ {
wg.Add(1)
go func(n int) {
defer wg.Done()
for j := 0; j < numLocks; j++ {
lockName := fmt.Sprintf("test-lock-%d-%d", n, j)
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
// Try to acquire the lock
lock, err := a.Lock(ctx, lockName)
if err == nil && lock != nil {
// Successfully acquired lock, release it after a short delay
time.Sleep(10 * time.Millisecond)
lock.Release()
}
cancel()
}
}(i)
}
wg.Wait()
}
// TestResourceLeaks tests for common resource leaks
func TestResourceLeaks(t *testing.T) {
// Test that acquiring concurrent locks doesn't leak resources
testConcurrentAcquireReleaseLeaks(t)
}
// testConcurrentAcquireReleaseLeaks tests resource cleanup with many lock operations
func testConcurrentAcquireReleaseLeaks(t *testing.T) {
a := New(WithName("test-agent"), WithDivision("test-division"))
if a == nil {
t.Fatalf("Failed to create agent")
}
defer a.Close()
// Create several locks in succession
for i := 0; i < 100; i++ {
lockName := fmt.Sprintf("test-lock-%d", i)
lock, err := a.Lock(context.Background(), lockName)
if err != nil {
// Not expected, but not the focus of this test
continue
}
// Release immediately
lock.Release()
}
// If there's a resource leak, running with -race would likely detect it
// This is more of a functional test than an assertion-based test
}