-
Notifications
You must be signed in to change notification settings - Fork 0
/
state-machine_test.go
111 lines (86 loc) · 2.35 KB
/
state-machine_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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package fsm
import (
"testing"
)
const (
Open = "open"
Close = "close"
OpenDoor = "open-door"
CloseDoor = "close-door"
)
type ComplexDoorState struct {
Id string
OpenedBy string
}
func getMachine() *Machine[string] {
machine := NewMachine(Close)
machine.SetTransition(Open, CloseDoor, Close)
machine.SetTransition(Close, OpenDoor, Open)
return machine
}
func getComplexMachine() *Machine[*ComplexDoorState] {
machine := NewMachine(&ComplexDoorState{Id: "close"})
machine.SetTransition(&ComplexDoorState{Id: "open"}, "close-door", &ComplexDoorState{Id: "close"})
machine.SetTransition(&ComplexDoorState{Id: "close"}, "open-door", &ComplexDoorState{Id: "open"})
machine.SetEnterAction(func(last, new *ComplexDoorState) error {
new.OpenedBy = "Peter"
return nil
})
machine.SetExitAction(func(old, next *ComplexDoorState) error {
return nil
})
return machine
}
func TestState(t *testing.T) {
machine := getMachine()
if machine.State() != Close {
t.Error("expecting state to be close")
}
machine.Transition(OpenDoor)
if machine.State() != Open {
t.Error("expecting state to be open")
}
}
func TestTransition(t *testing.T) {
machine := getMachine()
if _, _, err := machine.Transition(OpenDoor); err != nil {
t.Error(err)
}
if _, _, err := machine.Transition(OpenDoor); err == nil {
t.Error("expecting door to be opened")
}
}
func TestCanTransition(t *testing.T) {
machine := getMachine()
if !machine.CanTransition(OpenDoor) {
t.Error("expecting machine.CanTransition(\"open-door\") to return true")
}
if machine.CanTransition(CloseDoor) {
t.Error("expecting machine.CanTransition(\"close-door\") to return false")
}
}
func TestComplexTransition(t *testing.T) {
machine := getComplexMachine()
var last *ComplexDoorState
var current *ComplexDoorState
if l, c, err := machine.Transition(OpenDoor); err != nil {
t.Error(err)
} else {
last = *l
current = *c
}
if _, _, err := machine.Transition(OpenDoor); err == nil {
t.Error("expecting door to be opened")
}
state := machine.State()
if state.OpenedBy != "Peter" {
t.Errorf("expecting state %s to be 'Peter', not %s", state.Id, state.OpenedBy)
}
if state.Id != current.Id {
t.Errorf("States are not equal (%s vs %s)", state.Id, current.Id)
}
last.Id = "this should have no effect"
if state.Id == last.Id {
t.Errorf("State and last state are equal")
}
}