Home | History | Annotate | Download | only in tests
      1 import os
      2 import sys
      3 import textwrap
      4 import unittest
      5 import subprocess
      6 from test import test_support
      7 from test.script_helper import assert_python_ok
      8 
      9 class TestTool(unittest.TestCase):
     10     data = """
     11 
     12         [["blorpie"],[ "whoops" ] , [
     13                                  ],\t"d-shtaeou",\r"d-nthiouh",
     14         "i-vhbjkhnth", {"nifty":87}, {"morefield" :\tfalse,"field"
     15             :"yes"}  ]
     16            """
     17 
     18     expect = textwrap.dedent("""\
     19     [
     20         [
     21             "blorpie"
     22         ],
     23         [
     24             "whoops"
     25         ],
     26         [],
     27         "d-shtaeou",
     28         "d-nthiouh",
     29         "i-vhbjkhnth",
     30         {
     31             "nifty": 87
     32         },
     33         {
     34             "field": "yes",
     35             "morefield": false
     36         }
     37     ]
     38     """)
     39 
     40     def test_stdin_stdout(self):
     41         proc = subprocess.Popen(
     42                 (sys.executable, '-m', 'json.tool'),
     43                 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
     44         out, err = proc.communicate(self.data.encode())
     45         self.assertEqual(out.splitlines(), self.expect.encode().splitlines())
     46         self.assertEqual(err, None)
     47 
     48     def _create_infile(self):
     49         infile = test_support.TESTFN
     50         with open(infile, "w") as fp:
     51             self.addCleanup(os.remove, infile)
     52             fp.write(self.data)
     53         return infile
     54 
     55     def test_infile_stdout(self):
     56         infile = self._create_infile()
     57         rc, out, err = assert_python_ok('-m', 'json.tool', infile)
     58         self.assertEqual(out.splitlines(), self.expect.encode().splitlines())
     59         self.assertEqual(err, b'')
     60 
     61     def test_infile_outfile(self):
     62         infile = self._create_infile()
     63         outfile = test_support.TESTFN + '.out'
     64         rc, out, err = assert_python_ok('-m', 'json.tool', infile, outfile)
     65         self.addCleanup(os.remove, outfile)
     66         with open(outfile, "r") as fp:
     67             self.assertEqual(fp.read(), self.expect)
     68         self.assertEqual(out, b'')
     69         self.assertEqual(err, b'')
     70