1 |
|
---|
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
|
---|
8 | from typing import Dict, List, Set, Any, Union, Optional
|
---|
9 | import unittest
|
---|
10 | from uuid import uuid4, UUID
|
---|
11 |
|
---|
12 | from pyson.Deserializer import Deserializer
|
---|
13 | from pyson.JsonDeserialize import JsonDeserialize
|
---|
14 | from pyson.JsonGetter import JsonGetter
|
---|
15 | from pyson.JsonSubTypes import JsonSubTypes
|
---|
16 | from pyson.JsonTypeInfo import Id, As
|
---|
17 | from pyson.JsonTypeInfo import JsonTypeInfo
|
---|
18 | from pyson.JsonValue import JsonValue
|
---|
19 | from pyson.ObjectMapper import ObjectMapper
|
---|
20 | from MyDeserializer import ValueDeserializer2
|
---|
21 |
|
---|
22 | class ValueDeserializer(Deserializer):
|
---|
23 | def __hash__(self):
|
---|
24 | return hash(self.geta())
|
---|
25 | def deserialize(self, data:object, clas: object)-> object:
|
---|
26 | if type(data)!=str:
|
---|
27 | raise ValueError("Expected str starting with '$', got "+str(data))
|
---|
28 | return Simple(int(data[1:]))
|
---|
29 |
|
---|
30 |
|
---|
31 | @JsonDeserialize(using =ValueDeserializer)
|
---|
32 | class Simple:
|
---|
33 | def __init__(self, a:int):
|
---|
34 | self._a=a
|
---|
35 | def geta(self)->int:
|
---|
36 | return self._a
|
---|
37 | def __eq__(self, other):
|
---|
38 | return isinstance(other, self.__class__) and \
|
---|
39 | self._a==other._a
|
---|
40 | def __str__(self):
|
---|
41 | return self._name+","+str(self._a)
|
---|
42 |
|
---|
43 |
|
---|
44 |
|
---|
45 | @JsonDeserialize(using =ValueDeserializer2)
|
---|
46 | class Simple2:
|
---|
47 | def __init__(self, a:int):
|
---|
48 | self._a=a
|
---|
49 | def geta(self)->int:
|
---|
50 | return self._a
|
---|
51 | def __eq__(self, other):
|
---|
52 | return isinstance(other, self.__class__) and \
|
---|
53 | self._a==other._a
|
---|
54 | def __str__(self):
|
---|
55 | return self._name+","+str(self._a)
|
---|
56 |
|
---|
57 |
|
---|
58 |
|
---|
59 |
|
---|
60 | class DeserializerTest(unittest.TestCase):
|
---|
61 | '''
|
---|
62 | Test a lot of back-and-forth cases.
|
---|
63 | FIXME Can we make this a parameterized test?
|
---|
64 | '''
|
---|
65 | pyson=ObjectMapper()
|
---|
66 |
|
---|
67 | def testDeserialize(self):
|
---|
68 | objson= "$12"
|
---|
69 | self.assertEqual(Simple(12), self.pyson.parse(objson, Simple))
|
---|
70 |
|
---|
71 | def testExternalDeserialize2(self):
|
---|
72 | objson= "$13"
|
---|
73 | self.assertEqual(13, self.pyson.parse(objson, Simple2))
|
---|
74 |
|
---|