Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/src/sugar/tutorius/tests/coretests.py
blob: 297a7c352d7f00314d23127b560ebe01c46f26d5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# Copyright (C) 2009, Tutorius.org
# Copyright (C) 2009, Michael Janelle-Montcalm <michael.jmontcalm@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
"""
Core Tests

This module contains all the tests that pertain to the usage of the Tutorius
Core. This means that the Event Filters, the Finite State Machine and all the 
related elements and interfaces are tested here.

"""

import unittest

import logging
from sugar.tutorius.actions import Action, OnceWrapper
from sugar.tutorius.core import *
from sugar.tutorius.filters import *

# Helper classes to help testing
class SimpleTutorial(Tutorial):
    """
    Fake tutorial
    """
    def __init__(self, start_name="INIT"):
        #Tutorial.__init__(self, "Simple Tutorial", None)
        self.current_state_name = start_name
        self.activity = "TODO : This should be an activity"
    
    def set_state(self, name):
        self.current_state_name = name

class TrueWhileActiveAction(Action):
    """
    This action's active member is set to True after a do and to False after
    an undo.
    
    Used to verify that a State correctly triggers the do and undo actions.
    """
    def __init__(self):
        self.active = False
        
    def do(self):
        self.active = True
        
    def undo(self):
        self.active = False


class CountAction(Action):
    """
    This action counts how many times it's do and undo methods get called
    """
    def __init__(self):
        self.do_count = 0
        self.undo_count = 0

    def do(self):
        self.do_count += 1

    def undo(self):
        self.undo_count += 1

class TriggerEventFilter(EventFilter):
    """
    This event filter can be triggered by simply calling its do_callback function.
    
    Used to fake events and see the effect on the FSM.
    """
    def __init__(self, next_state):
        EventFilter.__init__(self, next_state)
        self.toggle_on_callback = False
    
    def install_handlers(self, callback, **kwargs):
        """
        Forsakes the incoming callback function and just set the inner one.
        """
        self._callback = self._inner_cb
    
    def _inner_cb(self, event_filter):
        self.toggle_on_callback = not self.toggle_on_callback

class FakeEventFilter(TriggerEventFilter):
    """
    This is a fake event that is connected to the tutorial.
    
    The difference between this one and the TriggerEventFilter is that the
    tutorial's set_state will be called on the callback.
    
    Do not forget to add the do_callback() after creating the object.
    """
    def set_tutorial(self, tutorial):
        self.tutorial = tutorial
    
    def _inner_cb(self, event_filter):
        self.toggle_on_callback = not self.toggle_on_callback
        self.tutorial.set_state(event_filter.get_next_state())

class OnceWrapperTests(unittest.TestCase):
    def test_onceaction_toggle(self):
        """
        Validate that the OnceWrapper wrapper works properly using the
        CountAction
        """
        act = CountAction()
        wrap = OnceWrapper(act)

        assert act.do_count == 0, "do() should not have been called in __init__()"
        assert act.undo_count == 0, "undo() should not have been called in __init__()"

        wrap.undo()

        assert act.undo_count == 0, "undo() should not be called if do() has not been called"

        wrap.do()
        assert act.do_count == 1, "do() should have been called once"

        wrap.do()
        assert act.do_count == 1, "do() should have been called only once"

        wrap.undo()
        assert act.undo_count == 1, "undo() should have been called once"

        wrap.undo()
        assert act.undo_count == 1, "undo() should have been called only once"


# State testing class
class StateTest(unittest.TestCase):
    """
    This class has to test the State interface as well as the expected 
    functionality.
    """
    
    def test_action_toggle(self):
        """
        Validate that the actions are properly done on setup and undone on
        teardown.
        
        Pretty awesome.
        """
        act = TrueWhileActiveAction()
        
        state = State("action_test", action_list=[act])
        
        assert act.active == False, "Action is not initialized properly"
        
        state.setup()
        
        assert act.active == True, "Action was not triggered properly"
        
        state.teardown()
        
        assert act.active == False, "Action was not undone properly"
    
    def test_event_filter(self):
        """
        Tests the fact that the event filters are correctly installed on setup
        and uninstalled on teardown.
        """
        event_filter = TriggerEventFilter("second_state")
        
        state = State("event_test", event_filter_list=[event_filter])
        state.set_tutorial(SimpleTutorial())
        
        assert event_filter.toggle_on_callback == False, "Wrong init of event_filter"
        assert event_filter._callback == None, "Event filter has a registered callback before installing handlers"
        
        state.setup()
        
        assert event_filter._callback != None, "Event filter did not register callback!"
        
        # 'Trigger' the event - This is more like a EventFilter test.
        event_filter.do_callback()
        
        assert event_filter.toggle_on_callback == True, "Event filter did not execute callback"
        
        state.teardown()
        
        assert event_filter._callback == None, "Event filter did not remove callback properly"
    
    def test_warning_set_tutorial_twice(self):
        """
        Calls set_tutorial twice and expects a warning on the second.
        """
        state = State("start_state")
        tut = SimpleTutorial("First")
        tut2 = SimpleTutorial("Second")
        
        state.set_tutorial(tut)
        
        try:
            state.set_tutorial(tut2)
            assert False, "No RuntimeWarning was raised on second set_tutorial"
        except :
            pass
    
class FSMTest(unittest.TestCase):
    """
    This class needs to text the interface and functionality of the Finite 
    State Machine.
    """

    def test_sample_usage(self):
        act_init = TrueWhileActiveAction()
        act_second = TrueWhileActiveAction()
        
        event_init = FakeEventFilter("SECOND")
        
        content = {
            "INIT": State("INIT", action_list=[act_init],event_filter_list=[event_init]),
            "SECOND": State("SECOND", action_list=[act_second])
        }
        
        fsm = FiniteStateMachine("SampleUsage", state_dict=content)
        
        assert fsm is not None, "Unable to create FSM"
        
        tut = Tutorial("SampleUsageTutorial", fsm)
        
        tut.attach(None)
        event_init.set_tutorial(tut)
        
        assert fsm.current_state.name == "INIT", "Unable to set state to initial state"
        
        assert act_init.active, "FSM did not call the state's action DO properly"
        
        # Trigger the event of the INIT state
        event_init.do_callback()
        
        assert act_init.active == False, "FSM did not teardown INIT properly"
        
        assert fsm.current_state.name == "SECOND", "FSM did not switch to SECOND state"
        
        assert act_second.active == True, "FSM did not setup SECOND properly"
        
        tut.detach()
        
        assert act_second.active == False, "FSM did not teardown SECOND properly"

class FSMExplorationTests(unittest.TestCase):
    def buildFSM(self):
        """
        Create a sample FSM to play with in the rest of the tests.
        """
        st1 = State("INIT")
        st1.add_action(CountAction())
        st1.add_event_filter(TriggerEventFilter("Second"))
        st1.add_event_filter(TriggerEventFilter("Third"))
        
        st2 = State("Second")
        st2.add_action(TrueWhileActiveAction())
        st2.add_event_filter(TriggerEventFilter("Third"))
        st2.add_event_filter(TriggerEventFilter("Fourth"))
        
        st3 = State("Third")
        st3.add_action(CountAction())
        st3.add_action(TrueWhileActiveAction())

        self.fsm = FiniteStateMachine("ExplorationTestingMachine")
        self.fsm.add_state(st1)
        self.fsm.add_state(st2)
        self.fsm.add_state(st3)
    
    def validate_following_states(self, in_name, out_name_list):
        nextStates = self.fsm.get_following_states(in_name)
        assert list(nextStates).sort() == list(out_name_list).sort(), \
            "The following states for %s are wrong : got %s"%\
            (in_name, str(nextStates))
            
    def validate_previous_states(self, in_name, out_name_list):
        prevStates = self.fsm.get_previous_states(in_name)
        assert list(prevStates).sort() == list(out_name_list).sort(), \
            "The following states for %s are wrong : got %s"%\
            (in_name, str(prevStates))
    
    def test_get_following_states(self):
        self.buildFSM()
        self.validate_following_states("INIT", ('Second', 'Third'))
        
        self.validate_following_states("Second", ("Third", "Fourth"))
        
        self.validate_following_states("Third", ())
    
    def test_get_previous_states(self):
        self.buildFSM()
        self.validate_previous_states("INIT", ())
        
        self.validate_previous_states("Second", ("INIT"))
        
        self.validate_previous_states("Third", ("INIT", "Second"))
        
        self.validate_previous_states("Fourth", ("Second"))
    
if __name__ == "__main__":
    unittest.main()