How to use xmlschema - 10 common examples

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 / validators / facets.py View on Github external
def base64_min_length_validator(self, x):
        x = x.replace(' ', '')
        if (len(x) // 4 * 3 - (x[-1] in ('=', 61)) - (x[-2] in ('=', 61))) < self.value:
            yield XMLSchemaValidationError(self, x, "binary length cannot be lesser than %r." % self.value)
github sissaschool / xmlschema / xmlschema / validators / facets.py View on Github external
def max_length_validator(self, x):
        if len(x) > self.value:
            yield XMLSchemaValidationError(self, x, "length cannot be greater than %r." % self.value)

    def hex_max_length_validator(self, x):
        if len(x) > self.value * 2:
            yield XMLSchemaValidationError(self, x, "binary length cannot be greater than %r." % self.value)

    def base64_max_length_validator(self, x):
        x = x.replace(' ', '')
        if (len(x) // 4 * 3 - (x[-1] == '=') - (x[-2] == '=')) > self.value:
            yield XMLSchemaValidationError(self, x, "binary length cannot be greater than %r." % self.value)


class XsdMinInclusiveFacet(XsdFacet):
    """
    XSD *minInclusive* facet.

    ..  
          Content: (annotation?)
        
    """
    _ADMITTED_TAGS = XSD_MIN_INCLUSIVE,

    def _parse_value(self, elem):
        try:
            self.value = self.base_type.primitive_type.decode(elem.attrib['value'])
github sissaschool / xmlschema / xmlschema / validators / facets.py View on Github external
def min_length_validator(self, x):
        if len(x) < self.value:
            yield XMLSchemaValidationError(self, x, "length cannot be lesser than %r." % self.value)

    def hex_min_length_validator(self, x):
        if len(x) < self.value * 2:
            yield XMLSchemaValidationError(self, x, "binary length cannot be lesser than %r." % self.value)

    def base64_min_length_validator(self, x):
        x = x.replace(' ', '')
        if (len(x) // 4 * 3 - (x[-1] in ('=', 61)) - (x[-2] in ('=', 61))) < self.value:
            yield XMLSchemaValidationError(self, x, "binary length cannot be lesser than %r." % self.value)


class XsdMaxLengthFacet(XsdFacet):
    """
    XSD *maxLength* facet.

    ..  
          Content: (annotation?)
        
    """
    _ADMITTED_TAGS = XSD_MAX_LENGTH,

    def _parse_value(self, elem):
        self.value = int(elem.attrib['value'])
        if self.base_value is not None and self.value > self.base_value:
github sissaschool / xmlschema / xmlschema / validators / facets.py View on Github external
def length_validator(self, x):
        if len(x) != self.value:
            yield XMLSchemaValidationError(self, x, "length has to be %r." % self.value)

    def hex_length_validator(self, x):
        if len(x) != self.value * 2:
            yield XMLSchemaValidationError(self, x, "binary length has to be %r." % self.value)

    def base64_length_validator(self, x):
        x = x.replace(' ', '')
        if (len(x) // 4 * 3 - (x[-1] == '=') - (x[-2] == '=')) != self.value:
            yield XMLSchemaValidationError(self, x, "binary length has to be %r." % self.value)


class XsdMinLengthFacet(XsdFacet):
    """
    XSD *minLength* facet.

    ..  
          Content: (annotation?)
        
    """
    _ADMITTED_TAGS = XSD_MIN_LENGTH,

    def _parse_value(self, elem):
        self.value = int(elem.attrib['value'])
        if self.base_value is not None and self.value < self.base_value:
github pytest-dev / pytest / testing / test_junitxml.py View on Github external
@pytest.fixture(scope="session")
def schema():
    """Returns a xmlschema.XMLSchema object for the junit-10.xsd file"""
    fn = Path(__file__).parent / "example_scripts/junit-10.xsd"
    with fn.open() as f:
        return xmlschema.XMLSchema(f)
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 / groups.py View on Github external
xsd_type = xsd_element.type
            else:
                alternatives = xsd_element.alternatives
                try:
                    type_name = elem.attrib[XSI_TYPE].strip()
                except KeyError:
                    xsd_type = xsd_element.type
                else:
                    xsd_type = self.maps.get_instance_type(type_name, xsd_element.type, converter)

            if model_element is not xsd_element and model_element.block:
                for derivation in model_element.block.split():
                    if xsd_type is not model_element.type and \
                            xsd_type.is_derived(model_element.type, derivation):
                        reason = "usage of %r with type %s is blocked by head element"
                        raise XMLSchemaValidationError(self, elem, reason % (xsd_element, derivation))

            if XSI_TYPE not in elem.attrib:
                return

        # If it's a restriction the context is the base_type's group
        group = self.restriction if self.restriction is not None else self

        # Dynamic EDC check of matched element
        for e in filter(lambda x: isinstance(x, XsdElement), group.iter_elements()):
            if e.name == elem.tag:
                other = e
            else:
                for other in e.iter_substitutes():
                    if other.name == elem.tag:
                        break
                else:
github sissaschool / xmlschema / xmlschema / resources.py View on Github external
while x.startswith('file:////'):
            x = x.replace('file:////', 'file:///', 1)
        if urlsplit(x).scheme in {'', 'file'}:
            x = x.replace('#', '%23')
        return x

    url = filter_url(url)

    if base_url is not None:
        base_url = filter_url(base_url)
        base_url_parts = urlsplit(base_url)
        base_url = add_trailing_slash(base_url_parts)
        if base_url_parts.scheme not in uses_relative:
            base_url_parts = urlsplit('file:///{}'.format(base_url))
        else:
            base_url_parts = urlsplit(base_url)

        if base_url_parts.scheme not in ('', 'file'):
            url = urljoin(base_url, url)
        else:
            url_parts = urlsplit(url)
            if url_parts.scheme not in ('', 'file'):
                url = urljoin(base_url, url)
            elif not url_parts.netloc or base_url_parts.netloc == url_parts.netloc:
                # Join paths only if host parts (netloc) are equal, using the os.path.join
                # instead of urljoin for path normalization.
                url = urlunsplit((
                    '',
                    base_url_parts.netloc,
                    os.path.normpath(os.path.join(base_url_parts.path, url_parts.path)),
                    url_parts.query,
                    url_parts.fragment,
github sissaschool / xmlschema / xmlschema / resources.py View on Github external
while x.startswith('//'):
            x = x.replace('//', '/', 1)
        while x.startswith('file:////'):
            x = x.replace('file:////', 'file:///', 1)
        if urlsplit(x).scheme in {'', 'file'}:
            x = x.replace('#', '%23')
        return x

    url = filter_url(url)

    if base_url is not None:
        base_url = filter_url(base_url)
        base_url_parts = urlsplit(base_url)
        base_url = add_trailing_slash(base_url_parts)
        if base_url_parts.scheme not in uses_relative:
            base_url_parts = urlsplit('file:///{}'.format(base_url))
        else:
            base_url_parts = urlsplit(base_url)

        if base_url_parts.scheme not in ('', 'file'):
            url = urljoin(base_url, url)
        else:
            url_parts = urlsplit(url)
            if url_parts.scheme not in ('', 'file'):
                url = urljoin(base_url, url)
            elif not url_parts.netloc or base_url_parts.netloc == url_parts.netloc:
                # Join paths only if host parts (netloc) are equal, using the os.path.join
                # instead of urljoin for path normalization.
                url = urlunsplit((
                    '',
                    base_url_parts.netloc,
                    os.path.normpath(os.path.join(base_url_parts.path, url_parts.path)),