1 | n/a | from io import StringIO |
---|
2 | n/a | from test.test_json import PyTest, CTest |
---|
3 | n/a | |
---|
4 | n/a | from test.support import bigmemtest, _1G |
---|
5 | n/a | |
---|
6 | n/a | class TestDump: |
---|
7 | n/a | def test_dump(self): |
---|
8 | n/a | sio = StringIO() |
---|
9 | n/a | self.json.dump({}, sio) |
---|
10 | n/a | self.assertEqual(sio.getvalue(), '{}') |
---|
11 | n/a | |
---|
12 | n/a | def test_dumps(self): |
---|
13 | n/a | self.assertEqual(self.dumps({}), '{}') |
---|
14 | n/a | |
---|
15 | n/a | def test_encode_truefalse(self): |
---|
16 | n/a | self.assertEqual(self.dumps( |
---|
17 | n/a | {True: False, False: True}, sort_keys=True), |
---|
18 | n/a | '{"false": true, "true": false}') |
---|
19 | n/a | self.assertEqual(self.dumps( |
---|
20 | n/a | {2: 3.0, 4.0: 5, False: 1, 6: True}, sort_keys=True), |
---|
21 | n/a | '{"false": 1, "2": 3.0, "4.0": 5, "6": true}') |
---|
22 | n/a | |
---|
23 | n/a | # Issue 16228: Crash on encoding resized list |
---|
24 | n/a | def test_encode_mutated(self): |
---|
25 | n/a | a = [object()] * 10 |
---|
26 | n/a | def crasher(obj): |
---|
27 | n/a | del a[-1] |
---|
28 | n/a | self.assertEqual(self.dumps(a, default=crasher), |
---|
29 | n/a | '[null, null, null, null, null]') |
---|
30 | n/a | |
---|
31 | n/a | # Issue 24094 |
---|
32 | n/a | def test_encode_evil_dict(self): |
---|
33 | n/a | class D(dict): |
---|
34 | n/a | def keys(self): |
---|
35 | n/a | return L |
---|
36 | n/a | |
---|
37 | n/a | class X: |
---|
38 | n/a | def __hash__(self): |
---|
39 | n/a | del L[0] |
---|
40 | n/a | return 1337 |
---|
41 | n/a | |
---|
42 | n/a | def __lt__(self, o): |
---|
43 | n/a | return 0 |
---|
44 | n/a | |
---|
45 | n/a | L = [X() for i in range(1122)] |
---|
46 | n/a | d = D() |
---|
47 | n/a | d[1337] = "true.dat" |
---|
48 | n/a | self.assertEqual(self.dumps(d, sort_keys=True), '{"1337": "true.dat"}') |
---|
49 | n/a | |
---|
50 | n/a | |
---|
51 | n/a | class TestPyDump(TestDump, PyTest): pass |
---|
52 | n/a | |
---|
53 | n/a | class TestCDump(TestDump, CTest): |
---|
54 | n/a | |
---|
55 | n/a | # The size requirement here is hopefully over-estimated (actual |
---|
56 | n/a | # memory consumption depending on implementation details, and also |
---|
57 | n/a | # system memory management, since this may allocate a lot of |
---|
58 | n/a | # small objects). |
---|
59 | n/a | |
---|
60 | n/a | @bigmemtest(size=_1G, memuse=1) |
---|
61 | n/a | def test_large_list(self, size): |
---|
62 | n/a | N = int(30 * 1024 * 1024 * (size / _1G)) |
---|
63 | n/a | l = [1] * N |
---|
64 | n/a | encoded = self.dumps(l) |
---|
65 | n/a | self.assertEqual(len(encoded), N * 3) |
---|
66 | n/a | self.assertEqual(encoded[:1], "[") |
---|
67 | n/a | self.assertEqual(encoded[-2:], "1]") |
---|
68 | n/a | self.assertEqual(encoded[1:-2], "1, " * (N - 1)) |
---|