1
2from twisted.trial import unittest
3
4from vertex import statemachine
5
6S_1, S_2 = 'S_1', 'S_2'
7I_1, I_2 = 'I_1', 'I_2'
8O_1, O_2 = 'O_1', 'O_2'
9
10class TestMachine(statemachine.StateMachine):
11    states = {
12        S_1: {
13            I_1: (O_1, S_1),
14            I_2: (O_1, S_2),
15            },
16        S_2: {
17            I_1: (O_2, S_2),
18            I_2: (O_1, S_2),
19            },
20        }
21
22    initialState = S_1
23
24    def _event(self, name):
25        def method():
26            self.events.append(name)
27        return method
28
29    def __getattr__(self, name):
30        if (name.startswith('exit_') or name.startswith('enter_') or
31            name.startswith('transition_') or name.startswith('output_')):
32            return self._event(name)
33        raise AttributeError(name)
34
35class Transitions(unittest.TestCase):
36    def testOutput(self):
37        m = TestMachine()
38
39        self.assertEquals(m.state, S_1)
40
41        m.events = []
42        m.input(I_1)
43        self.assertEquals(
44            m.events,
45            ['output_O_1'])
46        self.assertEquals(m.state, S_1)
47
48        m.events = []
49        m.input(I_2)
50        self.assertEquals(
51            m.events,
52            ['exit_S_1', 'enter_S_2', 'transition_S_1_to_S_2', 'output_O_1'])
53        self.assertEquals(m.state, S_2)
54
55        m.events = []
56        m.input(I_1)
57        self.assertEquals(
58            m.events,
59            ['output_O_2'])
60        self.assertEquals(m.state, S_2)
61
62        m.events = []
63        m.input(I_2)
64        self.assertEquals(
65            m.events,
66            ['output_O_1'])
67        self.assertEquals(m.state, S_2)
68