blob: 816b9d1570acf2ec7c7ac60521a55b2a636e3cef [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
Mark Hammonde7fefbf2002-04-03 01:47:00 +000017
Walter Dörwald4b884a52007-01-24 00:42:19 +000018class PopenTest(unittest.TestCase):
19 def _do_test_commandline(self, cmdline, expected):
Benjamin Peterson7a1b4352010-01-14 02:40:10 +000020 cmd = '"%s" -c "import sys;print sys.argv" %s' % (python, cmdline)
Benjamin Peterson667dc192010-01-15 02:26:07 +000021 data = os.popen(cmd).read() + '\n'
Walter Dörwald4b884a52007-01-24 00:42:19 +000022 got = eval(data)[1:] # strip off argv[0]
23 self.assertEqual(got, expected)
Mark Hammonde7fefbf2002-04-03 01:47:00 +000024
Walter Dörwald4b884a52007-01-24 00:42:19 +000025 def test_popen(self):
26 self.assertRaises(TypeError, os.popen)
27 self._do_test_commandline(
28 "foo bar",
29 ["foo", "bar"]
30 )
31 self._do_test_commandline(
32 'foo "spam and eggs" "silly walk"',
33 ["foo", "spam and eggs", "silly walk"]
34 )
35 self._do_test_commandline(
36 'foo "a \\"quoted\\" arg" bar',
37 ["foo", 'a "quoted" arg', "bar"]
38 )
39 test_support.reap_children()
Mark Hammonde7fefbf2002-04-03 01:47:00 +000040
Amaury Forgeot d'Arc91757422009-07-11 09:09:59 +000041 def test_return_code(self):
42 self.assertEqual(os.popen("exit 0").close(), None)
43 if os.name == 'nt':
44 self.assertEqual(os.popen("exit 42").close(), 42)
45 else:
46 self.assertEqual(os.popen("exit 42").close(), 42 << 8)
47
Walter Dörwald4b884a52007-01-24 00:42:19 +000048def test_main():
49 test_support.run_unittest(PopenTest)
50
51if __name__ == "__main__":
52 test_main()