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