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, Collection import unittest from uuid import uuid4, UUID from pyson.Deserializer import Deserializer from pyson.Serializer import Serializer from pyson.JsonSerialize import JsonSerialize 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 from plum import dispatch ''' Testing deserialization of overloaded class constructors. Note that plum/dispatch is a third party library, only imported here for testing. It's NOT part of the standard pyson library and you can theoretically use other libraries for this. Also note that MYPY type editor will not like these overloads. ''' class Ovload: @dispatch # signature of primary constructor def __init__(self, data: int ): self.data=data @dispatch def __init__(self, data:str): self.data=int(data) def getData(self)->int: return self.data def __eq__(self, other): return isinstance(other, self.__class__) and \ self.data==other.data def __repr__(self): return "Ovload:"+str(self.data) class OverloadTest(unittest.TestCase): ''' The class has an overloaded constructor. Check if it works. ''' pyson=ObjectMapper() def testBasicOverload(self): o=Ovload(1) print(o) print(Ovload("2")) def testRawPlum(self): clazz = Ovload # we can call the constructor only with a list, not with a dict. #293 clazz(*[1]) clazz(*["1"]) def testOverloadSerialize(self): objson = self.pyson.toJson(Ovload(1)) self.assertEqual({'data': 1},objson) def testOverloadDeserialize(self): objson= {'data': 1} self.assertEqual(Ovload(1), self.pyson.parse(objson, Ovload))