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