test_commands.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. '''
  2. Tests for commands module
  3. Nick Mathewson
  4. '''
  5. import unittest
  6. import os, tempfile, re
  7. from test.test_support import run_unittest, reap_children, import_module, \
  8. check_warnings
  9. # Silence Py3k warning
  10. commands = import_module('commands', deprecated=True)
  11. # The module says:
  12. # "NB This only works (and is only relevant) for UNIX."
  13. #
  14. # Actually, getoutput should work on any platform with an os.popen, but
  15. # I'll take the comment as given, and skip this suite.
  16. if os.name != 'posix':
  17. raise unittest.SkipTest('Not posix; skipping test_commands')
  18. class CommandTests(unittest.TestCase):
  19. def test_getoutput(self):
  20. self.assertEqual(commands.getoutput('echo xyzzy'), 'xyzzy')
  21. self.assertEqual(commands.getstatusoutput('echo xyzzy'), (0, 'xyzzy'))
  22. # we use mkdtemp in the next line to create an empty directory
  23. # under our exclusive control; from that, we can invent a pathname
  24. # that we _know_ won't exist. This is guaranteed to fail.
  25. dir = None
  26. try:
  27. dir = tempfile.mkdtemp()
  28. name = os.path.join(dir, "foo")
  29. status, output = commands.getstatusoutput('cat ' + name)
  30. self.assertNotEqual(status, 0)
  31. finally:
  32. if dir is not None:
  33. os.rmdir(dir)
  34. def test_getstatus(self):
  35. # This pattern should match 'ls -ld /.' on any posix
  36. # system, however perversely configured. Even on systems
  37. # (e.g., Cygwin) where user and group names can have spaces:
  38. # drwxr-xr-x 15 Administ Domain U 4096 Aug 12 12:50 /
  39. # drwxr-xr-x 15 Joe User My Group 4096 Aug 12 12:50 /
  40. # Note that the first case above has a space in the group name
  41. # while the second one has a space in both names.
  42. # Special attributes supported:
  43. # + = has ACLs
  44. # @ = has Mac OS X extended attributes
  45. # . = has a SELinux security context
  46. pat = r'''d......... # It is a directory.
  47. [.+@]? # It may have special attributes.
  48. \s+\d+ # It has some number of links.
  49. [^/]* # Skip user, group, size, and date.
  50. /\. # and end with the name of the file.
  51. '''
  52. with check_warnings((".*commands.getstatus.. is deprecated",
  53. DeprecationWarning)):
  54. self.assertTrue(re.match(pat, commands.getstatus("/."), re.VERBOSE))
  55. def test_main():
  56. run_unittest(CommandTests)
  57. reap_children()
  58. if __name__ == "__main__":
  59. test_main()