forked from qmuntal/stateless
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph_test.go
109 lines (98 loc) · 2.32 KB
/
graph_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
package stateless_test
import (
"bytes"
"context"
"flag"
"os"
"reflect"
"runtime"
"strings"
"testing"
"github.com/kkettinger/stateless"
)
var update = flag.Bool("update", false, "update golden files on failure")
func emptyWithInitial() *stateless.StateMachine {
return stateless.NewStateMachine("A")
}
func withSubstate() *stateless.StateMachine {
sm := stateless.NewStateMachine("B")
sm.Configure("A").Permit("Z", "B")
sm.Configure("B").SubstateOf("C").Permit("X", "A")
sm.Configure("C").Permit("Y", "A").Ignore("X")
return sm
}
func withInitialState() *stateless.StateMachine {
sm := stateless.NewStateMachine("A")
sm.Configure("A").
Permit("X", "B")
sm.Configure("B").
InitialTransition("C")
sm.Configure("C").
InitialTransition("D").
SubstateOf("B")
sm.Configure("D").
SubstateOf("C")
return sm
}
func withGuards() *stateless.StateMachine {
sm := stateless.NewStateMachine("B")
sm.SetTriggerParameters("X", reflect.TypeOf(0))
sm.Configure("A").
Permit("X", "D", func(_ context.Context, args ...interface{}) bool {
return args[0].(int) == 3
})
sm.Configure("B").
SubstateOf("A").
Permit("X", "C", func(_ context.Context, args ...interface{}) bool {
return args[0].(int) == 2
})
return sm
}
func œ(_ context.Context, args ...interface{}) bool {
return args[0].(int) == 2
}
func withUnicodeNames() *stateless.StateMachine {
sm := stateless.NewStateMachine("Ĕ")
sm.Configure("Ĕ").
Permit("◵", "ų", œ)
sm.Configure("ų").
InitialTransition("ㇴ")
sm.Configure("ㇴ").
InitialTransition("ꬠ").
SubstateOf("ų")
sm.Configure("ꬠ").
SubstateOf("𒀄")
sm.Configure("1").
SubstateOf("𒀄")
sm.Configure("2").
SubstateOf("1")
return sm
}
func TestStateMachine_ToGraph(t *testing.T) {
tests := []func() *stateless.StateMachine{
emptyWithInitial,
withSubstate,
withInitialState,
withGuards,
withUnicodeNames,
}
for _, fn := range tests {
name := runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name()
sp := strings.Split(name, ".")
name = sp[len(sp)-1]
t.Run(name, func(t *testing.T) {
got := fn().ToGraph()
name := "testdata/golden/" + name + ".dot"
want, err := os.ReadFile(name)
if *update {
if !bytes.Equal([]byte(got), want) {
os.WriteFile(name, []byte(got), 0666)
}
} else {
if err != nil {
t.Fatal(err)
}
}
})
}
}