Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/tests/vaulttests.py
blob: e45adcb18593eb59efad8317a6f18a85fd24627d (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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
# 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
"""
Vault Tests

This module contains all the tests that pertain to the usage of the Tutorius
Vault object. The Vault manage all the interactions with the various Tutorius
modules dans the local file system. This include saving a tutorial to a .xml
file, generating the metadata file, finding existing tutorials in the file
system and building chosen tutorials.
"""

import unittest

import os
import shutil
import zipfile
import cStringIO

from sugar.tutorius import addon
from sugar.tutorius.tutorial import Tutorial
from sugar.tutorius.actions import *
from sugar.tutorius.filters import *
from sugar.tutorius.vault import Vault, XMLSerializer, Serializer, TutorialBundler

import sugar

from uuid import uuid1

class VaultInterfaceTest(unittest.TestCase):
    """
    Test the high-level interfaces functions of the Vault
    """
    
    def create_test_metadata_file(self, ini_file_path, guid):
        ini_file = open(ini_file_path, 'wt')
        ini_file.write("[GENERAL_METADATA]\n")
        ini_file.write('guid=' + str(guid) + '\n')
        ini_file.write('name=TestTutorial1\n')
        ini_file.write('version=1\n')
        ini_file.write('description=This is a test tutorial 1\n')
        ini_file.write('rating=3.5\n')
        ini_file.write('category=Test\n')
        ini_file.write('publish_state=false\n')
        ini_file.write('[RELATED_ACTIVITIES]\n')
        ini_file.write('org.laptop.TutoriusActivity = 1\n')
        ini_file.write('org.laptop.Writus = 1\n')
        ini_file.close()
    
    
    def setUp(self):
        os.environ["SUGAR_BUNDLE_PATH"] = os.path.join(sugar.tutorius.vault._get_store_root(), 'test_bundle_path')
        path = os.path.join(sugar.tutorius.vault._get_store_root(), 'test_bundle_path', 'data', 'tutorius', 'data')
        if os.path.isdir(path) != True:
            os.makedirs(path)
        
        # Generate a first test GUID
        self.test_guid = uuid1()
        self.guid_path = os.path.join(sugar.tutorius.vault._get_store_root(),str(self.test_guid))
        os.mkdir(self.guid_path)
        
        # Create a first dummy .ini file
        self.ini_file_path = os.path.join(self.guid_path, "meta.ini")
        self.create_test_metadata_file(self.ini_file_path, self.test_guid)
        
        # Generate a second test GUID
        self.test_guid2 = uuid1()
        self.guid_path2 = os.path.join(sugar.tutorius.vault._get_store_root(),str(self.test_guid2))
        os.mkdir(self.guid_path2)
        
        # Create a second dummy .ini file
        self.ini_file_path2 = os.path.join(self.guid_path2, "meta.ini")
        
        ini_file2 = open(self.ini_file_path2, 'wt')
        ini_file2.write("[GENERAL_METADATA]\n")
        ini_file2.write('guid=' + str(self.test_guid2) + '\n')
        ini_file2.write('name=TestTutorial2\n')
        ini_file2.write('version=2\n')
        ini_file2.write('description=This is a test tutorial 2\n')
        ini_file2.write('rating=4\n')
        ini_file2.write('category=Test2\n')
        ini_file2.write('publish_state=false\n')
        ini_file2.write('[RELATED_ACTIVITIES]\n')
        ini_file2.write('org.laptop.TutoriusActivity = 2\n')
        ini_file2.write('org.laptop.Writus = 1\n')
        ini_file2.write('org.laptop.Testus = 1\n')
        ini_file2.close()
        
        # Create a dummy fsm
        self.fsm = Tutorial("TestTutorial1")
        # Add a few states
        act1 = addon.create('BubbleMessage', message="Hi", position=[300, 450])
        ev1 = addon.create('GtkWidgetEventFilter', "0.12.31.2.2", "clicked")
        act2 = addon.create('BubbleMessage', message="Second message", position=[250, 150], tail_pos=[1,2])
        self.fsm.add_action("INIT", act1)
        st2 = self.fsm.add_state((act2,))
        self.fsm.add_transition("INIT",(ev1, st2))
        self.tuto_guid = uuid1()
        
        # Create a dummy metadata dictionnary
        self.test_metadata_dict = {}
        self.save_test_guid = uuid1()
        self.test_metadata_dict['name'] = 'TestTutorial1'
        self.test_metadata_dict['guid'] = str(self.save_test_guid)
        self.test_metadata_dict['version'] = '1'
        self.test_metadata_dict['description'] = 'This is a test tutorial 1'
        self.test_metadata_dict['rating'] = '3.5'
        self.test_metadata_dict['category'] = 'Test'
        self.test_metadata_dict['publish_state'] = 'false'
        activities_dict = {}
        activities_dict['org.laptop.tutoriusactivity'] = '1'
        activities_dict['org.laptop,writus'] = '1'
        self.test_metadata_dict['activities'] = activities_dict
        
    
    def test_installTutorials(self):
        
        # TODO : Test for erronous file too (not .xml, not .ini, not .zip, etc.)
         
        # create dummy tutorial        
        
        # create a test folder in the file
        # system outside the Vault
        test_path = os.path.join(os.getenv("HOME"),".sugar", 'default', 'tutorius', 'tmp')
        if os.path.isdir(test_path) == True:
            shutil.rmtree(os.path.join(os.getenv("HOME"),".sugar", 'default', 'tutorius', 'tmp'))
        os.makedirs(test_path)
        
        # Creat a dummy tutorial .xml file
        serializer = XMLSerializer()
        
        with file(os.path.join(test_path, 'tutorial.xml'), 'w') as fsmfile:
            serializer.save_tutorial(self.fsm, fsmfile)
        
        # Create a dummy tutorial metadata file
        self.create_test_metadata_file(os.path.join(test_path, 'meta.ini'), self.tuto_guid)
        
        #Zip these tutorials files in the pkzip file format
        archive_list = [os.path.join(test_path, 'meta.ini'), os.path.join(test_path, 'tutorial.xml')]
        
        zfilename = "TestTutorial.zip"
        
        zout = zipfile.ZipFile(os.path.join(test_path, zfilename), "w")
        for fname in archive_list:
            fname_splitted = fname.rsplit('/')
            file_only_name = fname_splitted[fname_splitted.__len__() - 1]
            zout.write(fname, file_only_name)
        zout.close()
        
        # test if the file is a valid pkzip file
        assert zipfile.is_zipfile(os.path.join(test_path, zfilename)) == True, "The zipping of the tutorial files failed."
        
        # test installTutorials function
        vault = Vault()
        
        install_return = vault.installTutorials(test_path, 'TestTutorial.zip', False)
        assert install_return != 2, "Tutorial install has returned an error"
        
        # check if the tutorial is now in the vault
        try :
            bundler = TutorialBundler(self.tuto_guid)
            bundler.get_tutorial_path(self.tuto_guid)
        except IOError:
            print("Cannot find the specified tutorial's GUID in the vault")
            

    def test_query(self):
        """
        Test the query function that return a list of tutorials (dictionnaries) that
        correspond to the specified parameters.
        """
        
        # Note : Temporary only test query that return ALL tutorials in the vault.
        # TODO : Test with varying parameters
        
        tutorial_list = Vault.query()
        
        if tutorial_list.__len__() < 2:
            assert False, 'Error, list doesnt have enough tutorial in it : ' + str(tutorial_list.__len__()) + ' element'
                    
        for tuto_dictionnary in tutorial_list:
            if tuto_dictionnary['name'] == 'TestTutorial1':
                related = tuto_dictionnary['activities']
                assert tuto_dictionnary['version'] == '1'
                assert tuto_dictionnary['description'] == 'This is a test tutorial 1'
                assert tuto_dictionnary['rating'] == '3.5'
                assert tuto_dictionnary['category'] == 'Test'
                assert tuto_dictionnary['publish_state'] == 'false'
                assert related.has_key('org.laptop.tutoriusactivity')
                assert related.has_key('org.laptop.writus')
                
            elif tuto_dictionnary['name'] == 'TestTutorial2':
                related = tuto_dictionnary['activities']
                assert tuto_dictionnary['version'] == '2'
                assert tuto_dictionnary['description'] == 'This is a test tutorial 2'
                assert tuto_dictionnary['rating'] == '4'
                assert tuto_dictionnary['category'] == 'Test2'
                assert tuto_dictionnary['publish_state'] == 'false'
                assert related.has_key('org.laptop.tutoriusactivity')
                assert related.has_key('org.laptop.writus')
                assert related.has_key('org.laptop.testus')
                
            else:
                assert False, 'list is empty or name property is wrong'
        
               
    def test_loadTutorial(self):
        """
        Test the opening of a tutorial from the vault by passing it is guid and
        returning the Tutorial object representation. This test verify that the
        initial underlying FSM and the new loaded one are equivalent.
        """
        
        # call test_installTutorials to be sure that the tuto is now in the Vault
        self.test_installTutorials()
        bundler = TutorialBundler(self.tuto_guid)
        test = bundler.get_tutorial_path(self.tuto_guid)
        # load tutorial created in the test_installTutorial function
        vault = Vault()
        reloaded_tuto = vault.loadTutorial(self.tuto_guid)
        
        # Compare the two FSMs
        assert reloaded_tuto.get_state_dict().keys() == self.fsm.get_state_dict().keys(), \
            'FSM underlying dictionary differ from original to reformed one'
            
    def test_saveTutorial(self):
        """
        This test verify the vault function that save a new tutorial (Tutorial object +metadata).
        """
            
        # Save the tutorial in the vault
        vault = Vault()
        tutorial = self.fsm
        vault.saveTutorial(tutorial, self.test_metadata_dict)
        
        # Get the tutorial back
        reloaded_tuto = vault.loadTutorial(self.save_test_guid)
        
        # Compare the two FSMs
        assert reloaded_tuto.get_state_dict().keys() == self.fsm.get_state_dict().keys(), \
            'FSM underlying dictionary differ from original to reformed one'
        
        # TODO : Compare the initial and reloaded metadata when vault.Query() will accept specifc argument
        # (so we can specifiy that we want only the metadata for this particular tutorial
        
    def test_update_metadata(self):
        """
        This test verify that the vault interface funciton update_metadata succesfully update a tutorial metadata.
        """
        # Create and save a tutorial
        tutorial = Tutorial('test')
        Vault.saveTutorial(tutorial, self.test_metadata_dict)
        
        bundler = TutorialBundler(self.save_test_guid)
        
        # Create a metadata dictionnary different than the initial one
        test_new_metadata_dict = {}
        test_new_metadata_dict['name'] = 'TestTutorial_modified'
        test_new_metadata_dict['guid'] = str(self.save_test_guid)
        test_new_metadata_dict['version'] = '3'
        test_new_metadata_dict['description'] = 'This is a test tutorial modified'
        test_new_metadata_dict['rating'] = '4.5'
        test_new_metadata_dict['category'] = 'Test_modified'
        test_new_metadata_dict['publish_state'] = 'true'
        new_activities_dict = {}
        new_activities_dict['org.laptop.tutoriusactivity'] = '2'
        new_activities_dict['org.laptop.writus'] = '2'
        test_new_metadata_dict['activities'] = new_activities_dict
        
        # Test update_metadata
        Vault.update_metadata(self.save_test_guid, test_new_metadata_dict)
        
        # Get the metadata back
        tutorial_list = Vault.query()
        
        new_metadata_found = False
        
        # Test that the metadata in the tutorial is indeed the new one
        for tuto_dictionnary in tutorial_list:
            if tuto_dictionnary['name'] == 'TestTutorial_modified':
                # Flag that indicate that the modified metadata has been found
                new_metadata_found = True
                related = tuto_dictionnary['activities']
                assert tuto_dictionnary['version'] == '3'
                assert tuto_dictionnary['description'] == 'This is a test tutorial modified'
                assert tuto_dictionnary['rating'] == '4.5'
                assert tuto_dictionnary['category'] == 'Test_modified'
                assert tuto_dictionnary['publish_state'] == 'true'
                assert related.has_key('org.laptop.tutoriusactivity')
                assert related.has_key('org.laptop.writus')
                
        # If false, new metadata hasn't been found in the vault
        assert new_metadata_found == True, 'Modified metadata not found in the vault'
    
        
    def test_add_delete_get_path_resource(self):
        """
        This test verify that the vault interface function add_resource succesfully add resource in the vault
        and return the new resource id. It also test the deletion of the resource.
        """
        # Path of an image file in the test folder
        test_path = os.path.join(os.getenv("HOME"),".sugar", 'default', 'tutorius', 'tmp')
        if os.path.isdir(test_path) == True:
            shutil.rmtree(os.path.join(os.getenv("HOME"),".sugar", 'default', 'tutorius', 'tmp'))
        os.makedirs(test_path)
        file_path = os.path.join(test_path, 'test_resource.svg')
        resource_file = open(file_path, 'wt')
        resource_file.write('test')
        resource_file.close()

        # Create and save a tutorial
        tutorial = Tutorial('test')
        Vault.saveTutorial(tutorial, self.test_metadata_dict)
        
        bundler = TutorialBundler(self.save_test_guid)
        tuto_path = bundler.get_tutorial_path(self.save_test_guid)
 
        # add the resource to the tutorial
        resource_id = Vault.add_resource(self.save_test_guid, file_path)
        
        # Check that the image file is now in the vault
        assert os.path.isfile(os.path.join(tuto_path, 'resources', resource_id)), 'image file not found in vault'
        
        # Check if get_resource_path Vault interface function is working
        vault_path = Vault.get_resource_path(self.save_test_guid, resource_id)
        
        assert os.path.isfile(vault_path), 'path returned is not a file'
        basename, extension = os.path.splitext(vault_path)
        assert extension == '.svg', 'wrong file path have been returned'
        
        # Delete the resource
        Vault.delete_resource(self.save_test_guid, resource_id)
        
        # Check that the resource is not in the vault anymore
        assert os.path.isfile(os.path.join(tuto_path, 'resources', resource_id)) == False, 'image file found in vault when it should have been deleted.'
    
    def test_get_tutorial_archive(self):
        """
        This test verify that the vault interface function get_tutorial_archive zip a tutorial and
        return the zipped archive object succesfully.
        """
        # Create and save a tutorial
        tutorial = Tutorial('test')
        Vault.saveTutorial(tutorial, self.test_metadata_dict)
        
        bundler = TutorialBundler(self.save_test_guid)
        
        # Add test ressources to the tutorial
        test_path = os.path.join(os.getenv("HOME"),".sugar", 'default', 'tutorius', 'tmp')
        if os.path.isdir(test_path) == True:
            shutil.rmtree(os.path.join(os.getenv("HOME"),".sugar", 'default', 'tutorius', 'tmp'))
        os.makedirs(test_path)
        file_path = os.path.join(test_path, 'test_resource.svg')
        resource_file = open(file_path, 'wt')
        resource_file.write('test')
        resource_file.close()
        
        resource_id = Vault.add_resource(self.save_test_guid, file_path)
        
        # Test get_tutorial_archive()
        archive_object = Vault.get_tutorial_archive(self.save_test_guid)
        
        # Write the archive data as a new file
        zip_path = str(self.save_test_guid) + '_test_.zip'
        file = open(zip_path, 'wt')
        file.write(archive_object)
        file.close()
        
        # Test if new zip is valid
        assert zipfile.is_zipfile(zip_path)
        # Remove test file
        os.remove(zip_path)
            
        
    
    def tearDown(self):
        folder = os.path.join(os.getenv("HOME"),".sugar", 'default', 'tutorius', 'data');
        for file in os.listdir(folder):
            file_path = os.path.join(folder, file)
            shutil.rmtree(file_path)
        
        if (os.path.isdir(os.path.join(os.getenv("HOME"),".sugar", 'default', 'tutorius', 'tmp'))):       
            shutil.rmtree(os.path.join(os.getenv("HOME"),".sugar", 'default', 'tutorius', 'tmp'))


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

class XMLSerializerTest(unittest.TestCase):
    """
    Tests the transformation of XML to FSM, then back.
    """

    def setUp(self):
        # Create the sample FSM
        self.fsm = Tutorial("TestTutorial1")
        
        # Add a few states
        act1 = addon.create('BubbleMessage', message="Hi", position=[300, 450])
        ev1 = addon.create('GtkWidgetEventFilter', "0.12.31.2.2", "clicked")
        act2 = addon.create('BubbleMessage', message="Second message", position=[250, 150], tail_pos=[1,2])
        
        self.fsm.add_action("INIT",act1)
        st2 = self.fsm.add_state((act2,))
        self.fsm.add_transition("INIT",(ev1, st2))
        
        self.uuid = uuid1()
        
    def tearDown(self):
        """
        Nothing to do anymore.
        """
        pass

    def create_test_metadata(self, file_obj, guid):
        file_obj.write("[GENERAL_METADATA]\n")
        file_obj.write('guid=' + str(guid) + '\n')
        file_obj.write('name=TestTutorial1\n')
        file_obj.write('version=1\n')
        file_obj.write('description=This is a test tutorial 1\n')
        file_obj.write('rating=3.5\n')
        file_obj.write('category=Test\n')
        file_obj.write('publish_state=false\n')
        file_obj.write('[RELATED_ACTIVITIES]\n')
        file_obj.write('org.laptop.TutoriusActivity = 1\n')
        file_obj.write('org.laptop.Writus = 1\n')
    
    def test_save_and_load(self):
        """
        Writes an FSM to disk, then compares the file to the expected results.
        Load up the written FSM and compare it with the object representation.
        """
        xml_ser = XMLSerializer()
        tuto_file = cStringIO.StringIO()
        xml_ser.save_tutorial(self.fsm, tuto_file)

        xml_ser = XMLSerializer()
        load_tuto_file = cStringIO.StringIO(tuto_file.getvalue())
        loaded_fsm = xml_ser.load_tutorial(load_tuto_file)
        
        # Compare the two FSMs
        assert loaded_fsm == self.fsm, "Loaded FSM differs from original one"
    
    def test_all_actions(self):
        """
        Inserts all the known action types in a FSM, then attempt to load it.
        """
        fsm = Tutorial("TestActions")
        tuto_file = cStringIO.StringIO()
        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:
            fsm.add_action("INIT", action)
            
        xml_ser = XMLSerializer()
        xml_ser.save_tutorial(fsm, tuto_file)
        load_tuto_file = cStringIO.StringIO(tuto_file.getvalue())
        
        reloaded_fsm = xml_ser.load_tutorial(load_tuto_file)
        # Compare the two FSMs
        assert reloaded_fsm == fsm, "Loaded FSM differs from original one"
        assert fsm.get_action_dict() == reloaded_fsm.get_action_dict(), \
            "Actions should be the same"
        
    def test_all_filters(self):
        """
        Inserts all the known action filters in a FSM, then attempt to load it.
        """
        fsm = Tutorial("TestFilters")
        tuto_file = cStringIO.StringIO()
        
        ev1 = addon.create('TimerEvent', 1000)
        ev2 = addon.create('GtkWidgetEventFilter', object_id="0.0.1.1.0.0.1", event_name="clicked")
        ev3 = addon.create('GtkWidgetTypeFilter',  "0.0.1.1.1.2.3", text="Typed stuff")
        ev4 = addon.create('GtkWidgetTypeFilter',  "0.0.1.1.1.2.3", strokes="acbd")
        filters = [ev1, ev2, ev3, ev4]
        
        for efilter in filters:
            fsm.add_transition("INIT", (efilter, 'END'))
            
        xml_ser = XMLSerializer()
        xml_ser.save_tutorial(fsm, tuto_file)
        load_tuto_file = cStringIO.StringIO(tuto_file.getvalue())

        reloaded_fsm = xml_ser.load_tutorial(load_tuto_file)
        # Compare the two FSMs
        assert reloaded_fsm == fsm, "Loaded FSM differs from original one"
        assert fsm.get_transition_dict() == reloaded_fsm.get_transition_dict(), \
            "Transitions should be the same"
    

class TutorialBundlerTests(unittest.TestCase):
    """
    TutorialBundler tests

    This module contains all the tests for the storage mecanisms for tutorials
    This mean testing saving and loading tutorial, .ini file management and
    adding resources to tutorial
    """
    
    def setUp(self):
        os.environ["SUGAR_BUNDLE_PATH"] = os.path.join(sugar.tutorius.vault._get_store_root(), 'test_bundle_path')
        path = os.path.join(sugar.tutorius.vault._get_store_root(), 'test_bundle_path')
        if os.path.isdir(path) != True:
            os.makedirs(path)
        
        #generate a test GUID
        self.test_guid = uuid1()
        self.guid_path = os.path.join(sugar.tutorius.vault._get_store_root(),str(self.test_guid))
        os.mkdir(self.guid_path)
        
        self.ini_file = os.path.join(self.guid_path, "meta.ini")
        
        ini_file = open(self.ini_file, 'wt')
        ini_file.write('[GENERAL_METADATA]\n')
        ini_file.write('guid=' + str(self.test_guid) + '\n')
        ini_file.write('name=TestTutorial\n')
        ini_file.write('version=1\n')
        ini_file.write('description=This is a test tutorial\n')
        ini_file.write('rating=3.5\n')
        ini_file.write('category=Test\n')
        ini_file.write('publish_state=false\n')
        ini_file.write('[RELATED_ACTIVITES]\n')
        ini_file.write('org.laptop.TutoriusActivity = 1\n')
        ini_file.write('org.laptop.Writus = 1\n')
        ini_file.close()
        
    def tearDown(self):
        os.remove(self.ini_file)
        os.rmdir(self.guid_path)
        
        folder = os.path.join(os.getenv("HOME"),".sugar", 'default', 'tutorius', 'data');
        for file in os.listdir(folder):
            file_path = os.path.join(folder, file)
            shutil.rmtree(file_path)


if __name__ == "__main__":
    unittest.main()