[statemachine] simplify test states

This commit is contained in:
Mark Spanbroek 2023-02-09 10:19:13 +01:00
parent 54e534183a
commit af092fc1b3
No known key found for this signature in database
GPG Key ID: FBE3E9548D427C00
1 changed files with 11 additions and 17 deletions

View File

@ -10,52 +10,46 @@ type
State2 = ref object of TestState
State3 = ref object of TestState
var state1Invoked = 0
var state2Invoked = 0
var state2Cancelled = 0
var state3Invoked = 0
var runs, cancellations = [0, 0, 0]
method onMoveToNextStateEvent*(state: TestState): ?AsyncState {.base.} =
discard
method run(state: State1): Future[?AsyncState] {.async.} =
inc state1Invoked
inc runs[0]
return some AsyncState(State2.new())
method run(state: State2): Future[?AsyncState] {.async.} =
inc state2Invoked
inc runs[1]
try:
await sleepAsync(1.hours)
except CancelledError:
inc state2Cancelled
inc cancellations[1]
method onMoveToNextStateEvent(state: State2): ?AsyncState =
return some AsyncState(State3.new())
method run(state: State3): Future[?AsyncState] {.async.} =
inc state3Invoked
inc runs[2]
suite "async state machines":
var machine: AsyncStateMachine
var state1, state2: AsyncState
setup:
state1Invoked = 0
state2Invoked = 0
state2Cancelled = 0
state3Invoked = 0
runs = [0, 0, 0]
cancellations = [0, 0, 0]
machine = AsyncStateMachine.new()
state1 = State1.new()
state2 = State2.new()
test "should call run on start state":
machine.start(state1)
check eventually state1Invoked == 1
check eventually runs[0] == 1
test "moves to next state when run completes":
machine.start(state1)
check eventually state2Invoked == 1
check eventually runs == [1, 1, 0]
test "state2 moves to state3 on event":
machine.start(state2)
@ -65,7 +59,7 @@ suite "async state machines":
machine.schedule(Event(moveToNextStateEvent))
check eventually state3Invoked == 1
check eventually runs == [0, 1, 1]
test "state transition will cancel the running state":
machine.start(state2)
@ -75,4 +69,4 @@ suite "async state machines":
machine.schedule(Event(moveToNextStateEvent))
check eventually state2Cancelled == 1
check eventually cancellations == [0, 1, 0]