• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
10if not hasattr(os, 'popen'):
11    raise unittest.SkipTest("need os.popen()")
12
13# Test that command-lines get down as we expect.
14# To do this we execute:
15#    python -c "import sys;print(sys.argv)" {rest_of_commandline}
16# This results in Python being spawned and printing the sys.argv list.
17# We can then eval() the result of this, and see what each argv was.
18python = sys.executable
19if ' ' in python:
20    python = '"' + python + '"'     # quote embedded space for cmdline
21
22class PopenTest(unittest.TestCase):
23
24    def _do_test_commandline(self, cmdline, expected):
25        cmd = '%s -c "import sys; print(sys.argv)" %s'
26        cmd = cmd % (python, cmdline)
27        with os.popen(cmd) as p:
28            data = p.read()
29        got = eval(data)[1:] # strip off argv[0]
30        self.assertEqual(got, expected)
31
32    def test_popen(self):
33        self.assertRaises(TypeError, os.popen)
34        self._do_test_commandline(
35            "foo bar",
36            ["foo", "bar"]
37        )
38        self._do_test_commandline(
39            'foo "spam and eggs" "silly walk"',
40            ["foo", "spam and eggs", "silly walk"]
41        )
42        self._do_test_commandline(
43            'foo "a \\"quoted\\" arg" bar',
44            ["foo", 'a "quoted" arg', "bar"]
45        )
46        support.reap_children()
47
48    def test_return_code(self):
49        self.assertEqual(os.popen("exit 0").close(), None)
50        status = os.popen("exit 42").close()
51        if os.name == 'nt':
52            self.assertEqual(status, 42)
53        else:
54            self.assertEqual(os.waitstatus_to_exitcode(status), 42)
55
56    def test_contextmanager(self):
57        with os.popen("echo hello") as f:
58            self.assertEqual(f.read(), "hello\n")
59
60    def test_iterating(self):
61        with os.popen("echo hello") as f:
62            self.assertEqual(list(f), ["hello\n"])
63
64    def test_keywords(self):
65        with os.popen(cmd="exit 0", mode="w", buffering=-1):
66            pass
67
68if __name__ == "__main__":
69    unittest.main()
70