from abc import ABC from datetime import datetime from decimal import Decimal import json import re import sys, traceback from typing import Dict, List, Set, Any, Union, Optional import unittest from uuid import uuid4, UUID from pyson.Deserializer import Deserializer from pyson.JsonDeserialize import JsonDeserialize from pyson.JsonGetter import JsonGetter from pyson.JsonSubTypes import JsonSubTypes from pyson.JsonTypeInfo import Id, As from pyson.JsonTypeInfo import JsonTypeInfo from pyson.JsonValue import JsonValue from pyson.ObjectMapper import ObjectMapper from pickle import NONE #from test.MyDeserializer import ValueDeserializer2 # deserializer DROPS FIRST CHAR from string and assumes rest is an int. # Then returns Simple(int) class ValueDeserializer(Deserializer): def __hash__(self): return hash(self.geta()) def deserialize(self, data:object, clas: object)-> object: if type(data)!=str: raise ValueError("Expected str starting with '$', got "+str(data)) return Simple(int(data[1:])) @JsonDeserialize("test.DeserializerTest.ValueDeserializer") 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) @JsonDeserialize("test.MyDeserializer.ValueDeserializer2") class Simple2: 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) #None cancels out the existing deserializer. # parsing with str should now fail. @JsonDeserialize(None) class Simple3 (Simple): pass class MyDict: def __init__(self, data ): self._data=data def getData(self)->int: return self._data def __eq__(self, other): return isinstance(other, self.__class__) and \ self._data==other._data def __str__(self): return self._name+","+str(self._data) class DeserializerTest(unittest.TestCase): ''' Test a lot of back-and-forth cases. FIXME Can we make this a parameterized test? ''' pyson=ObjectMapper() def testDeserialize(self): objson= "$12" self.assertEqual(Simple(12), self.pyson.parse(objson, Simple)) def testExternalDeserialize2(self): objson= "$13" self.assertEqual(13, self.pyson.parse(objson, Simple2)) def testExternalDeserialize3(self): objson= "$13" self.assertRaises(AttributeError, lambda:self.pyson.parse(objson, Simple3)) def testDeserializeMap(self): objson='{ "Simple(1)": Simple(12), "Simple(2)": Simple(22) }' self.pyson.parse(objson, MyDict)