blob: cb65fdf2fcde2a19c664876e37a8c550b3908608 [file] [log] [blame]
Mark Hammonde7fefbf2002-04-03 01:47:00 +00001#! /usr/bin/env python
2"""Basic tests for os.popen()
3
4 Particularly useful for platforms that fake popen.
5"""
6
Walter Dörwald4b884a52007-01-24 00:42:19 +00007import unittest
8from test import test_support
9import os, sys
Mark Hammonde7fefbf2002-04-03 01:47:00 +000010
11# Test that command-lines get down as we expect.
12# To do this we execute:
13# python -c "import sys;print sys.argv" {rest_of_commandline}
14# This results in Python being spawned and printing the sys.argv list.
15# We can then eval() the result of this, and see what each argv was.
Tim Peters61cd0db2003-03-07 21:10:21 +000016python = sys.executable
17if ' ' in python:
18 python = '"' + python + '"' # quote embedded space for cmdline
Mark Hammonde7fefbf2002-04-03 01:47:00 +000019
Walter Dörwald4b884a52007-01-24 00:42:19 +000020class PopenTest(unittest.TestCase):
21 def _do_test_commandline(self, cmdline, expected):
22 cmd = '%s -c "import sys;print sys.argv" %s' % (python, cmdline)
23 data = os.popen(cmd).read()
24 got = eval(data)[1:] # strip off argv[0]
25 self.assertEqual(got, expected)
Mark Hammonde7fefbf2002-04-03 01:47:00 +000026
Walter Dörwald4b884a52007-01-24 00:42:19 +000027 def test_popen(self):
28 self.assertRaises(TypeError, os.popen)
29 self._do_test_commandline(
30 "foo bar",
31 ["foo", "bar"]
32 )
33 self._do_test_commandline(
34 'foo "spam and eggs" "silly walk"',
35 ["foo", "spam and eggs", "silly walk"]
36 )
37 self._do_test_commandline(
38 'foo "a \\"quoted\\" arg" bar',
39 ["foo", 'a "quoted" arg', "bar"]
40 )
41 test_support.reap_children()
Mark Hammonde7fefbf2002-04-03 01:47:00 +000042
Amaury Forgeot d'Arc91757422009-07-11 09:09:59 +000043 def test_return_code(self):
44 self.assertEqual(os.popen("exit 0").close(), None)
45 if os.name == 'nt':
46 self.assertEqual(os.popen("exit 42").close(), 42)
47 else:
48 self.assertEqual(os.popen("exit 42").close(), 42 << 8)
49
Walter Dörwald4b884a52007-01-24 00:42:19 +000050def test_main():
51 test_support.run_unittest(PopenTest)
52
53if __name__ == "__main__":
54 test_main()