|
1 | 1 | package sshd |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "errors" |
| 5 | + "sync" |
4 | 6 | "testing" |
5 | 7 | "time" |
| 8 | + |
| 9 | + "github.com/arschles/assert" |
6 | 10 | ) |
7 | 11 |
|
8 | 12 | const ( |
9 | 13 | callbackTimeout = 1 * time.Second |
10 | 14 | ) |
11 | 15 |
|
| 16 | +var ( |
| 17 | + errWGTimedOut = errors.New("waitgroup wait timed out") |
| 18 | +) |
| 19 | + |
| 20 | +// waitWithTimeout waits for wg.Done() until timeout expires. returns errWGTimedOut if timeout expired before wg.Done() returned, otherwise returns nil. this func is naturally leaky if wg.Done() never returns |
| 21 | +func waitWithTimeout(wg *sync.WaitGroup, timeout time.Duration) error { |
| 22 | + ch := make(chan struct{}) |
| 23 | + go func() { |
| 24 | + defer close(ch) |
| 25 | + wg.Wait() |
| 26 | + }() |
| 27 | + select { |
| 28 | + case <-time.After(timeout): |
| 29 | + return errWGTimedOut |
| 30 | + case <-ch: |
| 31 | + return nil |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +func TestMultipleSameRepoLocks(t *testing.T) { |
| 36 | + var wg sync.WaitGroup |
| 37 | + const repo = "repo1" |
| 38 | + const numTries = 100 |
| 39 | + lck := NewInMemoryRepositoryLock() |
| 40 | + assert.NoErr(t, lck.Lock(repo, 0*time.Second)) |
| 41 | + for i := 0; i < numTries; i++ { |
| 42 | + wg.Add(1) |
| 43 | + go func() { |
| 44 | + defer wg.Done() |
| 45 | + assert.True(t, lck.Lock(repo, 0*time.Second) != nil, "lock of already locked repo should return error") |
| 46 | + }() |
| 47 | + } |
| 48 | + assert.NoErr(t, waitWithTimeout(&wg, 1*time.Second)) |
| 49 | + assert.NoErr(t, lck.Unlock(repo, 0*time.Second)) |
| 50 | + for i := 0; i < numTries; i++ { |
| 51 | + wg.Add(1) |
| 52 | + go func() { |
| 53 | + defer wg.Done() |
| 54 | + assert.True(t, lck.Unlock(repo, 0*time.Second) != nil, "unlock of already unlocked repo should return error") |
| 55 | + }() |
| 56 | + } |
| 57 | + assert.NoErr(t, waitWithTimeout(&wg, 1*time.Second)) |
| 58 | +} |
| 59 | + |
12 | 60 | func TestSingleLock(t *testing.T) { |
13 | 61 | rl := NewInMemoryRepositoryLock() |
14 | 62 | key := "fakeid" |
|
0 commit comments