~frankban/python-shelltoolbox/apt-and-run

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# Copyright 2012 Canonical Ltd.  This software is licensed under the
# GNU General Public License version 3 (see the file LICENSE).

"""Tests for Python shell toolbox."""

__metaclass__ = type


import os
from subprocess import CalledProcessError
import unittest

from shelltoolbox import (
    cd,
    command,
    DictDiffer,
    run,
    su,
    )


class TestRun(unittest.TestCase):

    def testSimpleCommand(self):
        # Running a simple command (ls) works and running the command
        # produces a string.
        self.assertIsInstance(run('/bin/ls'), str)

    def testStdoutReturned(self):
        # Running a simple command (ls) works and running the command
        # produces a string.
        self.assertIn('Usage:', run('/bin/ls', '--help'))

    def testCalledProcessErrorRaised(self):
        # If an error occurs a CalledProcessError is raised with the return
        # code, command executed, and the output of the command.
        with self.assertRaises(CalledProcessError) as info:
            run('ls', '--not a valid switch')
        exception = info.exception
        self.assertEqual(2, exception.returncode)
        self.assertEqual("('ls', '--not a valid switch')", exception.cmd)
        self.assertIn('unrecognized option', exception.output)


class TestCommand(unittest.TestCase):

    def testSimpleCommand(self):
        # Creating a simple command (ls) works and running the command
        # produces a string.
        ls = command('/bin/ls')
        self.assertIsInstance(ls(), str)

    def testArguments(self):
        # Arguments can be passed to commands.
        ls = command('/bin/ls')
        self.assertIn('Usage:', ls('--help'))

    def testMissingExecutable(self):
        # If the command does not exist, an OSError (No such file or
        # directory) is raised.
        bad = command('this command does not exist')
        with self.assertRaises(OSError) as info:
            bad()
        self.assertEqual(2, info.exception.errno)

    def testError(self):
        # If the command returns a non-zero exit code, an exception is raised.
        ls = command('/bin/ls')
        with self.assertRaises(CalledProcessError):
            ls('--not a valid switch')

    def testBakedInArguments(self):
        # Arguments can be passed when creating the command as well as when
        # executing it.
        ll = command('/bin/ls', '-al')
        self.assertIn('rw', ll()) # Assumes a file is r/w in the pwd.
        self.assertIn('Usage:', ll('--help'))

    def testQuoting(self):
        # There is no need to quote special shell characters in commands.
        ls = command('/bin/ls')
        ls('--help', '>')


class TestDictDiffer(unittest.TestCase):

    def testStr(self):
        a = dict(cow='moo', pig='oink')
        b = dict(cow='moo', pig='oinkoink', horse='nay')
        diff = DictDiffer(b, a)
        s = str(diff)
        self.assertIn("added: {'horse': None} -> {'horse': 'nay'}", s)
        self.assertIn("removed: {} -> {}", s)
        self.assertIn("changed: {'pig': 'oink'} -> {'pig': 'oinkoink'}", s)
        self.assertIn("unchanged: ['cow']", s)

    def testStrUnmodified(self):
        a = dict(cow='moo', pig='oink')
        diff = DictDiffer(a, a)
        s = str(diff)
        self.assertEquals('no changes', s)

    def testAddedOrChanged(self):
        a = dict(cow='moo', pig='oink')
        b = dict(cow='moo', pig='oinkoink', horse='nay')
        diff = DictDiffer(b, a)
        expected = set(['horse', 'pig'])
        self.assertEquals(expected, diff.added_or_changed)


current_euid = os.geteuid()
current_egid = os.getegid()
current_home = os.environ['HOME']
example_euid = current_euid + 1
example_egid = current_egid + 1
example_home = '/var/lib/example'
userinfo = {'example_user': dict(
        ids=(example_euid, example_egid), home=example_home)}
effective_values = dict(uid=current_euid, gid=current_egid)


def stub_os_seteuid(value):
    effective_values['uid'] = value


def stub_os_setegid(value):
    effective_values['gid'] = value


class TestSuContextManager(unittest.TestCase):

    def setUp(self):
        import shelltoolbox
        self.os_seteuid = os.seteuid
        self.os_setegid = os.setegid
        self.shelltoolbox_get_user_ids = shelltoolbox.get_user_ids
        self.shelltoolbox_get_user_home = shelltoolbox.get_user_home
        os.seteuid = stub_os_seteuid
        os.setegid = stub_os_setegid
        shelltoolbox.get_user_ids = lambda user: userinfo[user]['ids']
        shelltoolbox.get_user_home = lambda user: userinfo[user]['home']

    def tearDown(self):
        import shelltoolbox
        os.seteuid = self.os_seteuid
        os.setegid = self.os_setegid
        shelltoolbox.get_user_ids = self.shelltoolbox_get_user_ids
        shelltoolbox.get_user_home = self.shelltoolbox_get_user_home

    def testChange(self):
        with su('example_user'):
            self.assertEqual(example_euid, effective_values['uid'])
            self.assertEqual(example_egid, effective_values['gid'])
            self.assertEqual(example_home, os.environ['HOME'])

    def testEnvironment(self):
        with su('example_user') as e:
            self.assertEqual(example_euid, e.uid)
            self.assertEqual(example_egid, e.gid)
            self.assertEqual(example_home, e.home)

    def testRevert(self):
        with su('example_user'):
            pass
        self.assertEqual(current_euid, effective_values['uid'])
        self.assertEqual(current_egid, effective_values['gid'])
        self.assertEqual(current_home, os.environ['HOME'])

    def testRevertAfterFailure(self):
        try:
            with su('example_user'):
                raise RuntimeError()
        except RuntimeError:
            self.assertEqual(current_euid, effective_values['uid'])
            self.assertEqual(current_egid, effective_values['gid'])
            self.assertEqual(current_home, os.environ['HOME'])


class TestCdContextManager(unittest.TestCase):
    def test_cd(self):
        curdir = os.getcwd()
        self.assertNotEqual('/var', curdir)
        with cd('/var'):
            self.assertEqual('/var', os.getcwd())
        self.assertEqual(curdir, os.getcwd())


if __name__ == '__main__':
    unittest.main()