diff options
Diffstat (limited to 'tests/vaulttests.py')
-rw-r--r-- | tests/vaulttests.py | 489 |
1 files changed, 489 insertions, 0 deletions
diff --git a/tests/vaulttests.py b/tests/vaulttests.py new file mode 100644 index 0000000..ca61225 --- /dev/null +++ b/tests/vaulttests.py @@ -0,0 +1,489 @@ +# 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 + + vault = Vault() + + 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_add_delete_get_path_ressource(self): + """ + This test verify that the vault interface function add_ressource succesfully add ressource in the vault + and return the new ressource id. It also test the deletion of the ressource. + """ + # Path of an image file in the test folder + image_path = os.path.join(os.getcwd(), 'tests', 'ressources', 'icon.svg') + assert os.path.isfile(image_path), 'cannot find the test image file' + + # Create and save a tutorial + Vault.saveTutorial(self.fsm, self.test_metadata_dict) + + bundler = TutorialBundler(self.save_test_guid) + tuto_path = bundler.get_tutorial_path(self.save_test_guid) + + # add the ressource to the tutorial + ressource_id = Vault.add_resource(self.save_test_guid, image_path) + + # Check that the image file is now in the vault + assert os.path.isfile(os.path.join(tuto_path, 'ressources', ressource_id)), 'image file not found in vault' + + # Check if get_ressource_path Vault interface function is working + vault_path = Vault.get_resource_path(self.save_test_guid, ressource_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 ressource + Vault.delete_resource(self.save_test_guid, ressource_id) + + # Check that the ressource is not in the vault anymore + assert os.path.isfile(os.path.join(tuto_path, 'ressources', ressource_id)) == False, 'image file found in vault when it should have been deleted.' + + 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 ressources 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() |