def test_is_serializable__named_tuple(): ntuple = NamedTuple('ntuple', [('field1', str)]) assert is_serializable(ntuple('aaa')) assert is_serializable( Signature([Field('aaa', int, False)], Field(None, int, False)))
def test_is_serializable__init_hints(): class Ser: def __init__(self, a: int): self.a = a class Unser(Unserializable): pass assert is_serializable(Ser(1)) assert not is_serializable(Unser())
def test_is_serializable__external(): class ExternalClass: def __init__(self, a): self.b = a class ExternalSerializer(StaticSerializer): real_type = ExternalClass @classmethod def deserialize(cls, obj: dict) -> object: return ExternalClass(obj['c']) @classmethod def serialize(cls, instance: ExternalClass) -> dict: return {'c': instance.b} class ExternalNoSerializer: def __init__(self, a): self.b = a assert is_serializable(ExternalClass(1)) assert not is_serializable(ExternalNoSerializer(1))
def serialize(obj, as_class: SerializerType = None): """ Convert object into JSON-compatible dict (or other structure) :param obj: object to serialize :param as_class: type to serialize as or serializer :return: JSON-compatible object """ if as_class is Any: return obj if not is_serializable(obj): raise UnserializableError(obj) is_serializer_hierarchy = (issubclass_safe(as_class, Serializer) and issubclass_safe(obj, as_class) and not as_class._is_dynamic and obj._is_dynamic) if issubclass_safe(obj, Serializer) and (as_class is None or is_serializer_hierarchy): # serialize type itself return _serialize_to(obj, obj) if is_union(as_class): return _serialize_union(obj, as_class) obj_type = type(obj) # as_class not specified or obj_type is subclass of as_class if as_class is None or issubclass_safe( obj_type, as_class) and not issubclass_safe(as_class, Serializer): as_class = obj_type # as_class has registered serializer if has_serializer(as_class): as_class = SERIALIZER_MAPPING[as_class] # as_class is serializer if issubclass_safe(as_class, Serializer): return _serialize_with_serializer(obj, as_class) # as_class is just regular type return _serialize_as_type(obj, as_class)
def test_is_serializable__field(): assert is_serializable(Field('aaa', int, False))