test_popen.py 2.1 KB

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