since 2014-04-15
http://d.nishimotz.com/archives/1685
ジェネレータ式で状態遷移を書いてみる:
import unittest class State: FIRST = 1 SECOND = 2 END = 3 class Event: DUMMY = 100 GOTO_SECOND = 101 GOTO_END = 102 def stateManagerGenerator(): while True: ev, arg = (yield State.FIRST) if ev == Event.GOTO_SECOND: break while True: ev, arg = (yield State.SECOND) if ev == Event.GOTO_END: break while True: ev, arg = (yield State.END) def makeStateManager(): return stateManagerGenerator() class StateManagerTests(unittest.TestCase): def test_transition(self): stateManager = makeStateManager() state = stateManager.send(None) self.assertEqual(state, State.FIRST) state = stateManager.send((Event.DUMMY, "dummyArg")) self.assertEqual(state, State.FIRST) state = stateManager.send((Event.GOTO_SECOND, "dummyArg")) self.assertEqual(state, State.SECOND) state = stateManager.send((Event.GOTO_END, "dummyArg")) self.assertEqual(state, State.END) state = stateManager.send((Event.DUMMY, "dummyArg")) self.assertEqual(state, State.END) if __name__ == '__main__': unittest.main()