Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update to release v1.9.2 #279

Merged
merged 3 commits into from
Dec 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 3 additions & 1 deletion .coveragerc
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
[run]
branch = True
source = xmlschema/
omit = xmlschema/testing/*
omit =
xmlschema/testing/*
xmlschema/aliases.py

[report]
exclude_lines =
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/test-xmlschema.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,5 +53,5 @@ jobs:
- name: Lint with mypy
if: ${{ matrix.python-version != 'pypy3' }}
run: |
pip install mypy==0.910 elementpath==2.4.0 lxml-stubs
pip install mypy==0.930 elementpath==2.4.0 lxml-stubs
mypy --show-error-codes --no-warn-unused-ignores xmlschema
5 changes: 5 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
CHANGELOG
*********

`v1.9.2`_ (2021-12-23)
======================
* Fix for global simple type naming (issue #278)

`v1.9.1`_ (2021-12-08)
======================
* Improve error reporting for encoded data (issue #275)
Expand Down Expand Up @@ -505,3 +509,4 @@ v0.9.6 (2017-05-05)
.. _v1.8.2: https://github.com/brunato/xmlschema/compare/v1.8.1...v1.8.2
.. _v1.9.0: https://github.com/brunato/xmlschema/compare/v1.8.2...v1.9.0
.. _v1.9.1: https://github.com/brunato/xmlschema/compare/v1.9.0...v1.9.1
.. _v1.9.2: https://github.com/brunato/xmlschema/compare/v1.9.1...v1.9.2
2 changes: 1 addition & 1 deletion doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@
# The short X.Y version.
version = '1.9'
# The full version, including alpha/beta/rc tags.
release = '1.9.1'
release = '1.9.2'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
Expand Down
4 changes: 2 additions & 2 deletions publiccode.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ publiccodeYmlVersion: '0.2'
name: xmlschema
url: 'https://github.com/sissaschool/xmlschema'
landingURL: 'https://github.com/sissaschool/xmlschema'
releaseDate: '2021-12-08'
softwareVersion: v1.9.1
releaseDate: '2021-12-23'
softwareVersion: v1.9.2
developmentStatus: stable
platforms:
- linux
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

setup(
name='xmlschema',
version='1.9.1',
version='1.9.2',
packages=find_packages(include=['xmlschema', 'xmlschema.*']),
include_package_data=True,
entry_points={
Expand Down
2 changes: 1 addition & 1 deletion tests/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ def test_get_prefixed_qname(self):

self.assertEqual(get_prefixed_qname('', namespaces), '')
self.assertEqual(get_prefixed_qname(None, namespaces), None)
# self.assertEqual(get_prefixed_qname(0, namespaces), 0)
self.assertEqual(get_prefixed_qname('{uri}element', namespaces), '{uri}element')

self.assertEqual(get_prefixed_qname(XSI_TYPE, {}), XSI_TYPE)
self.assertEqual(get_prefixed_qname(None, {}), None)
Expand Down
11 changes: 11 additions & 0 deletions tests/test_namespaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,17 @@ def test_repr(self):
ns_view = NamespaceView(qnames, 'tns0')
self.assertEqual(repr(ns_view), "NamespaceView({'name0': 0})")

def test_contains(self):
qnames = {'{tns0}name0': 0, '{tns1}name1': 1, 'name2': 2}
ns_view = NamespaceView(qnames, 'tns1')

self.assertIn('name1', ns_view)
self.assertNotIn('{tns1}name1', ns_view)
self.assertNotIn('{tns0}name0', ns_view)
self.assertNotIn('name0', ns_view)
self.assertNotIn('name2', ns_view)
self.assertNotIn(1, ns_view)

def test_as_dict(self):
qnames = {'{tns0}name0': 0, '{tns1}name1': 1, '{tns1}name2': 2, 'name3': 3}
ns_view = NamespaceView(qnames, 'tns1')
Expand Down
31 changes: 31 additions & 0 deletions tests/test_resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,20 +321,39 @@ def test_is_url_function(self):

def test_is_local_url_function(self):
self.assertTrue(is_local_url(self.col_xsd_file))
self.assertTrue(is_local_url(Path(self.col_xsd_file)))

self.assertTrue(is_local_url('/home/user/'))
self.assertFalse(is_local_url('<home/>'))
self.assertTrue(is_local_url('/home/user/schema.xsd'))
self.assertTrue(is_local_url(' /home/user/schema.xsd '))
self.assertTrue(is_local_url('C:\\Users\\foo\\schema.xsd'))
self.assertTrue(is_local_url(' file:///home/user/schema.xsd'))
self.assertFalse(is_local_url('http://example.com/schema.xsd'))

self.assertTrue(is_local_url(b'/home/user/'))
self.assertFalse(is_local_url(b'<home/>'))
self.assertTrue(is_local_url(b'/home/user/schema.xsd'))
self.assertTrue(is_local_url(b' /home/user/schema.xsd '))
self.assertTrue(is_local_url(b'C:\\Users\\foo\\schema.xsd'))
self.assertTrue(is_local_url(b' file:///home/user/schema.xsd'))
self.assertFalse(is_local_url(b'http://example.com/schema.xsd'))

def test_is_remote_url_function(self):
self.assertFalse(is_remote_url(self.col_xsd_file))

self.assertFalse(is_remote_url('/home/user/'))
self.assertFalse(is_remote_url('<home/>'))
self.assertFalse(is_remote_url('/home/user/schema.xsd'))
self.assertFalse(is_remote_url(' file:///home/user/schema.xsd'))
self.assertTrue(is_remote_url(' http://example.com/schema.xsd'))

self.assertFalse(is_remote_url(b'/home/user/'))
self.assertFalse(is_remote_url(b'<home/>'))
self.assertFalse(is_remote_url(b'/home/user/schema.xsd'))
self.assertFalse(is_remote_url(b' file:///home/user/schema.xsd'))
self.assertTrue(is_remote_url(b' http://example.com/schema.xsd'))

def test_url_path_is_file_function(self):
self.assertTrue(url_path_is_file(self.col_xml_file))
self.assertTrue(url_path_is_file(normalize_url(self.col_xml_file)))
Expand Down Expand Up @@ -449,6 +468,15 @@ def test_xml_resource_from_url(self):
with self.assertRaises(XMLResourceError):
resource.load()

def test_xml_resource_from_url_in_bytes(self):
resource = XMLResource(self.vh_xml_file.encode('utf-8'), lazy=False)
self.assertEqual(resource.source, self.vh_xml_file.encode('utf-8'))
self.assertEqual(resource.root.tag, '{http://example.com/vehicles}vehicles')
self.check_url(resource.url, self.vh_xml_file)
self.assertIsNone(resource.text)
resource.load()
self.assertTrue(resource.text.startswith('<?xml'))

def test_xml_resource_from_path(self):
path = Path(self.vh_xml_file)

Expand Down Expand Up @@ -834,6 +862,9 @@ def test_xml_resource_base_url(self):
with self.assertRaises(ValueError):
XMLResource(self.vh_xml_file, base_url='<root/>')

with self.assertRaises(ValueError):
XMLResource(self.vh_xml_file, base_url=b'<root/>')

def test_xml_resource_is_local(self):
resource = XMLResource(self.vh_xml_file)
self.assertTrue(resource.is_local())
Expand Down
5 changes: 5 additions & 0 deletions tests/validators/test_particles.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,11 @@ def test_has_occurs_restriction(self):
self.assertTrue(xsd_group[9].has_occurs_restriction(xsd_group[1]))
self.assertTrue(xsd_group[9].has_occurs_restriction(xsd_group[2]))

def test_default_parse_error(self):
with self.assertRaises(ValueError) as ctx:
ParticleMixin().parse_error('unexpected error')
self.assertEqual(str(ctx.exception), 'unexpected error')

def test_parse_particle(self):
schema = XMLSchema10("""<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="root"/>
Expand Down
6 changes: 3 additions & 3 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ commands =

[testenv:mypy-py{36,37}]
deps =
mypy==0.910
mypy==0.930
elementpath==2.4.0
lxml-stubs
jinja2
Expand All @@ -65,7 +65,7 @@ commands =

[testenv:mypy-py{38,39,310}]
deps =
mypy==0.910
mypy==0.930
elementpath==2.4.0
lxml-stubs
jinja2
Expand All @@ -89,7 +89,7 @@ deps =
elementpath>=2.4.0, <3.0.0
lxml
jinja2
mypy==0.910
mypy==0.930
lxml-stubs
commands =
pytest tests -ra
Expand Down
2 changes: 1 addition & 1 deletion xmlschema/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
XsdComponent, XsdType, XsdElement, XsdAttribute
)

__version__ = '1.9.1'
__version__ = '1.9.2'
__author__ = "Davide Brunato"
__contact__ = "brunato@sissa.it"
__copyright__ = "Copyright 2016-2021, SISSA"
Expand Down
10 changes: 4 additions & 6 deletions xmlschema/resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -631,7 +631,7 @@ def _lazy_iterparse(self, resource: IO[AnyStr], nsmap: Optional[NsmapType] = Non
root_started = False
nsmap_update = False

_root: ElementType = getattr(self, '_root', None)
_root = cast(Optional[ElementType], getattr(self, '_root', None))

try:
for event, node in tree_iterator:
Expand Down Expand Up @@ -890,9 +890,8 @@ def tostring(self, indent: str = '', max_lines: Optional[int] = None,
namespaces = self.get_namespaces(root_only=False)
_string = etree_tostring(elem, namespaces, indent, max_lines,
spaces_for_tab, xml_declaration)
if isinstance(_string, bytes):
return _string.decode('utf-8')
return _string

return _string.decode('utf-8') if isinstance(_string, bytes) else _string

def subresource(self, elem: ElementType) -> 'XMLResource':
"""Create an XMLResource instance from a subelement of a non-lazy XML tree."""
Expand Down Expand Up @@ -1024,8 +1023,7 @@ def is_loaded(self) -> bool:
"""Returns `True` if the XML text of the data source is loaded."""
return self._text is not None

def iter(self, tag: Optional[str] = None,
nsmap: Union[None, List[Tuple[str, str]], MutableMapping[str, str]] = None) \
def iter(self, tag: Optional[str] = None, nsmap: Optional[NsmapType] = None) \
-> Iterator[ElementType]:
"""
XML resource tree iterator. The iteration of a lazy resource
Expand Down
9 changes: 3 additions & 6 deletions xmlschema/validators/builtins.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"""
from decimal import Decimal
from elementpath import datatypes
from typing import Any, Dict, Optional, Type, Tuple, Union
from typing import cast, Any, Dict, Optional, Type, Tuple, Union

from ..exceptions import XMLSchemaValueError
from ..names import XSD_LENGTH, XSD_MIN_LENGTH, XSD_MAX_LENGTH, XSD_ENUMERATION, \
Expand Down Expand Up @@ -83,7 +83,7 @@
)


XSD_COMMON_BUILTIN_TYPES = (
XSD_COMMON_BUILTIN_TYPES: Tuple[Dict[str, Any], ...] = (
# ***********************
# *** Primitive types ***
# ***********************
Expand Down Expand Up @@ -491,15 +491,12 @@ def xsd_builtin_types_factory(
item = item.copy()
name: str = item['name']
try:
value = xsd_types[name]
value = cast(Tuple[ElementType, SchemaType], xsd_types[name])
except KeyError:
# If builtin type element is missing create a dummy element. Necessary for the
# meta-schema XMLSchema.xsd of XSD 1.1, that not includes builtins declarations.
elem = etree_element(XSD_SIMPLE_TYPE, name=name, id=name)
else:
if not isinstance(value, tuple):
continue

elem, schema = value
if schema is not meta_schema:
raise XMLSchemaValueError("loaded entry schema is not the meta-schema!")
Expand Down
10 changes: 5 additions & 5 deletions xmlschema/validators/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -791,7 +791,7 @@ def simple_type_factory(self, elem: ElementType,
try:
child = elem[1]
except IndexError:
self.parse_error("(restriction | list | union) expected", elem)
schema.parse_error("(restriction | list | union) expected", elem)
return cast(XsdSimpleType, self.maps.types[XSD_ANY_SIMPLE_TYPE])

xsd_type: XsdSimpleType
Expand All @@ -802,21 +802,21 @@ def simple_type_factory(self, elem: ElementType,
elif child.tag == XSD_UNION:
xsd_type = self.xsd_union_class(child, schema, parent)
else:
self.parse_error("(restriction | list | union) expected", elem)
schema.parse_error("(restriction | list | union) expected", elem)
return cast(XsdSimpleType, self.maps.types[XSD_ANY_SIMPLE_TYPE])

if annotation is not None:
xsd_type._annotation = annotation

try:
xsd_type.name = get_qname(self.target_namespace, elem.attrib['name'])
xsd_type.name = get_qname(schema.target_namespace, elem.attrib['name'])
except KeyError:
if parent is None:
self.parse_error("missing attribute 'name' in a global simpleType", elem)
schema.parse_error("missing attribute 'name' in a global simpleType", elem)
xsd_type.name = 'nameless_%s' % str(id(xsd_type))
else:
if parent is not None:
self.parse_error("attribute 'name' not allowed for a local simpleType", elem)
schema.parse_error("attribute 'name' not allowed for a local simpleType", elem)
xsd_type.name = None

if 'final' in elem.attrib:
Expand Down
20 changes: 16 additions & 4 deletions xmlschema/validators/simple_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,8 +253,14 @@ def simple_type(self) -> 'XsdSimpleType':
def min_value(self) -> Optional[AtomicValueType]:
min_exclusive: Optional['AtomicValueType']
min_inclusive: Optional['AtomicValueType']
min_exclusive = getattr(self.get_facet(XSD_MIN_EXCLUSIVE), 'value', None)
min_inclusive = getattr(self.get_facet(XSD_MIN_INCLUSIVE), 'value', None)
min_exclusive = cast(
Optional['AtomicValueType'],
getattr(self.get_facet(XSD_MIN_EXCLUSIVE), 'value', None)
)
min_inclusive = cast(
Optional['AtomicValueType'],
getattr(self.get_facet(XSD_MIN_INCLUSIVE), 'value', None)
)

if min_exclusive is None:
return min_inclusive
Expand All @@ -269,8 +275,14 @@ def min_value(self) -> Optional[AtomicValueType]:
def max_value(self) -> Optional[AtomicValueType]:
max_exclusive: Optional['AtomicValueType']
max_inclusive: Optional['AtomicValueType']
max_exclusive = getattr(self.get_facet(XSD_MAX_EXCLUSIVE), 'value', None)
max_inclusive = getattr(self.get_facet(XSD_MAX_INCLUSIVE), 'value', None)
max_exclusive = cast(
Optional['AtomicValueType'],
getattr(self.get_facet(XSD_MAX_EXCLUSIVE), 'value', None)
)
max_inclusive = cast(
Optional['AtomicValueType'],
getattr(self.get_facet(XSD_MAX_INCLUSIVE), 'value', None)
)

if max_exclusive is None:
return max_inclusive
Expand Down
8 changes: 4 additions & 4 deletions xmlschema/validators/xsdbase.py
Original file line number Diff line number Diff line change
Expand Up @@ -466,7 +466,7 @@ def _parse_target_namespace(self) -> None:
"must have the same namespace as its parent schema")

if self.name is None:
pass
pass # pragma: no cover
elif not self._target_namespace:
self.name = local_name(self.name)
else:
Expand Down Expand Up @@ -581,7 +581,7 @@ def get_global(self) -> 'XsdComponent':
return component
component = component.parent
else:
return self
raise XMLSchemaValueError(f"parent circularity from {self}") # pragma: no cover

def get_parent_type(self) -> Optional['XsdType']:
"""
Expand Down Expand Up @@ -745,7 +745,7 @@ def simple_type(self) -> Optional['XsdSimpleType']:
complexType is the instance's *content* if this is a simpleType
or `None` if the instance's *content* is a model group.
"""
return None
raise NotImplementedError()

@property
def model_group(self) -> Optional['XsdGroup']:
Expand Down Expand Up @@ -968,7 +968,7 @@ def decode(self, obj: ST, validation: str = 'strict', **kwargs: Any) -> DecodeTy
else:
errors.append(result)

return (None, errors) if validation == 'lax' else None
return (None, errors) if validation == 'lax' else None # fallback: pragma: no cover

def encode(self, obj: Any, validation: str = 'strict', **kwargs: Any) -> EncodeType[Any]:
"""
Expand Down
5 changes: 3 additions & 2 deletions xmlschema/xpath.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,9 @@ def __init__(self, schema: Optional[XMLSchemaProtocol] = None,
base_element: Optional[ElementProtocol] = None) -> None:

if schema is None:
from xmlschema import XMLSchema
schema = getattr(XMLSchema, 'meta_schema', None)
from xmlschema import XMLSchema10
schema = cast(XMLSchemaProtocol, getattr(XMLSchema10, 'meta_schema', None))

super(XMLSchemaProxy, self).__init__(schema, base_element)

if base_element is not None:
Expand Down