[837] | 1 | from __future__ import annotations
|
---|
[489] | 2 | from abc import ABC
|
---|
| 3 | from datetime import datetime
|
---|
| 4 | from decimal import Decimal
|
---|
| 5 | import json
|
---|
| 6 | import re
|
---|
| 7 | import sys, traceback
|
---|
[749] | 8 | from typing import Dict, List, Set, Any, Union, Optional, Collection
|
---|
[489] | 9 | import unittest
|
---|
| 10 | from uuid import uuid4, UUID
|
---|
| 11 |
|
---|
| 12 | from pyson.Deserializer import Deserializer
|
---|
[570] | 13 | from pyson.Serializer import Serializer
|
---|
| 14 | from pyson.JsonSerialize import JsonSerialize
|
---|
[489] | 15 | from pyson.JsonDeserialize import JsonDeserialize
|
---|
| 16 | from pyson.JsonGetter import JsonGetter
|
---|
| 17 | from pyson.JsonSubTypes import JsonSubTypes
|
---|
| 18 | from pyson.JsonTypeInfo import Id, As
|
---|
| 19 | from pyson.JsonTypeInfo import JsonTypeInfo
|
---|
| 20 | from pyson.JsonValue import JsonValue
|
---|
| 21 | from pyson.ObjectMapper import ObjectMapper
|
---|
[568] | 22 | from pickle import NONE
|
---|
[571] | 23 | from test.MyDeserializer import ValueDeserializer2
|
---|
[938] | 24 | from cgitb import reset
|
---|
[489] | 25 |
|
---|
[568] | 26 | # deserializer DROPS FIRST CHAR from string and assumes rest is an int.
|
---|
| 27 | # Then returns Simple(int)
|
---|
[490] | 28 | class ValueDeserializer(Deserializer):
|
---|
| 29 | def __hash__(self):
|
---|
| 30 | return hash(self.geta())
|
---|
| 31 | def deserialize(self, data:object, clas: object)-> object:
|
---|
| 32 | if type(data)!=str:
|
---|
| 33 | raise ValueError("Expected str starting with '$', got "+str(data))
|
---|
| 34 | return Simple(int(data[1:]))
|
---|
[489] | 35 |
|
---|
[570] | 36 | # serializes Simple object, just prefixing its value (as string) with "$"
|
---|
| 37 | class ValueSerializer(Serializer):
|
---|
| 38 | def serialize(self, obj:object)-> object:
|
---|
| 39 | if not isinstance(obj, Simple):
|
---|
| 40 | raise ValueError("Expected Dimple object")
|
---|
| 41 | return "$" + str(obj.geta())
|
---|
[490] | 42 |
|
---|
[570] | 43 | class Basic:
|
---|
| 44 | def __init__(self, v:float):
|
---|
| 45 | self._v=v
|
---|
| 46 | def __eq__(self, other):
|
---|
| 47 | return isinstance(other, self.__class__) and \
|
---|
| 48 | self._v==other._v
|
---|
| 49 | def getV(self):
|
---|
| 50 | return self._v
|
---|
| 51 | def __repr__(self):
|
---|
| 52 | return "Basic:"+str(self._v)
|
---|
| 53 | def __hash__(self):
|
---|
| 54 | return hash(self._v)
|
---|
| 55 |
|
---|
[571] | 56 | @JsonDeserialize(ValueDeserializer)
|
---|
[572] | 57 | @JsonSerialize(ValueSerializer)
|
---|
[489] | 58 | class Simple:
|
---|
| 59 | def __init__(self, a:int):
|
---|
| 60 | self._a=a
|
---|
| 61 | def geta(self)->int:
|
---|
| 62 | return self._a
|
---|
| 63 | def __eq__(self, other):
|
---|
| 64 | return isinstance(other, self.__class__) and \
|
---|
| 65 | self._a==other._a
|
---|
[570] | 66 | def __repr__(self):
|
---|
| 67 | return "Simple:"+str(self._a)
|
---|
| 68 | def __hash__(self):
|
---|
| 69 | return hash(self._a)
|
---|
[489] | 70 |
|
---|
| 71 |
|
---|
| 72 |
|
---|
[571] | 73 | @JsonDeserialize(ValueDeserializer2)
|
---|
[490] | 74 | class Simple2:
|
---|
| 75 | def __init__(self, a:int):
|
---|
| 76 | self._a=a
|
---|
| 77 | def geta(self)->int:
|
---|
| 78 | return self._a
|
---|
| 79 | def __eq__(self, other):
|
---|
| 80 | return isinstance(other, self.__class__) and \
|
---|
| 81 | self._a==other._a
|
---|
[570] | 82 | def __repr__(self):
|
---|
[490] | 83 | return self._name+","+str(self._a)
|
---|
[568] | 84 |
|
---|
| 85 | #None cancels out the existing deserializer.
|
---|
| 86 | # parsing with str should now fail.
|
---|
| 87 | @JsonDeserialize(None)
|
---|
| 88 | class Simple3 (Simple):
|
---|
| 89 | pass
|
---|
[967] | 90 |
|
---|
[489] | 91 |
|
---|
[570] | 92 | class MyList:
|
---|
| 93 | def __init__(self, data: List[Simple] ):
|
---|
| 94 | self.data=data
|
---|
| 95 | def getData(self)->List[Simple]:
|
---|
| 96 | return self.data
|
---|
| 97 |
|
---|
| 98 | class BasicDict:
|
---|
| 99 | def __init__(self, data: Dict[Basic,Basic] ):
|
---|
| 100 | self.data=data
|
---|
| 101 | def getData(self)->Dict[Basic,Basic]:
|
---|
| 102 | return self.data
|
---|
| 103 | def __repr__(self):
|
---|
| 104 | return "BasicDict:"+str(self.data)
|
---|
[568] | 105 | def __eq__(self, other):
|
---|
| 106 | return isinstance(other, self.__class__) and \
|
---|
[570] | 107 | self.data==other.data
|
---|
[490] | 108 |
|
---|
[570] | 109 |
|
---|
| 110 | class SimpleDict:
|
---|
| 111 | def __init__(self, data: Dict[Simple,Simple] ):
|
---|
| 112 | self.data=data
|
---|
| 113 | def getData(self)->Dict[Simple,Simple]:
|
---|
| 114 | return self.data
|
---|
| 115 | def __eq__(self, other):
|
---|
| 116 | return isinstance(other, self.__class__) and \
|
---|
| 117 | self.data==other.data
|
---|
| 118 | def __repr__(self):
|
---|
| 119 | return "SimpleDict:"+str(self.data)
|
---|
[490] | 120 |
|
---|
[570] | 121 |
|
---|
[827] | 122 | class MyOptionalString:
|
---|
| 123 | def __init__(self, s:Optional[str]):
|
---|
[829] | 124 | self.data:Optional[str] = s
|
---|
| 125 | def getData(self)->Optional[str]:
|
---|
[827] | 126 | return self.data
|
---|
| 127 | def __eq__(self, other):
|
---|
| 128 | return isinstance(other, self.__class__) and \
|
---|
| 129 | self.data==other.data
|
---|
| 130 | def __repr__(self):
|
---|
[829] | 131 | return "MyOptionalString:"+str(self.data)
|
---|
[835] | 132 |
|
---|
[836] | 133 |
|
---|
[938] | 134 | @JsonSubTypes(['test.DeserializerTest.A','test.DeserializerTest.B','test.DeserializerTest.C'])
|
---|
[836] | 135 | @JsonTypeInfo(use=Id.NAME, include=As.WRAPPER_OBJECT)
|
---|
| 136 | class Root:
|
---|
| 137 | def __init__(self, data: int ):
|
---|
| 138 | self.data:int=data
|
---|
| 139 | def getData(self)->int:
|
---|
| 140 | return self.data
|
---|
| 141 | def __eq__(self, other):
|
---|
| 142 | return isinstance(other, self.__class__) and \
|
---|
| 143 | self.data==other.data
|
---|
| 144 | def __repr__(self):
|
---|
| 145 | return type(self).__name__ + "/" + str(self.data)
|
---|
| 146 | def __hash__(self):
|
---|
| 147 | return 0
|
---|
| 148 |
|
---|
| 149 |
|
---|
| 150 | class A(Root):
|
---|
[835] | 151 | pass
|
---|
[827] | 152 |
|
---|
[836] | 153 | class B(Root):
|
---|
[835] | 154 | pass
|
---|
| 155 |
|
---|
[938] | 156 | class C(Root):
|
---|
| 157 | def __init__(self, data:int, name: str):
|
---|
| 158 | super().__init__(data)
|
---|
| 159 | self.name = name
|
---|
| 160 | def __eq__(self, other):
|
---|
| 161 | return isinstance(other, self.__class__) and \
|
---|
| 162 | self.data==other.data and self.name==other.name
|
---|
| 163 | def __repr__(self):
|
---|
| 164 | return super().__repr__()+","+self.name
|
---|
[836] | 165 |
|
---|
| 166 |
|
---|
[938] | 167 |
|
---|
| 168 |
|
---|
[967] | 169 | class BaseValueDeserializer (Deserializer):
|
---|
| 170 | def deserialize(self, data:object, clas: object) -> 'BaseValue':
|
---|
| 171 | if isinstance(data,str):
|
---|
| 172 | return BaseDiscreteValue(data)
|
---|
| 173 | raise ValueError("Expected number or double quoted string but found " + str(data)
|
---|
| 174 | + " of type " + str(type(data)))
|
---|
| 175 |
|
---|
| 176 | @JsonDeserialize(using=BaseValueDeserializer)
|
---|
| 177 | class BaseValue(ABC):
|
---|
| 178 | def __init__(self, value):
|
---|
| 179 | self._value = value;
|
---|
| 180 |
|
---|
| 181 | @JsonValue()
|
---|
| 182 | def getValue(self) -> str:
|
---|
| 183 | return self._value;
|
---|
| 184 |
|
---|
| 185 |
|
---|
| 186 | class BaseDiscreteValue(BaseValue):
|
---|
| 187 | def __init__(self, value:str):
|
---|
| 188 | self.__value=value
|
---|
| 189 |
|
---|
| 190 |
|
---|
[489] | 191 | class DeserializerTest(unittest.TestCase):
|
---|
| 192 | '''
|
---|
| 193 | Test a lot of back-and-forth cases.
|
---|
| 194 | FIXME Can we make this a parameterized test?
|
---|
| 195 | '''
|
---|
| 196 | pyson=ObjectMapper()
|
---|
[836] | 197 | mixedList:List[Root] = [A(1), B(1)]
|
---|
| 198 | mixedlistjson:List = [{'A': {'data': 1}}, {'B': {'data': 1}}]
|
---|
[489] | 199 |
|
---|
[836] | 200 | mixedDict:Dict[Root,int] = {A(1):1, B(1):2}
|
---|
| 201 | mixedDictJson:dict = {'{"A": {"data": 1}}': 1, '{"B": {"data": 1}}': 2}
|
---|
[938] | 202 | MyC:C = C(3, "MyC")
|
---|
[836] | 203 |
|
---|
[489] | 204 | def testDeserialize(self):
|
---|
| 205 | objson= "$12"
|
---|
[490] | 206 | self.assertEqual(Simple(12), self.pyson.parse(objson, Simple))
|
---|
[489] | 207 |
|
---|
[490] | 208 | def testExternalDeserialize2(self):
|
---|
| 209 | objson= "$13"
|
---|
| 210 | self.assertEqual(13, self.pyson.parse(objson, Simple2))
|
---|
[568] | 211 |
|
---|
| 212 |
|
---|
| 213 | def testExternalDeserialize3(self):
|
---|
| 214 | objson= "$13"
|
---|
[569] | 215 | self.assertRaises(ValueError, lambda:self.pyson.parse(objson, Simple3))
|
---|
[568] | 216 |
|
---|
[570] | 217 | def testDeserializeMyList(self):
|
---|
| 218 | print(self.pyson.toJson(MyList([12,13])))
|
---|
| 219 |
|
---|
| 220 | # the json we provide is NOT the proper json but a STRING.
|
---|
| 221 | # This triggers a fallback mechanism that tries to parse the string as json.
|
---|
| 222 | objson={"data": ["$12", "$13"]}
|
---|
| 223 | res = self.pyson.parse(objson, MyList)
|
---|
| 224 | print(res)
|
---|
| 225 | self.assertEqual([Simple(12),Simple(13)], res.data)
|
---|
| 226 |
|
---|
[748] | 227 | def testDeserializeCollection(self):
|
---|
| 228 | objson=[1,2,3]
|
---|
| 229 | # this checks that pyson can parse a list as Collection.
|
---|
| 230 | # The result is a simple list like in java/jackson.
|
---|
[749] | 231 | # Collection without typing info means Collectino[Any]
|
---|
[748] | 232 | res = self.pyson.parse(objson, Collection)
|
---|
| 233 | print(res)
|
---|
| 234 | self.assertEqual([1,2,3], res)
|
---|
[570] | 235 |
|
---|
[748] | 236 |
|
---|
[570] | 237 | def testSerializeBasicDict(self):
|
---|
| 238 | '''
|
---|
| 239 | Basic object keys. Special (de)serializer should kick in #190
|
---|
| 240 | '''
|
---|
| 241 | d= BasicDict( { Basic(1.):Basic(2.), Basic(3.): Basic(4.) } )
|
---|
| 242 | objson={"data": {"{\"v\": 1.0}": {"v": 2.0}, "{\"v\": 3.0}": {"v": 4.0}}}
|
---|
| 243 | dump=json.dumps(self.pyson.toJson(d));
|
---|
| 244 | print(dump)
|
---|
| 245 | # self.assertEqual(objson, dump);
|
---|
| 246 | res=self.pyson.parse(objson, BasicDict)
|
---|
| 247 | print("res="+str(res))
|
---|
| 248 | self.assertEqual(d, res)
|
---|
| 249 |
|
---|
| 250 |
|
---|
| 251 | def testSerializeSimpleDictCustomSerializer(self):
|
---|
| 252 | d= SimpleDict( { Simple(1):Simple(2), Simple(3): Simple(4) } )
|
---|
| 253 |
|
---|
| 254 | # The keys need extra quotes, they are deserialied by
|
---|
| 255 | # our special deserializer that parses the string as json,
|
---|
| 256 | # and json requires double quotes around its strings.
|
---|
| 257 | objson = {"data": {'"$1"': "$2", '"$3"': "$4"}}
|
---|
| 258 |
|
---|
| 259 | obj=self.pyson.toJson(d)
|
---|
| 260 | print(json.dumps(obj))
|
---|
| 261 | self.assertEqual(objson, obj)
|
---|
| 262 |
|
---|
| 263 | res = self.pyson.parse(objson, SimpleDict)
|
---|
| 264 | print("res="+str(res))
|
---|
| 265 | self.assertEqual(d, res)
|
---|
[827] | 266 |
|
---|
| 267 | def testDeserializeOptString(self):
|
---|
[828] | 268 | objson:dict={'s':None}
|
---|
[827] | 269 | res = self.pyson.parse(objson, MyOptionalString)
|
---|
| 270 | print(res)
|
---|
[829] | 271 | self.assertEqual(MyOptionalString(None), res)
|
---|
[570] | 272 |
|
---|
[828] | 273 | objson={'s':"something"}
|
---|
[827] | 274 | res = self.pyson.parse(objson, MyOptionalString)
|
---|
| 275 | print(res)
|
---|
[829] | 276 | self.assertEqual(MyOptionalString("something"), res)
|
---|
[827] | 277 |
|
---|
[835] | 278 | def testSerializeMixedList(self):
|
---|
| 279 | # see #296
|
---|
[836] | 280 | res=self.pyson.toJson(self.mixedList)
|
---|
| 281 | print(res)
|
---|
| 282 | self.assertEqual(self.mixedlistjson, res)
|
---|
[835] | 283 |
|
---|
[836] | 284 | def testDeserializeMixedList(self):
|
---|
| 285 | # see #296
|
---|
| 286 | res=self.pyson.parse(self.mixedlistjson, List[Root])
|
---|
| 287 | print(res)
|
---|
| 288 | self.assertEqual(self.mixedList,res)
|
---|
| 289 |
|
---|
[837] | 290 | def testDeserializeBadList(self):
|
---|
| 291 | # see #298. This SHOULD fail because B is not subtype of A
|
---|
| 292 | self.assertRaises(ValueError, lambda:self.pyson.parse(self.mixedlistjson, List[A]))
|
---|
| 293 |
|
---|
[836] | 294 |
|
---|
| 295 | def testSerializeMixedDict(self):
|
---|
| 296 | # see #296
|
---|
| 297 | res=self.pyson.toJson(self.mixedDict)
|
---|
| 298 | print(res)
|
---|
| 299 | self.assertEqual(self.mixedDictJson, res)
|
---|
| 300 |
|
---|
| 301 | def testDeserializeMixedDict(self):
|
---|
| 302 | # see #296
|
---|
| 303 | print("testDeserializeMixedDict")
|
---|
| 304 | res=self.pyson.parse(self.mixedDictJson, Dict[Root,int])
|
---|
| 305 | print(res)
|
---|
| 306 | self.assertEqual(self.mixedDict,res)
|
---|
| 307 |
|
---|
[938] | 308 | def testDeserializeC(self):
|
---|
| 309 | # see #298. Sub-class should not expect
|
---|
| 310 | res=self.pyson.parse({'C':{'data':3, 'name':'MyC' }}, Root)
|
---|
| 311 | print(reset)
|
---|
| 312 | self.assertEqual(self.MyC, res)
|
---|
| 313 | # even if you serialize as C, you still need the 'C' wrapper
|
---|
| 314 | res=self.pyson.parse({'C':{'data':3, 'name':'MyC' }}, C)
|
---|
| 315 | self.assertEqual(self.MyC, res)
|
---|
| 316 |
|
---|
[967] | 317 | def testDeserializeBaseValue(self):
|
---|
| 318 | # see #331
|
---|
| 319 | res=self.pyson.parse({'yes': 1, 'no': 0}, Dict[BaseDiscreteValue, int])
|
---|
| 320 | print(res)
|
---|
| 321 |
|
---|