Home | History | Annotate | Download | only in test
      1 """Basic tests for os.popen()
      2 
      3   Particularly useful for platforms that fake popen.
      4 """
      5 
      6 import unittest
      7 from test import test_support
      8 import os, sys
      9 
     10 # Test that command-lines get down as we expect.
     11 # To do this we execute:
     12 #    python -c "import sys;print sys.argv" {rest_of_commandline}
     13 # This results in Python being spawned and printing the sys.argv list.
     14 # We can then eval() the result of this, and see what each argv was.
     15 python = sys.executable
     16 
     17 class PopenTest(unittest.TestCase):
     18     def _do_test_commandline(self, cmdline, expected):
     19         cmd = '%s -c "import sys;print sys.argv" %s' % (python, cmdline)
     20         data = os.popen(cmd).read() + '\n'
     21         got = eval(data)[1:] # strip off argv[0]
     22         self.assertEqual(got, expected)
     23 
     24     def test_popen(self):
     25         self.assertRaises(TypeError, os.popen)
     26         self._do_test_commandline(
     27             "foo bar",
     28             ["foo", "bar"]
     29         )
     30         self._do_test_commandline(
     31             'foo "spam and eggs" "silly walk"',
     32             ["foo", "spam and eggs", "silly walk"]
     33         )
     34         self._do_test_commandline(
     35             'foo "a \\"quoted\\" arg" bar',
     36             ["foo", 'a "quoted" arg', "bar"]
     37         )
     38         test_support.reap_children()
     39 
     40     def test_return_code(self):
     41         self.assertEqual(os.popen("exit 0").close(), None)
     42         if os.name == 'nt':
     43             self.assertEqual(os.popen("exit 42").close(), 42)
     44         else:
     45             self.assertEqual(os.popen("exit 42").close(), 42 << 8)
     46 
     47 def test_main():
     48     test_support.run_unittest(PopenTest)
     49 
     50 if __name__ == "__main__":
     51     test_main()
     52