test_popen.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. """Basic tests for os.popen()
  2. Particularly useful for platforms that fake popen.
  3. """
  4. import unittest
  5. from test import test_support
  6. import os, sys
  7. # Test that command-lines get down as we expect.
  8. # To do this we execute:
  9. # python -c "import sys;print sys.argv" {rest_of_commandline}
  10. # This results in Python being spawned and printing the sys.argv list.
  11. # We can then eval() the result of this, and see what each argv was.
  12. python = sys.executable
  13. class PopenTest(unittest.TestCase):
  14. def _do_test_commandline(self, cmdline, expected):
  15. cmd = '%s -c "import sys;print sys.argv" %s' % (python, cmdline)
  16. data = os.popen(cmd).read() + '\n'
  17. got = eval(data)[1:] # strip off argv[0]
  18. self.assertEqual(got, expected)
  19. def test_popen(self):
  20. self.assertRaises(TypeError, os.popen)
  21. self._do_test_commandline(
  22. "foo bar",
  23. ["foo", "bar"]
  24. )
  25. self._do_test_commandline(
  26. 'foo "spam and eggs" "silly walk"',
  27. ["foo", "spam and eggs", "silly walk"]
  28. )
  29. self._do_test_commandline(
  30. 'foo "a \\"quoted\\" arg" bar',
  31. ["foo", 'a "quoted" arg', "bar"]
  32. )
  33. test_support.reap_children()
  34. def test_return_code(self):
  35. self.assertEqual(os.popen("exit 0").close(), None)
  36. if os.name == 'nt':
  37. self.assertEqual(os.popen("exit 42").close(), 42)
  38. else:
  39. self.assertEqual(os.popen("exit 42").close(), 42 << 8)
  40. def test_main():
  41. test_support.run_unittest(PopenTest)
  42. if __name__ == "__main__":
  43. test_main()