1import os 2import sys 3import textwrap 4import unittest 5import subprocess 6from test import support 7from test.support.script_helper import assert_python_ok 8 9 10class TestTool(unittest.TestCase): 11 data = """ 12 13 [["blorpie"],[ "whoops" ] , [ 14 ],\t"d-shtaeou",\r"d-nthiouh", 15 "i-vhbjkhnth", {"nifty":87}, {"morefield" :\tfalse,"field" 16 :"yes"} ] 17 """ 18 19 expect_without_sort_keys = textwrap.dedent("""\ 20 [ 21 [ 22 "blorpie" 23 ], 24 [ 25 "whoops" 26 ], 27 [], 28 "d-shtaeou", 29 "d-nthiouh", 30 "i-vhbjkhnth", 31 { 32 "nifty": 87 33 }, 34 { 35 "field": "yes", 36 "morefield": false 37 } 38 ] 39 """) 40 41 expect = textwrap.dedent("""\ 42 [ 43 [ 44 "blorpie" 45 ], 46 [ 47 "whoops" 48 ], 49 [], 50 "d-shtaeou", 51 "d-nthiouh", 52 "i-vhbjkhnth", 53 { 54 "nifty": 87 55 }, 56 { 57 "morefield": false, 58 "field": "yes" 59 } 60 ] 61 """) 62 63 def test_stdin_stdout(self): 64 with subprocess.Popen( 65 (sys.executable, '-m', 'json.tool'), 66 stdin=subprocess.PIPE, stdout=subprocess.PIPE) as proc: 67 out, err = proc.communicate(self.data.encode()) 68 self.assertEqual(out.splitlines(), self.expect.encode().splitlines()) 69 self.assertEqual(err, None) 70 71 def _create_infile(self): 72 infile = support.TESTFN 73 with open(infile, "w") as fp: 74 self.addCleanup(os.remove, infile) 75 fp.write(self.data) 76 return infile 77 78 def test_infile_stdout(self): 79 infile = self._create_infile() 80 rc, out, err = assert_python_ok('-m', 'json.tool', infile) 81 self.assertEqual(rc, 0) 82 self.assertEqual(out.splitlines(), self.expect.encode().splitlines()) 83 self.assertEqual(err, b'') 84 85 def test_infile_outfile(self): 86 infile = self._create_infile() 87 outfile = support.TESTFN + '.out' 88 rc, out, err = assert_python_ok('-m', 'json.tool', infile, outfile) 89 self.addCleanup(os.remove, outfile) 90 with open(outfile, "r") as fp: 91 self.assertEqual(fp.read(), self.expect) 92 self.assertEqual(rc, 0) 93 self.assertEqual(out, b'') 94 self.assertEqual(err, b'') 95 96 def test_help_flag(self): 97 rc, out, err = assert_python_ok('-m', 'json.tool', '-h') 98 self.assertEqual(rc, 0) 99 self.assertTrue(out.startswith(b'usage: ')) 100 self.assertEqual(err, b'') 101 102 def test_sort_keys_flag(self): 103 infile = self._create_infile() 104 rc, out, err = assert_python_ok('-m', 'json.tool', '--sort-keys', infile) 105 self.assertEqual(rc, 0) 106 self.assertEqual(out.splitlines(), 107 self.expect_without_sort_keys.encode().splitlines()) 108 self.assertEqual(err, b'') 109