How to use the xmlschema.exceptions.XMLSchemaTypeError function in xmlschema

To help you get started, we’ve selected a few xmlschema examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github sissaschool / xmlschema / xmlschema / helpers.py View on Github external
:param qname: an expanded QName or a prefixed name or a local name.
    """
    try:
        if qname[0] == '{':
            _, qname = qname.split('}')
        elif ':' in qname:
            _, qname = qname.split(':')
    except IndexError:
        return ''
    except ValueError:
        raise XMLSchemaValueError("the argument 'qname' has a wrong format: %r" % qname)
    except TypeError:
        if qname is None:
            return qname
        raise XMLSchemaTypeError("the argument 'qname' must be a string-like object or None")
    else:
        return qname
github sissaschool / xmlschema / xmlschema / validators / schema.py View on Github external
"""Processes schema document inclusions and redefinitions."""
        for child in filter(lambda x: x.tag == XSD_INCLUDE, self.root):
            try:
                location = child.attrib['schemaLocation'].strip()
                logger.info("Include schema from %r", location)
                self.include_schema(location, self.base_url)
            except KeyError:
                pass
            except (OSError, IOError) as err:
                # Attribute missing error already found by validation against meta-schema.
                # It is not an error if the location fail to resolve:
                #   https://www.w3.org/TR/2012/REC-xmlschema11-1-20120405/#compound-schema
                #   https://www.w3.org/TR/2012/REC-xmlschema11-1-20120405/#src-include
                self.warnings.append("Include schema failed: %s." % str(err))
                warnings.warn(self.warnings[-1], XMLSchemaIncludeWarning, stacklevel=3)
            except (XMLSchemaURLError, XMLSchemaParseError, XMLSchemaTypeError, ParseError) as err:
                msg = 'cannot include schema %r: %s' % (child.attrib['schemaLocation'], err)
                if isinstance(err, (XMLSchemaParseError, ParseError)):
                    self.parse_error(msg)
                elif self.validation == 'strict':
                    raise type(err)(msg)
                else:
                    self.errors.append(type(err)(msg))

        for child in filter(lambda x: x.tag == XSD_REDEFINE, self.root):
            try:
                location = child.attrib['schemaLocation'].strip()
                logger.info("Redefine schema %r", location)
                schema = self.include_schema(location, self.base_url)
            except KeyError:
                pass  # Attribute missing error already found by validation against meta-schema
            except (OSError, IOError) as err:
github sissaschool / xmlschema / xmlschema / validators / globals_.py View on Github external
def get_instance_type(self, type_name, base_type, namespaces):
        """
        Returns the instance XSI type from global maps, validating it with the reference base type.

        :param type_name: the XSI type attribute value, a QName in prefixed format.
        :param base_type: the XSD from which the instance type has to be derived.
        :param namespaces: a map from prefixes to namespaces.
        """
        if base_type.is_complex() and XSI_TYPE in base_type.attributes:
            base_type.attributes[XSI_TYPE].validate(type_name)

        extended_name = qname_to_extended(type_name, namespaces)
        xsi_type = lookup_type(extended_name, self.types, self.validator.BUILDERS_MAP)
        if not xsi_type.is_derived(base_type):
            raise XMLSchemaTypeError("%r is not a derived type of %r" % (xsi_type, self))
        return xsi_type
github sissaschool / xmlschema / xmlschema / etree.py View on Github external
elif isinstance(elem, py_etree_element):
        if namespaces:
            for prefix, uri in namespaces.items():
                if not re.match(r'ns\d+$', prefix):
                    PyElementTree.register_namespace(prefix, uri)
        tostring = PyElementTree.tostring

    elif lxml_etree is not None:
        if namespaces:
            for prefix, uri in namespaces.items():
                if prefix and not re.match(r'ns\d+$', prefix):
                    lxml_etree_register_namespace(prefix, uri)
        tostring = lxml_etree.tostring
    else:
        raise XMLSchemaTypeError("cannot serialize %r: lxml library not available." % type(elem))

    if PY3:
        xml_text = tostring(elem, encoding="unicode").replace('\t', ' ' * spaces_for_tab)
    else:
        xml_text = unicode(tostring(elem)).replace('\t', ' ' * spaces_for_tab)

    lines = [''] if xml_declaration else []
    lines.extend(xml_text.splitlines())
    while lines and not lines[-1].strip():
        lines.pop(-1)

    last_indent = ' ' * min(k for k in range(len(lines[-1])) if lines[-1][k] != ' ')
    if len(lines) > 2:
        child_indent = ' ' * min(k for line in lines[1:-1] for k in range(len(line)) if line[k] != ' ')
        min_indent = min(child_indent, last_indent)
    else:
github sissaschool / xmlschema / xmlschema / xpath.py View on Github external
def __init__(self, schema=None, base_element=None):
        if schema is None:
            from xmlschema import XMLSchema
            schema = XMLSchema.meta_schema
        super(XMLSchemaProxy, self).__init__(schema, base_element)

        if base_element is not None:
            try:
                if base_element.schema is not schema:
                    raise XMLSchemaValueError("%r is not an element of %r" % (base_element, schema))
            except AttributeError:
                raise XMLSchemaTypeError("%r is not an XsdElement" % base_element)
github sissaschool / xmlschema / xmlschema / resources.py View on Github external
finally:
                self._url = _url

        else:
            # Try ElementTree object at last
            try:
                root = source.getroot()
            except (AttributeError, TypeError):
                pass
            else:
                if hasattr(root, 'tag'):
                    self._lazy = False
                    return root, None, None

        if url is None:
            raise XMLSchemaTypeError(
                "wrong type %r for 'source' attribute: an ElementTree object or an Element instance or a "
                "string containing XML data or an URL or a file-like object is required." % type(source)
            )
        else:
            resource = urlopen(url, timeout=self.timeout)
            _url, self._url = self._url, url
            try:
                if self._lazy:
                    for _, root in self.iterparse(resource, events=('start',)):
                        return root, None, url
                else:
                    return self.parse(resource).getroot(), None, url
            finally:
                self._url = _url
                resource.close()
github sissaschool / xmlschema / xmlschema / validators / schema.py View on Github external
with self.meta_schema.lock:
            if not self.meta_schema.maps.types:
                self.meta_schema.maps.build()

        # Create or set the XSD global maps instance
        if global_maps is None:
            if use_meta and self.target_namespace not in self.meta_schema.maps.namespaces:
                self.maps = self.meta_schema.maps.copy(self, validation=validation)
            else:
                self.maps = XsdGlobals(self, validation)

        elif isinstance(global_maps, XsdGlobals):
            self.maps = global_maps
        else:
            raise XMLSchemaTypeError("'global_maps' argument must be an %r instance." % XsdGlobals)

        if self.XSD_VERSION > '1.0' and any(ns == VC_NAMESPACE for ns in self.namespaces.values()):
            # For XSD 1.1+ apply versioning filter to schema tree. See the paragraph
            # 4.2.2 of XSD 1.1 (Part 1: Structures) definition for details.
            # Ref: https://www.w3.org/TR/xmlschema11-1/#cip
            if prune_etree(root, selector=lambda x: not self.version_check(x)):
                for k in list(root.attrib):
                    if k not in {'targetNamespace', VC_MIN_VERSION, VC_MAX_VERSION}:
                        del root.attrib[k]

        # Validate the schema document (transforming validation errors to parse errors)
        if validation != 'skip':
            for e in self.meta_schema.iter_errors(root, namespaces=self.namespaces):
                self.parse_error(e.reason, elem=e.elem)

        self._parse_inclusions()
github sissaschool / xmlschema / xmlschema / validators / xsdbase.py View on Github external
def __setattr__(self, name, value):
        if name == "elem":
            if not is_etree_element(value):
                raise XMLSchemaTypeError("%r attribute must be an Etree Element: %r" % (name, value))
            elif value.tag not in self._ADMITTED_TAGS:
                raise XMLSchemaValueError(
                    "wrong XSD element %r for %r, must be one of %r." % (
                        local_name(value.tag), self,
                        [local_name(tag) for tag in self._ADMITTED_TAGS]
                    )
                )
            super(XsdComponent, self).__setattr__(name, value)
            self._parse()
            return
        elif name == "schema":
            if hasattr(self, 'schema') and self.schema.target_namespace != value.target_namespace:
                raise XMLSchemaValueError(
                    "cannot change 'schema' attribute of %r: the actual %r has a different "
                    "target namespace than %r." % (self, self.schema, value)
                )
github sissaschool / xmlschema / xmlschema / components / xsdbase.py View on Github external
def __setattr__(self, name, value):
        if name == "elem":
            if not etree_iselement(value):
                raise XMLSchemaTypeError("%r attribute must be an Etree Element: %r" % (name, value))
            elif value.tag not in self.admitted_tags:
                raise XMLSchemaValueError(
                    "wrong XSD element %r for %r, must be one of %r." % (
                        local_name(value.tag), self,
                        [local_name(tag) for tag in self.admitted_tags]
                    )
                )
            elif hasattr(self, 'elem'):
                self._elem = self.elem  # redefinition cases
        elif name == "schema":
            if hasattr(self, 'schema') and self.schema.target_namespace != value.target_namespace:
                raise XMLSchemaValueError(
                    "cannot change 'schema' attribute of %r: the actual %r has a different "
                    "target namespace than %r." % (self, self.schema, value)
                )
            self.target_namespace = value.target_namespace