def test_serialize_to_builtins_class(): class A(Serializable): def __init__(self, a: int, b: str): super().__init__() self.a = a self.b = b a = A(1, 'one') expected = {'a': 1, 'b': 'one'} assert serialize_to_builtins(a) == expected assert serialize_to_builtins([a, a]) == [expected, expected] assert serialize_to_builtins({'a': a}) == {'a': expected}
def serialize(self, message): """Serialize object to builtins and then optionally apply packer.""" serialized = serialize_to_builtins(message) serialized[MESSAGE_KEY] = type(message).__name__ if self.packer: serialized = self.packer.dumps(serialized) return serialized
def test_serialize_to_builtins_default_values_not_contained(): class A(Serializable): def __init__(self, a: int=42, b: str='forty-two'): super().__init__() self.a = a self.b = b o = A() # no entries in dictionary as only defaults are contained: assert len(serialize_to_builtins(o)) == 0
def test_serialize_to_builtins_class_of_class(): class A(Serializable): def __init__(self, a: int, b: str): super().__init__() self.a = a self.b = b class B(Serializable): def __init__(self, a: A): super().__init__() self.a = a o = B(A(1, 'one')) assert serialize_to_builtins(o) == {'a': {'a': 1, 'b': 'one'}}
def test_serialize_to_builtins_builtins(): assert serialize_to_builtins(5) is 5 assert serialize_to_builtins('a string') is 'a string' assert serialize_to_builtins([1, 2, 'a string']) == [1, 2, 'a string'] assert serialize_to_builtins({1: 'one', 'two': 2}) == {1: 'one', 'two': 2}
def test_serialize_to_builtins_enum(): class MyEnum(enum.Enum): Literal1 = 1 Literal2 = 2 assert serialize_to_builtins(MyEnum.Literal1) == 'Literal1'
def test_serialize_to_builtins_none(): assert serialize_to_builtins(None) is None