-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcircuit_test.go
More file actions
60 lines (55 loc) · 1.28 KB
/
circuit_test.go
File metadata and controls
60 lines (55 loc) · 1.28 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
package sshd
import (
"math/rand"
"sync"
"sync/atomic"
"testing"
"time"
)
const (
numConcurrents = 1000
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func TestOpenCloseSerial(t *testing.T) {
c := NewCircuit()
if c.State() != OpenState {
t.Fatalf("unexpected initial circuit state. want %s, got %s", OpenState, c.State())
}
if b := c.Close(); !b {
t.Fatalf("tried to close the circuit but it said it was already closed")
}
if c.State() != ClosedState {
t.Fatalf("unexpected circuit state. want %s, got %s", ClosedState, c.State())
}
if b := c.Open(); !b {
t.Fatalf("tried to open the circuit but it said it was already opened")
}
if c.State() != OpenState {
t.Fatalf("unexpected circuit state. want %s, got %s", OpenState, c.State())
}
}
func TestOpenCloseConcurrent(t *testing.T) {
c := NewCircuit()
var wg sync.WaitGroup
state := uint32(0)
for i := 0; i < numConcurrents; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
r := rand.Int() % 2
if r == 0 {
c.Open()
atomic.StoreUint32(&state, OpenState.toUint32())
} else {
c.Close()
atomic.StoreUint32(&state, ClosedState.toUint32())
}
}(i)
}
wg.Wait()
if state != c.State().toUint32() {
t.Fatalf("expected state %d wasn't equal to actual %d", state, c.State().toUint32())
}
}