示例#1
0
    def check_root_element(self):
        """Checks if root element is valid"""
        logmgr_flog()

        tag = etree.QName(self.__root.tag)
        if tag.localname not in VALIDROOTS:
            raise DMInvalidXMLRootElement("Cannot add info element to file %r. "
                                          "This file does not contain a valid "
                                          "DocBook 5 root element. Found %s",
                                          self._filename, localname(self.__root.tag),
                                          ReturnCodes.E_INVALID_ROOT_ELEMENT)
示例#2
0
    def get_attr(self, props, data):
        """Gets one or more attributes of a property
        :param list props: The properties
        :param list data: A list of all attributes
        """
        attrs = OrderedDict()
        nodes = []

        if props:
            for prop in props:
                attrs[prop] = OrderedDict()
                node = self.find_elem(prop)

                if node is not None:
                    nodes.append((localname(node.tag), node))
        else:
            for idx, i in enumerate(self.__docmanager.iter()):
                # this is needed because otherwise we also get the "docmanager"
                # element
                if idx:
                    xpath = get_property_xpath(i)

                    attrs[xpath] = OrderedDict()
                    nodes.append((xpath, i))

        for node in nodes:
            prop = node[0]
            elem = node[1]

            if data:
                for i in data:
                    try:
                        attrs[prop][i] = elem.attrib[i]
                    except KeyError:
                        pass
            else:
                for i in elem.attrib:
                    attrs[prop][i] = elem.attrib[i]

        return attrs
def test_docmanager_delcheck2(tmp_valid_xml):
    handler = XmlHandler(tmp_valid_xml.strpath)
    handler.init_default_props(False)
    dm = handler.tree.find("//dm:docmanager", namespaces=NS)
    dmset = set(localname(e.tag) for e in list(dm.iterchildren()))
    assert dmset == set(DEFAULT_DM_PROPERTIES)
示例#4
0
def test_localname(text, expected):
    result = localname(text)
    assert result == expected
示例#5
0
    def fetch_data(self, filter=None, sort=None, default_output=None):
        """Fetches the requested properties from self.extract_fields()

        :param list filter: The filter list from args.filter (can be None if we don't need the filter function)
        :param string sort: The sort item for the sort function (this is a property - can be None if we don't
                            want to use the sort function)
        :return dict: a dictionary with all properties and their values
        """

        data = dict()

        if not filter:
            self.filters_matched = True

        if self.fields:
            # build the xpath for selecting all needed properties
            xpath = "*[self::dm:" + " or self::dm:".join(self.fields)
            if sort is None:
                xpath += "]"
            else:
                # when the args.sort is set, we can append that string to our
                # xpath. that's needed if we want to display 'maintainer' but
                # sort
                xpath += " or self::dm:" + sort + "]"
                self.fields.add(sort)

            # if there are invalid characters in the xpath, lxml throws an exception.
            # We have to catch that.
            try:
                data = {
                    localname(e.tag): e.text
                    for e in self.xmlhandler.dm.xpath(xpath, namespaces=NS)
                }
            except etree.XPathEvalError:
                log.error(
                    "The given XML properties in --sort/-s or --queryformat/-qf are invalid."
                )
                sys.exit(ReturnCodes.E_INVALID_XML_PROPERTIES)

            # loop over all 'properties' and fetch their values from the XML file. properties
            # without values will become an empty string if the 'default-option' was not set
            for f in self.fields:
                data.setdefault(f, data.get(f, None))

                if not data[f]:
                    if not default_output:
                        data[f] = ''
                    else:
                        data[f] = default_output

        if filter:
            filters = dict()
            filters_xpath = ""

            for idx, f in enumerate(filter):
                try:
                    # validate the filter syntax of any given filter
                    mode, prop, condition = self.validate_filter(f)

                    # save the details about a filter in a dictionary
                    filters[prop] = dict()
                    filters[prop]['mode'] = mode
                    filters[prop]['condition'] = condition

                    if idx == 0:
                        filters_xpath += "self::dm:" + prop
                    else:
                        filters_xpath += " or self::dm:" + prop
                except DMAnalyzeInvalidFilterSyntax:
                    # syntax is wrong
                    log.error("Invalid syntax in filter: '{}'".format(f))
                    log.error(
                        "Look into the manual page for more information about using filters."
                    )
                    sys.exit(ReturnCodes.E_ANALYZE_FILTER_INVALID_SYNTAX)

            # catch the values of the filter properties
            f_xpath = {
                localname(e.tag): e.text
                for e in self.xmlhandler.dm.xpath(
                    "*[{}]".format(filters_xpath), namespaces=NS)
            }

            for f in filters:
                # if the filter property was not found in the XML file -> the filter didn't
                # not match and we have to return an empty dictionary
                if f not in f_xpath:
                    self.filters_matched = False
                    return {}

                    # f_xpath[f] = ''

                # condition checks
                if filters[f]['mode'] == '+':
                    if f_xpath[f] != filters[f]['condition']:
                        self.filters_matched = False
                        return {}
                elif filters[f]['mode'] == '-':
                    if f_xpath[f] == filters[f]['condition']:
                        self.filters_matched = False
                        return {}

        return data