ยปCore Development>Code coverage>Lib/test/test_json/test_recursion.py

Python code coverage for Lib/test/test_json/test_recursion.py

#countcontent
1n/afrom test.test_json import PyTest, CTest
2n/a
3n/a
4n/aclass JSONTestObject:
5n/a pass
6n/a
7n/a
8n/aclass TestRecursion:
9n/a def test_listrecursion(self):
10n/a x = []
11n/a x.append(x)
12n/a try:
13n/a self.dumps(x)
14n/a except ValueError:
15n/a pass
16n/a else:
17n/a self.fail("didn't raise ValueError on list recursion")
18n/a x = []
19n/a y = [x]
20n/a x.append(y)
21n/a try:
22n/a self.dumps(x)
23n/a except ValueError:
24n/a pass
25n/a else:
26n/a self.fail("didn't raise ValueError on alternating list recursion")
27n/a y = []
28n/a x = [y, y]
29n/a # ensure that the marker is cleared
30n/a self.dumps(x)
31n/a
32n/a def test_dictrecursion(self):
33n/a x = {}
34n/a x["test"] = x
35n/a try:
36n/a self.dumps(x)
37n/a except ValueError:
38n/a pass
39n/a else:
40n/a self.fail("didn't raise ValueError on dict recursion")
41n/a x = {}
42n/a y = {"a": x, "b": x}
43n/a # ensure that the marker is cleared
44n/a self.dumps(x)
45n/a
46n/a def test_defaultrecursion(self):
47n/a class RecursiveJSONEncoder(self.json.JSONEncoder):
48n/a recurse = False
49n/a def default(self, o):
50n/a if o is JSONTestObject:
51n/a if self.recurse:
52n/a return [JSONTestObject]
53n/a else:
54n/a return 'JSONTestObject'
55n/a return pyjson.JSONEncoder.default(o)
56n/a
57n/a enc = RecursiveJSONEncoder()
58n/a self.assertEqual(enc.encode(JSONTestObject), '"JSONTestObject"')
59n/a enc.recurse = True
60n/a try:
61n/a enc.encode(JSONTestObject)
62n/a except ValueError:
63n/a pass
64n/a else:
65n/a self.fail("didn't raise ValueError on default recursion")
66n/a
67n/a
68n/a def test_highly_nested_objects_decoding(self):
69n/a # test that loading highly-nested objects doesn't segfault when C
70n/a # accelerations are used. See #12017
71n/a with self.assertRaises(RecursionError):
72n/a self.loads('{"a":' * 100000 + '1' + '}' * 100000)
73n/a with self.assertRaises(RecursionError):
74n/a self.loads('{"a":' * 100000 + '[1]' + '}' * 100000)
75n/a with self.assertRaises(RecursionError):
76n/a self.loads('[' * 100000 + '1' + ']' * 100000)
77n/a
78n/a def test_highly_nested_objects_encoding(self):
79n/a # See #12051
80n/a l, d = [], {}
81n/a for x in range(100000):
82n/a l, d = [l], {'k':d}
83n/a with self.assertRaises(RecursionError):
84n/a self.dumps(l)
85n/a with self.assertRaises(RecursionError):
86n/a self.dumps(d)
87n/a
88n/a def test_endless_recursion(self):
89n/a # See #12051
90n/a class EndlessJSONEncoder(self.json.JSONEncoder):
91n/a def default(self, o):
92n/a """If check_circular is False, this will keep adding another list."""
93n/a return [o]
94n/a
95n/a with self.assertRaises(RecursionError):
96n/a EndlessJSONEncoder(check_circular=False).encode(5j)
97n/a
98n/a
99n/aclass TestPyRecursion(TestRecursion, PyTest): pass
100n/aclass TestCRecursion(TestRecursion, CTest): pass