| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# Copyright (c) 2017 Ansible Project |
| 3 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import selectors |
| 8 |
from itertools import product |
| 9 |
from io import BytesIO |
| 10 |
|
| 11 |
import pytest |
| 12 |
|
| 13 |
from ansible.module_utils.common.text.converters import to_native |
| 14 |
|
| 15 |
|
| 16 |
class OpenBytesIO(BytesIO): |
| 17 |
"""BytesIO with dummy close() method |
| 18 |
|
| 19 |
So that you can inspect the content after close() was called. |
| 20 |
""" |
| 21 |
|
| 22 |
def close(self): |
| 23 |
pass |
| 24 |
|
| 25 |
|
| 26 |
@pytest.fixture |
| 27 |
def mock_os(mocker): |
| 28 |
def mock_os_abspath(path): |
| 29 |
if path.startswith('/'): |
| 30 |
return path |
| 31 |
else: |
| 32 |
return os.getcwd.return_value + '/' + path |
| 33 |
|
| 34 |
os = mocker.patch('ansible.module_utils.basic.os') |
| 35 |
|
| 36 |
os.path.expandvars.side_effect = lambda x: x |
| 37 |
os.path.expanduser.side_effect = lambda x: x |
| 38 |
os.environ = {'PATH': '/bin'} |
| 39 |
os.getcwd.return_value = '/home/foo' |
| 40 |
os.path.isdir.return_value = True |
| 41 |
os.path.abspath.side_effect = mock_os_abspath |
| 42 |
|
| 43 |
yield os |
| 44 |
|
| 45 |
|
| 46 |
class SpecialBytesIO(BytesIO): |
| 47 |
def __init__(self, *args, **kwargs): |
| 48 |
fh = kwargs.pop('fh', None) |
| 49 |
super(SpecialBytesIO, self).__init__(*args, **kwargs) |
| 50 |
self.fh = fh |
| 51 |
|
| 52 |
def fileno(self): |
| 53 |
return self.fh |
| 54 |
|
| 55 |
# We need to do this because some of our tests create a new value for stdout and stderr |
| 56 |
# The new value is able to affect the string that is returned by the subprocess stdout and |
| 57 |
# stderr but by the time the test gets it, it is too late to change the SpecialBytesIO that |
| 58 |
# subprocess.Popen returns for stdout and stderr. If we could figure out how to change those as |
| 59 |
# well, then we wouldn't need this. |
| 60 |
def __eq__(self, other): |
| 61 |
if id(self) == id(other) or self.fh == other.fileno(): |
| 62 |
return True |
| 63 |
return False |
| 64 |
|
| 65 |
|
| 66 |
class DummyKey: |
| 67 |
def __init__(self, fileobj): |
| 68 |
self.fileobj = fileobj |
| 69 |
|
| 70 |
|
| 71 |
@pytest.fixture |
| 72 |
def mock_subprocess(mocker): |
| 73 |
|
| 74 |
class MockSelector(selectors.BaseSelector): |
| 75 |
def __init__(self): |
| 76 |
super(MockSelector, self).__init__() |
| 77 |
self._file_objs = [] |
| 78 |
|
| 79 |
def register(self, fileobj, events, data=None): |
| 80 |
self._file_objs.append(fileobj) |
| 81 |
|
| 82 |
def unregister(self, fileobj): |
| 83 |
self._file_objs.remove(fileobj) |
| 84 |
|
| 85 |
def select(self, timeout=None): |
| 86 |
ready = [] |
| 87 |
for file_obj in self._file_objs: |
| 88 |
ready.append((DummyKey(subprocess._output[file_obj.fileno()]), selectors.EVENT_READ)) |
| 89 |
return ready |
| 90 |
|
| 91 |
def get_map(self): |
| 92 |
return self._file_objs |
| 93 |
|
| 94 |
def close(self): |
| 95 |
super(MockSelector, self).close() |
| 96 |
self._file_objs = [] |
| 97 |
|
| 98 |
selectors.PollSelector = MockSelector |
| 99 |
|
| 100 |
subprocess = mocker.patch('ansible.module_utils.basic.subprocess') |
| 101 |
subprocess._output = {mocker.sentinel.stdout: SpecialBytesIO(b'', fh=mocker.sentinel.stdout), |
| 102 |
mocker.sentinel.stderr: SpecialBytesIO(b'', fh=mocker.sentinel.stderr)} |
| 103 |
|
| 104 |
cmd = mocker.MagicMock() |
| 105 |
cmd.returncode = 0 |
| 106 |
cmd.stdin = OpenBytesIO() |
| 107 |
cmd.stdout = subprocess._output[mocker.sentinel.stdout] |
| 108 |
cmd.stderr = subprocess._output[mocker.sentinel.stderr] |
| 109 |
subprocess.Popen.return_value = cmd |
| 110 |
|
| 111 |
yield subprocess |
| 112 |
|
| 113 |
|
| 114 |
@pytest.fixture() |
| 115 |
def rc_am(mocker, am, mock_os, mock_subprocess): |
| 116 |
am.fail_json = mocker.MagicMock(side_effect=SystemExit) |
| 117 |
am._os = mock_os |
| 118 |
am._subprocess = mock_subprocess |
| 119 |
yield am |
| 120 |
|
| 121 |
|
| 122 |
class TestRunCommandArgs: |
| 123 |
# Format is command as passed to run_command, command to Popen as list, command to Popen as string |
| 124 |
ARGS_DATA = ( |
| 125 |
(['/bin/ls', 'a', 'b', 'c'], [b'/bin/ls', b'a', b'b', b'c'], b'/bin/ls a b c'), |
| 126 |
('/bin/ls a " b" "c "', [b'/bin/ls', b'a', b' b', b'c '], b'/bin/ls a " b" "c "'), |
| 127 |
) |
| 128 |
|
| 129 |
@pytest.mark.parametrize('cmd, expected, shell, stdin', |
| 130 |
[(arg, cmd_str if sh else cmd_lst, sh, {}) |
| 131 |
for (arg, cmd_lst, cmd_str), sh in product(ARGS_DATA, (True, False))], |
| 132 |
indirect=['stdin']) |
| 133 |
def test_args(self, cmd, expected, shell, rc_am): |
| 134 |
rc_am.run_command(cmd, use_unsafe_shell=shell) |
| 135 |
assert rc_am._subprocess.Popen.called |
| 136 |
args, kwargs = rc_am._subprocess.Popen.call_args |
| 137 |
assert args == (expected, ) |
| 138 |
assert kwargs['shell'] == shell |
| 139 |
|
| 140 |
@pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) |
| 141 |
def test_tuple_as_args(self, rc_am): |
| 142 |
with pytest.raises(SystemExit): |
| 143 |
rc_am.run_command(('ls', '/')) |
| 144 |
assert rc_am.fail_json.called |
| 145 |
|
| 146 |
|
| 147 |
class TestRunCommandCwd: |
| 148 |
@pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) |
| 149 |
def test_cwd(self, mocker, rc_am): |
| 150 |
rc_am.run_command('/bin/ls', cwd='/new') |
| 151 |
assert rc_am._subprocess.Popen.mock_calls[0][2]['cwd'] == b'/new' |
| 152 |
|
| 153 |
@pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) |
| 154 |
def test_cwd_relative_path(self, mocker, rc_am): |
| 155 |
rc_am.run_command('/bin/ls', cwd='sub-dir') |
| 156 |
assert rc_am._subprocess.Popen.mock_calls[0][2]['cwd'] == b'/home/foo/sub-dir' |
| 157 |
|
| 158 |
@pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) |
| 159 |
def test_cwd_not_a_dir(self, mocker, rc_am): |
| 160 |
rc_am.run_command('/bin/ls', cwd='/not-a-dir') |
| 161 |
assert rc_am._subprocess.Popen.mock_calls[0][2]['cwd'] == b'/not-a-dir' |
| 162 |
|
| 163 |
@pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) |
| 164 |
def test_cwd_not_a_dir_noignore(self, rc_am): |
| 165 |
rc_am._os.path.isdir.side_effect = lambda d: d != b'/not-a-dir' |
| 166 |
with pytest.raises(SystemExit): |
| 167 |
rc_am.run_command('/bin/ls', cwd='/not-a-dir', ignore_invalid_cwd=False) |
| 168 |
assert rc_am.fail_json.called |
| 169 |
|
| 170 |
|
| 171 |
class TestRunCommandPrompt: |
| 172 |
@pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) |
| 173 |
def test_prompt_bad_regex(self, rc_am): |
| 174 |
with pytest.raises(SystemExit): |
| 175 |
rc_am.run_command('foo', prompt_regex='[pP)assword:') |
| 176 |
assert rc_am.fail_json.called |
| 177 |
|
| 178 |
@pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) |
| 179 |
def test_prompt_no_match(self, mocker, rc_am): |
| 180 |
rc_am._os._cmd_out[mocker.sentinel.stdout] = BytesIO(b'hello') |
| 181 |
(rc, stdout, stderr) = rc_am.run_command('foo', prompt_regex='[pP]assword:') |
| 182 |
assert rc == 0 |
| 183 |
|
| 184 |
@pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) |
| 185 |
def test_prompt_match_wo_data(self, mocker, rc_am): |
| 186 |
rc_am._subprocess._output = {mocker.sentinel.stdout: |
| 187 |
SpecialBytesIO(b'Authentication required!\nEnter password: ', |
| 188 |
fh=mocker.sentinel.stdout), |
| 189 |
mocker.sentinel.stderr: |
| 190 |
SpecialBytesIO(b'', fh=mocker.sentinel.stderr)} |
| 191 |
(rc, stdout, stderr) = rc_am.run_command('foo', prompt_regex=r'[pP]assword:', data=None) |
| 192 |
assert rc == 257 |
| 193 |
|
| 194 |
|
| 195 |
class TestRunCommandRc: |
| 196 |
@pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) |
| 197 |
def test_check_rc_false(self, rc_am): |
| 198 |
rc_am._subprocess.Popen.return_value.returncode = 1 |
| 199 |
(rc, stdout, stderr) = rc_am.run_command('/bin/false', check_rc=False) |
| 200 |
assert rc == 1 |
| 201 |
|
| 202 |
@pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) |
| 203 |
def test_check_rc_true(self, rc_am): |
| 204 |
rc_am._subprocess.Popen.return_value.returncode = 1 |
| 205 |
with pytest.raises(SystemExit): |
| 206 |
rc_am.run_command('/bin/false', check_rc=True) |
| 207 |
assert rc_am.fail_json.called |
| 208 |
args, kwargs = rc_am.fail_json.call_args |
| 209 |
assert kwargs['rc'] == 1 |
| 210 |
|
| 211 |
|
| 212 |
class TestRunCommandOutput: |
| 213 |
@pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) |
| 214 |
def test_text_stdin(self, rc_am): |
| 215 |
(rc, stdout, stderr) = rc_am.run_command('/bin/foo', data='hello world') |
| 216 |
assert rc_am._subprocess.Popen.return_value.stdin.getvalue() == b'hello world\n' |
| 217 |
|
| 218 |
@pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) |
| 219 |
def test_ascii_stdout(self, mocker, rc_am): |
| 220 |
rc_am._subprocess._output = {mocker.sentinel.stdout: |
| 221 |
SpecialBytesIO(b'hello', fh=mocker.sentinel.stdout), |
| 222 |
mocker.sentinel.stderr: |
| 223 |
SpecialBytesIO(b'', fh=mocker.sentinel.stderr)} |
| 224 |
(rc, stdout, stderr) = rc_am.run_command('/bin/cat hello.txt') |
| 225 |
assert rc == 0 |
| 226 |
# module_utils function. On py3 it returns text and py2 it returns |
| 227 |
# bytes because it's returning native strings |
| 228 |
assert stdout == 'hello' |
| 229 |
|
| 230 |
@pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) |
| 231 |
def test_utf8_output(self, mocker, rc_am): |
| 232 |
rc_am._subprocess._output = {mocker.sentinel.stdout: |
| 233 |
SpecialBytesIO(u'Žarn§'.encode('utf-8'), |
| 234 |
fh=mocker.sentinel.stdout), |
| 235 |
mocker.sentinel.stderr: |
| 236 |
SpecialBytesIO(u'لرئيسية'.encode('utf-8'), |
| 237 |
fh=mocker.sentinel.stderr)} |
| 238 |
(rc, stdout, stderr) = rc_am.run_command('/bin/something_ugly') |
| 239 |
assert rc == 0 |
| 240 |
# module_utils function. On py3 it returns text and py2 it returns |
| 241 |
# bytes because it's returning native strings |
| 242 |
assert stdout == to_native(u'Žarn§') |
| 243 |
assert stderr == to_native(u'لرئيسية') |
| 244 |
|
| 245 |
|
| 246 |
@pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) |
| 247 |
def test_run_command_fds(mocker, rc_am): |
| 248 |
subprocess_mock = mocker.patch('ansible.module_utils.basic.subprocess') |
| 249 |
subprocess_mock.Popen.side_effect = AssertionError |
| 250 |
|
| 251 |
try: |
| 252 |
rc_am.run_command('synchronize', pass_fds=(101, 42)) |
| 253 |
except SystemExit: |
| 254 |
pass |
| 255 |
|
| 256 |
assert subprocess_mock.Popen.call_args[1]['pass_fds'] == (101, 42) |
| 257 |
assert subprocess_mock.Popen.call_args[1]['close_fds'] is True |
| 258 |
|
| 259 |
|
| 260 |
class TestRunCommandNoneRead: |
| 261 |
""" |
| 262 |
Test handling of read() returning None from non-blocking pipes. |
| 263 |
|
| 264 |
This tests the fix for issue #86920 where read() can return None |
| 265 |
in certain edge cases with non-blocking I/O, which would cause |
| 266 |
TypeError when trying to concatenate None to bytes. |
| 267 |
""" |
| 268 |
|
| 269 |
class NoneReturningBytesIO(SpecialBytesIO): |
| 270 |
""" |
| 271 |
BytesIO that returns None on first read, then actual data. |
| 272 |
|
| 273 |
This simulates edge cases where non-blocking read() returns None |
| 274 |
to indicate "no data available right now" rather than empty bytes. |
| 275 |
""" |
| 276 |
|
| 277 |
def __init__(self, *args, **kwargs): |
| 278 |
# Pop 'data' before calling super().__init__() since BytesIO doesn't accept it |
| 279 |
self.data = kwargs.pop('data', b'test output') |
| 280 |
self.read_count = 0 |
| 281 |
super(TestRunCommandNoneRead.NoneReturningBytesIO, self).__init__(*args, **kwargs) |
| 282 |
|
| 283 |
def read(self, size=-1): |
| 284 |
self.read_count += 1 |
| 285 |
if self.read_count == 1: |
| 286 |
# First read returns None (no data available) |
| 287 |
return None |
| 288 |
elif self.read_count == 2: |
| 289 |
# Second read returns actual data |
| 290 |
return self.data |
| 291 |
else: |
| 292 |
# Subsequent reads return empty bytes (EOF) |
| 293 |
return b'' |
| 294 |
|
| 295 |
@pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) |
| 296 |
def test_none_from_stdout_read(self, mocker, rc_am): |
| 297 |
"""Test that None returned from stdout.read() doesn't cause TypeError.""" |
| 298 |
rc_am._subprocess._output = { |
| 299 |
mocker.sentinel.stdout: |
| 300 |
self.NoneReturningBytesIO(fh=mocker.sentinel.stdout, data=b'command output'), |
| 301 |
mocker.sentinel.stderr: |
| 302 |
SpecialBytesIO(b'', fh=mocker.sentinel.stderr) |
| 303 |
} |
| 304 |
(rc, stdout, stderr) = rc_am.run_command('/bin/test') |
| 305 |
assert rc == 0 |
| 306 |
assert stdout == 'command output' |
| 307 |
assert stderr == '' |
| 308 |
|
| 309 |
@pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) |
| 310 |
def test_none_from_stderr_read(self, mocker, rc_am): |
| 311 |
"""Test that None returned from stderr.read() doesn't cause TypeError.""" |
| 312 |
rc_am._subprocess._output = { |
| 313 |
mocker.sentinel.stdout: |
| 314 |
SpecialBytesIO(b'', fh=mocker.sentinel.stdout), |
| 315 |
mocker.sentinel.stderr: |
| 316 |
self.NoneReturningBytesIO(fh=mocker.sentinel.stderr, data=b'error output') |
| 317 |
} |
| 318 |
(rc, stdout, stderr) = rc_am.run_command('/bin/test') |
| 319 |
assert rc == 0 |
| 320 |
assert stdout == '' |
| 321 |
assert stderr == 'error output' |
| 322 |
|
| 323 |
@pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) |
| 324 |
def test_none_from_both_pipes(self, mocker, rc_am): |
| 325 |
"""Test that None returned from both pipes doesn't cause TypeError.""" |
| 326 |
rc_am._subprocess._output = { |
| 327 |
mocker.sentinel.stdout: |
| 328 |
self.NoneReturningBytesIO(fh=mocker.sentinel.stdout, data=b'stdout data'), |
| 329 |
mocker.sentinel.stderr: |
| 330 |
self.NoneReturningBytesIO(fh=mocker.sentinel.stderr, data=b'stderr data') |
| 331 |
} |
| 332 |
(rc, stdout, stderr) = rc_am.run_command('/bin/test') |
| 333 |
assert rc == 0 |
| 334 |
assert stdout == 'stdout data' |
| 335 |
assert stderr == 'stderr data' |