Debian Codegraph @

Lib/test/test_json/test_decode.py

raw
1 import decimal
2 import unittest.mock
3 from io import StringIO
4 from collections import OrderedDict
5 from test.test_json import PyTest, CTest
6 from test import support
7
8
9 class TestDecode:
10 def test_decimal(self):
11 rval = self.loads('1.1', parse_float=decimal.Decimal)
12 self.assertIsInstance(rval, decimal.Decimal)
13 self.assertEqual(rval, decimal.Decimal('1.1'))
14
15 def test_float(self):
16 rval = self.loads('1', parse_int=float)
17 self.assertIsInstance(rval, float)
18 self.assertEqual(rval, 1.0)
19
20 def test_nonascii_digits_rejected(self):
21 # JSON specifies only ascii digits, see gh-125687
22 for num in ["1\uff10", "0.\uff10", "0e\uff10"]:
23 with self.assertRaises(self.JSONDecodeError):
24 self.loads(num)
25
26 def test_bytes(self):
27 self.assertEqual(self.loads(b"1"), 1)
28
29 def test_parse_constant(self):
30 for constant, expected in [
31 ("Infinity", "INFINITY"),
32 ("-Infinity", "-INFINITY"),
33 ("NaN", "NAN"),
34 ]:
35 self.assertEqual(
36 self.loads(constant, parse_constant=str.upper), expected
37 )
38
39 def test_constant_invalid_case(self):
40 for constant in [
41 "nan", "NAN", "naN", "infinity", "INFINITY", "inFiniTy"
42 ]:
43 with self.assertRaises(self.JSONDecodeError):
44 self.loads(constant)
45
46 def test_empty_objects(self):
47 self.assertEqual(self.loads('{}'), {})
48 self.assertEqual(self.loads('[]'), [])
49 self.assertEqual(self.loads('""'), "")
50
51 def test_object_pairs_hook(self):
52 s = '{"xkd":1, "kcw":2, "art":3, "hxm":4, "qrt":5, "pad":6, "hoy":7}'
53 p = [("xkd", 1), ("kcw", 2), ("art", 3), ("hxm", 4),
54 ("qrt", 5), ("pad", 6), ("hoy", 7)]
55 self.assertEqual(self.loads(s), eval(s))
56 self.assertEqual(self.loads(s, object_pairs_hook=lambda x: x), p)
57 self.assertEqual(self.json.load(StringIO(s),
58 object_pairs_hook=lambda x: x), p)
59 od = self.loads(s, object_pairs_hook=OrderedDict)
60 self.assertEqual(od, OrderedDict(p))
61 self.assertEqual(type(od), OrderedDict)
62 # the object_pairs_hook takes priority over the object_hook
63 self.assertEqual(self.loads(s, object_pairs_hook=OrderedDict,
64 object_hook=lambda x: None),
65 OrderedDict(p))
66 # check that empty object literals work (see #17368)
67 self.assertEqual(self.loads('{}', object_pairs_hook=OrderedDict),
68 OrderedDict())
69 self.assertEqual(self.loads('{"empty": {}}',
70 object_pairs_hook=OrderedDict),
71 OrderedDict([('empty', OrderedDict())]))
72
73 def test_decoder_optimizations(self):
74 # Several optimizations were made that skip over calls to
75 # the whitespace regex, so this test is designed to try and
76 # exercise the uncommon cases. The array cases are already covered.
77 rval = self.loads('{ "key" : "value" , "k":"v" }')
78 self.assertEqual(rval, {"key":"value", "k":"v"})
79
80 def check_keys_reuse(self, source, loads):
81 rval = loads(source)
82 (a, b), (c, d) = sorted(rval[0]), sorted(rval[1])
83 self.assertIs(a, c)
84 self.assertIs(b, d)
85
86 def test_keys_reuse(self):
87 s = '[{"a_key": 1, "b_\xe9": 2}, {"a_key": 3, "b_\xe9": 4}]'
88 self.check_keys_reuse(s, self.loads)
89 decoder = self.json.decoder.JSONDecoder()
90 self.check_keys_reuse(s, decoder.decode)
91 self.assertFalse(decoder.memo)
92
93 def test_extra_data(self):
94 s = '[1, 2, 3]5'
95 msg = 'Extra data'
96 self.assertRaisesRegex(self.JSONDecodeError, msg, self.loads, s)
97
98 def test_invalid_escape(self):
99 s = '["abc\\y"]'
100 msg = 'escape'
101 self.assertRaisesRegex(self.JSONDecodeError, msg, self.loads, s)
102
103 def test_invalid_input_type(self):
104 msg = 'the JSON object must be str'
105 for value in [1, 3.14, [], {}, None]:
106 self.assertRaisesRegex(TypeError, msg, self.loads, value)
107
108 def test_string_with_utf8_bom(self):
109 # see #18958
110 bom_json = "[1,2,3]".encode('utf-8-sig').decode('utf-8')
111 with self.assertRaises(self.JSONDecodeError) as cm:
112 self.loads(bom_json)
113 self.assertIn('BOM', str(cm.exception))
114 with self.assertRaises(self.JSONDecodeError) as cm:
115 self.json.load(StringIO(bom_json))
116 self.assertIn('BOM', str(cm.exception))
117 # make sure that the BOM is not detected in the middle of a string
118 bom = ''.encode('utf-8-sig').decode('utf-8')
119 bom_in_str = f'"{bom}"'
120 self.assertEqual(self.loads(bom_in_str), '\ufeff')
121 self.assertEqual(self.json.load(StringIO(bom_in_str)), '\ufeff')
122
123 def test_negative_index(self):
124 d = self.json.JSONDecoder()
125 self.assertRaises(ValueError, d.raw_decode, 'a'*42, -50000)
126
127 def test_unterminated_string(self):
128 d = self.json.JSONDecoder()
129 self.assertRaises(self.JSONDecodeError, d.raw_decode, '"\\')
130
131 def test_limit_int(self):
132 maxdigits = 5000
133 with support.adjust_int_max_str_digits(maxdigits):
134 self.loads('1' * maxdigits)
135 with self.assertRaises(ValueError):
136 self.loads('1' * (maxdigits + 1))
137
138 def test_explicit_cls_skips_json_decoder_default(self):
139 class CustomDecoder:
140 pass
141
142 with unittest.mock.patch.object(
143 CustomDecoder, 'decode', create=True) as mock_decode:
144 self.loads('{}', cls=CustomDecoder)
145 mock_decode.assert_called_once()
146
147
148 class TestPyDecode(TestDecode, PyTest): pass
149 class TestCDecode(TestDecode, CTest): pass