def handleExtractPackage(self, client, filename): """ Create a new package consisting of the current node and export """ filename = Path(filename) saveDir = filename.dirname() if saveDir and not saveDir.exists(): client.alert(_(u'Cannot access directory named ') + unicode(saveDir) + _(u'. Please use ASCII names.')) return if not filename.lower().endswith('.elp'): filename += '.elp' if Path(filename).exists(): client.alert(_(u'EXPORT FAILED.\n"%s" already exists.\n' 'Please try again with ' 'a different filename') % filename) return package = Package(filename.namebase) package.style = self.package.style package.author = self.package.author extractNode = self.package.currentNode.clone() extractNode.mergeIntoPackage(package) package.root = package.currentNode = extractNode package.save(filename) client.alert(_(u'Package saved to: %s' % filename))
class Saver(): def __init__(self,outputfilename="prova2.elp",titol="Exportacio de LliureX"): self._outputfile = outputfilename self._titol = titol self.document = Package('LLiureX') self.document.set_name('Lliurex') self.document.set_description('Lliurex') self.document.set_author('Lliurex') self.document.set_title('Documentacio LLiurex') def addWikipedia(self,title,url,parent): W = WikipediaIdeviceLliurex(url) W.set_title(title) W.edit = False W.loadArticle("") W.undo = False parent.addIdevice(W) def save(self): self.document.save(self._outputfile) def AddNode(self,parent,titol): Fill = parent.createChild(); Fill.setTitle(titol) return Fill def getRoot(self): return self.document.root
def handleExtractPackage(self, client, filename, existOk): """ Create a new package consisting of the current node and export 'existOk' means the user has been informed of existance and ok'd it """ filename = Path(filename) saveDir = filename.dirname() if saveDir and not saveDir.exists(): client.alert(_(u'Cannot access directory named ') + unicode(saveDir) + _(u'. Please use ASCII names.')) return if not filename.lower().endswith('.elp'): filename += '.elp' if Path(filename).exists() and existOk != 'true': msg = _(u'"%s" already exists.\nPlease try again with a different filename') % filename client.alert(_(u'EXTRACT FAILED!\n%s' % msg)) return try: package = Package(filename.namebase) package.style = self.package.style package.author = self.package.author extractNode = self.package.currentNode.clone() extractNode.mergeIntoPackage(package) package.root = package.currentNode = extractNode package.save(filename) except Exception, e: client.alert(_('EXTRACT FAILED!\n%s' % str(e))) raise
def __exportIdevice(self, filename): """ export the current generic idevices. """ if not filename.endswith('.idp'): filename = filename + '.idp' name = Path(filename).namebase package = Package(name) package.idevices.append(self.editorPane.idevice.clone()) package.save(filename)
def __exportIdevice(self, filename): """ export the current generic idevices. """ if not filename.endswith(".idp"): filename = filename + ".idp" name = Path(filename).namebase package = Package(name) package.idevices.append(self.editorPane.idevice.clone()) package.save(filename)
def __exportIdevice(self, filename): """ export the current generic idevices. """ if not filename.endswith('.idp'): filename = filename + '.idp' name = Path(filename).namebase package = Package(name) for idevice in self.ideviceStore.generic: package.idevices.append(idevice.clone()) package.save(filename)
def createPackageFromTemplate(self, templateBase): """ Creates a new package from Template """ log.debug(u"createPackageFromTemplate") package = Package.load(templateBase, isTemplate=True) package.set_templateFile(str(templateBase.basename().splitext()[0])) # Make up an initial unique name i = 1 name = u"newPackage" while name in self.loaded: name = u"newPackage" + unicode(i) i += 1 # Prevent the package from opening on the last node edited package.currentNode = package.root package.name = name package.filename = "" # We have to make sure the DocType of the package is the one selected # in preferences and not the one used to save de template package.docType = G.application.config.docType if G.application.config.locale.split('_')[0] != 'zh': package.lang = G.application.config.locale.split('_')[0] else: package.lang = G.application.config.locale package.translatePackage() package.isChanged = False self.loaded[package.name] = package return package
def _loadPackage(self, client, filename, newLoad=True, destinationPackage=None): """Load the package named 'filename'""" try: encoding = sys.getfilesystemencoding() if encoding is None: encoding = 'utf-8' filename2 = toUnicode(filename, encoding) log.debug("filename and path" + filename2) # see if the file exists AND is readable by the user try: open(filename2, 'rb').close() except IOError: filename2 = toUnicode(filename, 'utf-8') try: open(filename2, 'rb').close() except IOError: client.alert(_(u'File %s does not exist or is not readable.') % filename2) return None package = Package.load(filename2, newLoad, destinationPackage) if package is None: raise Exception(_("Couldn't load file, please email file to [email protected]")) except Exception, exc: if log.getEffectiveLevel() == logging.DEBUG: client.alert(_(u'Sorry, wrong file format:\n%s') % unicode(exc)) else: client.alert(_(u'Sorry, wrong file format')) log.error(u'Error loading package "%s": %s' % (filename2, unicode(exc))) log.error(u'Traceback:\n%s' % traceback.format_exc()) raise
def createPackageFromTemplate(self, templateBase, is_new_package=False): """ Creates a new package from Template """ log.debug(u"createPackageFromTemplate") package = Package.load(templateBase, isTemplate=True, is_new_package=is_new_package) package.set_templateFile(str(templateBase.basename().splitext()[0])) # Make up an initial unique name i = 1 name = u"newPackage" while name in self.loaded: name = u"newPackage" + unicode(i) i += 1 # Prevent the package from opening on the last node edited package.currentNode = package.root package.name = name package.filename = "" # We have to make sure the DocType of the package is the one selected # in preferences and not the one used to save de template package.docType = G.application.config.docType if G.application.config.locale.split('_')[0] != 'zh': package.lang = G.application.config.locale.split('_')[0] else: package.lang = G.application.config.locale package.translatePackage() package.isChanged = False self.loaded[package.name] = package return package
def setUp(self): """ Creates an application and almost launches it. """ # Make whatever config class that application uses only look for our # Set up our customised config file logFileName = Path('tmp/app data/test.conf') sys.argv[0] = 'exe/exe' Config._getConfigPathOptions = lambda s: [logFileName] if not logFileName.dirname().exists(): logFileName.dirname().makedirs() confParser = ConfigParser() self._setupConfigFile(confParser) confParser.write(logFileName) # Start up the app and friends if G.application is None: G.application = Application() self.app = G.application G.application = self.app self.app.loadConfiguration() self.app.preLaunch() self.client = FakeClient() self.package = Package('temp') self.session = FakeSession() self.app.webServer.root.bindNewPackage(self.package, self.session) self.mainpage = self.app.webServer.root.mainpages[ self.session.uid]['temp'] self.mainpage.idevicePane.client = self.client
def testExport(self): # Delete the output dir outdir = TempDirPath() G.application = Application() G.application.loadConfiguration() G.application.preLaunch() # Load a package package = Package.load('testing/testPackage2.elp') # Do the export style_dir = G.application.config.stylesDir / package.style exporter = WebsiteExport(G.application.config, style_dir, outdir) exporter.export(package) # Check that it all exists now assert outdir.isdir() assert (outdir / 'index.html').isfile() # Check that the style sheets have been copied for filename in style_dir.files(): assert ((outdir / filename.basename()).exists(), 'Style file "%s" not copied' % (outdir / filename.basename())) # Check that each node in the package has had a page made pagenodes = Set([p.node for p in exporter.pages]) othernodes = Set(self._getNodes([], package.root)) assert pagenodes == othernodes for page in exporter.pages: self._testPage(page, outdir)
def createPackageFromTemplate(self, templateBase): """ Creates a new package from Template """ log.debug(u"createPackageFromTemplate") package = Package.load(templateBase, isTemplate=True) package.set_templateFile(str(templateBase.basename().splitext()[0])) # Make up an initial unique name i = 1 name = u"newPackage" while name in self.loaded: name = u"newPackage" + unicode(i) i += 1 # Prevent the package from opening on the last node edited package.currentNode = package.root package.name = name package.filename = "" if G.application.config.locale.split('_')[0] != 'zh': package.lang = G.application.config.locale.split('_')[0] else: package.lang = G.application.config.locale package.translatePackage() package.isChanged = False self.loaded[package.name] = package return package
def do_export(self, inputf, outputf): if hasattr(self, 'export_' + self.options["export"]): LOG.debug("Exporting to type %s, in: %s, out: %s, overwrite: %s" \ % (self.options["export"], inputf, outputf, str(self.options["overwrite"]))) if not outputf: if self.options["export"] in ('website', 'singlepage'): outputf = inputf.rsplit(".elp")[0] else: outputf = inputf + self.extensions[self.options["export"]] outputfp = Path(outputf) if outputfp.exists() and not self.options["overwrite"]: error = _(u'"%s" already exists.\nPlease try again \ with a different filename') % outputf raise Exception(error.encode(sys.stdout.encoding)) else: if outputfp.exists() and self.options["overwrite"]: if outputfp.isdir(): for filen in outputfp.walkfiles(): filen.remove() outputfp.rmdir() else: outputfp.remove() pkg = Package.load(inputf) LOG.debug("Package %s loaded" % (inputf)) if not pkg: error = _(u"Invalid input package") raise Exception(error.encode(sys.stdout.encoding)) self.styles_dir = self.web_dir.joinpath('style', pkg.style) LOG.debug("Styles dir: %s" % (self.styles_dir)) getattr(self, 'export_' + self.options["export"])(pkg, outputf) return outputf else: raise Exception(_(u"Export format not implemented")\ .encode(sys.stdout.encoding))
def doTest(self, ExporterClass): """Exports a package with meta data""" # Load our test package package = Package.load('testPackage.elp') # Do the export outFilename = Path('scormtest.zip') exporter = ExporterClass(self.app.config, '../exe/webui/style/default', outFilename) exporter.export(package) # Check that it made a nice zip file assert outFilename.exists() # See if the manifest file was created zipped = ZipFile(outFilename) filenames = zipped.namelist() assert 'imsmanifest.xml' in filenames, filenames self._testManifest(zipped.read('imsmanifest.xml')) # Test that all the node's html files have been generated pagenodes = Set([p.node for p in exporter.pages]) othernodes = Set(self._getNodes([], package.root)) assert pagenodes == othernodes for page in exporter.pages: self._testPage(page, zipped) # Clean up zipped.close()
def loadPackage(self, path): """ Load a package from disk, add it to the store and return it """ package = Package.load(path) self.loaded[package.name] = package return package
def testExport(self): # Delete the output dir outdir = TempDirPath() # Load a package package = Package.load('testPackage.elp') # Do the export exporter = WebsiteExport('../exe/webui/style/default', outdir, '../exe/webui/images', '../exe/webui/scripts', '../exe/webui/templates') exporter.export(package) # Check that it all exists now assert outdir.isdir() assert (outdir / 'index.html').isfile() # Check that the style sheets have been copied for filename in Path('../exe/webui/style/default').files(): assert ((outdir / filename.basename()).exists(), 'Style file "%s" not copied' % (outdir / filename.basename())) # Check that each node in the package has had a page made pagenodes = Set([p.node for p in exporter.pages]) othernodes = Set(self._getNodes([], package.root)) assert pagenodes == othernodes for page in exporter.pages: self._testPage(page, outdir)
def setUp(self): class MyConfig: def __init__(self): self.port = 8081 self.dataDir = Path(".") self.webDir = Path(".") self.exeDir = Path(".") self.configDir = Path(".") self.styles = ["default"] app = Application() app.config = MyConfig() app.preLaunch() self.client = FakeClient() self.package = Package('temp') app.webServer.root.bindNewPackage(self.package) self.outline = app.webServer.root.children['temp'].outlinePane
def import_xml(self, inputf, outputf): if not outputf: outputf = inputf.rsplit(".xml")[0] xml = open(inputf).read() pkg = Package.load(outputf, fromxml=xml) if not pkg: raise Exception(_(u"Invalid output package '%s'") % outputf) pkg.save() return outputf
def import_xliff(self, inputf, outputf): if not outputf: outputf = inputf.rsplit(".xlf")[0] pkg = Package.load(outputf) if not pkg: raise Exception(_(u"Invalid output package '%s'") % outputf) importer = XliffImport(pkg, inputf) importer.parseAndImport(self.options["from-source"]) pkg.save() return outputf
def __init__(self,outputfilename="prova2.elp",titol="Exportacio de LliureX"): self._outputfile = outputfilename self._titol = titol self.document = Package('LLiureX') self.document.set_name('Lliurex') self.document.set_description('Lliurex') self.document.set_author('Lliurex') self.document.set_title('Documentacio LLiurex')
def doEditTemplate(self, template): try: templateEdit = Package.load(Template(self.config.templatesDir / template).path, isTemplate=True) self.webServer.root.bindNewPackage(templateEdit, self.client.session) self.client.sendScript((u'eXe.app.gotoUrl("/%s")' % \ templateEdit.name).encode('utf8')) except: self.alert(_(u'Error'), _(u'An unexpected error has occurred'))
def _loadPackage(self, client, filename): """Load the package named 'filename'""" try: encoding = sys.getfilesystemencoding() if encoding is None: encoding = 'utf-8' filename2 = unicode(filename, encoding) log.debug("filename and path" + filename2) package = Package.load(filename2) if package is None: filename2 = unicode(filename, 'utf-8') package = Package.load(filename2) if package is None: raise Exception(_("Couldn't load file, please email file to [email protected]")) except Exception, exc: if log.getEffectiveLevel() == logging.DEBUG: client.alert(_(u'Sorry, wrong file format:\n%s') % unicode(exc)) else: client.alert(_(u'Sorry, wrong file format')) log.error(u'Error loading package "%s": %s' % (filename2, unicode(exc))) log.error(u'Traceback:\n%s' % traceback.format_exc()) raise
def render_POST(self, request): #check the parameters required_headers = ['ldshake_frame_origin','name','sectoken'] for r_h in required_headers: if r_h not in request.args: return 'error' #get an id and increment the counter self.id_count_lock.acquire() id = self.id_count; self.id_count += 1 self.id_count_lock.release() package_name = request.args['sectoken'][0] if 'document' not in request.args: package = Package(package_name) else: fullpath = '/var/local/exelearning/' + package_name + '_' + str(random.randrange(1,999999)) + '.elp' try: elp_file = open(fullpath, "wb") elp_file.write(request.args['document'][0]) elp_file.close() package = Package.load(fullpath, True, None) package.set_name(package_name) except: return 'error' self.putChild(str(id), LdShakeDocument({ 'name': request.args['name'][0], 'sectoken': request.args['sectoken'][0], 'ldshake_frame_origin': request.args['ldshake_frame_origin'][0] }, self, package, self.webserver)) #return the resource URL return request.prePathURL() + str(id) + '/'
def createPackage(self): """ Creates a package """ log.debug(u"createPackage") # Make up an initial unique name i = 1 name = u"newPackage" while name in self.loaded: name = u"newPackage" + unicode(i) i += 1 package = Package(name) self.loaded[package.name] = package return package
def __importIdevice(self, filename): """ import the idevices which are not existed in current package from another package """ newPackage = Package.load(filename) for idevice in newPackage.idevices: isExisted = False for currentIdevice in self.ideviceStore.generic: if idevice.title == currentIdevice.title: isExisted = True break if not isExisted: newIdevice = idevice.clone() self.ideviceStore.addIdevice(newIdevice) self.ideviceStore.save()
def launch(self): """ launches the webbrowser """ if self.packagePath: try: package = Package.load(self.packagePath) self.webServer.root.package = package launchBrowser(self.config, package.name) except: self.webServer.root.packagePath = None launchBrowser(self.config, "") else: launchBrowser(self.config, "")
def _loadPackage(self, client, filename): """Load the package named 'filename'""" try: encoding = sys.getfilesystemencoding() if encoding is None: encoding = 'ascii' filename = unicode(filename, encoding) log.debug("filename and path" + filename) package = Package.load(filename) except Exception, exc: if log.getEffectiveLevel() == logging.DEBUG: client.alert(_(u'Sorry, wrong file format:\n%s') % unicode(exc)) else: client.alert(_(u'Sorry, wrong file format')) log.error(_(u'Error loading package "%s": %s') % \ (filename, unicode(exc))) log.error((u'Traceback:\n%s' % traceback.format_exc())) raise
def testSaveAndLoad(self): packageStore = PackageStore() package = packageStore.createPackage() # Check that it has been given a default name self.assertEquals(package.name, "newPackage") package.author = "UoA" package.description = "Nice test package" Config._getConfigPathOptions = lambda s: ['exe.conf'] config = Config() filePath = config.dataDir / 'package1.elp' package.save(filePath) package1 = Package.load(filePath) self.assert_(package1) self.assertEquals(package1.author, "UoA") self.assertEquals(package1.description, "Nice test package") # Package name should have been set when it was saved self.assertEquals(package.name, "package1") self.assertEquals(package1.name, "package1")
def doTest(self, ExporterClass): """Exports a package with meta data""" package = Package.load('testPackage.elp') outFilename = Path('scormtest.zip') exporter = ExporterClass(self.app.config, '../exe/webui/style/default', outFilename) exporter.export(package) assert outFilename.exists() zipped = ZipFile(outFilename) filenames = zipped.namelist() assert 'imsmanifest.xml' in filenames, filenames self._testManifest(zipped.read('imsmanifest.xml')) pagenodes = Set([p.node for p in exporter.pages]) othernodes = Set(self._getNodes([], package.root)) assert pagenodes == othernodes for page in exporter.pages: self._testPage(page, zipped) zipped.close()
def __importIdevice(self, filename): """ import the idevices which are not existed in current package from another package """ try: newPackage = Package.load(filename) except: self.message = _("Sorry, wrong file format.") return if newPackage: newIdevice = newPackage.idevices[-1].clone() for currentIdevice in self.ideviceStore.generic: if newIdevice.title == currentIdevice.title: newIdevice.title += "1" break self.ideviceStore.addIdevice(newIdevice) self.ideviceStore.save() else: self.message = _("Sorry, wrong file format.")
def testExport(self): outdir = TempDirPath() package = Package.load('testPackage.elp') exporter = WebsiteExport('../exe/webui/style/default', outdir, '../exe/webui/images', '../exe/webui/scripts', '../exe/webui/templates') exporter.export(package) assert outdir.isdir() assert (outdir / 'index.html').isfile() for filename in Path('../exe/webui/style/default').files(): assert ((outdir / filename.basename()).exists(), 'Style file "%s" not copied' % (outdir / filename.basename())) pagenodes = Set([p.node for p in exporter.pages]) othernodes = Set(self._getNodes([], package.root)) assert pagenodes == othernodes for page in exporter.pages: self._testPage(page, outdir)
def _testSaveAndLoad(self): packageStore = PackageStore() package = packageStore.createPackage() # Check that it has been given a default name self.assertEquals(package.name, "newPackage") package.author = "UoA" package.description = "Nice test package" Config._getConfigPathOptions = lambda s: ["exe.conf"] config = Config() filePath = config.dataDir / "package1.elp" package.save(filePath) package1 = Package.load(filePath) self.assert_(package1) self.assertEquals(package1.author, "UoA") self.assertEquals(package1.description, "Nice test package") # Package name should have been set when it was saved self.assertEquals(package.name, "package1") self.assertEquals(package1.name, "package1")
def _loadPackage(self, client, filename, newLoad=True, destinationPackage=None): """Load the package named 'filename'""" try: encoding = sys.getfilesystemencoding() if encoding is None: encoding = 'utf-8' filename2 = toUnicode(filename, encoding) log.debug("filename and path" + filename2) # see if the file exists AND is readable by the user try: open(filename2, 'rb').close() except IOError: filename2 = toUnicode(filename, 'utf-8') try: open(filename2, 'rb').close() except IOError: client.alert( _(u'File %s does not exist or is not readable.') % filename2) return None package = Package.load(filename2, newLoad, destinationPackage) if package is None: raise Exception( _("Couldn't load file, please email file to [email protected]" )) except Exception, exc: if log.getEffectiveLevel() == logging.DEBUG: client.alert( _(u'Sorry, wrong file format:\n%s') % unicode(exc)) else: client.alert(_(u'Sorry, wrong file format')) log.error(u'Error loading package "%s": %s' % (filename2, unicode(exc))) log.error(u'Traceback:\n%s' % traceback.format_exc()) raise
def setUp(self): """ Creates an application and almost launches it. """ # Make whatever config class that application uses only look for our # Set up our customised config file logFileName = Path('tmp/app data/test.conf') Config._getConfigPathOptions = lambda s: [logFileName] if not logFileName.dirname().exists(): logFileName.dirname().makedirs() confParser = ConfigParser() self._setupConfigFile(confParser) confParser.write(logFileName) # Start up the app and friends self.app = Application() self.app.loadConfiguration() self.app.preLaunch() self.client = FakeClient() self.package = Package('temp') self.app.webServer.root.bindNewPackage(self.package) self.mainpage = self.app.webServer.root.children['temp']
def testSaveAndLoad(self): packageStore = PackageStore() package = packageStore.createPackage() # Check that it has been given a default name self.assertEquals(package.name, "newPackage") package.author = "UoA" package.description = "Nice test package" Config._getConfigPathOptions = lambda s: ['exe.conf'] config = Config() SuperTestCase.update_config_parser(config.configParser) config.loadSettings() filePath = config.dataDir/'package1.elp' package.save(filePath) package1 = Package.load(filePath) self.assert_(package1) self.assertEquals(package1.author, "UoA") self.assertEquals(package1.description, "Nice test package") # Package name should have been set when it was saved self.assertEquals(package.name, "package1") self.assertEquals(package1.name, "package1")
file_w.write(u'# Generated on %s\n' % str(datetime.now())) file_w.write(u'\ntemplates = {\n') # Go through all templates (only take into account .elt files) package_index = 0 for file_name in [ f for f in os.listdir(application.config.templatesDir) if os.path.splitext(f)[1] == '.elt' ]: print(u'Extracting messages from %s...' % (application.config.templatesDir / file_name)) # Load the template as a package template = Template(application.config.templatesDir / file_name) package = Package.load(application.config.templatesDir / file_name, newLoad=True) # Write template header comment and definition start file_w.write(put_tabs(1)) file_w.write(u'# Template: %s\n' % file_name) file_w.write(put_tabs(1)) file_w.write(u'\'template_%i\': {\n' % package_index) # Template name file_w.write(put_tabs(2)) file_w.write(u'\'template_name\': _(u\'%s\'),\n' % normalize_text(template.name)) # Template author if template.author != u'': file_w.write(put_tabs(2)) file_w.write(u'\'template_author\': _(u\'%s\'),\n' %
def __init__(self, package, clear=True): log.info('****** Checking package at %s ******' % package.filename) self.package = package from exe.engine.package import Package self.tmppackage = Package('temp') self.inconsistencies = [] self.nodes = [self.package.root] + list( self.package.root.walkDescendants()) self.clear = clear self.idevices = {} idevice_ids = [] duplicated_idevice_ids = [] log.info('Computing content resource references') for node in self.nodes: for idevice in node.idevices: if idevice.id in idevice_ids: duplicated_idevice_ids.append((idevice, node)) idevice_ids.append(idevice.id) if not idevice.parentNode: log.error( 'No parent node for idevice %s in node %s! Fixing...' % (idevice.klass, node.title)) idevice.parentNode = node if idevice.parentNode != node: log.error( 'Parent node of idevice %s in node %s not match! Fixing...' % (idevice.klass, node.title)) idevice.parentNode = node fields = idevice.getRichTextFields() if fields and idevice.klass != 'ImageMagnifierIdevice': for field in fields: if hasattr(field, 'parentNode'): if not field.parentNode: log.error( 'No parent node for field in idevice %s in node %s! Fixing...' % (idevice.klass, node.title)) field.parentNode = node if field.parentNode != node: log.error( 'Parent node of field in idevice %s in node %s not match! Fixing...' % (idevice.klass, node.title)) field.parentNode = node for resource in field.ListActiveResources( field.content_w_resourcePaths): path = self.package.resourceDir / resource if not path.exists(): msg = "%s referenced in idevice %s of node %s not exists" % ( resource, idevice.klass, node.title) self.appendInconsistency( msg, 'contentResourceNonExistant', self.package, path) else: if path in self.idevices: self.idevices[path].append(field) else: self.idevices[path] = [field] else: for resource in idevice.userResources: path = self.package.resourceDir / resource.storageName if not path.exists(): msg = "%s referenced in idevice %s of node %s not exists" % ( resource, idevice.klass, node.title) self.appendInconsistency( msg, 'contentResourceNonExistant', self.package, path) else: if path in self.idevices: self.idevices[path].append(idevice) else: self.idevices[path] = [idevice] for idevice, node in duplicated_idevice_ids: log.error( 'Duplicated idevice id %s in node %s of type %s. Fixing...' % (idevice.id, node.title, idevice.klass)) while idevice.id in idevice_ids: idevice.id = unicode(int(idevice.id) + 1) idevice_ids.append(idevice.id) max_idevice_id = 0 if not idevice_ids else max( map(lambda x: int(x), idevice_ids)) if Idevice.nextId <= max_idevice_id: log.error('Wrong idevice next id. Fixing...') Idevice.nextId = max_idevice_id + 1
class TestOutline(unittest.TestCase): def setUp(self): class MyConfig: def __init__(self): self.port = 8081 self.dataDir = Path(".") self.webDir = Path(".") self.exeDir = Path(".") self.configDir = Path(".") self.styles = ["default"] app = Application() app.config = MyConfig() app.preLaunch() self.client = FakeClient() self.package = Package('temp') app.webServer.root.bindNewPackage(self.package) self.outline = app.webServer.root.children['temp'].outlinePane #self.outline = OutlinePane(None, None, None, server) def testAddAndDel(self): """Should be able to add a node to the package""" def checkAdd(id_, title): assert ('call', ('XHAddChildTreeItem', id_, title), {}) in self.client.calls, self.client.calls assert str(self.package.currentNode.title) == title, title assert self.package.currentNode.id == id_, id_ self.outline.handleAddChild(self.client, '0') # Home/root node checkAdd('1', 'Topic') # 1.0 self.outline.handleAddChild(self.client, '1') checkAdd('2', 'Section') # 1.0.0 self.outline.handleAddChild(self.client, '2') checkAdd('3', 'Unit') # 1.0.0.0 self.outline.handleAddChild(self.client, '3') checkAdd('4', '?????') # 1.0.0.0.0 self.outline.handleAddChild(self.client, '0') checkAdd('5', 'Topic') # 1.1 self.outline.handleAddChild(self.client, '0') checkAdd('6', 'Topic') # 1.2 self.outline.handleAddChild(self.client, '1') checkAdd('7', 'Section') # 1.0.1 self.outline.handleAddChild(self.client, '1') checkAdd('8', 'Section') # 1.0.2 self.outline.handleAddChild(self.client, '2') checkAdd('9', 'Unit') # 1.0.0.1 self.outline.handleAddChild(self.client, '2') checkAdd('10', 'Unit') # 1.0.0.2 # Check that we are parent and children attributes are bieng created properly n12 = self.package.findNode('10') n4 = self.package.findNode('2') assert n12.parent is n4, n12.parent assert n12 in n4.children assert n4.parent.id == '1' assert n4.parent.parent.id == '0' assert n4.parent.parent.parent is None # Tree now looks like this # 01 # |_02 # | |_03 # | | |_04 # | | | |_05 # | | |_09 # | | |_10 # | |_07 # | |_08 # |_05 # |_06 # Now do some deletion self.client.calls = [] # Do nothing because confirm is false self.outline.handleDelNode(self.client, 'false', '2') # Del assert not self.client.calls assert self.package.findNode('2') # Do nothing because its the home node self.outline.handleDelNode(self.client, 'true', '0') assert not self.client.calls assert self.package.findNode('0') # Now delete the selected node, should select its parent oldNode = self.package.currentNode self.package.currentNode = self.package.findNode('3') self.outline.handleDelNode(self.client, 'true', '3') assert ('call', ('XHDelNode', '3'), {}) in self.client.calls, self.client.calls assert self.package.currentNode.id == '2', self.package.currentNode.id assert self.package.findNode('3') is None assert self.package.findNode('4') is None # Now wipe out a whole tree! assert self.package.findNode('1') assert self.package.findNode('2') assert self.package.findNode('9') assert self.package.findNode('10') assert self.package.findNode('7') assert self.package.findNode('8') oldNode = self.package.currentNode self.outline.handleDelNode(self.client, 'true', '1') assert ('call', ('XHDelNode', '1'), {}) in self.client.calls, self.client.calls # Check that all its children are gone assert self.package.findNode('1') is None assert self.package.findNode('2') is None assert self.package.findNode('9') is None assert self.package.findNode('10') is None assert self.package.findNode('7') is None assert self.package.findNode('8') is None assert self.package.currentNode == oldNode, "Current node shouldn't have changed" def testRenNode(self): """Should be able to rename nodes""" # self.outline.handleRenNode(self.client, '0', 'Scratch Pad') # assert str(self.package.findNode('0').title) == 'Scratch Pad' # assert ('sendScript', ('XHRenNode("Scratch Pad")',), {}) in self.client.calls, self.client.calls self.outline.handleRenNode(self.client, '0', 'Genesis') assert str(self.package.findNode('0').title) == 'Genesis' assert ('sendScript', ('XHRenNode("Genesis")', ), {}) in self.client.calls, self.client.calls
def testUstadMobileExport(self): # Load a package filePath = self.inFilePath package = Package.load(filePath) self.assertIsNotNone(package, "Failed to load package") #test the tincan.xml generation desc_text = "Description Test" package.set_description(desc_text) self.assertEqual(desc_text, package.get_tincan_description(), "Description set and picked up") #test description will be title when description is blank package.set_description("") self.assertEqual(package.get_tincan_title(), package.get_tincan_description(), "Description blank, tincan desc = title") styles_dir = G.application.config.stylesDir / package.style xmlExport = XMLExport(G.application.config, styles_dir, self.epubOutPath) xmlExport.export(package) self.extract_dir = TempDirPath() zip_file = ZipFile(self.epubOutPath) zip_file.extractall(self.extract_dir) outdir = self.extract_dir/"EPUB" #test that we can force it to have a title and identifier missing_metadata_dict = {"title" : "", "identifier" : ""} cover = xmlExport.make_cover_page(package) self.assertIsNotNone(cover, "Can create cover for package") publication= xmlExport.make_publication_epub3(outdir, package, cover) self.assertIsNotNone(publication, "Can create publication object") fixed_metadata = publication.check_metadata_for_epub( missing_metadata_dict, package) self.assertTrue(len(fixed_metadata['title']) > 0, "Title Added") self.assertEqual(fixed_metadata['identifier'], package.dublinCore.identifier, "Identifier added from dublin core") #check that the modification time on our resource files #are as per original so they can be easily cached xml_copy_list = xmlExport.make_xml_copy_list(package, outdir) TestUtils.check_copy_list_mod_time(xml_copy_list,self) mainFolder = Path(self.extract_dir/"EPUB") assert mainFolder.exists() exeTocPath = Path(mainFolder / "exetoc.xml") #check the tincan.xml tincan_etree_doc = ElementTree.parse( self.extract_dir/"tincan.xml") namespaces = {"tincan" : "http://projecttincan.com/tincan.xsd"} tincan_etree = tincan_etree_doc.getroot() launch_el_arr = tincan_etree.findall( "tincan:activities/tincan:activity/tincan:launch", namespaces) self.assertEqual(len(launch_el_arr), 1, "1 activity with launch") self.assertEqual( tincan_etree.find( "tincan:activities/tincan:activity[0]/tincan:name", namespaces).text, package.get_tincan_title()) self.assertEqual( tincan_etree.find( "tincan:activities/tincan:activity[0]/tincan:description", namespaces).text, package.get_tincan_description(), "Description serialized matchese tincan desc") str = exeTocPath.open().read() from xml.dom.minidom import parse, parseString dom = parseString(str) self.assertIsNotNone(dom, "Did not parse exetoc.xml it seems") self.assertEqual(dom.documentElement.tagName, "exebase", "exebase is not the tag") audioFormatList = dom.documentElement.getAttribute("audioformats") videoFormatList = dom.documentElement.getAttribute("videoformats") resolutionList = dom.documentElement.getAttribute("resolutions") pageNodeList = dom.getElementsByTagName("page") for page in pageNodeList: href = page.getAttribute("href") pagePath = Path(mainFolder / href) self.assertTrue(pagePath.exists(), "FAILED: " + href + " does not exist") pageString = pagePath.open().read() pageDOM = parseString(pageString) self.assertIsNotNone(pageDOM, "Failed to read " + href + " into DOM") ideviceListFromToc = page.getElementsByTagName("idevice") for ideviceEl in ideviceListFromToc: # look for the idevice in the DOM list of the page foundDeviceInPage = False foundIdeviceInPageEl = None ideviceIdFromToc = ideviceEl.getAttribute("id") ideviceListFromPage = pageDOM.getElementsByTagName("idevice") for ideviceElFromPage in ideviceListFromPage: if ideviceElFromPage.getAttribute("id") == ideviceIdFromToc: foundDeviceInPage = True foundIdeviceInPageEl = ideviceElFromPage self.assertTrue(foundDeviceInPage, "idevice id " \ + ideviceIdFromToc + " was not in page " + href) # procedure to check media slide if foundIdeviceInPageEl.getAttribute("type") == "mediaslide": #self.doCheckMediaSlide(foundIdeviceInPageEl, href, mainFolder, package, dom.documentElement) pass pass
def tick2(self, package): bkup = Package(package.name) bkup = Package('bakcup') package.root.copyToPackage(bkup) bkup.save(package.name + '.bk')
inputf = args[0] try: outputf = args[1] except IndexError: outputf = None if len(args) > 2: parser.error(_(u'Bad number of arguments supplied').encode(sys.stdout.encoding)) tempdir = TempDirPath() if options.set_options: try: path = Path(inputf) path.copy(tempdir) inputf = tempdir / path.basename() pkg = Package.load(inputf) if not pkg: error = _(u"Invalid input package") raise Exception(error.encode(sys.stdout.encoding)) set_options = options.set_options.split(',') for set_option in set_options: name, value = set_option.split('=') names = name.split('.') obj = pkg for name in names[:-1]: obj = getattr(obj, name) name = names[-1] prop_type = type(getattr(obj, name)) print("Printing name and value..") print(name)
def testExport(self): # Delete the output dir outdir = TempDirPath() G.application = Application() G.application.loadConfiguration() G.application.preLaunch() # Load a package package = Package.load('testing/testPackage2.elp') # Do the export style_dir = G.application.config.stylesDir / package.style exporter = WebsiteExport(G.application.config, style_dir, outdir) exporter.export(package) # Check that it all exists now assert outdir.isdir() assert (outdir / 'index.html').isfile() # Check that the style sheets have been copied for filename in style_dir.files(): #Skip the styles config.xml - that should not be included if filename.basename() == "config.xml": continue assert ((outdir / filename.basename()).exists(), 'Style file "%s" not copied' % (outdir / filename.basename())) #check the modification time is correct f_dst = Path(outdir/filename.basename()) f_src = Path(filename) self.assertTrue( TestUtils.mod_time_diff(f_dst, f_src) < 0.1, "Modification time in style dir preserved") for res_file in package.resourceDir.files(): dst_file = Path(outdir/ res_file.basename()) self.assertTrue(dst_file.isfile()) self.assertTrue( TestUtils.mod_time_diff(res_file, dst_file) < 0.1, "Resource file %s has same mod time as origin" \ % res_file.basename()) #test that everything that was copied hahs the right mod time copy_list = package.make_system_copy_list(style_dir, G.application.config.webDir/"scripts" , G.application.config.webDir/"templates", G.application.config.webDir/"images", G.application.config.webDir/"css", outdir) TestUtils.check_copy_list_mod_time(copy_list, self) # Check that each node in the package has had a page made pagenodes = Set([p.node for p in exporter.pages]) othernodes = Set(self._getNodes([], package.root)) assert pagenodes == othernodes for page in exporter.pages: self._testPage(page, outdir)
class TestOutline(unittest.TestCase): def setUp(self): class MyConfig: def __init__(self): self.port = 8081 self.dataDir = Path(".") self.webDir = Path(".") self.exeDir = Path(".") self.configDir = Path(".") self.styles = ["default"] app = Application() app.config = MyConfig() app.preLaunch() self.client = FakeClient() self.package = Package("temp") app.webServer.root.bindNewPackage(self.package) self.outline = app.webServer.root.children["temp"].outlinePane # self.outline = OutlinePane(None, None, None, server) def testAddAndDel(self): """Should be able to add a node to the package""" def checkAdd(id_, title): assert ("call", ("XHAddChildTreeItem", id_, title), {}) in self.client.calls, self.client.calls assert str(self.package.currentNode.title) == title, title assert self.package.currentNode.id == id_, id_ self.outline.handleAddChild(self.client, "0") # Home/root node checkAdd("1", "Topic") # 1.0 self.outline.handleAddChild(self.client, "1") checkAdd("2", "Section") # 1.0.0 self.outline.handleAddChild(self.client, "2") checkAdd("3", "Unit") # 1.0.0.0 self.outline.handleAddChild(self.client, "3") checkAdd("4", "?????") # 1.0.0.0.0 self.outline.handleAddChild(self.client, "0") checkAdd("5", "Topic") # 1.1 self.outline.handleAddChild(self.client, "0") checkAdd("6", "Topic") # 1.2 self.outline.handleAddChild(self.client, "1") checkAdd("7", "Section") # 1.0.1 self.outline.handleAddChild(self.client, "1") checkAdd("8", "Section") # 1.0.2 self.outline.handleAddChild(self.client, "2") checkAdd("9", "Unit") # 1.0.0.1 self.outline.handleAddChild(self.client, "2") checkAdd("10", "Unit") # 1.0.0.2 # Check that we are parent and children attributes are bieng created properly n12 = self.package.findNode("10") n4 = self.package.findNode("2") assert n12.parent is n4, n12.parent assert n12 in n4.children assert n4.parent.id == "1" assert n4.parent.parent.id == "0" assert n4.parent.parent.parent is None # Tree now looks like this # 01 # |_02 # | |_03 # | | |_04 # | | | |_05 # | | |_09 # | | |_10 # | |_07 # | |_08 # |_05 # |_06 # Now do some deletion self.client.calls = [] # Do nothing because confirm is false self.outline.handleDelNode(self.client, "false", "2") # Del assert not self.client.calls assert self.package.findNode("2") # Do nothing because its the home node self.outline.handleDelNode(self.client, "true", "0") assert not self.client.calls assert self.package.findNode("0") # Now delete the selected node, should select its parent oldNode = self.package.currentNode self.package.currentNode = self.package.findNode("3") self.outline.handleDelNode(self.client, "true", "3") assert ("call", ("XHDelNode", "3"), {}) in self.client.calls, self.client.calls assert self.package.currentNode.id == "2", self.package.currentNode.id assert self.package.findNode("3") is None assert self.package.findNode("4") is None # Now wipe out a whole tree! assert self.package.findNode("1") assert self.package.findNode("2") assert self.package.findNode("9") assert self.package.findNode("10") assert self.package.findNode("7") assert self.package.findNode("8") oldNode = self.package.currentNode self.outline.handleDelNode(self.client, "true", "1") assert ("call", ("XHDelNode", "1"), {}) in self.client.calls, self.client.calls # Check that all its children are gone assert self.package.findNode("1") is None assert self.package.findNode("2") is None assert self.package.findNode("9") is None assert self.package.findNode("10") is None assert self.package.findNode("7") is None assert self.package.findNode("8") is None assert self.package.currentNode == oldNode, "Current node shouldn't have changed" def testRenNode(self): """Should be able to rename nodes""" # self.outline.handleRenNode(self.client, '0', 'Scratch Pad') # assert str(self.package.findNode('0').title) == 'Scratch Pad' # assert ('sendScript', ('XHRenNode("Scratch Pad")',), {}) in self.client.calls, self.client.calls self.outline.handleRenNode(self.client, "0", "Genesis") assert str(self.package.findNode("0").title) == "Genesis" assert ("sendScript", ('XHRenNode("Genesis")',), {}) in self.client.calls, self.client.calls
def tick2(self,package): bkup = Package(package.name) bkup = Package('bakcup') package.root.copyToPackage(bkup) bkup.save(package.name+'.bk')