# 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 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): self.__old_home = os.getenv("HOME") # Create a temp vault path so to not add trash data to the real vault os.environ["HOME"] = os.path.join(os.getenv("HOME"), 'temp_vault_tests') 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. FOR_TEST\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) # Create 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[-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. """ # Test the return of all the tutorials tutorial_list = Vault.query() if len(tutorial_list) < 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. FOR_TEST' 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' # Test the return of just a given tutorial with a given keyword present in one # or more of is metadata fields. tutorial_list = Vault.query(keyword=['FOR_TEST']) # Should return only tutorial with metadata like tutorial # 2 if len(tutorial_list) == 0: assert False, 'Error on keyword, at least 1 tutorial should has been returned. ' related = tutorial_list[0]['activities'] assert tutorial_list[0]['version'] == '2' assert tutorial_list[0]['description'] == 'This is a test tutorial 2. FOR_TEST' assert tutorial_list[0]['rating'] == '4' assert tutorial_list[0]['category'] == 'Test2' assert tutorial_list[0]['publish_state'] == 'false' assert related.has_key('org.laptop.tutoriusactivity') assert related.has_key('org.laptop.writus') assert related.has_key('org.laptop.testus') # Test the return of just a given tutorial with a given related activity in is metadata tutorial_list = Vault.query(relatedActivityNames=['org.laptop.testus']) # Should return only tutorials like tutorial # 2 if len(tutorial_list) == 0: assert False, 'Error on related activity, at least 1 tutorial should has been returned. ' related = tutorial_list[0]['activities'] assert tutorial_list[0]['version'] == '2' assert tutorial_list[0]['description'] == 'This is a test tutorial 2. FOR_TEST' assert tutorial_list[0]['rating'] == '4' assert tutorial_list[0]['category'] == 'Test2' assert tutorial_list[0]['publish_state'] == 'false' assert related.has_key('org.laptop.tutoriusactivity') assert related.has_key('org.laptop.writus') assert related.has_key('org.laptop.testus') # Test the return of just a given tutorial with a given category in is metadata tutorial_list = Vault.query(category=['test']) # Should return only tutorials like tutorial # 1 if len(tutorial_list) == 0: assert False, 'Error on category, at least 1 tutorial should has been returned. ' related = tutorial_list[0]['activities'] assert tutorial_list[0]['version'] == '1' assert tutorial_list[0]['description'] == 'This is a test tutorial 1' assert tutorial_list[0]['rating'] == '3.5' assert tutorial_list[0]['category'] == 'Test' assert tutorial_list[0]['publish_state'] == 'false' assert related.has_key('org.laptop.tutoriusactivity') assert related.has_key('org.laptop.writus') 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')) # Restore home env variable to true value os.environ["HOME"] = self.__old_home 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): self.__old_home = os.getenv("HOME") # Create a temp vault path so to not add trash data to the real vault os.environ["HOME"] = os.path.join(os.getenv("HOME"), 'temp_vault_tests') # 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): # Restore home env variable to true value os.environ["HOME"] = self.__old_home 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): self.__old_home = os.getenv("HOME") # Create a temp vault path so to not add trash data to the real vault os.environ["HOME"] = os.path.join(os.getenv("HOME"), 'temp_vault_tests') 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) # Restore home env variable to true value os.environ["HOME"] = self.__old_home if __name__ == "__main__": unittest.main()