Python lxml.etree.DocumentInvalid() Examples

The following are 8 code examples of lxml.etree.DocumentInvalid(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module lxml.etree , or try the search function .
Example #1
Source File: xsd_validator.py    From core with Apache License 2.0 6 votes vote down vote up
def _validate(self, doc):
        """
        Do the actual validation.

        Arguments:
            doc (etree.ElementTree|str|bytes|pathlib.Path): the document. if etree: us as-is. if str/bytes: parse as XML string. If Path: read_text on it

        Returns: ValidationReport
        """
        report = ValidationReport()
        if isinstance(doc, Path):
            doc = ET.parse(str(doc))
        if isinstance(doc, (bytes, str)):
            doc = ET.fromstring(doc)
        try:
            self._xmlschema.assertValid(doc)
        except ET.DocumentInvalid as fail:
            for err in fail.error_log:  # pylint: disable=no-member
                report.add_error("Line %s: %s" % (err.line, err.message))
        return report 
Example #2
Source File: validation.py    From daf-recipes with GNU General Public License v3.0 5 votes vote down vote up
def _is_valid(cls, xml, xsd_filepath, xsd_name):
        '''Returns whether or not an XML file is valid according to
        an XSD. Returns a tuple, the first value is a boolean indicating
        whether the validation passed or not. The second is a list of tuples,
        each containing the error message and the error line.

        Params:
          xml - etree of the XML to be validated
          xsd_filepath - full path to the XSD file
          xsd_name - string describing the XSD

        Returns:
          (is_valid, [(error_message_string, error_line_number)])
        '''
        xsd = etree.parse(xsd_filepath)
        schema = etree.XMLSchema(xsd)
        # With libxml2 versions before 2.9, this fails with this error:
        #    gmx_schema = etree.XMLSchema(gmx_xsd)
        # File "xmlschema.pxi", line 103, in
        # lxml.etree.XMLSchema.__init__ (src/lxml/lxml.etree.c:116069)
        # XMLSchemaParseError: local list type: A type, derived by list or
        # union, must have the simple ur-type definition as base type,
        # not '{http://www.opengis.net/gml/3.2}doubleList'., line 118
        try:
            schema.assertValid(xml)
        except etree.DocumentInvalid:
            log.info(
                'Validation errors found using schema {0}'.format(xsd_name))
            errors = []
            for error in schema.error_log:
                errors.append((error.message, error.line))
            errors.insert
            return False, errors
        return True, [] 
Example #3
Source File: client.py    From aiohttp-xmlrpc with MIT License 5 votes vote down vote up
def _parse_response(body, method_name):
        try:
            if log.getEffectiveLevel() <= logging.DEBUG:
                log.debug("Server response: \n%s", body.decode())

            response = etree.fromstring(body)
            schema.assertValid(response)
        except etree.DocumentInvalid:
            raise ValueError("Invalid body")

        result = response.xpath('//params/param/value/*')
        if result:
            return xml2py(result[0])

        fault = response.xpath('//fault/value/*')
        if fault:
            err = xml2py(fault[0])

            raise xml2py_exception(
                err.get('faultCode', exceptions.SystemError.code),
                err.get('faultString', 'Unknown error'),
                default_exc_class=exceptions.ServerError
            )

        raise exceptions.ParseError('Respond body for method "%s" '
                                    'not contains any response.', method_name) 
Example #4
Source File: handler.py    From aiohttp-xmlrpc with MIT License 5 votes vote down vote up
def _parse_body(self, body):
        try:
            return self._parse_xml(body)
        except etree.DocumentInvalid:
            raise HTTPBadRequest 
Example #5
Source File: test.py    From signxml with Apache License 2.0 5 votes vote down vote up
def test_soap_request_with_inclusive_namespaces(self):
        with open(os.path.join(interop_dir, "soap", "request.xml")) as req_fh:
            with self.assertRaises(etree.DocumentInvalid):
                XMLVerifier().verify(req_fh.read(),
                                     ca_pem_file=os.path.join(interop_dir, "soap", "ca.pem"),
                                     expect_references=False)
            req_fh.seek(0)
            XMLVerifier().verify(req_fh.read(),
                                 ca_pem_file=os.path.join(interop_dir, "soap", "ca.pem"),
                                 expect_references=False,
                                 validate_schema=False) 
Example #6
Source File: _permission.py    From sros2 with Apache License 2.0 5 votes vote down vote up
def create_permission_file(path, domain_id, policy_element):
    print('creating permission')
    permissions_xsl_path = get_transport_template('dds', 'permissions.xsl')
    permissions_xsl = etree.XSLT(etree.parse(permissions_xsl_path))
    permissions_xsd_path = get_transport_schema('dds', 'permissions.xsd')
    permissions_xsd = etree.XMLSchema(etree.parse(permissions_xsd_path))

    kwargs = {}

    cert_path = os.path.join(os.path.dirname(path), 'cert.pem')
    cert_content = _utilities.load_cert(cert_path)
    kwargs['not_valid_before'] = etree.XSLT.strparam(cert_content.not_valid_before.isoformat())
    kwargs['not_valid_after'] = etree.XSLT.strparam(cert_content.not_valid_after.isoformat())

    if get_rmw_implementation_identifier() in _RMW_WITH_ROS_GRAPH_INFO_TOPIC:
        kwargs['allow_ros_discovery_topic'] = etree.XSLT.strparam('1')
    permissions_xml = permissions_xsl(policy_element, **kwargs)

    domain_id_elements = permissions_xml.findall('permissions/grant/*/domains/id')
    for domain_id_element in domain_id_elements:
        domain_id_element.text = domain_id

    try:
        permissions_xsd.assertValid(permissions_xml)
    except etree.DocumentInvalid as e:
        raise RuntimeError(str(e))

    with open(path, 'wb') as f:
        f.write(etree.tostring(permissions_xml, pretty_print=True)) 
Example #7
Source File: __init__.py    From sros2 with Apache License 2.0 5 votes vote down vote up
def load_policy(policy_file_path):
    if not os.path.isfile(policy_file_path):
        raise FileNotFoundError("policy file '%s' does not exist" % policy_file_path)
    policy = etree.parse(policy_file_path)
    policy.xinclude()
    try:
        policy_xsd_path = get_policy_schema('policy.xsd')
        policy_xsd = etree.XMLSchema(etree.parse(policy_xsd_path))
        policy_xsd.assertValid(policy)
    except etree.DocumentInvalid as e:
        raise RuntimeError(str(e))
    return policy 
Example #8
Source File: __init__.py    From sros2 with Apache License 2.0 5 votes vote down vote up
def dump_policy(policy, stream):
    policy_xsl_path = get_policy_template('policy.xsl')
    policy_xsl = etree.XSLT(etree.parse(policy_xsl_path))
    policy = policy_xsl(policy)
    try:
        policy_xsd_path = get_policy_schema('policy.xsd')
        policy_xsd = etree.XMLSchema(etree.parse(policy_xsd_path))
        policy_xsd.assertValid(policy)
    except etree.DocumentInvalid as e:
        raise RuntimeError(str(e))
    stream.write(etree.tostring(policy, pretty_print=True).decode())