CoolFace
Apppublic

guohanghui/graph-theory

sourceHugging Faceupdated 7mo agoView on Hugging Face
0likes
test_finite_state_machine.py92 linesDownload Raw Back to tests
1from graph.finite_state_machine import FiniteStateMachine2from itertools import cycle3 4 5def test_traffic_light():6    green, yellow, red = 'Green', 'Yellow', 'Red'7    seq = cycle([green, yellow, red])8    _ = next(seq)9    fsm = FiniteStateMachine()10    fsm.add_transition(green, 'switch', yellow)11    fsm.add_transition(yellow, 'switch', red)12    fsm.add_transition(red, 'switch', green)13    fsm.set_initial_state(green)14    for _ in range(20):15        current_state = fsm.current_state16        new_state = next(seq)17        fsm.next('switch')18        assert fsm.current_state == new_state, (fsm.current_state, new_state)19        assert new_state != current_state, (new_state, current_state)20 21 22def test_turnstile():23    locked, unlocked = 'locked', 'unlocked'  # states24    push, coin = 'push', 'coin'  # actions25    fsm = FiniteStateMachine()26    fsm.add_transition(locked, coin, unlocked)27    fsm.add_transition(unlocked, push, locked)28    fsm.add_transition(locked, push, locked)29    fsm.add_transition(unlocked, coin, unlocked)30    try:31        assert fsm._initial_state_was_set is False32        fsm.next(coin)33        raise AssertionError34    except ValueError:35        pass36 37    try:38        assert fsm._initial_state_was_set is False39        fsm.set_initial_state('fish')40        raise AssertionError41    except ValueError:42        pass43 44    fsm.set_initial_state(locked)45 46    try:47        assert fsm._initial_state_was_set is True48        fsm.set_initial_state(locked)49        raise AssertionError50    except ValueError:51        assert fsm._initial_state_was_set is True52        pass53 54    # pay and go:55    display_state = set(fsm.options())56    assert display_state == {coin, push}, display_state57    assert fsm.current_state == locked58    fsm.next(action=coin)59    display_state = set(fsm.options())60    assert display_state == {coin, push}, display_state61    assert fsm.current_state == unlocked62    fsm.next(action=push)63    assert fsm.current_state == locked64 65    # try to cheat66    fsm.next(action=push)67    assert fsm.current_state == locked68    fsm.next(action=push)69    assert fsm.current_state == locked70 71    # pay and go:72    fsm.next(action=coin)73    assert fsm.current_state == unlocked74    fsm.next(action=push)75    assert fsm.current_state == locked76 77    try:78        assert fsm._initial_state_was_set is True79        fsm.next(action='fish')80        raise AssertionError81    except ValueError:82        pass83 84    fsm.add_transition(locked, 'fire', 'fire escape mode')85    fsm.next('fire')86    try:87        fsm.next(push)88        raise AssertionError89    except StopIteration:90        pass91 92