-
Notifications
You must be signed in to change notification settings - Fork 1
/
gate_test.go
85 lines (79 loc) · 2.05 KB
/
gate_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
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gate_test
import (
"context"
"testing"
"time"
"github.com/neild/gate"
)
func TestGateLockAndUnlock(t *testing.T) {
g := gate.New(false)
if set := g.Lock(); set {
t.Errorf("g.Lock of never-locked gate: true, want false")
}
unlockedc := make(chan struct{})
donec := make(chan struct{})
go func() {
defer close(donec)
if set := g.Lock(); !set {
t.Errorf("g.Lock of set gate: false, want true")
}
select {
case <-unlockedc:
default:
t.Errorf("g.Lock succeeded while gate was held")
}
g.Unlock(false)
}()
time.Sleep(1 * time.Millisecond)
close(unlockedc)
g.Unlock(true)
<-donec
if set := g.Lock(); set {
t.Errorf("g.Lock of unset gate: true, want false")
}
}
func TestGateWaitAndLock(t *testing.T) {
g := gate.New(false)
// WaitAndLock is canceled.
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
defer cancel()
if err := g.WaitAndLock(ctx); err != context.DeadlineExceeded {
t.Fatalf("g.WaitAndLock = %v, want context.DeadlineExceeded", err)
}
// WaitAndLock succeeds.
set := false
go func() {
time.Sleep(1 * time.Millisecond)
g.Lock()
set = true
g.Unlock(true)
}()
if err := g.WaitAndLock(context.Background()); err != nil {
t.Fatalf("g.WaitAndLock = %v, want nil", err)
}
if !set {
t.Fatalf("g.WaitAndLock returned before gate was set")
}
g.Unlock(true)
// WaitAndLock succeeds when the gate is set and the context is canceled.
if err := g.WaitAndLock(ctx); err != nil {
t.Fatalf("g.WaitAndLock = %v, want nil", err)
}
}
func TestGateLockIfSet(t *testing.T) {
g := gate.New(false)
if locked := g.LockIfSet(); locked {
t.Fatalf("g.LockIfSet of unset gate = %v, want false", locked)
}
g.Lock()
if locked := g.LockIfSet(); locked {
t.Fatalf("g.LockIfSet of locked gate = %v, want false", locked)
}
g.Unlock(true)
if locked := g.LockIfSet(); !locked {
t.Fatalf("g.LockIfSet of set gate = %v, want true", locked)
}
}