Skip to content

Commit

Permalink
Apply translation function to validators
Browse files Browse the repository at this point in the history
  - Revert to not using translation function on base modules
  - Fix paths in scripts/make_translation.py
  • Loading branch information
brunato committed May 9, 2022
1 parent e12734c commit 3c82a29
Show file tree
Hide file tree
Showing 28 changed files with 858 additions and 667 deletions.
2 changes: 1 addition & 1 deletion scripts/make_translation.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
locale_dir = Path(__file__).parent.parent.joinpath('xmlschema/locale').resolve()
assert locale_dir.is_dir(), 'locale directory not found!'

package_dir = Path(__file__).parent.parent.resolve()
package_dir = Path(__file__).parent.parent.joinpath('xmlschema').resolve()
assert locale_dir.is_dir(), 'xmlschema/ package directory not found!'

template_file = locale_dir.joinpath('xmlschema.pot')
Expand Down
2 changes: 1 addition & 1 deletion tests/validation/test_decoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -757,7 +757,7 @@ def test_columnar_converter(self):
self.col_xml_file, converter=ColumnarConverter, attr_prefix='-',
)
self.assertEqual(str(ctx.exception),
"attr_prefix can be the empty string or a single/double underscore")
"'attr_prefix' can be the empty string or a single/double underscore")

def test_dict_granularity(self):
"""Based on Issue #22, test to make sure an xsd indicating list with
Expand Down
2 changes: 1 addition & 1 deletion tests/validators/test_attributes.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ def test_attribute_group_mapping(self):

with self.assertRaises(ValueError) as ec:
attribute_group['a3'] = attribute_group['a2']
self.assertEqual("'a2' name and key 'a3' mismatch", str(ec.exception))
self.assertIn("mismatch", str(ec.exception))

xsd_attribute = attribute_group['a2']
del attribute_group['a2']
Expand Down
4 changes: 2 additions & 2 deletions tests/validators/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,12 +81,12 @@ def test_exception_repr_lxml(self):

lines = str(ctx.exception).split('\n')
self.assertEqual(lines[0], "failed validating {'a': '10'} with XsdAttributeGroup():")
self.assertEqual(lines[2], "Reason: 'a' attribute not allowed for element.")
self.assertEqual(lines[2], "Reason: 'a' attribute not allowed for element")
self.assertEqual(lines[8], "Instance (line 1):")
self.assertEqual(lines[12], "Path: /root")

self.assertEqual(repr(ctx.exception), "XMLSchemaValidationError(reason=\"'a' "
"attribute not allowed for element.\")")
"attribute not allowed for element\")")

error = XMLSchemaValidationError(schema.elements['root'], root)
self.assertIsNone(error.reason)
Expand Down
2 changes: 1 addition & 1 deletion tests/validators/test_facets.py
Original file line number Diff line number Diff line change
Expand Up @@ -823,7 +823,7 @@ def test_fraction_digits_facet(self):
</xs:simpleType>
</xs:schema>"""))

self.assertIn("value has to be 0 for types derived from xs:integer", str(ec.exception))
self.assertIn("value must be 0 for types derived from xs:integer", str(ec.exception))

with self.assertRaises(XMLSchemaParseError) as ec:
self.schema_class(dedent("""\
Expand Down
2 changes: 1 addition & 1 deletion xmlschema/converters/abdera.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def element_encode(self, obj: Any, xsd_element: 'XsdElement', level: int = 0) ->
children = [children]
elif children and not isinstance(children[0], MutableMapping):
if len(children) > 1:
raise XMLSchemaValueError("Wrong format")
raise XMLSchemaValueError("Element %r should have only one child" % tag)
else:
return ElementData(tag, children[0], None, attributes)

Expand Down
8 changes: 4 additions & 4 deletions xmlschema/converters/columnar.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,11 @@ def __setattr__(self, name: str, value: Any) -> None:
if name != 'attr_prefix':
super(ColumnarConverter, self).__setattr__(name, value)
elif not isinstance(value, str):
msg = '{} must be a str, not {}'
raise XMLSchemaTypeError(msg.format(name, type(value).__name__))
msg = "%(name)r must be a <class 'str'> instance, not %(type)r"
raise XMLSchemaTypeError(msg % {'name': name, 'type': type(value)})
elif value not in {'', '_', '__'}:
msg = '{} can be the empty string or a single/double underscore'
raise XMLSchemaValueError(msg.format(name))
msg = '%r can be the empty string or a single/double underscore'
raise XMLSchemaValueError(msg % name)
else:
super(XMLSchemaConverter, self).__setattr__(name, value)

Expand Down
20 changes: 10 additions & 10 deletions xmlschema/converters/default.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,28 +113,28 @@ def __init__(self, namespaces: Optional[NamespacesType] = None,
def __setattr__(self, name: str, value: Any) -> None:
if name in {'attr_prefix', 'text_key', 'cdata_prefix'}:
if value is not None and not isinstance(value, str):
msg = '{} must be a str or None, not {}'
raise XMLSchemaTypeError(msg.format(name, type(value).__name__))
msg = "%(name)r must be a <class 'str'> instance or None, not %(type)r"
raise XMLSchemaTypeError(msg % {'name': name, 'type': type(value)})

elif name in {'strip_namespaces', 'preserve_root', 'force_dict', 'force_list'}:
if not isinstance(value, bool):
msg = '{} must be a bool, not {}'
raise XMLSchemaTypeError(msg.format(name, type(value).__name__))
msg = "%(name)r must be a <class 'bool'> instance, not %(type)r"
raise XMLSchemaTypeError(msg % {'name': name, 'type': type(value)})

elif name == 'indent':
if isinstance(value, bool) or not isinstance(value, int):
msg = '{} must be an int, not {}'
raise XMLSchemaTypeError(msg.format(name, type(value).__name__))
msg = "%(name)r must be a <class 'int'> instance, not %(type)r"
raise XMLSchemaTypeError(msg % {'name': name, 'type': type(value)})

elif name == 'dict':
if not issubclass(value, MutableMapping):
msg = '{!r} must be a MutableMapping subclass, not {}'
raise XMLSchemaTypeError(msg.format(name, value))
msg = "%(name)r must be a MutableMapping object, not %(type)r"
raise XMLSchemaTypeError(msg % {'name': name, 'type': type(value)})

elif name == 'list':
if not issubclass(value, MutableSequence):
msg = '{!r} must be a MutableSequence subclass, not {}'
raise XMLSchemaTypeError(msg.format(name, value))
msg = "%(name)r must be a MutableSequence object, not %(type)r"
raise XMLSchemaTypeError(msg % {'name': name, 'type': type(value)})

super(XMLSchemaConverter, self).__setattr__(name, value)

Expand Down
9 changes: 6 additions & 3 deletions xmlschema/converters/jsonml.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from collections.abc import MutableSequence
from typing import TYPE_CHECKING, Any, Optional, List, Dict, Type

from ..exceptions import XMLSchemaValueError
from ..exceptions import XMLSchemaTypeError, XMLSchemaValueError
from ..etree import ElementData
from ..aliases import NamespacesType, BaseXsdType
from .default import XMLSchemaConverter
Expand Down Expand Up @@ -76,8 +76,11 @@ def element_decode(self, data: ElementData, xsd_element: 'XsdElement',
def element_encode(self, obj: Any, xsd_element: 'XsdElement', level: int = 0) -> ElementData:
attributes: Dict[str, Any] = {}

if not isinstance(obj, MutableSequence) or not obj:
raise XMLSchemaValueError("Wrong data format, a not empty list required: %r." % obj)
if not isinstance(obj, MutableSequence):
msg = "The first argument must be a sequence, {} provided"
raise XMLSchemaTypeError(msg.format(type(obj)))
elif not obj:
raise XMLSchemaValueError("The first argument is an empty sequence")

data_len = len(obj)
if data_len == 1:
Expand Down
21 changes: 10 additions & 11 deletions xmlschema/dataobjects.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
from .exceptions import XMLSchemaAttributeError, XMLSchemaTypeError, XMLSchemaValueError
from .etree import ElementData, etree_tostring
from .aliases import ElementType, XMLSourceType, NamespacesType, BaseXsdType, DecodeType
from .translation import gettext as _
from .helpers import get_namespace, get_prefixed_qname, local_name, raw_xml_encode
from .converters import XMLSchemaConverter
from .resources import XMLResource
Expand Down Expand Up @@ -109,19 +108,19 @@ def __iter__(self) -> Iterator['DataElement']:
def __setattr__(self, key: str, value: Any) -> None:
if key == 'xsd_element':
if not isinstance(value, validators.XsdElement):
raise XMLSchemaTypeError(_("invalid type for attribute 'xsd_element'"))
raise XMLSchemaTypeError("invalid type for attribute 'xsd_element'")
elif self.xsd_element is value:
pass
elif self.xsd_element is not None:
raise XMLSchemaValueError(_("the instance is already bound to another XSD element"))
raise XMLSchemaValueError("the instance is already bound to another XSD element")
elif self.xsd_type is not None and self.xsd_type is not value.type:
raise XMLSchemaValueError(_("the instance is already bound to another XSD type"))
raise XMLSchemaValueError("the instance is already bound to another XSD type")

elif key == 'xsd_type':
if not isinstance(value, (validators.XsdSimpleType, validators.XsdComplexType)):
raise XMLSchemaTypeError(_("invalid type for attribute 'xsd_type'"))
raise XMLSchemaTypeError("invalid type for attribute 'xsd_type'")
elif self.xsd_type is not None and self.xsd_type is not value:
raise XMLSchemaValueError(_("the instance is already bound to another XSD type"))
raise XMLSchemaValueError("the instance is already bound to another XSD type")
elif self.xsd_element is None or value is not self.xsd_element.type:
self._encoder = value.schema.create_element(
self.tag, parent=value, form='unqualified'
Expand Down Expand Up @@ -208,7 +207,7 @@ def iter_errors(self, use_defaults: bool = True,
Accepts the same arguments of :meth:`validate`.
"""
if self._encoder is None:
raise XMLSchemaValueError(_("%r has no schema bindings") % self)
raise XMLSchemaValueError("%r has no schema bindings" % self)

kwargs: Dict[str, Any] = {
'converter': DataElementConverter,
Expand Down Expand Up @@ -248,7 +247,7 @@ def encode(self, validation: str = 'strict', **kwargs: Any) \
elif validation == 'skip':
encoder = validators.XMLSchema.builtin_types()['anyType']
else:
raise XMLSchemaValueError(_("%r has no schema bindings") % self)
raise XMLSchemaValueError("%r has no schema bindings" % self)

return encoder.encode(self, validation=validation, **kwargs)

Expand Down Expand Up @@ -340,11 +339,11 @@ def __new__(mcs, name: str, bases: Tuple[Type[Any], ...],
try:
xsd_element = attrs['xsd_element']
except KeyError:
msg = _("attribute 'xsd_element' is required for an XSD data binding class")
msg = "attribute 'xsd_element' is required for an XSD data binding class"
raise XMLSchemaAttributeError(msg) from None

if not isinstance(xsd_element, validators.XsdElement):
raise XMLSchemaTypeError(_("{!r} is not an XSD element").format(xsd_element))
raise XMLSchemaTypeError("{!r} is not an XSD element".format(xsd_element))

attrs['__module__'] = None
return super(DataBindingMeta, mcs).__new__(mcs, name, bases, attrs)
Expand Down Expand Up @@ -424,7 +423,7 @@ def element_encode(self, data_element: 'DataElement', xsd_element: 'XsdElement',
level: int = 0) -> ElementData:
self.namespaces.update(data_element.nsmap)
if not xsd_element.is_matching(data_element.tag, self._namespaces.get('')):
raise XMLSchemaValueError(_("Unmatched tag"))
raise XMLSchemaValueError("Unmatched tag")

attributes = {self.unmap_qname(k, xsd_element.attributes): v
for k, v in data_element.attrib.items()}
Expand Down
20 changes: 9 additions & 11 deletions xmlschema/documents.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
from .aliases import ElementType, XMLSourceType, NamespacesType, LocationsType, \
LazyType, SchemaSourceType, ConverterType, DecodeType, EncodeType, \
JsonDecodeType
from .translation import gettext as _
from .helpers import is_etree_document
from .resources import fetch_schema_locations, XMLResource
from .validators import XMLSchema10, XMLSchemaBase, XMLSchemaValidationError
Expand All @@ -44,7 +43,7 @@ def get_context(xml_document: Union[XMLSourceType, XMLResource],
if cls is None:
cls = XMLSchema10
elif not issubclass(cls, XMLSchemaBase):
raise XMLSchemaTypeError(_("invalid schema class %r") % cls)
raise XMLSchemaTypeError("invalid schema class %r" % cls)

if isinstance(xml_document, XMLResource):
resource = xml_document
Expand All @@ -66,7 +65,7 @@ def get_context(xml_document: Union[XMLSourceType, XMLResource],
elif dummy_schema:
return resource, get_dummy_schema(resource, cls)
else:
msg = _("no schema can be retrieved for the provided XML data")
msg = "no schema can be retrieved for the provided XML data"
raise XMLSchemaValueError(msg) from None

elif isinstance(schema, XMLSchemaBase):
Expand Down Expand Up @@ -402,7 +401,7 @@ def from_json(source: Union[str, bytes, IO[str]],
or also if it's invalid when ``validation='strict'`` is provided.
"""
if not isinstance(schema, XMLSchemaBase):
raise XMLSchemaTypeError(_("invalid type %r for argument 'schema'") % type(schema))
raise XMLSchemaTypeError("invalid type %r for argument 'schema'" % type(schema))
elif json_options is None:
json_options = {}

Expand Down Expand Up @@ -478,7 +477,7 @@ def __init__(self, source: XMLSourceType,
if XSI_TYPE in self._root.attrib:
self.schema = cls.meta_schema
elif validation != 'skip':
msg = _("no schema can be retrieved for the XML resource")
msg = "no schema can be retrieved for the XML resource"
raise XMLSchemaValueError(msg) from None
else:
self._fallback_schema = get_dummy_schema(self, cls)
Expand All @@ -499,7 +498,7 @@ def __init__(self, source: XMLSourceType,
elif validation == 'lax':
self.errors = [e for e in self.schema.iter_errors(self, namespaces=self.namespaces)]
elif validation != 'skip':
raise XMLSchemaValueError(_("%r is not a validation mode") % validation)
raise XMLSchemaValueError("%r is not a validation mode" % validation)

def parse(self, source: XMLSourceType, lazy: LazyType = False) -> None:
super(XmlDocument, self).parse(source, lazy)
Expand All @@ -523,8 +522,7 @@ def get_etree_document(self) -> Any:
if is_etree_document(self._source):
return self._source
elif self._lazy:
msg = _("cannot create an ElementTree from a lazy resource")
raise XMLResourceError(msg)
raise XMLResourceError("cannot create an ElementTree from a lazy resource")
elif hasattr(self._root, 'nsmap'):
return self._root.getroottree() # type: ignore[attr-defined]
else:
Expand All @@ -534,7 +532,7 @@ def tostring(self, indent: str = '', max_lines: Optional[int] = None,
spaces_for_tab: int = 4, xml_declaration: bool = False,
encoding: str = 'unicode', method: str = 'xml') -> str:
if self._lazy:
raise XMLResourceError(_("cannot serialize a lazy XML document"))
raise XMLResourceError("cannot serialize a lazy XML document")

_string = etree_tostring(
elem=self._root,
Expand Down Expand Up @@ -619,7 +617,7 @@ def write(self, file: Union[str, TextIO, BinaryIO],
default_namespace: Optional[str] = None, method: str = "xml") -> None:
"""Serialize an XML resource to a file. Cannot be used with lazy resources."""
if self._lazy:
raise XMLResourceError(_("cannot serialize a lazy XML document"))
raise XMLResourceError("cannot serialize a lazy XML document")

kwargs: Dict[str, Any] = {
'xml_declaration': xml_declaration,
Expand Down Expand Up @@ -664,5 +662,5 @@ def write(self, file: Union[str, TextIO, BinaryIO],
else:
file.write(_string)
else:
msg = _("unexpected type %r for 'file' argument")
msg = "unexpected type %r for 'file' argument"
raise XMLSchemaTypeError(msg % type(file))
5 changes: 2 additions & 3 deletions xmlschema/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
from .exceptions import XMLSchemaValueError, XMLSchemaTypeError
from .names import XSI_SCHEMA_LOCATION, XSI_NONS_SCHEMA_LOCATION
from .aliases import ElementType, NamespacesType, AtomicValueType, NumericValueType
from .translation import gettext as _

###
# Helper functions for QNames
Expand Down Expand Up @@ -74,9 +73,9 @@ def local_name(qname: str) -> str:
except IndexError:
return ''
except ValueError:
raise XMLSchemaValueError(_("the argument 'qname' has an invalid value %r") % qname)
raise XMLSchemaValueError("the argument 'qname' has an invalid value %r" % qname)
except TypeError:
raise XMLSchemaTypeError(_("the argument 'qname' must be a string-like object"))
raise XMLSchemaTypeError("the argument 'qname' must be a string-like object")
else:
return qname

Expand Down
9 changes: 4 additions & 5 deletions xmlschema/namespaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
Mapping, TypeVar

from .exceptions import XMLSchemaValueError, XMLSchemaTypeError
from .translation import gettext as _
from .helpers import local_name
from .aliases import NamespacesType

Expand Down Expand Up @@ -160,9 +159,9 @@ def _map_qname(self, qname: str) -> str:
except IndexError:
return qname
except ValueError:
raise XMLSchemaValueError(_("the argument 'qname' has an invalid value %r") % qname)
raise XMLSchemaValueError("the argument 'qname' has an invalid value %r" % qname)
except TypeError:
raise XMLSchemaTypeError(_("the argument 'qname' must be a string-like object"))
raise XMLSchemaTypeError("the argument 'qname' must be a string-like object")

for prefix, uri in sorted(self._namespaces.items(), reverse=True):
if uri == namespace:
Expand Down Expand Up @@ -192,15 +191,15 @@ def _unmap_qname(self, qname: str,
return qname
except ValueError:
if ':' in qname:
raise XMLSchemaValueError(_("the argument 'qname' has an invalid value %r") % qname)
raise XMLSchemaValueError("the argument 'qname' has an invalid value %r" % qname)
if not self._namespaces.get(''):
return qname
elif name_table is None or qname not in name_table:
return '{%s}%s' % (self._namespaces.get(''), qname)
else:
return qname
except (TypeError, AttributeError):
raise XMLSchemaTypeError(_("the argument 'qname' must be a string-like object"))
raise XMLSchemaTypeError("the argument 'qname' must be a string-like object")
else:
try:
uri = self._namespaces[prefix]
Expand Down
Loading

0 comments on commit 3c82a29

Please sign in to comment.