test_indent.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. from unittest import TestCase
  2. import textwrap
  3. import simplejson as json
  4. from simplejson.compat import StringIO
  5. class TestIndent(TestCase):
  6. def test_indent(self):
  7. h = [['blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh',
  8. 'i-vhbjkhnth',
  9. {'nifty': 87}, {'field': 'yes', 'morefield': False} ]
  10. expect = textwrap.dedent("""\
  11. [
  12. \t[
  13. \t\t"blorpie"
  14. \t],
  15. \t[
  16. \t\t"whoops"
  17. \t],
  18. \t[],
  19. \t"d-shtaeou",
  20. \t"d-nthiouh",
  21. \t"i-vhbjkhnth",
  22. \t{
  23. \t\t"nifty": 87
  24. \t},
  25. \t{
  26. \t\t"field": "yes",
  27. \t\t"morefield": false
  28. \t}
  29. ]""")
  30. d1 = json.dumps(h)
  31. d2 = json.dumps(h, indent='\t', sort_keys=True, separators=(',', ': '))
  32. d3 = json.dumps(h, indent=' ', sort_keys=True, separators=(',', ': '))
  33. d4 = json.dumps(h, indent=2, sort_keys=True, separators=(',', ': '))
  34. h1 = json.loads(d1)
  35. h2 = json.loads(d2)
  36. h3 = json.loads(d3)
  37. h4 = json.loads(d4)
  38. self.assertEqual(h1, h)
  39. self.assertEqual(h2, h)
  40. self.assertEqual(h3, h)
  41. self.assertEqual(h4, h)
  42. self.assertEqual(d3, expect.replace('\t', ' '))
  43. self.assertEqual(d4, expect.replace('\t', ' '))
  44. # NOTE: Python 2.4 textwrap.dedent converts tabs to spaces,
  45. # so the following is expected to fail. Python 2.4 is not a
  46. # supported platform in simplejson 2.1.0+.
  47. self.assertEqual(d2, expect)
  48. def test_indent0(self):
  49. h = {3: 1}
  50. def check(indent, expected):
  51. d1 = json.dumps(h, indent=indent)
  52. self.assertEqual(d1, expected)
  53. sio = StringIO()
  54. json.dump(h, sio, indent=indent)
  55. self.assertEqual(sio.getvalue(), expected)
  56. # indent=0 should emit newlines
  57. check(0, '{\n"3": 1\n}')
  58. # indent=None is more compact
  59. check(None, '{"3": 1}')
  60. def test_separators(self):
  61. lst = [1,2,3,4]
  62. expect = '[\n1,\n2,\n3,\n4\n]'
  63. expect_spaces = '[\n1, \n2, \n3, \n4\n]'
  64. # Ensure that separators still works
  65. self.assertEqual(
  66. expect_spaces,
  67. json.dumps(lst, indent=0, separators=(', ', ': ')))
  68. # Force the new defaults
  69. self.assertEqual(
  70. expect,
  71. json.dumps(lst, indent=0, separators=(',', ': ')))
  72. # Added in 2.1.4
  73. self.assertEqual(
  74. expect,
  75. json.dumps(lst, indent=0))