test_commands.py 2.41 KB
Newer Older
1 2 3 4 5 6
'''
   Tests for commands module
   Nick Mathewson
'''
import unittest
import os, tempfile, re
7

8 9
from test.test_support import run_unittest, reap_children, import_module, \
                              check_warnings
10 11

# Silence Py3k warning
12
commands = import_module('commands', deprecated=True)
13 14 15 16 17 18 19 20

# The module says:
#   "NB This only works (and is only relevant) for UNIX."
#
# Actually, getoutput should work on any platform with an os.popen, but
# I'll take the comment as given, and skip this suite.

if os.name != 'posix':
21
    raise unittest.SkipTest('Not posix; skipping test_commands')
22 23 24 25 26


class CommandTests(unittest.TestCase):

    def test_getoutput(self):
27 28
        self.assertEquals(commands.getoutput('echo xyzzy'), 'xyzzy')
        self.assertEquals(commands.getstatusoutput('echo xyzzy'), (0, 'xyzzy'))
29

30 31 32
        # we use mkdtemp in the next line to create an empty directory
        # under our exclusive control; from that, we can invent a pathname
        # that we _know_ won't exist.  This is guaranteed to fail.
33
        dir = None
34 35 36 37
        try:
            dir = tempfile.mkdtemp()
            name = os.path.join(dir, "foo")

38
            status, output = commands.getstatusoutput('cat ' + name)
39 40
            self.assertNotEquals(status, 0)
        finally:
41 42
            if dir is not None:
                os.rmdir(dir)
43 44

    def test_getstatus(self):
45
        # This pattern should match 'ls -ld /.' on any posix
46 47 48 49 50 51
        # system, however perversely configured.  Even on systems
        # (e.g., Cygwin) where user and group names can have spaces:
        #     drwxr-xr-x   15 Administ Domain U     4096 Aug 12 12:50 /
        #     drwxr-xr-x   15 Joe User My Group     4096 Aug 12 12:50 /
        # Note that the first case above has a space in the group name
        # while the second one has a space in both names.
52
        pat = r'''d.........   # It is a directory.
53
                  \+?          # It may have ACLs.
54
                  \s+\d+       # It has some number of links.
55
                  [^/]*        # Skip user, group, size, and date.
56
                  /\.          # and end with the name of the file.
57 58
               '''

59 60 61
        with check_warnings((".*commands.getstatus.. is deprecated",
                             DeprecationWarning)):
            self.assertTrue(re.match(pat, commands.getstatus("/."), re.VERBOSE))
62

63 64 65

def test_main():
    run_unittest(CommandTests)
66
    reap_children()
67 68 69 70


if __name__ == "__main__":
    test_main()