• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import textwrap
2from io import StringIO
3from test.test_json import PyTest, CTest
4
5
6class TestIndent:
7    def test_indent(self):
8        h = [['blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh', 'i-vhbjkhnth',
9             {'nifty': 87}, {'field': 'yes', 'morefield': False} ]
10
11        expect = textwrap.dedent("""\
12        [
13        \t[
14        \t\t"blorpie"
15        \t],
16        \t[
17        \t\t"whoops"
18        \t],
19        \t[],
20        \t"d-shtaeou",
21        \t"d-nthiouh",
22        \t"i-vhbjkhnth",
23        \t{
24        \t\t"nifty": 87
25        \t},
26        \t{
27        \t\t"field": "yes",
28        \t\t"morefield": false
29        \t}
30        ]""")
31
32        d1 = self.dumps(h)
33        d2 = self.dumps(h, indent=2, sort_keys=True, separators=(',', ': '))
34        d3 = self.dumps(h, indent='\t', sort_keys=True, separators=(',', ': '))
35        d4 = self.dumps(h, indent=2, sort_keys=True)
36        d5 = self.dumps(h, indent='\t', sort_keys=True)
37
38        h1 = self.loads(d1)
39        h2 = self.loads(d2)
40        h3 = self.loads(d3)
41
42        self.assertEqual(h1, h)
43        self.assertEqual(h2, h)
44        self.assertEqual(h3, h)
45        self.assertEqual(d2, expect.expandtabs(2))
46        self.assertEqual(d3, expect)
47        self.assertEqual(d4, d2)
48        self.assertEqual(d5, d3)
49
50    def test_indent0(self):
51        h = {3: 1}
52        def check(indent, expected):
53            d1 = self.dumps(h, indent=indent)
54            self.assertEqual(d1, expected)
55
56            sio = StringIO()
57            self.json.dump(h, sio, indent=indent)
58            self.assertEqual(sio.getvalue(), expected)
59
60        # indent=0 should emit newlines
61        check(0, '{\n"3": 1\n}')
62        # indent=None is more compact
63        check(None, '{"3": 1}')
64
65
66class TestPyIndent(TestIndent, PyTest): pass
67class TestCIndent(TestIndent, CTest): pass
68