ยปCore Development>Code coverage>Lib/test/test_json/test_tool.py

Python code coverage for Lib/test/test_json/test_tool.py

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