Mark Hammond | e7fefbf | 2002-04-03 01:47:00 +0000 | [diff] [blame] | 1 | """Basic tests for os.popen() |
| 2 | |
| 3 | Particularly useful for platforms that fake popen. |
| 4 | """ |
| 5 | |
Walter Dörwald | 4b884a5 | 2007-01-24 00:42:19 +0000 | [diff] [blame] | 6 | import unittest |
| 7 | from test import test_support |
| 8 | import os, sys |
Mark Hammond | e7fefbf | 2002-04-03 01:47:00 +0000 | [diff] [blame] | 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. |
Tim Peters | 61cd0db | 2003-03-07 21:10:21 +0000 | [diff] [blame] | 15 | python = sys.executable |
Mark Hammond | e7fefbf | 2002-04-03 01:47:00 +0000 | [diff] [blame] | 16 | |
Walter Dörwald | 4b884a5 | 2007-01-24 00:42:19 +0000 | [diff] [blame] | 17 | class PopenTest(unittest.TestCase): |
| 18 | def _do_test_commandline(self, cmdline, expected): |
Benjamin Peterson | 7aedb3b | 2010-01-31 18:02:35 +0000 | [diff] [blame] | 19 | cmd = '%s -c "import sys;print sys.argv" %s' % (python, cmdline) |
Benjamin Peterson | 667dc19 | 2010-01-15 02:26:07 +0000 | [diff] [blame] | 20 | data = os.popen(cmd).read() + '\n' |
Walter Dörwald | 4b884a5 | 2007-01-24 00:42:19 +0000 | [diff] [blame] | 21 | got = eval(data)[1:] # strip off argv[0] |
| 22 | self.assertEqual(got, expected) |
Mark Hammond | e7fefbf | 2002-04-03 01:47:00 +0000 | [diff] [blame] | 23 | |
Walter Dörwald | 4b884a5 | 2007-01-24 00:42:19 +0000 | [diff] [blame] | 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() |
Mark Hammond | e7fefbf | 2002-04-03 01:47:00 +0000 | [diff] [blame] | 39 | |
Amaury Forgeot d'Arc | 9175742 | 2009-07-11 09:09:59 +0000 | [diff] [blame] | 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 | |
Walter Dörwald | 4b884a5 | 2007-01-24 00:42:19 +0000 | [diff] [blame] | 47 | def test_main(): |
| 48 | test_support.run_unittest(PopenTest) |
| 49 | |
| 50 | if __name__ == "__main__": |
| 51 | test_main() |