fsm: run steps in order

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
2022-04-19 17:33:33 +03:00
parent 1db505decd
commit 08aaf14a79
2 changed files with 44 additions and 22 deletions

View File

@@ -10,40 +10,54 @@ import (
func TestFSMStart(t *testing.T) {
ctx := context.TODO()
buf := bytes.NewBuffer(nil)
pfb := func(_ context.Context, state string, _ map[string]interface{}) {
pfb := func(_ context.Context, state string, _ interface{}) {
fmt.Fprintf(buf, "before state %s\n", state)
}
pfa := func(_ context.Context, state string, _ map[string]interface{}) {
pfa := func(_ context.Context, state string, _ interface{}) {
fmt.Fprintf(buf, "after state %s\n", state)
}
f := New(StateInitial("1"), StateHookBefore(pfb), StateHookAfter(pfa))
f1 := func(_ context.Context, args map[string]interface{}) (string, map[string]interface{}, error) {
f1 := func(_ context.Context, req interface{}) (string, interface{}, error) {
args := req.(map[string]interface{})
if v, ok := args["request"].(string); !ok || v == "" {
return "", nil, fmt.Errorf("empty request")
}
return "2", map[string]interface{}{"response": "test2"}, nil
}
f2 := func(_ context.Context, args map[string]interface{}) (string, map[string]interface{}, error) {
f2 := func(_ context.Context, req interface{}) (string, interface{}, error) {
args := req.(map[string]interface{})
if v, ok := args["response"].(string); !ok || v == "" {
return "", nil, fmt.Errorf("empty response")
}
return "", map[string]interface{}{"response": "test"}, nil
}
f3 := func(_ context.Context, req interface{}) (string, interface{}, error) {
args := req.(map[string]interface{})
if v, ok := args["response"].(string); !ok || v == "" {
return "", nil, fmt.Errorf("empty response")
}
return StateEnd, map[string]interface{}{"response": "test_last"}, nil
}
f.State("1", f1)
f.State("2", f2)
args, err := f.Start(ctx, map[string]interface{}{"request": "test1"})
f.State("3", f3)
rsp, err := f.Start(ctx, map[string]interface{}{"request": "test1"})
if err != nil {
t.Fatal(err)
} else if v, ok := args["response"].(string); !ok || v == "" {
}
args := rsp.(map[string]interface{})
if v, ok := args["response"].(string); !ok || v == "" {
t.Fatalf("nil rsp: %#+v", args)
} else if v != "test" {
} else if v != "test_last" {
t.Fatalf("invalid rsp %#+v", args)
}
if !bytes.Contains(buf.Bytes(), []byte(`before state 1`)) ||
!bytes.Contains(buf.Bytes(), []byte(`before state 2`)) ||
!bytes.Contains(buf.Bytes(), []byte(`after state 1`)) ||
!bytes.Contains(buf.Bytes(), []byte(`after state 2`)) {
!bytes.Contains(buf.Bytes(), []byte(`after state 2`)) ||
!bytes.Contains(buf.Bytes(), []byte(`after state 3`)) ||
!bytes.Contains(buf.Bytes(), []byte(`after state 3`)) {
t.Fatalf("fsm not works properly or hooks error, buf: %s", buf.Bytes())
}
}