test_indent.py 1.78 KB
Newer Older
1
import textwrap
2
from io import StringIO
3
from test.test_json import PyTest, CTest
Ezio Melotti's avatar
Ezio Melotti committed
4

5

Ezio Melotti's avatar
Ezio Melotti committed
6
class TestIndent:
7 8 9 10 11 12
    def test_indent(self):
        h = [['blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh', 'i-vhbjkhnth',
             {'nifty': 87}, {'field': 'yes', 'morefield': False} ]

        expect = textwrap.dedent("""\
        [
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
        \t[
        \t\t"blorpie"
        \t],
        \t[
        \t\t"whoops"
        \t],
        \t[],
        \t"d-shtaeou",
        \t"d-nthiouh",
        \t"i-vhbjkhnth",
        \t{
        \t\t"nifty": 87
        \t},
        \t{
        \t\t"field": "yes",
        \t\t"morefield": false
        \t}
30 31
        ]""")

Ezio Melotti's avatar
Ezio Melotti committed
32 33 34
        d1 = self.dumps(h)
        d2 = self.dumps(h, indent=2, sort_keys=True, separators=(',', ': '))
        d3 = self.dumps(h, indent='\t', sort_keys=True, separators=(',', ': '))
35 36
        d4 = self.dumps(h, indent=2, sort_keys=True)
        d5 = self.dumps(h, indent='\t', sort_keys=True)
37

Ezio Melotti's avatar
Ezio Melotti committed
38 39 40
        h1 = self.loads(d1)
        h2 = self.loads(d2)
        h3 = self.loads(d3)
41

42 43 44 45 46
        self.assertEqual(h1, h)
        self.assertEqual(h2, h)
        self.assertEqual(h3, h)
        self.assertEqual(d2, expect.expandtabs(2))
        self.assertEqual(d3, expect)
47 48
        self.assertEqual(d4, d2)
        self.assertEqual(d5, d3)
49 50 51 52

    def test_indent0(self):
        h = {3: 1}
        def check(indent, expected):
Ezio Melotti's avatar
Ezio Melotti committed
53
            d1 = self.dumps(h, indent=indent)
54 55 56
            self.assertEqual(d1, expected)

            sio = StringIO()
Ezio Melotti's avatar
Ezio Melotti committed
57
            self.json.dump(h, sio, indent=indent)
58 59 60 61 62 63
            self.assertEqual(sio.getvalue(), expected)

        # indent=0 should emit newlines
        check(0, '{\n"3": 1\n}')
        # indent=None is more compact
        check(None, '{"3": 1}')
Ezio Melotti's avatar
Ezio Melotti committed
64 65 66 67


class TestPyIndent(TestIndent, PyTest): pass
class TestCIndent(TestIndent, CTest): pass