-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
fsm.go
81 lines (61 loc) · 1.65 KB
/
fsm.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
package testutils
import (
"context"
"sync"
"testing"
"time"
"github.com/hashicorp/consul/agent/consul/state"
"github.com/hashicorp/consul/agent/consul/stream"
"github.com/stretchr/testify/require"
)
func TestStateStore(t *testing.T, publisher state.EventPublisher) *state.Store {
t.Helper()
gc, err := state.NewTombstoneGC(time.Second, time.Millisecond)
require.NoError(t, err)
if publisher == nil {
publisher = stream.NoOpEventPublisher{}
}
return state.NewStateStoreWithEventPublisher(gc, publisher)
}
type Registrar func(*FakeFSM, *stream.EventPublisher)
type FakeFSMConfig struct {
Register Registrar
Refresh []stream.Topic
publisher *stream.EventPublisher
}
type FakeFSM struct {
config FakeFSMConfig
lock sync.Mutex
store *state.Store
}
func newFakeFSM(t *testing.T, config FakeFSMConfig) *FakeFSM {
t.Helper()
store := TestStateStore(t, config.publisher)
fsm := &FakeFSM{store: store, config: config}
config.Register(fsm, fsm.config.publisher)
return fsm
}
func (f *FakeFSM) GetStore() *state.Store {
f.lock.Lock()
defer f.lock.Unlock()
return f.store
}
func (f *FakeFSM) ReplaceStore(store *state.Store) {
f.lock.Lock()
defer f.lock.Unlock()
oldStore := f.store
f.store = store
oldStore.Abandon()
for _, topic := range f.config.Refresh {
f.config.publisher.RefreshTopic(topic)
}
}
func SetupFSMAndPublisher(t *testing.T, config FakeFSMConfig) (*FakeFSM, state.EventPublisher) {
t.Helper()
config.publisher = stream.NewEventPublisher(10 * time.Second)
fsm := newFakeFSM(t, config)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
go config.publisher.Run(ctx)
return fsm, config.publisher
}