import re import unittest import sys, traceback from packson3.ObjectMapper import ObjectMapper from packson3.JsonSubTypes import JsonSubTypes from packson3.JsonTypeInfo import JsonTypeInfo from packson3.JsonTypeInfo import Id,As from typing import Dict,List,Set import json class Props: ''' compound class with properties, used for testing ''' def __init__(self, age:int, name:str): if age<0: raise ValueError("age must be >0, got "+str(age)) self._age=age self._name=name; def __str__(self): return self._name+","+str(self._age) def getage(self): return self._age def getname(self): return self._name def __eq__(self, other): return isinstance(other, self.__class__) and \ self._name==other._name and self._age==other._age @JsonTypeInfo(use=Id.NAME, include=As.WRAPPER_OBJECT) class Simple: def __init__(self, a:int): self._a=a def geta(self)->int: return self._a def __eq__(self, other): return isinstance(other, self.__class__) and \ self._a==other._a def __str__(self): return self._name+","+str(self._a) class SimpleWithHash(Simple): def __hash__(self): return hash(self.geta()) # define abstract root class # These need to be reachable globally for reference @JsonSubTypes(["test.ObjectMapperTest.Bear"]) @JsonTypeInfo(use=Id.NAME, include=As.WRAPPER_OBJECT) class Animal: pass class Bear(Animal): def __init__(self, props:Props): self._props=props def __str__(self): return "Bear["+str(self._props)+"]" def getprops(self): return self._props def __eq__(self, other): return isinstance(other, self.__class__) and \ self._props==other._props # our parser supports non-primitive keys but python dict dont. # therefore the following fails even before we can start testing our code... # we need to create a hashable dict to get around ths class mydict(dict): def __hash__(self, *args, **kwargs): return 1 class ObjectMapperTest(unittest.TestCase): def testPrimitives(self): packson3=ObjectMapper() res=packson3.parse(3, int) self.assertEquals(3, res) # this throws correct, self.assertRaises(ValueError, lambda:packson3.parse(3, str)) # this throws correct, self.assertRaises(ValueError, lambda:packson3.parse("ja", int)) #DEMO with nested classes of different types. res=packson3.parse('three', str) print(res, type(res)) packson3.parse(3.0, float) packson3.parse(3.1, float) packson3.parse(3j, complex) packson3.parse(range(6), range) packson3.parse(True, bool) packson3.parse(False, bool) packson3.parse(b"Hello", bytes) packson3.parse(bytearray(b'\x00\x00\x00\x01'), bytearray) def testProps(self): packson3=ObjectMapper() propsjson={'age': 10, 'name': 'pietje'} props=Props(10, "pietje") self.assertEquals(propsjson,packson3.toJson(props)) self.assertEquals(props, packson3.parse(propsjson, Props)) def testParseDeepError(self): packson3=ObjectMapper() propsjson={'age': 10, 'name': 12} try: packson3.parse(propsjson, Props) raise AssertionError("parser did not throw") except ValueError as e: # we catch this to assure the exception contains # both top error and details. print("received error "+str(e)) self.assertTrue(str(e).find("Error parsing")) self.assertTrue(str(e).find("ValueError")) self.assertTrue(str(e).find("expected")) def testEmpty(self): packson3=ObjectMapper() class EmptyClass: def __init__(self): pass def __eq__(self, other): return isinstance(other, self.__class__) obj=EmptyClass() print(packson3.toJson(obj)) res=packson3.parse({}, EmptyClass) self.assertEqual(obj, res) def testSubType(self): packson3=ObjectMapper() class Cat(): def __init__(self, props:Props): self._props=props def __str__(self): return "Cat["+str(self._props)+"]" def getprops(self): return self._props obj=Cat(Props(1,'bruno')) print(packson3.toJson(obj)) bson={'props':{'age':1, 'name':'bruno'}} res=packson3.parse(bson, Cat) print(res, type(res)) self.assertEquals(type(res.getprops()), Props) def testInheritance(self): packson3=ObjectMapper() obj=Bear(Props(1,'bruno')) res=packson3.toJson(obj) print("result:"+str(res)) bson={'Bear': {'props': {'age': 1, 'name': 'bruno'}}} self.assertEquals(bson, res) res=packson3.parse(bson, Animal) print("Deserialized an Animal! -->"+str(res)) self. assertEqual(obj, res) def testUntypedList(self): class Prim: def __init__(self, a:list): self._a=a def geta(self)->list: return self._a packson3=ObjectMapper() obj=Prim([1,2]) objson = {'a':[1,2]} self.assertEqual(objson, packson3.toJson(obj)) self.assertRaises(ValueError, lambda:packson3.parse(objson, Prim)) def testTypedList(self): ''' deserializes typed list contained in another object ''' class Prim: def __init__(self, a:List[str]): self._a=a def geta(self)->List[str]: return self._a def __eq__(self, other): return isinstance(other, self.__class__) and \ self._a==other._a packson3=ObjectMapper() obj=Prim(["x","y"]) objson = {'a':["x","y"]} self.assertEqual(objson, packson3.toJson(obj)) self.assertEqual(obj, packson3.parse(objson, Prim)) def testTypedListDirect(self): ''' deserializes typed list directly ''' packson3=ObjectMapper() obj=["x","y"] objson = ["x","y"] self.assertEqual(objson, packson3.toJson(obj)) self.assertEqual(obj, packson3.parse(objson, List[str])) def testTypedListOfObjMissingAnnotation(self): class Prim: def __init__(self, a:int): self._a=a def geta(self)->int: return self._a def __eq__(self, other): return isinstance(other, self.__class__) and \ self._a==other._a packson3=ObjectMapper() obj=[Prim(1),Prim(3)] objson = [{"Prim":{'a':1}},{"Prim":{'a':3}}] self.assertRaises(ValueError, lambda:packson3.toJson(obj)) # object misses annotation, therefore this will try to parse # Prim objects without header here. self.assertRaises(ValueError, lambda:packson3.parse(objson, List[Prim])) def testTypedListOfObj(self): @JsonTypeInfo(use=Id.NAME, include=As.WRAPPER_OBJECT) class Prim: def __init__(self, a:int): self._a=a def geta(self)->int: return self._a def __eq__(self, other): return isinstance(other, self.__class__) and \ self._a==other._a packson3=ObjectMapper() obj=[Prim(1),Prim(3)] objson = [{"Prim":{'a':1}},{"Prim":{'a':3}}] self.assertEqual(objson, packson3.toJson(obj)) self.assertEqual(obj, packson3.parse(objson, List[Prim])) def testTypedSetOfObj(self): @JsonTypeInfo(use=Id.NAME, include=As.WRAPPER_OBJECT) class Prim: def __init__(self, a:int): self._a=a def geta(self)->int: return self._a def __eq__(self, other): return isinstance(other, self.__class__) and \ self._a==other._a packson3=ObjectMapper() obj=set([SimpleWithHash(1),SimpleWithHash(3)]) objson = [{"SimpleWithHash":{'a':1}},{"SimpleWithHash":{'a':3}}] self.assertEqual(objson, packson3.toJson(obj)) parsedobj=packson3.parse(objson, Set[SimpleWithHash]) self.assertEqual(obj, parsedobj) def testExpectListButGiveDict(self): @JsonTypeInfo(use=Id.NAME, include=As.WRAPPER_OBJECT) class Prim: def __init__(self, a:int): self._a=a def geta(self)->int: return self._a def __eq__(self, other): return isinstance(other, self.__class__) and \ self._a==other._a packson3=ObjectMapper() objson = { 'a':{"Prim":{'a':1}},'c':{"Prim":{'a':3}}} # we request List but obj is a dict. self.assertRaises(ValueError,lambda:packson3.parse(objson, List[Prim])) def testSerializeDict(self): packson3=ObjectMapper() obj={'a':Simple(1),'c':Simple(3)} objson = { 'a':{"Simple":{'a':1}},'c':{"Simple":{'a':3}}} self.assertEqual(objson, packson3.toJson(obj)) def testTypedDictOfObj(self): packson3=ObjectMapper() obj={'a':Simple(1),'c':Simple(3)} objson = { 'a':{"Simple":{'a':1}},'c':{"Simple":{'a':3}}} self.assertEqual(obj, packson3.parse(objson, Dict[str,Simple])) print("deserialized obj"+str(objson)+"="+str(obj)) def testTypedDictSimpleKey(self): packson3=ObjectMapper() key=mydict() key["Simple"]={'a':1} # simple is not hashable objson = { key : 'a' } self.assertRaises(ValueError,lambda:packson3.parse(objson, Dict[Simple,str])) def testTypedDictSimpleKeyHashable(self): packson3=ObjectMapper() # key is now not primitive! obj={SimpleWithHash(1):'a'} # simple is not hashable key=mydict() key["SimpleWithHash"]={'a':1} # simple is not hashable objson = { key : 'a' } self.assertEqual(obj, packson3.parse(objson, Dict[SimpleWithHash,str]))