def testRawSections(self): """ Tests :class:`foundations.parsers.SectionsFileParser` class raw sections consistencies. """ sectionsFileParser = SectionsFileParser(TEMPLATE_FILE) sectionsFileParser.parse(rawSections=("Script",)) self.assertListEqual(sectionsFileParser.sections["Script"]["__raw__"][0:10], SCRIPT_RAW_SECTION)
def __views_setUi(self): """ This method sets the Views. """ selectedTemplates = self.__templatesOutliner.getSelectedTemplates() template = foundations.common.getFirstItem(selectedTemplates) if not (template and foundations.common.pathExists(template.path)): for view in self.__views: self.__view_clearUi(view) return LOGGER.debug("> Attempting to read '{0}' Template settings file.".format(template.name)) commonAttributesOverrides = {} additionalAttributesOverrides = {} templateSettingsDirectory = os.path.join(self.__templatesSettingsDirectory, template.software, template.name) currentTemplateSettingsDirectory = os.path.join(templateSettingsDirectory, template.release) self.__templateSettingsFile = os.path.join(templateSettingsDirectory, template.release, os.path.basename(template.path)) not foundations.common.pathExists(currentTemplateSettingsDirectory) and \ foundations.io.setDirectory(currentTemplateSettingsDirectory) templateSettingsFile = None if foundations.common.pathExists(self.__templateSettingsFile): templateSettingsFile = self.__templateSettingsFile else: for version in sorted(( path for path in os.listdir(templateSettingsDirectory) if re.search(r"\d\.\d\.\d", path)), reverse=True, key=lambda x:(foundations.strings.getVersionRank(x))): path = os.path.join(templateSettingsDirectory, version, os.path.basename(template.path)) if foundations.common.pathExists(path): templateSettingsFile = path break if templateSettingsFile: LOGGER.debug("> Accessing '{0}' Template settings file: '{1}'.".format(template.name, templateSettingsFile)) templateSettingsSectionsFileParser = SectionsFileParser(templateSettingsFile) templateSettingsSectionsFileParser.read() and templateSettingsSectionsFileParser.parse() commonAttributesOverrides.update( templateSettingsSectionsFileParser.sections[self.__templateCommonAttributesSection]) additionalAttributesOverrides.update( templateSettingsSectionsFileParser.sections[self.__templateAdditionalAttributesSection]) else: LOGGER.debug("> No Template settings file found for : '{0}'.".format(template.name)) LOGGER.debug("> Parsing '{0}' Template for '{1}' and '{2}' section.".format( template.name, self.__templateCommonAttributesSection, self.__templateAdditionalAttributesSection)) templateSectionsFileParser = SectionsFileParser(template.path) templateSectionsFileParser.read() and templateSectionsFileParser.parse( rawSections=(self.__templateScriptSection)) self.__view_setUi(templateSectionsFileParser.sections.get(self.__templateCommonAttributesSection, {}), self.__commonView, commonAttributesOverrides) self.__view_setUi(templateSectionsFileParser.sections.get(self.__templateAdditionalAttributesSection, {}), self.__additionalView, additionalAttributesOverrides)
def testDefaultsSection(self): """ Tests :class:`foundations.parsers.SectionsFileParser` class default section consistency. """ sectionsFileParser = SectionsFileParser(DEFAULTS_FILE) sectionsFileParser.parse() for section in DEFAULTS_FILE_SECTIONS_AND_ATTRIBUTES: self.assertIn(section, sectionsFileParser.sections)
def test__len__(self): """ Tests :meth:`foundations.parsers.SectionsFileParser.__len__` method. """ for type, file in STANDARD_FILES.iteritems(): sectionsFileParser = SectionsFileParser(file) sectionsFileParser.parse(rawSections=STANDARD_FILES_RAW_SECTIONS[type]) self.assertEqual(len(sectionsFileParser), len(STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type].keys()))
def testDefaultsSection(self): """ Tests :class:`foundations.parsers.SectionsFileParser` class default section consistency. """ sectionsFileParser = SectionsFileParser(DEFAULTS_FILE) sectionsFileParser.parse() for section in DEFAULTS_FILE_SECTIONS_AND_ATTRIBUTES: self.assertIn(section, sectionsFileParser.sections)
def __views_setUi(self): """ Sets the Views. """ selectedTemplates = self.__templatesOutliner.getSelectedTemplates() template = foundations.common.getFirstItem(selectedTemplates) if not (template and foundations.common.pathExists(template.path)): for view in self.__views: self.__view_clearUi(view) return LOGGER.debug("> Attempting to read '{0}' Template settings file.".format(template.name)) commonAttributesOverrides = {} additionalAttributesOverrides = {} templateSettingsDirectory = os.path.join(self.__templatesSettingsDirectory, template.software, template.name) currentTemplateSettingsDirectory = os.path.join(templateSettingsDirectory, template.release) self.__templateSettingsFile = os.path.join(templateSettingsDirectory, template.release, os.path.basename(template.path)) not foundations.common.pathExists(currentTemplateSettingsDirectory) and \ foundations.io.setDirectory(currentTemplateSettingsDirectory) templateSettingsFile = None if foundations.common.pathExists(self.__templateSettingsFile): templateSettingsFile = self.__templateSettingsFile else: for version in sorted(( path for path in os.listdir(templateSettingsDirectory) if re.search(r"\d\.\d\.\d", path)), reverse=True, key=lambda x:(foundations.strings.getVersionRank(x))): path = os.path.join(templateSettingsDirectory, version, os.path.basename(template.path)) if foundations.common.pathExists(path): templateSettingsFile = path break if templateSettingsFile: LOGGER.debug("> Accessing '{0}' Template settings file: '{1}'.".format(template.name, templateSettingsFile)) templateSettingsSectionsFileParser = SectionsFileParser(templateSettingsFile) templateSettingsSectionsFileParser.parse() commonAttributesOverrides.update( templateSettingsSectionsFileParser.sections[self.__templateCommonAttributesSection]) additionalAttributesOverrides.update( templateSettingsSectionsFileParser.sections[self.__templateAdditionalAttributesSection]) else: LOGGER.debug("> No Template settings file found for : '{0}'.".format(template.name)) LOGGER.debug("> Parsing '{0}' Template for '{1}' and '{2}' section.".format( template.name, self.__templateCommonAttributesSection, self.__templateAdditionalAttributesSection)) templateSectionsFileParser = SectionsFileParser(template.path) templateSectionsFileParser.parse(rawSections=(self.__templateScriptSection)) self.__view_setUi(templateSectionsFileParser.sections.get(self.__templateCommonAttributesSection, {}), self.__commonView, commonAttributesOverrides) self.__view_setUi(templateSectionsFileParser.sections.get(self.__templateAdditionalAttributesSection, {}), self.__additionalView, additionalAttributesOverrides)
def testRawSections(self): """ Tests :class:`foundations.parsers.SectionsFileParser` class raw sections consistencies. """ sectionsFileParser = SectionsFileParser(TEMPLATE_FILE) sectionsFileParser.parse(rawSections=("Script", )) self.assertListEqual( sectionsFileParser.sections["Script"]["__raw__"][0:10], SCRIPT_RAW_SECTION)
def testParsingErrors(self): """ Tests :class:`foundations.parsers.SectionsFileParser` class parsing errors consistencies. """ sectionsFileParser = SectionsFileParser(PARSING_ERRORS_FILE) sectionsFileParser.parse(raiseParsingErrors=False) for exception in sectionsFileParser.parsingErrors: self.assertIn(exception.line, PARSING_ERRORS_LINES_AND_VALUES) self.assertEqual(exception.value, PARSING_ERRORS_LINES_AND_VALUES[exception.line])
def testSectionExists(self): """ Tests :meth:`foundations.parsers.SectionsFileParser.sectionExists` method. """ for type, file in STANDARD_FILES.iteritems(): sectionsFileParser = SectionsFileParser(file) sectionsFileParser.parse(rawSections=STANDARD_FILES_RAW_SECTIONS[type]) self.assertTrue(sectionsFileParser.sectionExists(STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type].keys()[0])) self.assertFalse(sectionsFileParser.sectionExists("Unknown"))
def test__contains__(self): """ Tests :meth:`foundations.parsers.SectionsFileParser.__contains__` method. """ for type, file in STANDARD_FILES.iteritems(): sectionsFileParser = SectionsFileParser(file) sectionsFileParser.parse(rawSections=STANDARD_FILES_RAW_SECTIONS[type]) for key in STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type].keys(): self.assertTrue(key in sectionsFileParser)
def testNamespaces(self): """ Tests :class:`foundations.parsers.SectionsFileParser` class namespaces consistencies. """ for type, file in STANDARD_FILES.iteritems(): sectionsFileParser = SectionsFileParser(file) sectionsFileParser.parse(rawSections=STANDARD_FILES_RAW_SECTIONS[type], namespaces=False) for section in STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type]: for attribute in sectionsFileParser.sections[section]: self.assertIn(attribute, STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type][section]["stripped"])
def test__getitem__(self): """ Tests :meth:`foundations.parsers.SectionsFileParser.__getitem__` method. """ sectionsFileParser = SectionsFileParser(IBL_SET_FILE) sectionsFileParser.parse() self.assertListEqual( sectionsFileParser["Header"].keys(), STANDARD_FILES_SECTIONS_AND_ATTRIBUTES.get("iblSet").get( "Header").get("namespaced"))
def test__getitem__(self): """ Tests :meth:`foundations.parsers.SectionsFileParser.__getitem__` method. """ sectionsFileParser = SectionsFileParser(IBL_SET_FILE) sectionsFileParser.parse() self.assertListEqual( sectionsFileParser["Header"].keys(), STANDARD_FILES_SECTIONS_AND_ATTRIBUTES.get("iblSet").get("Header").get("namespaced"), )
def setContent(self): """ Initializes the class attributes. :return: Method success. :rtype: bool """ sectionsFileParser = SectionsFileParser(self.path) sectionsFileParser.parse(rawSections=("Script")) if sectionsFileParser.sections: self.helpFile = foundations.parsers.getAttributeCompound("HelpFile", sectionsFileParser.getValue("HelpFile", "Template")).value and \ os.path.join(os.path.dirname(self.path), foundations.parsers.getAttributeCompound("HelpFile", sectionsFileParser.getValue("HelpFile", "Template")).value) or None self.title = foundations.parsers.getAttributeCompound( "Name", sectionsFileParser.getValue("Name", "Template")).value self.author = foundations.parsers.getAttributeCompound( "Author", sectionsFileParser.getValue("Author", "Template")).value self.email = foundations.parsers.getAttributeCompound( "Email", sectionsFileParser.getValue("Email", "Template")).value self.url = foundations.parsers.getAttributeCompound( "Url", sectionsFileParser.getValue("Url", "Template")).value self.release = foundations.parsers.getAttributeCompound( "Release", sectionsFileParser.getValue("Release", "Template")).value self.date = foundations.parsers.getAttributeCompound( "Date", sectionsFileParser.getValue("Date", "Template")).value self.software = foundations.parsers.getAttributeCompound( "Software", sectionsFileParser.getValue("Software", "Template")).value self.version = foundations.parsers.getAttributeCompound( "Version", sectionsFileParser.getValue("Version", "Template")).value self.renderer = foundations.parsers.getAttributeCompound( "Renderer", sectionsFileParser.getValue("Renderer", "Template")).value self.outputScript = foundations.parsers.getAttributeCompound( "OutputScript", sectionsFileParser.getValue("OutputScript", "Template")).value self.comment = foundations.parsers.getAttributeCompound( "Comment", sectionsFileParser.getValue("Comment", "Template")).value return True else: raise foundations.exceptions.FileStructureParsingError( "{0} | '{1}' no sections found, file structure seems invalid!". format(self.__class__.__name__, self.path))
def testParsingErrors(self): """ Tests :class:`foundations.parsers.SectionsFileParser` class parsing errors consistencies. """ sectionsFileParser = SectionsFileParser(PARSING_ERRORS_FILE) sectionsFileParser.parse(raiseParsingErrors=False) for exception in sectionsFileParser.parsingErrors: self.assertIn(exception.line, PARSING_ERRORS_LINES_AND_VALUES) self.assertEqual(exception.value, PARSING_ERRORS_LINES_AND_VALUES[exception.line])
def test__contains__(self): """ Tests :meth:`foundations.parsers.SectionsFileParser.__contains__` method. """ for type, file in STANDARD_FILES.iteritems(): sectionsFileParser = SectionsFileParser(file) sectionsFileParser.parse( rawSections=STANDARD_FILES_RAW_SECTIONS[type]) for key in STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type].keys(): self.assertTrue(key in sectionsFileParser)
def initializeProfile(self): """ Initializes the Component Profile. :return: Method success. :rtype: bool """ LOGGER.debug("> Building '{0}' profile.".format(self.__file)) sectionsFileParser = SectionsFileParser(self.__file) sectionsFileParser.parse() if sectionsFileParser.sections: fileStructureParsingError = lambda attribute: foundations.exceptions.FileStructureParsingError( "{0} | No '{1}' attribute found, '{2}' file structure seems invalid!".format( self.__class__.__name__, attribute, self.__file)) self.__directory = os.path.dirname(self.__file) self.__name = sectionsFileParser.getValue("Name", "Component", default=None) if self.__name is None: raise fileStructureParsingError("Name") self.__title = sectionsFileParser.getValue("Title", "Component", default=None) if self.__title is None: self.__title = self.__name self.__package = sectionsFileParser.getValue("Module", "Component", default=None) if self.__package is None: raise fileStructureParsingError("Module") self.__attribute = sectionsFileParser.getValue("Object", "Component", default=None) if self.__attribute is None: raise fileStructureParsingError("Object") self.__require = sectionsFileParser.getValue("Require", "Component", default=None) self.__require = list() if self.__require is None else self.__require.split("|") self.__version = sectionsFileParser.getValue("Version", "Component", default=None) if self.__version is None: raise fileStructureParsingError("Version") self.__author = sectionsFileParser.getValue("Author", "Informations", default=None) self.__email = sectionsFileParser.getValue("Email", "Informations", default=None) self.__url = sectionsFileParser.getValue("Url", "Informations", default=None) self.__description = sectionsFileParser.getValue("Description", "Informations", default=None) return True else: raise foundations.exceptions.FileStructureParsingError( "{0} | No sections found, '{1}' file structure seems invalid!".format(self.__class__.__name__, self.__file))
def testStripQuotationMarkers(self): """ Tests :class:`foundations.parsers.SectionsFileParser` class quotation markers consistencies. """ sectionsFileParser = SectionsFileParser(STRIPPING_FILE) sectionsFileParser.parse(stripQuotationMarkers=False) for section in STRIPPING_FILE_SECTIONS_AND_ATTRIBUTES_STRIPPED: self.assertIn(section, sectionsFileParser.sections) for attribute, value in STRIPPING_FILE_SECTIONS_AND_ATTRIBUTES_STRIPPED[section].iteritems(): self.assertIn(attribute, sectionsFileParser.sections[section]) self.assertIn(value, sectionsFileParser.sections[section].itervalues())
def __setActiveIblSetParser(self): """ Sets the :mod:`sibl_gui.components.core.inspector.inspector` Component Ibl Set parser. """ if foundations.common.pathExists(self.__activeIblSet.path): LOGGER.debug("> Parsing Inspector Ibl Set file: '{0}'.".format(self.__activeIblSet)) if not self.__sectionsFileParsersCache.getContent(self.__activeIblSet.path): sectionsFileParser = SectionsFileParser(self.__activeIblSet.path) sectionsFileParser.parse() self.__sectionsFileParsersCache.addContent(**{self.__activeIblSet.path: sectionsFileParser})
def test__len__(self): """ Tests :meth:`foundations.parsers.SectionsFileParser.__len__` method. """ for type, file in STANDARD_FILES.iteritems(): sectionsFileParser = SectionsFileParser(file) sectionsFileParser.parse( rawSections=STANDARD_FILES_RAW_SECTIONS[type]) self.assertEqual( len(sectionsFileParser), len(STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type].keys()))
def testSections(self): """ This method tests :class:`foundations.parsers.SectionsFileParser` class sections consistencies. """ for type, file in STANDARD_FILES.iteritems(): sectionsFileParser = SectionsFileParser(file) sectionsFileParser.read() and sectionsFileParser.parse(rawSections=STANDARD_FILES_RAW_SECTIONS[type]) self.assertListEqual(sectionsFileParser.sections.keys(), STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type].keys()) sectionsFileParser.parse(orderedDictionary=False, rawSections=STANDARD_FILES_RAW_SECTIONS[type]) for section in STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type]: self.assertIn(section, sectionsFileParser.sections)
def testGetAllAttributes(self): """ Tests :meth:`foundations.parsers.SectionsFileParser.getAllAttributes` method. """ for type, file in STANDARD_FILES.iteritems(): sectionsFileParser = SectionsFileParser(file) sectionsFileParser.parse(rawSections=STANDARD_FILES_RAW_SECTIONS[type]) attributes = sectionsFileParser.getAllAttributes() testsAttributes = [] for section in STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type]: testsAttributes.extend(STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type][section]["namespaced"]) self.assertListEqual(attributes.keys(), testsAttributes)
def testSectionExists(self): """ Tests :meth:`foundations.parsers.SectionsFileParser.sectionExists` method. """ for type, file in STANDARD_FILES.iteritems(): sectionsFileParser = SectionsFileParser(file) sectionsFileParser.parse( rawSections=STANDARD_FILES_RAW_SECTIONS[type]) self.assertTrue( sectionsFileParser.sectionExists( STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type].keys()[0])) self.assertFalse(sectionsFileParser.sectionExists("Unknown"))
def testComments(self): """ Tests :class:`foundations.parsers.SectionsFileParser` class comments consistencies. """ for type, file in STANDARD_FILES.iteritems(): sectionsFileParser = SectionsFileParser(file) sectionsFileParser.parse(rawSections=STANDARD_FILES_RAW_SECTIONS[type]) self.assertEqual(sectionsFileParser.comments, OrderedDict()) sectionsFileParser.parse(rawSections=STANDARD_FILES_RAW_SECTIONS[type], stripComments=False) for comment, value in RANDOM_COMMENTS[type].iteritems(): self.assertIn(comment, sectionsFileParser.comments) self.assertEqual(value["id"], sectionsFileParser.comments[comment]["id"])
def testParseInternational(self): """ Tests :meth:`foundations.parsers.SectionsFileParser.parse` in international specific context. """ sectionsFileParser = SectionsFileParser(CHINESE_IBL_SET_FILE) sectionsFileParser.parse() for attribute, value in CHINESE_IBL_SET_FILE_RANDOM_ATTRIBUTES.iteritems( ): self.assertEqual( value, sectionsFileParser.getValue( foundations.namespace.getLeaf(attribute), foundations.namespace.getRoot(attribute)))
def testParseInternational(self): """ Tests :meth:`foundations.parsers.SectionsFileParser.parse` in international specific context. """ sectionsFileParser = SectionsFileParser(CHINESE_IBL_SET_FILE) sectionsFileParser.parse() for attribute, value in CHINESE_IBL_SET_FILE_RANDOM_ATTRIBUTES.iteritems(): self.assertEqual( value, sectionsFileParser.getValue( foundations.namespace.getLeaf(attribute), foundations.namespace.getRoot(attribute) ), )
def testStripQuotationMarkers(self): """ Tests :class:`foundations.parsers.SectionsFileParser` class quotation markers consistencies. """ sectionsFileParser = SectionsFileParser(STRIPPING_FILE) sectionsFileParser.parse(stripQuotationMarkers=False) for section in STRIPPING_FILE_SECTIONS_AND_ATTRIBUTES_STRIPPED: self.assertIn(section, sectionsFileParser.sections) for attribute, value in STRIPPING_FILE_SECTIONS_AND_ATTRIBUTES_STRIPPED[ section].iteritems(): self.assertIn(attribute, sectionsFileParser.sections[section]) self.assertIn( value, sectionsFileParser.sections[section].itervalues())
def testNamespaces(self): """ Tests :class:`foundations.parsers.SectionsFileParser` class namespaces consistencies. """ for type, file in STANDARD_FILES.iteritems(): sectionsFileParser = SectionsFileParser(file) sectionsFileParser.parse( rawSections=STANDARD_FILES_RAW_SECTIONS[type], namespaces=False) for section in STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type]: for attribute in sectionsFileParser.sections[section]: self.assertIn( attribute, STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type] [section]["stripped"])
def getSectionsFileParser(file): """ Returns a sections file parser. :param file: File. :type file: unicode :return: Parser. :rtype: SectionsFileParser """ if not foundations.common.pathExists(file): raise foundations.exceptions.FileExistsError("{0} | '{1}' sections file doesn't exists!".format(__name__, file)) sectionsFileParser = SectionsFileParser(file) sectionsFileParser.parse() return sectionsFileParser
def getIblSetImagesPaths(self, iblSet, imageType): """ This method gets Ibl Set images paths. :param iblSet: Ibl Set. ( IblSet ) :param imageType: Image type. ( String ) :return: Images paths. ( List ) """ imagePaths = [] if imageType == "Background": path = iblSet.backgroundImage path and imagePaths.append(path) elif imageType == "Lighting": path = iblSet.lightingImage path and imagePaths.append(path) elif imageType == "Reflection": path = iblSet.reflectionImage path and imagePaths.append(path) elif imageType == "Plate": if foundations.common.pathExists(iblSet.path): LOGGER.debug("> Parsing Inspector Ibl Set file: '{0}'.".format(iblSet)) sectionsFileParser = SectionsFileParser(iblSet.path) sectionsFileParser.read() and sectionsFileParser.parse() for section in sectionsFileParser.sections: if re.search(r"Plate\d+", section): imagePaths.append(os.path.normpath(os.path.join(os.path.dirname(iblSet.path), sectionsFileParser.getValue("PLATEfile", section)))) for path in imagePaths[:]: if not foundations.common.pathExists(path): imagePaths.remove(path) and LOGGER.warning( "!> {0} | '{1}' image file doesn't exists and will be skipped!".format(self.__class__.__name__, path)) return imagePaths
def testGetAllAttributes(self): """ Tests :meth:`foundations.parsers.SectionsFileParser.getAllAttributes` method. """ for type, file in STANDARD_FILES.iteritems(): sectionsFileParser = SectionsFileParser(file) sectionsFileParser.parse( rawSections=STANDARD_FILES_RAW_SECTIONS[type]) attributes = sectionsFileParser.getAllAttributes() testsAttributes = [] for section in STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type]: testsAttributes.extend( STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type][section] ["namespaced"]) self.assertListEqual(attributes.keys(), testsAttributes)
def testParse(self): """ This method tests :meth:`foundations.parsers.SectionsFileParser.parse` method. """ for type, file in STANDARD_FILES.iteritems(): sectionsFileParser = SectionsFileParser(file) sectionsFileParser.read() parseSuccess = sectionsFileParser.parse(rawSections=STANDARD_FILES_RAW_SECTIONS[type]) self.assertTrue(parseSuccess) self.assertIsInstance(sectionsFileParser.sections, OrderedDict) self.assertIsInstance(sectionsFileParser.comments, OrderedDict) sectionsFileParser.parse(orderedDictionary=False, rawSections=STANDARD_FILES_RAW_SECTIONS[type]) self.assertIsInstance(sectionsFileParser.sections, dict) self.assertIsInstance(sectionsFileParser.comments, dict)
def __templatesOutliner_view_selectionModel__selectionChanged(self, selectedItems, deselectedItems): """ This method is triggered when **templatesOutliner.view** Model selection has changed. :param selectedItems: Selected items. ( QItemSelection ) :param deselectedItems: Deselected items. ( QItemSelection ) """ selectedTemplates = self.__templatesOutliner.getSelectedTemplates() template = foundations.common.getFirstItem(selectedTemplates) if not (template and foundations.common.pathExists(template.path)): return LOGGER.debug("> Parsing '{0}' Template for '{1}' section.".format(template.name, self.__templateRemoteConnectionSection)) templateSectionsFileParser = SectionsFileParser(template.path) templateSectionsFileParser.read() and templateSectionsFileParser.parse( rawSections=(self.__templateScriptSection)) if not self.__templateRemoteConnectionSection in templateSectionsFileParser.sections: return LOGGER.debug("> {0}' section found.".format(self.__templateRemoteConnectionSection)) connectionType = foundations.parsers.getAttributeCompound("ConnectionType", templateSectionsFileParser.getValue("ConnectionType", self.__templateRemoteConnectionSection)) if connectionType.value == "Socket": LOGGER.debug("> Remote connection type: 'Socket'.") self.__tcpClientUi.address = foundations.parsers.getAttributeCompound("DefaultAddress", templateSectionsFileParser.getValue("DefaultAddress", self.__templateRemoteConnectionSection)).value self.__tcpClientUi.port = int(foundations.parsers.getAttributeCompound("DefaultPort", templateSectionsFileParser.getValue("DefaultPort", self.__templateRemoteConnectionSection)).value) elif connectionType.value == "Win32": LOGGER.debug("> Remote connection: 'Win32'.")
def testSections(self): """ This method tests :class:`foundations.parsers.SectionsFileParser` class sections consistencies. """ for type, file in STANDARD_FILES.iteritems(): sectionsFileParser = SectionsFileParser(file) sectionsFileParser.read() and sectionsFileParser.parse( rawSections=STANDARD_FILES_RAW_SECTIONS[type]) self.assertListEqual( sectionsFileParser.sections.keys(), STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type].keys()) sectionsFileParser.parse( orderedDictionary=False, rawSections=STANDARD_FILES_RAW_SECTIONS[type]) for section in STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type]: self.assertIn(section, sectionsFileParser.sections)
def testGetAttributes(self): """ Tests :meth:`foundations.parsers.SectionsFileParser.getAttributes` method. """ for type, file in STANDARD_FILES.iteritems(): sectionsFileParser = SectionsFileParser(file) sectionsFileParser.parse(rawSections=STANDARD_FILES_RAW_SECTIONS[type]) for section in STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type]: self.assertListEqual( sectionsFileParser.getAttributes(section, stripNamespaces=True).keys(), STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type][section]["stripped"], ) self.assertListEqual( sectionsFileParser.getAttributes(section).keys(), STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type][section]["namespaced"], )
def testGetValue(self): """ Tests :meth:`foundations.parsers.SectionsFileParser.getValue` method. """ for type, file in STANDARD_FILES.iteritems(): sectionsFileParser = SectionsFileParser(file, preserveOrder=False) sectionsFileParser.parse(rawSections=STANDARD_FILES_RAW_SECTIONS[type]) for attribute, value in RANDOM_ATTRIBUTES[type].iteritems(): self.assertEqual( sectionsFileParser.getValue( attribute, foundations.namespace.getNamespace(attribute, rootOnly=True) ), value, ) self.assertEqual(sectionsFileParser.getValue("attribute", "section", default=None), None) self.assertEqual(sectionsFileParser.getValue("attribute", "section", default=list()), list())
def testComments(self): """ This method tests :class:`foundations.parsers.SectionsFileParser` class comments consistencies. """ for type, file in STANDARD_FILES.iteritems(): sectionsFileParser = SectionsFileParser(file) sectionsFileParser.read() and sectionsFileParser.parse( rawSections=STANDARD_FILES_RAW_SECTIONS[type]) self.assertEqual(sectionsFileParser.comments, OrderedDict()) sectionsFileParser.parse( rawSections=STANDARD_FILES_RAW_SECTIONS[type], stripComments=False) for comment, value in RANDOM_COMMENTS[type].iteritems(): self.assertIn(comment, sectionsFileParser.comments) self.assertEqual(value["id"], sectionsFileParser.comments[comment]["id"])
def sendLoaderScriptToSoftware(self, template, loaderScriptPath): """ This method sends the Loader Script to associated 3d package. :param template: Template. ( Template ) :param loaderScriptPath: Loader Script path. ( String ) :return: Method success. ( Boolean ) """ LOGGER.info("{0} | Starting remote connection!".format(self.__class__.__name__)) templateSectionsFileParser = SectionsFileParser(template.path) templateSectionsFileParser.read() and templateSectionsFileParser.parse( rawSections=(self.__templateScriptSection)) connectionType = foundations.parsers.getAttributeCompound("ConnectionType", templateSectionsFileParser.getValue("ConnectionType", self.__templateRemoteConnectionSection)) if connectionType.value == "Socket": try: connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connection.settimeout(2.5) connection.connect((foundations.strings.toString(self.__tcpClientUi.address), self.__tcpClientUi.port)) socketCommand = foundations.parsers.getAttributeCompound("ExecutionCommand", templateSectionsFileParser.getValue("ExecutionCommand", self.__templateRemoteConnectionSection)).value.replace("$loaderScriptPath", loaderScriptPath) LOGGER.debug("> Current socket command: '%s'.", socketCommand) connection.send(socketCommand) self.__engine.notificationsManager.notify( "{0} | Socket connection command dispatched!".format(self.__class__.__name__)) dataBack = connection.recv(4096) LOGGER.debug("> Received from connection: '{0}'.".format(dataBack)) connection.close() LOGGER.info("{0} | Closing remote connection!".format(self.__class__.__name__)) except socket.timeout as error: LOGGER.info("{0} | Closing remote connection on timeout!".format(self.__class__.__name__)) except Exception as error: raise sibl_gui.exceptions.SocketConnectionError( "{0} | Socket connection error: '{1}'!".format(self.__class__.__name__, error)) elif connectionType.value == "Win32": if platform.system() == "Windows" or platform.system() == "Microsoft": try: import win32com.client connection = win32com.client.Dispatch(foundations.parsers.getAttributeCompound("TargetApplication", templateSectionsFileParser.getValue("TargetApplication", self.__templateRemoteConnectionSection)).value) connection._FlagAsMethod(self.__win32ExecutionMethod) connectionCommand = foundations.parsers.getAttributeCompound("ExecutionCommand", templateSectionsFileParser.getValue("ExecutionCommand", self.__templateRemoteConnectionSection)).value.replace("$loaderScriptPath", loaderScriptPath) LOGGER.debug("> Current connection command: '%s'.", connectionCommand) getattr(connection, self.__win32ExecutionMethod)(connectionCommand) self.__engine.notificationsManager.notify( "{0} | Win32 connection command dispatched!".format(self.__class__.__name__)) except Exception as error: raise sibl_gui.exceptions.Win32OLEServerConnectionError( "{0} | Win32 OLE server connection error: '{1}'!".format(self.__class__.__name__, error)) return True
def setContent(self): """ Initializes the class attributes. :return: Method success. :rtype: bool """ sectionsFileParser = SectionsFileParser(self.path) sectionsFileParser.parse(rawSections=("Script")) if sectionsFileParser.sections: self.helpFile = foundations.parsers.getAttributeCompound("HelpFile", sectionsFileParser.getValue("HelpFile", "Template")).value and \ os.path.join(os.path.dirname(self.path), foundations.parsers.getAttributeCompound("HelpFile", sectionsFileParser.getValue("HelpFile", "Template")).value) or None self.title = foundations.parsers.getAttributeCompound("Name", sectionsFileParser.getValue("Name", "Template")).value self.author = foundations.parsers.getAttributeCompound("Author", sectionsFileParser.getValue("Author", "Template")).value self.email = foundations.parsers.getAttributeCompound("Email", sectionsFileParser.getValue("Email", "Template")).value self.url = foundations.parsers.getAttributeCompound("Url", sectionsFileParser.getValue("Url", "Template")).value self.release = foundations.parsers.getAttributeCompound("Release", sectionsFileParser.getValue("Release", "Template")).value self.date = foundations.parsers.getAttributeCompound("Date", sectionsFileParser.getValue("Date", "Template")).value self.software = foundations.parsers.getAttributeCompound("Software", sectionsFileParser.getValue("Software", "Template")).value self.version = foundations.parsers.getAttributeCompound("Version", sectionsFileParser.getValue("Version", "Template")).value self.renderer = foundations.parsers.getAttributeCompound("Renderer", sectionsFileParser.getValue("Renderer", "Template")).value self.outputScript = foundations.parsers.getAttributeCompound("OutputScript", sectionsFileParser.getValue("OutputScript", "Template")).value self.comment = foundations.parsers.getAttributeCompound("Comment", sectionsFileParser.getValue("Comment", "Template")).value return True else: raise foundations.exceptions.FileStructureParsingError( "{0} | '{1}' no sections found, file structure seems invalid!".format(self.__class__.__name__, self.path))
def listTemplatesReleases(): """ Lists Templates releases. :return: Definition success. :rtype: bool """ for template in sorted(list(foundations.walkers.filesWalker(os.path.normpath(TEMPLATES_PATH), (TEMPLATES_EXTENSION,), ("\._",)))): sectionsFileParser = SectionsFileParser(template) sectionsFileParser.parse(rawSections=("Script",)) LOGGER.info("{0} | '{1}': '{2}'.".format(listTemplatesReleases.__name__, foundations.strings.getSplitextBasename(template), foundations.parsers.getAttributeCompound("Release", sectionsFileParser.getValue("Release", "Template")).value)) return True
def getIblSetImagesPaths(self, iblSet, imageType): """ Gets Ibl Set images paths. :param iblSet: Ibl Set. :type iblSet: IblSet :param imageType: Image type. :type imageType: unicode :return: Images paths. :rtype: list """ imagePaths = [] if imageType == "Background": path = iblSet.backgroundImage path and imagePaths.append(path) elif imageType == "Lighting": path = iblSet.lightingImage path and imagePaths.append(path) elif imageType == "Reflection": path = iblSet.reflectionImage path and imagePaths.append(path) elif imageType == "Plate": if foundations.common.pathExists(iblSet.path): LOGGER.debug( "> Parsing Inspector Ibl Set file: '{0}'.".format(iblSet)) sectionsFileParser = SectionsFileParser(iblSet.path) sectionsFileParser.parse() for section in sectionsFileParser.sections: if re.search(r"Plate\d+", section): imagePaths.append( os.path.normpath( os.path.join( os.path.dirname(iblSet.path), sectionsFileParser.getValue( "PLATEfile", section)))) for path in imagePaths[:]: if not foundations.common.pathExists(path): imagePaths.remove(path) and LOGGER.warning( "!> {0} | '{1}' image file doesn't exists and will be skipped!" .format(self.__class__.__name__, path)) return imagePaths
def testGetAttributes(self): """ Tests :meth:`foundations.parsers.SectionsFileParser.getAttributes` method. """ for type, file in STANDARD_FILES.iteritems(): sectionsFileParser = SectionsFileParser(file) sectionsFileParser.parse( rawSections=STANDARD_FILES_RAW_SECTIONS[type]) for section in STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type]: self.assertListEqual( sectionsFileParser.getAttributes( section, stripNamespaces=True).keys(), STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type][section] ["stripped"]) self.assertListEqual( sectionsFileParser.getAttributes(section).keys(), STANDARD_FILES_SECTIONS_AND_ATTRIBUTES[type][section] ["namespaced"])
def testAttributeExists(self): """ Tests :meth:`foundations.parsers.SectionsFileParser.attributeExists` method. """ for type, file in STANDARD_FILES.iteritems(): sectionsFileParser = SectionsFileParser(file, preserveOrder=False) sectionsFileParser.parse(rawSections=STANDARD_FILES_RAW_SECTIONS[type]) for attribute in RANDOM_ATTRIBUTES[type]: self.assertTrue( sectionsFileParser.attributeExists( attribute, foundations.namespace.getNamespace(attribute, rootOnly=True) ) ) self.assertFalse( sectionsFileParser.attributeExists( "Unknown", foundations.namespace.getNamespace(attribute, rootOnly=True) ) )
def testParse(self): """ This method tests :meth:`foundations.parsers.SectionsFileParser.parse` method. """ for type, file in STANDARD_FILES.iteritems(): sectionsFileParser = SectionsFileParser(file) sectionsFileParser.read() parseSuccess = sectionsFileParser.parse( rawSections=STANDARD_FILES_RAW_SECTIONS[type]) self.assertTrue(parseSuccess) self.assertIsInstance(sectionsFileParser.sections, OrderedDict) self.assertIsInstance(sectionsFileParser.comments, OrderedDict) sectionsFileParser.parse( orderedDictionary=False, rawSections=STANDARD_FILES_RAW_SECTIONS[type]) self.assertIsInstance(sectionsFileParser.sections, dict) self.assertIsInstance(sectionsFileParser.comments, dict)
def setContent(self): """ Initializes the class attributes. :return: Method success. :rtype: bool """ sectionsFileParser = SectionsFileParser(self.path) sectionsFileParser.parse() if sectionsFileParser.sections: self.title = sectionsFileParser.getValue("Name", "Header") self.author = sectionsFileParser.getValue("Author", "Header") self.link = sectionsFileParser.getValue("Link", "Header") self.icon = os.path.normpath(os.path.join(os.path.dirname(self.path), sectionsFileParser.getValue("ICOfile", "Header"))) \ if sectionsFileParser.getValue("ICOfile", "Header") else None self.previewImage = os.path.normpath(os.path.join(os.path.dirname(self.path), sectionsFileParser.getValue("PREVIEWfile", "Header"))) \ if sectionsFileParser.getValue("PREVIEWfile", "Header") else None self.backgroundImage = os.path.normpath(os.path.join(os.path.dirname(self.path), sectionsFileParser.getValue("BGfile", "Background"))) \ if sectionsFileParser.getValue("BGfile", "Background") else None self.lightingImage = os.path.normpath(os.path.join(os.path.dirname(self.path), sectionsFileParser.getValue("EVfile", "Enviroment"))) \ if sectionsFileParser.getValue("EVfile", "Enviroment") else None self.reflectionImage = os.path.normpath(os.path.join(os.path.dirname(self.path), sectionsFileParser.getValue("REFfile", "Reflection"))) \ if sectionsFileParser.getValue("REFfile", "Reflection") else None self.location = sectionsFileParser.getValue("Location", "Header") self.latitude = sectionsFileParser.getValue("GEOlat", "Header") self.longitude = sectionsFileParser.getValue("GEOlong", "Header") self.date = sectionsFileParser.getValue("Date", "Header") self.time = sectionsFileParser.getValue("Time", "Header") self.comment = sectionsFileParser.getValue("Comment", "Header") return True else: raise foundations.exceptions.FileStructureParsingError( "{0} | '{1}' no sections found, file structure seems invalid!". format(self.__class__.__name__, self.path))
def testAttributeExists(self): """ Tests :meth:`foundations.parsers.SectionsFileParser.attributeExists` method. """ for type, file in STANDARD_FILES.iteritems(): sectionsFileParser = SectionsFileParser(file, preserveOrder=False) sectionsFileParser.parse( rawSections=STANDARD_FILES_RAW_SECTIONS[type]) for attribute in RANDOM_ATTRIBUTES[type]: self.assertTrue( sectionsFileParser.attributeExists( attribute, foundations.namespace.getNamespace(attribute, rootOnly=True))) self.assertFalse( sectionsFileParser.attributeExists( "Unknown", foundations.namespace.getNamespace(attribute, rootOnly=True)))
def setContent(self): """ Initializes the class attributes. :return: Method success. :rtype: bool """ sectionsFileParser = SectionsFileParser(self.path) sectionsFileParser.parse() if sectionsFileParser.sections: self.title = sectionsFileParser.getValue("Name", "Header") self.author = sectionsFileParser.getValue("Author", "Header") self.link = sectionsFileParser.getValue("Link", "Header") self.icon = os.path.normpath(os.path.join(os.path.dirname(self.path), sectionsFileParser.getValue("ICOfile", "Header"))) \ if sectionsFileParser.getValue("ICOfile", "Header") else None self.previewImage = os.path.normpath(os.path.join(os.path.dirname(self.path), sectionsFileParser.getValue("PREVIEWfile", "Header"))) \ if sectionsFileParser.getValue("PREVIEWfile", "Header") else None self.backgroundImage = os.path.normpath(os.path.join(os.path.dirname(self.path), sectionsFileParser.getValue("BGfile", "Background"))) \ if sectionsFileParser.getValue("BGfile", "Background") else None self.lightingImage = os.path.normpath(os.path.join(os.path.dirname(self.path), sectionsFileParser.getValue("EVfile", "Enviroment"))) \ if sectionsFileParser.getValue("EVfile", "Enviroment") else None self.reflectionImage = os.path.normpath(os.path.join(os.path.dirname(self.path), sectionsFileParser.getValue("REFfile", "Reflection"))) \ if sectionsFileParser.getValue("REFfile", "Reflection") else None self.location = sectionsFileParser.getValue("Location", "Header") self.latitude = sectionsFileParser.getValue("GEOlat", "Header") self.longitude = sectionsFileParser.getValue("GEOlong", "Header") self.date = sectionsFileParser.getValue("Date", "Header") self.time = sectionsFileParser.getValue("Time", "Header") self.comment = sectionsFileParser.getValue("Comment", "Header") return True else: raise foundations.exceptions.FileStructureParsingError( "{0} | '{1}' no sections found, file structure seems invalid!".format(self.__class__.__name__, self.path))
def testStripWhitespaces(self): """ This method tests :class:`foundations.parsers.SectionsFileParser` class whitespaces consistencies. """ sectionsFileParser = SectionsFileParser(STRIPPING_FILE) sectionsFileParser.read() and sectionsFileParser.parse(stripWhitespaces=False) for section in STRIPPING_FILE_SECTIONS_AND_ATTRIBUTES_NON_STRIPPED: self.assertIn(section, sectionsFileParser.sections) for attribute, value in STRIPPING_FILE_SECTIONS_AND_ATTRIBUTES_NON_STRIPPED[section].iteritems(): self.assertIn(attribute, sectionsFileParser.sections[section]) self.assertIn(value, sectionsFileParser.sections[section].itervalues())
def initializeProfile(self): """ This method gets initializes the Component Profile. :return: Method success. ( Boolean ) """ LOGGER.debug("> Building '{0}' profile.".format(self.__file)) sectionsFileParser = SectionsFileParser(self.__file) sectionsFileParser.read() and sectionsFileParser.parse() if sectionsFileParser.sections: fileStructureParsingError = lambda attribute: foundations.exceptions.FileStructureParsingError( "{0} | No '{1}' attribute found, '{2}' file structure seems invalid!".format( self.__class__.__name__, attribute, self.__file)) self.__directory = os.path.dirname(self.__file) self.__name = sectionsFileParser.getValue("Name", "Component", default=None) if self.__name is None: raise fileStructureParsingError("Name") self.__title = sectionsFileParser.getValue("Title", "Component", default=None) if self.__title is None: self.__title = self.__name self.__package = sectionsFileParser.getValue("Module", "Component", default=None) if self.__package is None: raise fileStructureParsingError("Module") self.__attribute = sectionsFileParser.getValue("Object", "Component", default=None) if self.__attribute is None: raise fileStructureParsingError("Object") self.__require = sectionsFileParser.getValue("Require", "Component", default=None) self.__require = list() if self.__require is None else self.__require.split("|") self.__version = sectionsFileParser.getValue("Version", "Component", default=None) if self.__version is None: raise fileStructureParsingError("Version") self.__author = sectionsFileParser.getValue("Author", "Informations", default=None) self.__email = sectionsFileParser.getValue("Email", "Informations", default=None) self.__url = sectionsFileParser.getValue("Url", "Informations", default=None) self.__description = sectionsFileParser.getValue("Description", "Informations", default=None) return True else: raise foundations.exceptions.FileStructureParsingError( "{0} | No sections found, '{1}' file structure seems invalid!".format(self.__class__.__name__, self.__file))
def testGetValue(self): """ Tests :meth:`foundations.parsers.SectionsFileParser.getValue` method. """ for type, file in STANDARD_FILES.iteritems(): sectionsFileParser = SectionsFileParser(file, preserveOrder=False) sectionsFileParser.parse( rawSections=STANDARD_FILES_RAW_SECTIONS[type]) for attribute, value in RANDOM_ATTRIBUTES[type].iteritems(): self.assertEqual( sectionsFileParser.getValue( attribute, foundations.namespace.getNamespace(attribute, rootOnly=True)), value) self.assertEqual( sectionsFileParser.getValue("attribute", "section", default=None), None) self.assertEqual( sectionsFileParser.getValue("attribute", "section", default=list()), list())
def testStripWhitespaces(self): """ This method tests :class:`foundations.parsers.SectionsFileParser` class whitespaces consistencies. """ sectionsFileParser = SectionsFileParser(STRIPPING_FILE) sectionsFileParser.read() and sectionsFileParser.parse( stripWhitespaces=False) for section in STRIPPING_FILE_SECTIONS_AND_ATTRIBUTES_NON_STRIPPED: self.assertIn(section, sectionsFileParser.sections) for attribute, value in STRIPPING_FILE_SECTIONS_AND_ATTRIBUTES_NON_STRIPPED[ section].iteritems(): self.assertIn(attribute, sectionsFileParser.sections[section]) self.assertIn( value, sectionsFileParser.sections[section].itervalues())
def testGetValue(self): """ This method tests :meth:`foundations.parsers.SectionsFileParser.getValue` method. """ for type, file in STANDARD_FILES.iteritems(): sectionsFileParser = SectionsFileParser(file) sectionsFileParser.read() and sectionsFileParser.parse(False, rawSections=STANDARD_FILES_RAW_SECTIONS[type]) for attribute, value in RANDOM_ATTRIBUTES[type].iteritems(): self.assertIsInstance(sectionsFileParser.getValue(attribute, namespace.getNamespace(attribute, rootOnly=True)), str) self.assertIsInstance(sectionsFileParser.getValue(attribute, namespace.getNamespace(attribute, rootOnly=True), encode=True), unicode) self.assertEqual(sectionsFileParser.getValue(attribute, namespace.getNamespace(attribute, rootOnly=True)), value)
def testWrite(self): """ This method tests :meth:`foundations.parsers.SectionsFileParser.write` method. """ # Standard sections files. for type, file in STANDARD_FILES.iteritems(): readSectionsFileParser = SectionsFileParser(file) readSectionsFileParser.read() and \ readSectionsFileParser.parse(stripComments=False, rawSections=STANDARD_FILES_RAW_SECTIONS[type]) writeSectionsFileParser = SectionsFileParser(tempfile.mkstemp()[1]) writeSectionsFileParser.sections = readSectionsFileParser.sections writeSectionsFileParser.comments = readSectionsFileParser.comments writeSectionsFileParser.write() checkingSectionsFileParser = SectionsFileParser(writeSectionsFileParser.file) checkingSectionsFileParser.read() and checkingSectionsFileParser.parse(stripComments=False, rawSections=STANDARD_FILES_RAW_SECTIONS[type]) self.assertDictEqual(readSectionsFileParser.sections, checkingSectionsFileParser.sections) os.remove(writeSectionsFileParser.file) # Standard sections files with namespaces. for type, file in STANDARD_FILES.iteritems(): readSectionsFileParser = SectionsFileParser(file) readSectionsFileParser.read() and readSectionsFileParser.parse(namespaces=True, stripComments=False, rawSections=STANDARD_FILES_RAW_SECTIONS[type]) writeSectionsFileParser = SectionsFileParser(tempfile.mkstemp()[1]) writeSectionsFileParser.sections = readSectionsFileParser.sections writeSectionsFileParser.comments = readSectionsFileParser.comments writeSectionsFileParser.write(namespaces=True) checkingSectionsFileParser = SectionsFileParser(writeSectionsFileParser.file) checkingSectionsFileParser.read() and checkingSectionsFileParser.parse(namespaces=False, stripComments=False, rawSections=STANDARD_FILES_RAW_SECTIONS[type]) self.assertDictEqual(readSectionsFileParser.sections, checkingSectionsFileParser.sections) os.remove(writeSectionsFileParser.file) # Default section file. readSectionsFileParser = SectionsFileParser(DEFAULTS_FILE) readSectionsFileParser.read() and readSectionsFileParser.parse() writeSectionsFileParser = SectionsFileParser(tempfile.mkstemp()[1]) writeSectionsFileParser.sections = readSectionsFileParser.sections writeSectionsFileParser.comments = readSectionsFileParser.comments writeSectionsFileParser.write() checkingSectionsFileParser = SectionsFileParser(writeSectionsFileParser.file) checkingSectionsFileParser.read() and checkingSectionsFileParser.parse() os.remove(writeSectionsFileParser.file)
def testGetValue(self): """ This method tests :meth:`foundations.parsers.SectionsFileParser.getValue` method. """ for type, file in STANDARD_FILES.iteritems(): sectionsFileParser = SectionsFileParser(file) sectionsFileParser.read() and sectionsFileParser.parse( False, rawSections=STANDARD_FILES_RAW_SECTIONS[type]) for attribute, value in RANDOM_ATTRIBUTES[type].iteritems(): self.assertIsInstance( sectionsFileParser.getValue( attribute, foundations.namespace.getNamespace(attribute, rootOnly=True)), str) self.assertIsInstance( sectionsFileParser.getValue( attribute, foundations.namespace.getNamespace(attribute, rootOnly=True), encode=True), unicode) self.assertEqual( sectionsFileParser.getValue( attribute, foundations.namespace.getNamespace(attribute, rootOnly=True)), value) self.assertEqual( sectionsFileParser.getValue("attribute", "section", default=None), None) self.assertEqual( sectionsFileParser.getValue("attribute", "section", default=list()), list())
def getLoaderScript(self, template, iblSet, overrideKeys): """ This method builds a Loader Script. :param template: Template path. ( String ) :param iblSet: Ibl Set path. ( String ) :param overrideKeys: Override keys. ( Dictionary ) :return: Loader Script. ( List ) """ LOGGER.debug("> Parsing Template file: '{0}'.".format(template)) templateSectionsFileParser = SectionsFileParser(template) templateSectionsFileParser.read() and templateSectionsFileParser.parse( rawSections=(self.__templateScriptSection)) templateSections = dict.copy(templateSectionsFileParser.sections) for attribute, value in dict.copy(templateSections[self.__templateIblSetAttributesSection]).iteritems(): templateSections[self.__templateIblSetAttributesSection][foundations.namespace.removeNamespace(attribute, rootOnly=True)] = value del templateSections[self.__templateIblSetAttributesSection][attribute] LOGGER.debug("> Binding Templates file attributes.") bindedAttributes = dict(((attribute, foundations.parsers.getAttributeCompound(attribute, value)) for section in templateSections if section not in (self.__templateScriptSection) for attribute, value in templateSections[section].iteritems())) LOGGER.debug("> Parsing Ibl Set file: '{0}'.".format(iblSet)) iblSetSectionsFileParser = SectionsFileParser(iblSet) iblSetSectionsFileParser.read() and iblSetSectionsFileParser.parse() iblSetSections = dict.copy(iblSetSectionsFileParser.sections) LOGGER.debug("> Flattening Ibl Set file attributes.") flattenedIblAttributes = dict(((attribute, foundations.parsers.getAttributeCompound(attribute, value)) for section in iblSetSections for attribute, value in iblSetSections[section].iteritems())) for attribute in flattenedIblAttributes: if attribute in bindedAttributes: bindedAttributes[attribute].value = flattenedIblAttributes[attribute].value if "Lights|DynamicLights" in bindedAttributes: LOGGER.debug("> Building '{0}' custom attribute.".format("Lights|DynamicLights")) dynamicLights = [] for section in iblSetSections: if re.search(r"Light\d+", section): dynamicLights.append(section) lightName = iblSetSectionsFileParser.getValue("LIGHTname", section) dynamicLights.append(lightName and lightName or self.__unnamedLightName) lightColorTokens = iblSetSectionsFileParser.getValue("LIGHTcolor", section).split(",") for color in lightColorTokens: dynamicLights.append(color) dynamicLights.append(iblSetSectionsFileParser.getValue("LIGHTmulti", section)) dynamicLights.append(iblSetSectionsFileParser.getValue("LIGHTu", section)) dynamicLights.append(iblSetSectionsFileParser.getValue("LIGHTv", section)) LOGGER.debug("> Adding '{0}' custom attribute with value: '{1}'.".format("Lights|DynamicLights", ", ".join(dynamicLights))) bindedAttributes["Lights|DynamicLights"].value = self.__defaultStringSeparator.join(dynamicLights) LOGGER.debug("> Updating attributes with override keys.") for attribute in overrideKeys: if attribute in bindedAttributes: bindedAttributes[attribute].value = overrideKeys[attribute] and overrideKeys[attribute].value or None LOGGER.debug("> Updating Loader Script content.") loaderScript = templateSectionsFileParser.sections[ self.__templateScriptSection][templateSectionsFileParser.rawSectionContentIdentifier] boundLoaderScript = [] for line in loaderScript: bindingParameters = re.findall(r"{0}".format(self.__bindingIdentifierPattern), line) if bindingParameters: for parameter in bindingParameters: for attribute in bindedAttributes.itervalues(): if not parameter == attribute.link: continue LOGGER.debug("> Updating Loader Script parameter '{0}' with value: '{1}'.".format(parameter, attribute.value)) line = line.replace(parameter, attribute.value if attribute.value else "-1") boundLoaderScript.append(line) return boundLoaderScript
def __releasesFileReply__finished(self): """ Defines the slot triggered by the releases file reply when finished. """ self.__engine.stopProcessing() if not self.__releasesFileReply.error(): content = [] while not self.__releasesFileReply.atEnd(): content.append( foundations.strings.toString( self.__releasesFileReply.readLine())) LOGGER.debug("> Parsing releases file content.") sectionsFileParser = SectionsFileParser() sectionsFileParser.content = content sectionsFileParser.parse() releases = {} for remoteObject in sectionsFileParser.sections: if remoteObject != Constants.applicationName: databaseTemplates = \ sibl_gui.components.core.database.operations.filterTemplates("^{0}$".format(remoteObject), "name") databaseTemplate = foundations.common.getFirstItem([ foundations.common.getFirstItem(databaseTemplate) for databaseTemplate in sorted(((databaseTemplate, databaseTemplate.release) for databaseTemplate in databaseTemplates), reverse=True, key=lambda x: (foundations.strings.getVersionRank(x[1]))) ]) if not self.__engine.parameters.databaseReadOnly: if databaseTemplate: if databaseTemplate.release != sectionsFileParser.getValue( "Release", remoteObject): releases[remoteObject] = ReleaseObject( name=remoteObject, repositoryVersion=sectionsFileParser. getValue("Release", remoteObject), localVersion=databaseTemplate.release, type=sectionsFileParser.getValue( "Type", remoteObject), url=sectionsFileParser.getValue( "Url", remoteObject), comment=sectionsFileParser.getValue( "Comment", remoteObject)) else: if not self.Ignore_Non_Existing_Templates_checkBox.isChecked( ): releases[remoteObject] = ReleaseObject( name=remoteObject, repositoryVersion=sectionsFileParser. getValue("Release", remoteObject), localVersion=None, type=sectionsFileParser.getValue( "Type", remoteObject), url=sectionsFileParser.getValue( "Url", remoteObject), comment=sectionsFileParser.getValue( "Comment", remoteObject)) else: LOGGER.info( "{0} | '{1}' repository remote object skipped by '{2}' command line parameter value!" .format(self.__class__.__name__, remoteObject, "databaseReadOnly")) else: if Constants.version != sectionsFileParser.getValue( "Release", remoteObject): releases[remoteObject] = ReleaseObject( name=remoteObject, repositoryVersion=sectionsFileParser.getValue( "Release", remoteObject), localVersion=Constants.version, url=sectionsFileParser.getValue( "Url", remoteObject), type=sectionsFileParser.getValue( "Type", remoteObject), comment=None) if releases: LOGGER.debug("> Initializing Remote Updater.") self.__remoteUpdater = RemoteUpdater(self, releases, Qt.Window) self.__remoteUpdater.show() else: self.__reportUpdateStatus and self.__engine.notificationsManager.notify( "{0} | '{1}' is up to date!".format( self.__class__.__name__, Constants.applicationName)) else: raise sibl_gui.exceptions.NetworkError( "{0} | QNetworkAccessManager error code: '{1}'.".format( self.__class__.__name__, self.__releasesFileReply.error()))
def testWrite(self): """ This method tests :meth:`foundations.parsers.SectionsFileParser.write` method. """ # Standard sections files. for type, file in STANDARD_FILES.iteritems(): readSectionsFileParser = SectionsFileParser(file) readSectionsFileParser.read() and \ readSectionsFileParser.parse(stripComments=False, rawSections=STANDARD_FILES_RAW_SECTIONS[type]) fileDescriptor, path = tempfile.mkstemp() writeSectionsFileParser = SectionsFileParser(path) writeSectionsFileParser.sections = readSectionsFileParser.sections writeSectionsFileParser.comments = readSectionsFileParser.comments writeSectionsFileParser.write() checkingSectionsFileParser = SectionsFileParser( writeSectionsFileParser.path) checkingSectionsFileParser.read( ) and checkingSectionsFileParser.parse( stripComments=False, rawSections=STANDARD_FILES_RAW_SECTIONS[type]) self.assertDictEqual(readSectionsFileParser.sections, checkingSectionsFileParser.sections) os.close(fileDescriptor) # Standard sections files with namespaces. for type, file in STANDARD_FILES.iteritems(): readSectionsFileParser = SectionsFileParser(file) readSectionsFileParser.read() and readSectionsFileParser.parse( namespaces=True, stripComments=False, rawSections=STANDARD_FILES_RAW_SECTIONS[type]) fileDescriptor, path = tempfile.mkstemp() writeSectionsFileParser = SectionsFileParser(path) writeSectionsFileParser.sections = readSectionsFileParser.sections writeSectionsFileParser.comments = readSectionsFileParser.comments writeSectionsFileParser.write(namespaces=True) checkingSectionsFileParser = SectionsFileParser( writeSectionsFileParser.path) checkingSectionsFileParser.read( ) and checkingSectionsFileParser.parse( namespaces=False, stripComments=False, rawSections=STANDARD_FILES_RAW_SECTIONS[type]) self.assertDictEqual(readSectionsFileParser.sections, checkingSectionsFileParser.sections) os.close(fileDescriptor) # Default section file. readSectionsFileParser = SectionsFileParser(DEFAULTS_FILE) readSectionsFileParser.read() and readSectionsFileParser.parse() fileDescriptor, path = tempfile.mkstemp() writeSectionsFileParser = SectionsFileParser(path) writeSectionsFileParser.sections = readSectionsFileParser.sections writeSectionsFileParser.comments = readSectionsFileParser.comments writeSectionsFileParser.write() checkingSectionsFileParser = SectionsFileParser( writeSectionsFileParser.path) checkingSectionsFileParser.read() and checkingSectionsFileParser.parse( ) os.close(fileDescriptor)