summaryrefslogtreecommitdiff
path: root/tests/test_run.py
blob: baa6b497f6621c06453bf0f505e1eae87ad3b532 (plain)
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
#!/usr/bin/env python
# encoding: utf-8
'''
PEXPECT LICENSE

    This license is approved by the OSI and FSF as GPL-compatible.
        http://opensource.org/licenses/isc-license.txt

    Copyright (c) 2012, Noah Spurrier <noah@noah.org>
    PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
    PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
    COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
    MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

'''
import pexpect
import unittest
import subprocess
import sys
import os
from . import PexpectTestCase

unicode_type = str if pexpect.PY3 else unicode


def timeout_callback(values):
    if values["event_count"] > 3:
        return 1
    return 0


def function_events_callback(values):
    try:
        previous_echoed = (values["child_result_list"][-1]
                           .decode().split("\n")[-2].strip())
        if previous_echoed.endswith("stage-1"):
            return "echo stage-2\n"
        elif previous_echoed.endswith("stage-2"):
            return "echo stage-3\n"
        elif previous_echoed.endswith("stage-3"):
            return "exit\n"
        else:
            raise Exception("Unexpected output {0}".format(previous_echoed))
    except IndexError:
        return "echo stage-1\n"


class RunFuncTestCase(PexpectTestCase.PexpectTestCase):
    runfunc = staticmethod(pexpect.run)
    cr = b'\r'
    empty = b''
    prep_subprocess_out = staticmethod(lambda x: x)

    def setUp(self):
        self.runenv = os.environ.copy()
        self.runenv['PS1'] = 'GO:'
        super(RunFuncTestCase, self).setUp()

    def test_run_exit(self):
        (data, exitstatus) = self.runfunc(sys.executable + ' exit1.py', withexitstatus=1)
        assert exitstatus == 1, "Exit status of 'python exit1.py' should be 1."

    def test_run(self):
        the_old_way = subprocess.Popen(
            args=['uname', '-m', '-n'],
            stdout=subprocess.PIPE
        ).communicate()[0].rstrip()

        (the_new_way, exitstatus) = self.runfunc(
            'uname -m -n', withexitstatus=1)
        the_new_way = the_new_way.replace(self.cr, self.empty).rstrip()

        self.assertEqual(self.prep_subprocess_out(the_old_way), the_new_way)
        self.assertEqual(exitstatus, 0)

    def test_run_callback(self):
        # TODO it seems like this test could block forever if run fails...
        events = {pexpect.TIMEOUT: timeout_callback}
        self.runfunc("cat", timeout=1, events=events)

    def test_run_bad_exitstatus(self):
        (the_new_way, exitstatus) = self.runfunc(
            'ls -l /najoeufhdnzkxjd', withexitstatus=1)
        assert exitstatus != 0

    def test_run_event_as_string(self):
        events = [
            # second match on 'abc', echo 'def'
            ('abc\r\n.*GO:', 'echo "def"\n'),
            # final match on 'def': exit
            ('def\r\n.*GO:', 'exit\n'),
            # first match on 'GO:' prompt, echo 'abc'
            ('GO:', 'echo "abc"\n')
        ]

        (data, exitstatus) = pexpect.run(
            'bash --norc',
            withexitstatus=True,
            events=events,
            env=self.runenv,
            timeout=10)
        assert exitstatus == 0

    def test_run_event_as_function(self):
        events = [
            ('GO:', function_events_callback)
        ]

        (data, exitstatus) = pexpect.run(
            'bash --norc',
            withexitstatus=True,
            events=events,
            env=self.runenv,
            timeout=10)
        assert exitstatus == 0

    def test_run_event_as_method(self):
        events = [
            ('GO:', self._method_events_callback)
        ]

        (data, exitstatus) = pexpect.run(
            'bash --norc',
            withexitstatus=True,
            events=events,
            env=self.runenv,
            timeout=10)
        assert exitstatus == 0

    def test_run_event_typeerror(self):
        events = [('GO:', -1)]
        with self.assertRaises(TypeError):
            pexpect.run('bash --norc',
                        withexitstatus=True,
                        events=events,
                        env=self.runenv,
                        timeout=10)

    def _method_events_callback(self, values):
        try:
            previous_echoed = (values["child_result_list"][-1].decode()
                               .split("\n")[-2].strip())
            if previous_echoed.endswith("foo1"):
                return "echo foo2\n"
            elif previous_echoed.endswith("foo2"):
                return "echo foo3\n"
            elif previous_echoed.endswith("foo3"):
                return "exit\n"
            else:
                raise Exception("Unexpected output {0!r}"
                                .format(previous_echoed))
        except IndexError:
            return "echo foo1\n"


class RunUnicodeFuncTestCase(RunFuncTestCase):
    runfunc = staticmethod(pexpect.runu)
    cr = b'\r'.decode('ascii')
    empty = b''.decode('ascii')
    prep_subprocess_out = staticmethod(lambda x: x.decode('utf-8', 'replace'))

    def test_run_unicode(self):
        if pexpect.PY3:
            char = chr(254)   # รพ
            pattern = '<in >'
        else:
            char = unichr(254)  # analysis:ignore
            pattern = '<in >'.decode('ascii')

        def callback(values):
            if values['event_count'] == 0:
                return char + '\n'
            else:
                return True  # Stop the child process

        output = pexpect.runu(self.PYTHONBIN + ' echo_w_prompt.py',
                              env={'PYTHONIOENCODING': 'utf-8'},
                              events={pattern: callback})
        assert isinstance(output, unicode_type), type(output)
        assert ('<out>' + char) in output, output

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