How to use the xmlschema.exceptions.XMLSchemaValueError 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 / converters.py View on Github external
def element_encode(self, obj, xsd_element, level=0):
        unmap_qname = self.unmap_qname
        attributes = {}
        if not isinstance(obj, (self.list, list)) or not obj:
            raise XMLSchemaValueError("Wrong data format, a not empty list required: %r." % obj)

        data_len = len(obj)
        if data_len == 1:
            if not xsd_element.is_matching(unmap_qname(obj[0]), self._namespaces.get('')):
                raise XMLSchemaValueError("Unmatched tag")
            return ElementData(xsd_element.name, None, None, attributes)

        try:
            for k, v in obj[1].items():
                if k == 'xmlns':
                    self[''] = v
                elif k.startswith('xmlns:'):
                    self[k.split('xmlns:')[1]] = v
                else:
                    attributes[self.unmap_qname(k, xsd_element.attributes)] = v
        except AttributeError:
github sissaschool / xmlschema / xmlschema / converters.py View on Github external
try:
            for k, v in obj[1].items():
                if k == 'xmlns':
                    self[''] = v
                elif k.startswith('xmlns:'):
                    self[k.split('xmlns:')[1]] = v
                else:
                    attributes[self.unmap_qname(k, xsd_element.attributes)] = v
        except AttributeError:
            content_index = 1
        else:
            content_index = 2

        if not xsd_element.is_matching(unmap_qname(obj[0]), self._namespaces.get('')):
            raise XMLSchemaValueError("Unmatched tag")

        if data_len <= content_index:
            return ElementData(xsd_element.name, None, [], attributes)
        elif data_len == content_index + 1 and \
                (xsd_element.type.is_simple() or xsd_element.type.has_simple_content()):
            return ElementData(xsd_element.name, obj[content_index], [], attributes)
        else:
            cdata_num = iter(range(1, data_len))
            list_types = list if self.list is list else (self.list, list)
            content = [
                (unmap_qname(e[0]), e) if isinstance(e, list_types) else (next(cdata_num), e)
                for e in obj[content_index:]
            ]
            return ElementData(xsd_element.name, None, content, attributes)
github sissaschool / xmlschema / xmlschema / validators / complex_types.py View on Github external
def _parse_derivation_elem(self, elem):
        derivation_elem = self._parse_child_component(elem)
        if getattr(derivation_elem, 'tag', None) not in (XSD_RESTRICTION, XSD_EXTENSION):
            self.parse_error("restriction or extension tag expected", derivation_elem)
            self.content_type = self.schema.create_any_content_group(self)
            self.attributes = self.schema.create_any_attribute_group(self)
            return

        derivation = local_name(derivation_elem.tag)
        if self.derivation is None:
            self.derivation = derivation
        elif self.redefine is None:
            raise XMLSchemaValueError("%r is expected to have a redefined/overridden component" % self)

        if self.base_type is not None and derivation in self.base_type.final:
            self.parse_error("%r derivation not allowed for %r." % (derivation, self))
        return derivation_elem
github sissaschool / xmlschema / xmlschema / validators / xsdbase.py View on Github external
raise XMLSchemaValueError("'elem' argument must be an Element instance, not %r." % elem)

        if isinstance(error, XMLSchemaParseError):
            error.validator = self
            error.namespaces = getattr(self, 'namespaces', None)
            error.elem = elem
            error.source = getattr(self, 'source', None)
        elif isinstance(error, Exception):
            message = unicode_type(error).strip()
            if message[0] in '\'"' and message[0] == message[-1]:
                message = message.strip('\'"')
            error = XMLSchemaParseError(self, message, elem)
        elif isinstance(error, string_base_type):
            error = XMLSchemaParseError(self, error, elem)
        else:
            raise XMLSchemaValueError("'error' argument must be an exception or a string, not %r." % error)

        if validation == 'lax':
            self.errors.append(error)
        else:
            raise error
github sissaschool / xmlschema / xmlschema / validators / schema.py View on Github external
def __setattr__(self, name, value):
        if name == 'root' and value.tag not in (XSD_SCHEMA, 'schema'):
            raise XMLSchemaValueError("schema root element must has %r tag." % XSD_SCHEMA)
        elif name == 'maps':
            if self.meta_schema is None and hasattr(self, 'maps'):
                raise XMLSchemaValueError("cannot change the global maps instance of a meta-schema")
            super(XMLSchemaBase, self).__setattr__(name, value)
            self.notations = NamespaceView(value.notations, self.target_namespace)
            self.types = NamespaceView(value.types, self.target_namespace)
            self.attributes = NamespaceView(value.attributes, self.target_namespace)
            self.attribute_groups = NamespaceView(value.attribute_groups, self.target_namespace)
            self.groups = NamespaceView(value.groups, self.target_namespace)
            self.elements = NamespaceView(value.elements, self.target_namespace)
            self.substitution_groups = NamespaceView(value.substitution_groups, self.target_namespace)
            self.identities = NamespaceView(value.identities, self.target_namespace)
            self.global_maps = (self.notations, self.types, self.attributes,
                                self.attribute_groups, self.groups, self.elements)
            value.register(self)
        elif name == 'validation' and value not in ('strict', 'lax', 'skip'):
            raise XMLSchemaValueError("Wrong value %r for attribute 'validation'." % value)
        else:
            super(XMLSchemaBase, self).__setattr__(name, value)
github sissaschool / xmlschema / xmlschema / resources.py View on Github external
def open(self):
        """
        Returns a opened resource reader object for the instance URL. If the
        source attribute is a seekable file-like object rewind the source and
        return it.
        """
        if self.seek(0) == 0:
            return self.source
        elif self._url is None:
            raise XMLSchemaValueError("can't open, the resource has no URL associated.")

        try:
            return urlopen(self._url, timeout=self.timeout)
        except URLError as err:
            raise XMLSchemaURLError("cannot access to resource %r: %s" % (self._url, err.reason))
github sissaschool / xmlschema / xmlschema / validators / parseutils.py View on Github external
def get_xsd_component(elem, required=True, strict=True):
    """
    Returns the first XSD component child, excluding the annotation.

    :param elem: the parent Element.
    :param required: if `True`, that is the default, raises a *ValueError* if there \
    is not any component; with `False` in those cases `None` is returned.
    :param strict: raises a *ValueError* if there is more than one component.
    """
    components_iterator = iter_xsd_components(elem)
    try:
        xsd_component = next(components_iterator)
    except StopIteration:
        if required:
            raise XMLSchemaValueError("missing XSD component")
        return None
    else:
        if not strict:
            return xsd_component
        try:
            next(components_iterator)
        except StopIteration:
            return xsd_component
        else:
            raise XMLSchemaValueError("too many XSD components")
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)
                )
        super(XsdComponent, self).__setattr__(name, value)
github sissaschool / xmlschema / xmlschema / validators / simple_types.py View on Github external
def normalize(self, text):
        """
        Normalize and restrict value-space with pre-lexical and lexical facets.
        The normalized string is returned. Returns the argument if it isn't a string.

        :param text: text string encoded value.
        :return: normalized string.
        """
        if isinstance(text, bytes):
            text = text.decode('utf-8')
        elif not isinstance(text, string_base_type):
            raise XMLSchemaValueError('argument is not a string: %r' % text)

        if self.white_space == 'replace':
            return self._REGEX_SPACE.sub(' ', text)
        elif self.white_space == 'collapse':
            return self._REGEX_SPACES.sub(' ', text).strip()
        else:
            return text