Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_dump_and_cast(self):
class C:
def __init__(self, x: int):
self.x = x
self.assertEqual(42, jsons.dump('42', int))
self.assertEqual(42.0, jsons.dump('42', float))
self.assertEqual('42', jsons.dump(42, str))
self.assertEqual(True, jsons.dump(42, bool))
with self.assertRaises(SerializationError):
jsons.dump('fortytwo', int)
try:
jsons.dump('fortytwo', int)
except SerializationError as err:
self.assertTrue('fortytwo' in err.message)
The way objects are serialized can be finetuned by setting serializer
functions for the specific type using ``set_serializer``.
You can also provide ``cls`` to specify that ``obj`` needs to be serialized
as if it was of type ``cls`` (meaning to only take into account attributes
from ``cls``). The type ``cls`` must have a ``__slots__`` defined. Any type
will do, but in most cases you may want ``cls`` to be a base class of
``obj``.
:param obj: a Python instance of any sort.
:param cls: if given, ``obj`` will be dumped as if it is of type ``type``.
:param fork_inst: if given, it uses this fork of ``JsonSerializable``.
:param kwargs: the keyword args are passed on to the serializer function.
:return: the serialized obj as a JSON type.
"""
if cls and not hasattr(cls, '__slots__'):
raise SerializationError('Invalid type: "{}". Only types that have a '
'__slots__ defined are allowed when '
'providing "cls".'
.format(get_class_name(cls, fork_inst=fork_inst,
fully_qualified=True)))
cls_ = cls or obj.__class__
serializer = _get_serializer(cls_, fork_inst)
kwargs_ = {
'fork_inst': fork_inst,
**kwargs
}
announce_class(cls_, fork_inst=fork_inst)
try:
return serializer(obj, cls=cls, **kwargs_)
except Exception as err:
raise SerializationError(str(err))
def _do_dump(obj, serializer, cls, initial, kwargs):
try:
result = serializer(obj, cls=cls, **kwargs)
if initial:
clear()
return result
except Exception as err:
clear()
raise SerializationError(str(err))
@property
def target(self) -> Optional[type]:
"""
The target type to which `source` was to be deserialized.
:return: the type to which `source` was to be deserialized.
"""
return self._target
class SerializationError(JsonsError):
"""
Raised when serialization failed for some reason.
"""
class RecursionDetectedError(SerializationError):
"""
Raised when a recursive structure was detected and a stack overflow was
prevented during serialization.
"""
class DecodeError(DeserializationError, JSONDecodeError):
"""
Raised when decoding a string or bytes to Python types failed. This error
is actually a wrapper around `json.JSONDecodeError`.
"""
def __init__(self, message: str, source: object, target: type,
error: JSONDecodeError):
"""
Constructor.
:param message: the message of this error.
:param kwargs: Any keyword arguments that are passed through the
serialization process.
:return: An object of the first type of the Union that could be
serialized successfully.
"""
for sub_type in get_union_params(cls):
try:
return dump(obj, sub_type, **kwargs)
except JsonsError:
pass # Try the next one.
else:
args_msg = ', '.join([get_class_name(cls_)
for cls_ in get_union_params(cls)])
err_msg = ('Could not match the object of type "{}" to any type of '
'the Union: {}'.format(str(cls), args_msg))
raise SerializationError(err_msg)
def default_primitive_serializer(obj: object,
cls: Optional[type] = None,
**kwargs) -> object:
"""
Serialize a primitive; simply return the given ``obj``.
:param obj: the primitive.
:param cls: the type of ``obj``.
:return: ``obj``.
"""
result = obj
if cls and obj is not None and not isinstance(obj, cls):
try:
result = cls(obj)
except ValueError:
raise SerializationError('Could not cast "{}" into "{}"'
.format(obj, cls.__name__))
return result
raise SerializationError('Invalid type: "{}". Only types that have a '
'__slots__ defined are allowed when '
'providing "cls".'
.format(get_class_name(cls, fork_inst=fork_inst,
fully_qualified=True)))
cls_ = cls or obj.__class__
serializer = _get_serializer(cls_, fork_inst)
kwargs_ = {
'fork_inst': fork_inst,
**kwargs
}
announce_class(cls_, fork_inst=fork_inst)
try:
return serializer(obj, cls=cls, **kwargs_)
except Exception as err:
raise SerializationError(str(err))