From 926238a2c54daae80d4c561b4cda8546d40173a7 Mon Sep 17 00:00:00 2001 From: JCTutorius Date: Wed, 21 Oct 2009 05:06:48 +0000 Subject: vault merge --- (limited to 'tests/vaulttests.py') diff --git a/tests/vaulttests.py b/tests/vaulttests.py new file mode 100644 index 0000000..02c34e8 --- /dev/null +++ b/tests/vaulttests.py @@ -0,0 +1,516 @@ +# Copyright (C) 2009, Tutorius.org +# Copyright (C) 2009, Jean-Christophe Savard +# +# 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 + +from sugar.tutorius import addon +from sugar.tutorius.core import State, FiniteStateMachine, 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 = 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") + 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, 'Second') + st2 = State("Second") + st2.add_action(act2) + self.fsm.add_state(st1) + self.fsm.add_state(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() + + serializer.save_fsm(self.fsm, 'tutorial.xml', test_path) + + # 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 + reloaded_fsm = reloaded_tuto.state_machine + + assert reloaded_fsm._states.get("INIT").name == self.fsm._states.get("INIT").name, \ + 'FSM underlying dictionary differ from original to reformed one' + assert reloaded_fsm._states.get("Second").name == self.fsm._states.get("Second").name, \ + 'FSM underlying dictionary differ from original to reformed one' + assert reloaded_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(reloaded_fsm.get_action_list()) == 0, "FSM should not have any actions on itself" + + 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 = Tutorial('test', 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 + reloaded_fsm = reloaded_tuto.state_machine + + assert reloaded_fsm._states.get("INIT").name == self.fsm._states.get("INIT").name, \ + 'FSM underlying dictionary differ from original to reformed one' + assert reloaded_fsm._states.get("Second").name == self.fsm._states.get("Second").name, \ + 'FSM underlying dictionary differ from original to reformed one' + assert reloaded_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(reloaded_fsm.get_action_list()) == 0, "FSM should not have any actions on itself" + + # 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 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_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): + + 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) + + # 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") + 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, 'Second') + + 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(sugar.tutorius.vault._get_store_root(), 'test_bundle_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) + + def create_test_metadata(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 test_save(self): + """ + Writes an FSM to disk, then compares the file to the expected results. + "Remove" boolean argument specify if the test data must be removed or not + """ + xml_ser = XMLSerializer() + os.makedirs(os.path.join(sugar.tutorius.vault._get_store_root(), str(self.uuid))) + xml_ser.save_fsm(self.fsm, sugar.tutorius.vault.TUTORIAL_FILENAME, os.path.join(sugar.tutorius.vault._get_store_root(), str(self.uuid))) + self.create_test_metadata(os.path.join(sugar.tutorius.vault._get_store_root(), str(self.uuid), 'meta.ini'), self.uuid) + + + def test_save_and_load(self): + """ + Load up the written FSM and compare it with the object representation. + """ + self.test_save() + xml_ser = XMLSerializer() + + 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 reformed one' + assert loaded_fsm._states.get("Second").name == self.fsm._states.get("Second").name, \ + 'FSM underlying dictionary differ from original to 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)) + + # TODO : Cannot do object equivalence, must check equality of all underlying object + # assert self.fsm == reloaded_fsm, "Expected equivalence before saving vs after loading." + + def test_all_filters(self): + """ + Inserts all the known action filters in a FSM, then attempt to load it. + """ + st = State("INIT") + + 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 filter in filters: + st.add_event_filter(filter, '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)) + + # TODO : Cannot do object equivalence, must check equality of all underlying object + # assert self.fsm == reloaded_fsm, "Expected equivalence before saving vs after loading." + + +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() -- cgit v0.9.1