1"""Basic tests for os.popen() 2 3 Particularly useful for platforms that fake popen. 4""" 5 6import unittest 7from test import support 8import 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. 15python = sys.executable 16if ' ' in python: 17 python = '"' + python + '"' # quote embedded space for cmdline 18 19class PopenTest(unittest.TestCase): 20 21 def _do_test_commandline(self, cmdline, expected): 22 cmd = '%s -c "import sys; print(sys.argv)" %s' 23 cmd = cmd % (python, cmdline) 24 with os.popen(cmd) as p: 25 data = p.read() 26 got = eval(data)[1:] # strip off argv[0] 27 self.assertEqual(got, expected) 28 29 def test_popen(self): 30 self.assertRaises(TypeError, os.popen) 31 self._do_test_commandline( 32 "foo bar", 33 ["foo", "bar"] 34 ) 35 self._do_test_commandline( 36 'foo "spam and eggs" "silly walk"', 37 ["foo", "spam and eggs", "silly walk"] 38 ) 39 self._do_test_commandline( 40 'foo "a \\"quoted\\" arg" bar', 41 ["foo", 'a "quoted" arg', "bar"] 42 ) 43 support.reap_children() 44 45 def test_return_code(self): 46 self.assertEqual(os.popen("exit 0").close(), None) 47 status = os.popen("exit 42").close() 48 if os.name == 'nt': 49 self.assertEqual(status, 42) 50 else: 51 self.assertEqual(os.waitstatus_to_exitcode(status), 42) 52 53 def test_contextmanager(self): 54 with os.popen("echo hello") as f: 55 self.assertEqual(f.read(), "hello\n") 56 57 def test_iterating(self): 58 with os.popen("echo hello") as f: 59 self.assertEqual(list(f), ["hello\n"]) 60 61 def test_keywords(self): 62 with os.popen(cmd="exit 0", mode="w", buffering=-1): 63 pass 64 65if __name__ == "__main__": 66 unittest.main() 67