Channel Manager State Machine with Tests
Closed this issue · 0 comments
nullcount commented
example:
import unittest
class StateMachine:
def __init__(self, initial_state):
self.state = initial_state
def transition(self, event):
self.state = self.state.transition(event)
class State:
def transition(self, event):
raise NotImplementedError
class InitialState(State):
def transition(self, event):
if event == "start":
return StartedState()
return self
class StartedState(State):
def transition(self, event):
if event == "stop":
return StoppedState()
return self
class StoppedState(State):
def transition(self, event):
if event == "start":
return StartedState()
return self
class TestStateMachine(unittest.TestCase):
def test_state_machine(self):
machine = StateMachine(InitialState())
# Test initial state
self.assertEqual(machine.state.__class__, InitialState)
# Test transition to StartedState
machine.transition("start")
self.assertEqual(machine.state.__class__, StartedState)
# Test transition to StoppedState
machine.transition("stop")
self.assertEqual(machine.state.__class__, StoppedState)
# Test transition back to StartedState
machine.transition("start")
self.assertEqual(machine.state.__class__, StartedState)
if __name__ == "__main__":
unittest.main()