##// END OF EJS Templates
test json_clean on integer subclasses
MinRK -
Show More
@@ -1,143 +1,147 b''
1 """Test suite for our JSON utilities.
1 """Test suite for our JSON utilities.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (C) 2010-2011 The IPython Development Team
4 # Copyright (C) 2010-2011 The IPython Development Team
5 #
5 #
6 # Distributed under the terms of the BSD License. The full license is in
6 # Distributed under the terms of the BSD License. The full license is in
7 # the file COPYING.txt, distributed as part of this software.
7 # the file COPYING.txt, distributed as part of this software.
8 #-----------------------------------------------------------------------------
8 #-----------------------------------------------------------------------------
9
9
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Imports
11 # Imports
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # stdlib
13 # stdlib
14 import datetime
14 import datetime
15 import json
15 import json
16 from base64 import decodestring
16 from base64 import decodestring
17
17
18 # third party
18 # third party
19 import nose.tools as nt
19 import nose.tools as nt
20
20
21 # our own
21 # our own
22 from IPython.utils import jsonutil, tz
22 from IPython.utils import jsonutil, tz
23 from ..jsonutil import json_clean, encode_images
23 from ..jsonutil import json_clean, encode_images
24 from ..py3compat import unicode_to_str, str_to_bytes, iteritems
24 from ..py3compat import unicode_to_str, str_to_bytes, iteritems
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Test functions
27 # Test functions
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29 class Int(int):
30 def __str__(self):
31 return 'Int(%i)' % self
29
32
30 def test():
33 def test():
31 # list of input/expected output. Use None for the expected output if it
34 # list of input/expected output. Use None for the expected output if it
32 # can be the same as the input.
35 # can be the same as the input.
33 pairs = [(1, None), # start with scalars
36 pairs = [(1, None), # start with scalars
34 (1.0, None),
37 (1.0, None),
35 ('a', None),
38 ('a', None),
36 (True, None),
39 (True, None),
37 (False, None),
40 (False, None),
38 (None, None),
41 (None, None),
39 # complex numbers for now just go to strings, as otherwise they
42 # complex numbers for now just go to strings, as otherwise they
40 # are unserializable
43 # are unserializable
41 (1j, '1j'),
44 (1j, '1j'),
42 # Containers
45 # Containers
43 ([1, 2], None),
46 ([1, 2], None),
44 ((1, 2), [1, 2]),
47 ((1, 2), [1, 2]),
45 (set([1, 2]), [1, 2]),
48 (set([1, 2]), [1, 2]),
46 (dict(x=1), None),
49 (dict(x=1), None),
47 ({'x': 1, 'y':[1,2,3], '1':'int'}, None),
50 ({'x': 1, 'y':[1,2,3], '1':'int'}, None),
48 # More exotic objects
51 # More exotic objects
49 ((x for x in range(3)), [0, 1, 2]),
52 ((x for x in range(3)), [0, 1, 2]),
50 (iter([1, 2]), [1, 2]),
53 (iter([1, 2]), [1, 2]),
54 (Int(5), 5),
51 ]
55 ]
52
56
53 for val, jval in pairs:
57 for val, jval in pairs:
54 if jval is None:
58 if jval is None:
55 jval = val
59 jval = val
56 out = json_clean(val)
60 out = json_clean(val)
57 # validate our cleanup
61 # validate our cleanup
58 nt.assert_equal(out, jval)
62 nt.assert_equal(out, jval)
59 # and ensure that what we return, indeed encodes cleanly
63 # and ensure that what we return, indeed encodes cleanly
60 json.loads(json.dumps(out))
64 json.loads(json.dumps(out))
61
65
62
66
63
67
64 def test_encode_images():
68 def test_encode_images():
65 # invalid data, but the header and footer are from real files
69 # invalid data, but the header and footer are from real files
66 pngdata = b'\x89PNG\r\n\x1a\nblahblahnotactuallyvalidIEND\xaeB`\x82'
70 pngdata = b'\x89PNG\r\n\x1a\nblahblahnotactuallyvalidIEND\xaeB`\x82'
67 jpegdata = b'\xff\xd8\xff\xe0\x00\x10JFIFblahblahjpeg(\xa0\x0f\xff\xd9'
71 jpegdata = b'\xff\xd8\xff\xe0\x00\x10JFIFblahblahjpeg(\xa0\x0f\xff\xd9'
68
72
69 fmt = {
73 fmt = {
70 'image/png' : pngdata,
74 'image/png' : pngdata,
71 'image/jpeg' : jpegdata,
75 'image/jpeg' : jpegdata,
72 }
76 }
73 encoded = encode_images(fmt)
77 encoded = encode_images(fmt)
74 for key, value in iteritems(fmt):
78 for key, value in iteritems(fmt):
75 # encoded has unicode, want bytes
79 # encoded has unicode, want bytes
76 decoded = decodestring(encoded[key].encode('ascii'))
80 decoded = decodestring(encoded[key].encode('ascii'))
77 nt.assert_equal(decoded, value)
81 nt.assert_equal(decoded, value)
78 encoded2 = encode_images(encoded)
82 encoded2 = encode_images(encoded)
79 nt.assert_equal(encoded, encoded2)
83 nt.assert_equal(encoded, encoded2)
80
84
81 b64_str = {}
85 b64_str = {}
82 for key, encoded in iteritems(encoded):
86 for key, encoded in iteritems(encoded):
83 b64_str[key] = unicode_to_str(encoded)
87 b64_str[key] = unicode_to_str(encoded)
84 encoded3 = encode_images(b64_str)
88 encoded3 = encode_images(b64_str)
85 nt.assert_equal(encoded3, b64_str)
89 nt.assert_equal(encoded3, b64_str)
86 for key, value in iteritems(fmt):
90 for key, value in iteritems(fmt):
87 # encoded3 has str, want bytes
91 # encoded3 has str, want bytes
88 decoded = decodestring(str_to_bytes(encoded3[key]))
92 decoded = decodestring(str_to_bytes(encoded3[key]))
89 nt.assert_equal(decoded, value)
93 nt.assert_equal(decoded, value)
90
94
91 def test_lambda():
95 def test_lambda():
92 jc = json_clean(lambda : 1)
96 jc = json_clean(lambda : 1)
93 assert isinstance(jc, str)
97 assert isinstance(jc, str)
94 assert '<lambda>' in jc
98 assert '<lambda>' in jc
95 json.dumps(jc)
99 json.dumps(jc)
96
100
97 def test_extract_dates():
101 def test_extract_dates():
98 timestamps = [
102 timestamps = [
99 '2013-07-03T16:34:52.249482',
103 '2013-07-03T16:34:52.249482',
100 '2013-07-03T16:34:52.249482Z',
104 '2013-07-03T16:34:52.249482Z',
101 '2013-07-03T16:34:52.249482Z-0800',
105 '2013-07-03T16:34:52.249482Z-0800',
102 '2013-07-03T16:34:52.249482Z+0800',
106 '2013-07-03T16:34:52.249482Z+0800',
103 '2013-07-03T16:34:52.249482Z+08:00',
107 '2013-07-03T16:34:52.249482Z+08:00',
104 '2013-07-03T16:34:52.249482Z-08:00',
108 '2013-07-03T16:34:52.249482Z-08:00',
105 '2013-07-03T16:34:52.249482-0800',
109 '2013-07-03T16:34:52.249482-0800',
106 '2013-07-03T16:34:52.249482+0800',
110 '2013-07-03T16:34:52.249482+0800',
107 '2013-07-03T16:34:52.249482+08:00',
111 '2013-07-03T16:34:52.249482+08:00',
108 '2013-07-03T16:34:52.249482-08:00',
112 '2013-07-03T16:34:52.249482-08:00',
109 ]
113 ]
110 extracted = jsonutil.extract_dates(timestamps)
114 extracted = jsonutil.extract_dates(timestamps)
111 ref = extracted[0]
115 ref = extracted[0]
112 for dt in extracted:
116 for dt in extracted:
113 nt.assert_true(isinstance(dt, datetime.datetime))
117 nt.assert_true(isinstance(dt, datetime.datetime))
114 nt.assert_equal(dt, ref)
118 nt.assert_equal(dt, ref)
115
119
116 def test_parse_ms_precision():
120 def test_parse_ms_precision():
117 base = '2013-07-03T16:34:52.'
121 base = '2013-07-03T16:34:52.'
118 digits = '1234567890'
122 digits = '1234567890'
119
123
120 for i in range(len(digits)):
124 for i in range(len(digits)):
121 ts = base + digits[:i]
125 ts = base + digits[:i]
122 parsed = jsonutil.parse_date(ts)
126 parsed = jsonutil.parse_date(ts)
123 if i >= 1 and i <= 6:
127 if i >= 1 and i <= 6:
124 assert isinstance(parsed, datetime.datetime)
128 assert isinstance(parsed, datetime.datetime)
125 else:
129 else:
126 assert isinstance(parsed, str)
130 assert isinstance(parsed, str)
127
131
128 def test_date_default():
132 def test_date_default():
129 data = dict(today=datetime.datetime.now(), utcnow=tz.utcnow())
133 data = dict(today=datetime.datetime.now(), utcnow=tz.utcnow())
130 jsondata = json.dumps(data, default=jsonutil.date_default)
134 jsondata = json.dumps(data, default=jsonutil.date_default)
131 nt.assert_in("+00", jsondata)
135 nt.assert_in("+00", jsondata)
132 nt.assert_equal(jsondata.count("+00"), 1)
136 nt.assert_equal(jsondata.count("+00"), 1)
133 extracted = jsonutil.extract_dates(json.loads(jsondata))
137 extracted = jsonutil.extract_dates(json.loads(jsondata))
134 for dt in extracted.values():
138 for dt in extracted.values():
135 nt.assert_true(isinstance(dt, datetime.datetime))
139 nt.assert_true(isinstance(dt, datetime.datetime))
136
140
137 def test_exception():
141 def test_exception():
138 bad_dicts = [{1:'number', '1':'string'},
142 bad_dicts = [{1:'number', '1':'string'},
139 {True:'bool', 'True':'string'},
143 {True:'bool', 'True':'string'},
140 ]
144 ]
141 for d in bad_dicts:
145 for d in bad_dicts:
142 nt.assert_raises(ValueError, json_clean, d)
146 nt.assert_raises(ValueError, json_clean, d)
143
147
General Comments 0
You need to be logged in to leave comments. Login now