|
1
|
|
|
import json |
|
2
|
|
|
import unittest |
|
3
|
|
|
from datetime import datetime |
|
4
|
|
|
from uuid import UUID |
|
5
|
|
|
|
|
6
|
|
|
import iso8601 |
|
7
|
|
|
|
|
8
|
|
|
from foil.deserializers import make_json_decoder_hook |
|
9
|
|
|
|
|
10
|
|
|
|
|
11
|
|
|
def parse_foobar(value): |
|
12
|
|
|
if value == 'foobar': |
|
13
|
|
|
return True |
|
14
|
|
|
else: |
|
15
|
|
|
return value |
|
16
|
|
|
|
|
17
|
|
|
|
|
18
|
|
|
class TestJSONDeserializer(unittest.TestCase): |
|
19
|
|
|
def test_json_decoder_hook(self): |
|
20
|
|
|
serialized_data = json.dumps( |
|
21
|
|
|
{'time': '2017-01-19T21:41:18.056446Z', |
|
22
|
|
|
'date': '2013-04-05', 'date_str': '2013-04-05', |
|
23
|
|
|
'id': '060444c9-e2d7-4a55-964d-e495f2d5527f', |
|
24
|
|
|
'description': 'foo', 'data': {'count': 4}, |
|
25
|
|
|
'foobar_field': 'foobar'} |
|
26
|
|
|
) |
|
27
|
|
|
converters = {'date_str': str} |
|
28
|
|
|
extra_decoders = (parse_foobar,) |
|
29
|
|
|
object_hook = make_json_decoder_hook( |
|
30
|
|
|
converters=converters, extra_str_decoders=extra_decoders |
|
31
|
|
|
) |
|
32
|
|
|
|
|
33
|
|
|
expected = { |
|
34
|
|
|
'time': datetime(2017, 1, 19, 21, 41, 18, 56446, |
|
35
|
|
|
tzinfo=iso8601.UTC), |
|
36
|
|
|
'date': datetime(2013, 4, 5).date(), 'date_str': '2013-04-05', |
|
37
|
|
|
'id': UUID('060444c9-e2d7-4a55-964d-e495f2d5527f', version=4), |
|
38
|
|
|
'description': 'foo', 'data': {'count': 4}, 'foobar_field': True |
|
39
|
|
|
} |
|
40
|
|
|
result = json.loads(serialized_data, object_hook=object_hook) |
|
41
|
|
|
|
|
42
|
|
|
self.assertEqual(expected, result) |
|
43
|
|
|
|
|
44
|
|
|
def test_nested_converters(self): |
|
45
|
|
|
serialized_data = json.dumps( |
|
46
|
|
|
{'time': {'date': '2014-04-01', 'time': '03:33:23'}} |
|
47
|
|
|
) |
|
48
|
|
|
converters = {'date': str} |
|
49
|
|
|
object_hook = make_json_decoder_hook(converters=converters) |
|
50
|
|
|
|
|
51
|
|
|
expected = {'time': {'date': '2014-04-01', 'time': '03:33:23'}} |
|
52
|
|
|
result = json.loads(serialized_data, object_hook=object_hook) |
|
53
|
|
|
|
|
54
|
|
|
self.assertEqual(expected, result) |
|
55
|
|
|
|