Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/tests/serializertests.py
blob: c939b7acdb7c0e10320257df851e09c460697a30 (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
# Copyright (C) 2009, Tutorius.org
# Copyright (C) 2009, Jean-Christophe Savard <savard.jean.christophe@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
"""
Serialization Tests

This module contains all the tests that pertain to the usage of the Tutorius
Serializer object. This means testing saving a tutorial dictionary to a .tml
file, loading the list of tutorials for this activity and building chosen
tutorial.
"""

import unittest

import os
import shutil

from sugar.tutorius import bundler, addon
from sugar.tutorius.core import State, FiniteStateMachine
from sugar.tutorius.actions import *
from sugar.tutorius.filters import *
from sugar.tutorius.bundler import XMLSerializer, Serializer
import sugar
from uuid import uuid1

class SerializerInterfaceTest(unittest.TestCase):
    """
    For completeness' sake.
    """
    def test_save(self):
        ser = Serializer()
        
        try:
            ser.save_fsm(None)
            assert False, "save_fsm() should throw an unimplemented error"
        except:
            pass
            
    def test_load(self):
        ser = Serializer()
        
        try:
            ser.load_fsm(str(uuid.uuid1()))
            assert False, "load_fsm() should throw an unimplemented error"
        except:
            pass

class XMLSerializerTest(unittest.TestCase):
    """
    Tests the transformation of XML to FSM, then back.
    """
    def setUp(self):
        # Make the serializer believe the test is in a activity path
        self.testpath = "/tmp/testdata/"
        os.environ["SUGAR_BUNDLE_PATH"] = self.testpath
        os.environ["SUGAR_PREFIX"] = self.testpath
        os.environ["SUGAR_PROFILE"] = 'test'
##        os.mkdir(sugar.tutorius.bundler._get_store_root())
        
        # Create the sample FSM
        self.fsm = FiniteStateMachine("testingMachine")
        
        # Add a few states
        act1 = addon.create('BubbleMessage', message="Hi", position=[300, 450])
        ev1 = addon.create('GtkWidgetEventFilter', "0.12.31.2.2", "clicked", "Second")
        act2 = addon.create('BubbleMessage', message="Second message", position=[250, 150], tail_pos=[1,2])
        
        st1 = State("INIT")
        st1.add_action(act1)
        st1.add_event_filter(ev1)
        
        st2 = State("Second")
        
        st2.add_action(act2)
        
        self.fsm.add_state(st1)
        self.fsm.add_state(st2)
        
        self.uuid = uuid1()
        
        # Flag to set to True if the output can be deleted after execution of 
        # the test
        self.remove = True
        
    def tearDown(self):
        """
        Removes the created files, if need be.
        """
        if self.remove == True:
            shutil.rmtree(os.path.join(os.getenv("HOME"),".sugar",os.getenv("SUGAR_PROFILE")))
            if os.path.isdir(self.testpath):
                shutil.rmtree(self.testpath)
    
    def test_save(self):
        """
        Writes an FSM to disk, then compares the file to the expected results.
        "Remove" boolean member specifies if the test data must be removed or not
        """
        xml_ser = XMLSerializer()
        os.makedirs(os.path.join(sugar.tutorius.bundler._get_store_root(), str(self.uuid)))
        xml_ser.save_fsm(self.fsm, bundler.TUTORIAL_FILENAME, os.path.join(sugar.tutorius.bundler._get_store_root(), str(self.uuid)))

    def test_save_and_load(self):
        """
        Load up the written FSM and compare it with the object representation.
        """
        self.test_save()
        testpath = "/tmp/testdata/"
        #rpdb2.start_embedded_debugger('flakyPass')
        xml_ser = XMLSerializer()
        
        # This interface needs to be redone... It's not clean because there is 
        # a responsibility mixup between the XML reader and the bundler.
        loaded_fsm = xml_ser.load_fsm(str(self.uuid))
        
        # Compare the two FSMs
        assert loaded_fsm._states.get("INIT").name == self.fsm._states.get("INIT").name, \
            'FSM underlying dictionary differ from original to pickled/reformed one'
        assert loaded_fsm._states.get("Second").name == self.fsm._states.get("Second").name, \
            'FSM underlying dictionary differ from original to pickled/reformed one'
        assert loaded_fsm._states.get("INIT").get_action_list()[0].message == \
            self.fsm._states.get("INIT").get_action_list()[0].message, \
            'FSM underlying State underlying Action differ from original to reformed one'
        assert len(loaded_fsm.get_action_list()) == 0, "FSM should not have any actions on itself"
    
    def test_all_actions(self):
        """
        Inserts all the known action types in a FSM, then attempt to load it.
        """
        st = State("INIT")
        
        act1 = addon.create('BubbleMessage', "Hi!", position=[10,120], tail_pos=[-12,30])
        act2 = addon.create('DialogMessage', "Hello again.", position=[120,10])
        act3 = addon.create('WidgetIdentifyAction')
        act4 = addon.create('DisableWidgetAction', "0.0.0.1.0.0.0")
        act5 = addon.create('TypeTextAction', "0.0.0.1.1.1.0.0", "New text")
        act6 = addon.create('ClickAction', "0.0.1.0.1.1")
        act7 = addon.create('OnceWrapper', action=act1)
        act8 = addon.create('ChainAction', actions=[act1, act2, act3, act4])
        actions = [act1, act2, act3, act4, act5, act6, act7, act8]
        
        for action in actions:
            st.add_action(action)
            
        self.fsm.remove_state("Second")
        self.fsm.remove_state("INIT")
        self.fsm.add_state(st)
        
        xml_ser = XMLSerializer()
        
        self.test_save()

        reloaded_fsm = xml_ser.load_fsm(str(self.uuid))
        assert self.fsm.is_identical(reloaded_fsm), "Expected equivalence before saving vs after loading."
        
    def test_all_filters(self):
        """
        Inserts all the known action types in a FSM, then attempt to load it.
        """
        st = State("INIT")
        
        ev1 = addon.create('TimerEvent', "Second", 1000)
        ev2 = addon.create('GtkWidgetEventFilter', next_state="Second", object_id="0.0.1.1.0.0.1", event_name="clicked")
        ev3 = addon.create('GtkWidgetTypeFilter', "Second", "0.0.1.1.1.2.3", text="Typed stuff")
        ev4 = addon.create('GtkWidgetTypeFilter', "Second", "0.0.1.1.1.2.3", strokes="acbd")
        filters = [ev1, ev2, ev3, ev4]
        
        for filter in filters:
            st.add_event_filter(filter)
            
        self.fsm.remove_state("INIT")
        self.fsm.add_state(st)
        
        xml_ser = XMLSerializer()
        
        self.test_save()
        
        reloaded_fsm = xml_ser.load_fsm(str(self.uuid))

        assert self.fsm.is_identical(reloaded_fsm), "Expected equivalence before saving vs after loading."
    
if __name__ == "__main__":
    unittest.main()