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 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
|
# pylint: disable=W0212
import datetime
import io
import json
import os
import signal
import time
import stat
from pathlib import Path
import pytest
from ansible_runner.utils import (
isplaybook,
isinventory,
check_isolation_executable_installed,
args2cmdline,
sanitize_container_name,
signal_handler,
)
from ansible_runner.utils.base64io import _to_bytes, Base64IO
from ansible_runner.utils.streaming import stream_dir, unstream_dir
@pytest.mark.parametrize('playbook', ('foo', {}, {'foo': 'bar'}, True, False, None))
def test_isplaybook_invalid(playbook):
assert isplaybook(playbook) is False
@pytest.mark.parametrize('playbook', (['foo'], []))
def test_isplaybook(playbook):
assert isplaybook(playbook) is True
@pytest.mark.parametrize('inventory', ('hosts,', {}, {'foo': 'bar'}))
def test_isinventory(inventory):
assert isinventory(inventory) is True
@pytest.mark.parametrize('inventory', ([], ['foo'], True, False, None))
def test_isinventory_invalid(inventory):
assert isinventory(inventory) is False
def test_args2cmdline():
res = args2cmdline('ansible', '-m', 'setup', 'localhost')
assert res == 'ansible -m setup localhost'
def test_check_isolation_executable_installed():
assert check_isolation_executable_installed("true")
assert not check_isolation_executable_installed("does-not-exist")
@pytest.mark.parametrize('container_name,expected_name', [
('foo?bar', 'foo_bar'),
('096aac5c-024d-453e-9725-779dc8b3faee', '096aac5c-024d-453e-9725-779dc8b3faee'), # uuid4
(42, '42') # AWX will use primary keys and may not be careful about type
])
def test_sanitize_container_name(container_name, expected_name):
assert sanitize_container_name(str(container_name)) == expected_name
@pytest.mark.parametrize('symlink_dest,check_content', [
('/bin', []),
('ordinary_file.txt', ['my_link']),
('ordinary_directory', ['my_link/dir_file.txt']),
('.', ['my_link/ordinary_directory/dir_file.txt', 'my_link/my_link/ordinary_file.txt']),
('filedoesnotexist.txt', [])
], ids=['global', 'local', 'directory', 'recursive', 'bad'])
def test_transmit_symlink(tmp_path, symlink_dest, check_content):
symlink_dest = Path(symlink_dest)
# prepare the input private_data_dir directory to zip
pdd = tmp_path / 'symlink_zip_test'
pdd.mkdir()
# Create some basic shared demo content
with open(pdd / 'ordinary_file.txt', 'w') as f:
f.write('hello world')
ord_dir = pdd / 'ordinary_directory'
ord_dir.mkdir()
with open(ord_dir / 'dir_file.txt', 'w') as f:
f.write('hello world')
old_symlink_path = pdd / 'my_link'
old_symlink_path.symlink_to(symlink_dest)
# SANITY - set expectations for the symlink
assert old_symlink_path.is_symlink()
assert os.readlink(old_symlink_path) == str(symlink_dest)
# zip and stream the data into the in-memory buffer outgoing_buffer
outgoing_buffer = io.BytesIO()
outgoing_buffer.name = 'not_stdout'
stream_dir(pdd, outgoing_buffer)
# prepare the destination private_data_dir to transmit to
dest_dir = tmp_path / 'symlink_zip_dest'
dest_dir.mkdir()
# Extract twice so we assure that existing data does not break things
for _ in range(2):
# rewind the buffer and extract into destination private_data_dir
outgoing_buffer.seek(0)
first_line = outgoing_buffer.readline()
size_data = json.loads(first_line.strip())
unstream_dir(outgoing_buffer, size_data['zipfile'], dest_dir)
# Assure the new symlink is still the same type of symlink
new_symlink_path = dest_dir / 'my_link'
assert new_symlink_path.is_symlink()
assert os.readlink(new_symlink_path) == str(symlink_dest)
for fname in check_content:
abs_path = dest_dir / fname
assert abs_path.exists(), f'Expected "{fname}" in target dir to be a file with content.'
with open(abs_path, 'r') as f:
assert f.read() == 'hello world'
@pytest.mark.timeout(timeout=3)
def test_stream_dir_no_hang_on_pipe(tmp_path):
# prepare the input private_data_dir directory to zip
pdd = tmp_path / 'timeout_test'
pdd.mkdir()
with open(pdd / 'ordinary_file.txt', 'w') as f:
f.write('hello world')
# make pipe, similar to open_fifo_write
os.mkfifo(pdd / 'my_pipe', stat.S_IRUSR | stat.S_IWUSR)
# zip and stream the data into the in-memory buffer outgoing_buffer
outgoing_buffer = io.BytesIO()
outgoing_buffer.name = 'not_stdout'
stream_dir(pdd, outgoing_buffer)
@pytest.mark.timeout(timeout=3)
def test_unstream_dir_no_hang_on_pipe(tmp_path):
# prepare the input private_data_dir directory to zip
pdd = tmp_path / 'timeout_test_source_dir'
pdd.mkdir()
with open(pdd / 'ordinary_file.txt', 'w') as f:
f.write('hello world')
# zip and stream the data into the in-memory buffer outgoing_buffer
outgoing_buffer = io.BytesIO()
outgoing_buffer.name = 'not_stdout'
stream_dir(pdd, outgoing_buffer)
dest_dir = tmp_path / 'timeout_test_dest'
dest_dir.mkdir()
# We create the pipe in the same location as an archived file to trigger the bug
os.mkfifo(dest_dir / 'ordinary_file.txt', stat.S_IRUSR | stat.S_IWUSR)
outgoing_buffer.seek(0)
first_line = outgoing_buffer.readline()
size_data = json.loads(first_line.strip())
unstream_dir(outgoing_buffer, size_data['zipfile'], dest_dir)
@pytest.mark.parametrize('fperm', [
0o777,
0o666,
0o555,
0o700,
])
def test_transmit_permissions(tmp_path, fperm):
# breakpoint()
pdd = tmp_path / 'transmit_permission_test'
pdd.mkdir()
old_file_path = pdd / 'ordinary_file.txt'
with open(old_file_path, 'w') as f:
f.write('hello world')
old_file_path.chmod(fperm)
# SANITY - set expectations for the file
# assert oct(os.stat(old_file_path).st_mode & 0o777) == oct(fperm)
assert oct(old_file_path.stat().st_mode & 0o777) == oct(fperm)
outgoing_buffer = io.BytesIO()
outgoing_buffer.name = 'not_stdout'
stream_dir(pdd, outgoing_buffer)
dest_dir = tmp_path / 'transmit_permission_dest'
outgoing_buffer.seek(0)
first_line = outgoing_buffer.readline()
size_data = json.loads(first_line.strip())
unstream_dir(outgoing_buffer, size_data['zipfile'], dest_dir)
# Assure the new file is the same permissions
new_file_path = dest_dir / 'ordinary_file.txt'
assert oct(new_file_path.stat().st_mode) == oct(old_file_path.stat().st_mode)
def test_transmit_modtimes(tmp_path):
source_dir = tmp_path / 'source'
source_dir.mkdir()
# python ZipFile uses an old standard that stores seconds in 2 second increments
# https://stackoverflow.com/questions/64048499/zipfile-lib-weird-behaviour-with-seconds-in-modified-time
(source_dir / 'b.txt').touch()
time.sleep(2.0) # flaky for anything less
(source_dir / 'a.txt').touch()
very_old_file = source_dir / 'very_old.txt'
very_old_file.touch()
old_datetime = os.path.getmtime(source_dir / 'a.txt') - datetime.timedelta(days=1).total_seconds()
os.utime(very_old_file, (old_datetime, old_datetime))
# sanity, verify assertions pass for source dir
mod_delta = os.path.getmtime(source_dir / 'a.txt') - os.path.getmtime(source_dir / 'b.txt')
assert mod_delta >= 1.0
outgoing_buffer = io.BytesIO()
outgoing_buffer.name = 'not_stdout'
stream_dir(source_dir, outgoing_buffer)
dest_dir = tmp_path / 'dest'
dest_dir.mkdir()
outgoing_buffer.seek(0)
first_line = outgoing_buffer.readline()
size_data = json.loads(first_line.strip())
unstream_dir(outgoing_buffer, size_data['zipfile'], dest_dir)
# Assure modification times are internally consistent
mod_delta = os.path.getmtime(dest_dir / 'a.txt') - os.path.getmtime(dest_dir / 'b.txt')
assert mod_delta >= 1.0
# Assure modification times are same as original (to the rounded second)
for filename in ('a.txt', 'b.txt', 'very_old.txt'):
difference = abs(os.path.getmtime(dest_dir / filename) - os.path.getmtime(source_dir / filename))
assert difference < 2.0
# Assure the very old timestamp is preserved
old_delta = os.path.getmtime(dest_dir / 'a.txt') - os.path.getmtime(source_dir / 'very_old.txt')
assert old_delta >= datetime.timedelta(days=1).total_seconds() - 2.
def test_transmit_file_from_before_1980s(tmp_path):
source_dir = tmp_path / 'source'
source_dir.mkdir()
old_file = source_dir / 'cassette_tape.txt'
old_file.touch()
old_timestamp = datetime.datetime(year=1978, month=7, day=28).timestamp()
os.utime(old_file, (old_timestamp, old_timestamp))
outgoing_buffer = io.BytesIO()
outgoing_buffer.name = 'not_stdout'
stream_dir(source_dir, outgoing_buffer)
dest_dir = tmp_path / 'dest'
dest_dir.mkdir()
outgoing_buffer.seek(0)
first_line = outgoing_buffer.readline()
size_data = json.loads(first_line.strip())
unstream_dir(outgoing_buffer, size_data['zipfile'], dest_dir)
def test_signal_handler(mocker):
"""Test the default handler is set to handle the correct signals"""
class MockEvent:
def __init__(self):
self._is_set = False
def set(self):
self._is_set = True
def is_set(self):
return self._is_set
mocker.patch('ansible_runner.utils.threading.main_thread', return_value='thread0')
mocker.patch('ansible_runner.utils.threading.current_thread', return_value='thread0')
mocker.patch('ansible_runner.utils.threading.Event', MockEvent)
mock_signal = mocker.patch('ansible_runner.utils.signal.signal')
assert signal_handler()() is False
assert mock_signal.call_args_list[0][0][0] == signal.SIGTERM
assert mock_signal.call_args_list[1][0][0] == signal.SIGINT
def test_signal_handler_outside_main_thread(mocker):
"""Test that the default handler will not try to set signal handlers if not in the main thread"""
mocker.patch('ansible_runner.utils.threading.main_thread', return_value='thread0')
mocker.patch('ansible_runner.utils.threading.current_thread', return_value='thread1')
assert signal_handler() is None
def test_signal_handler_set(mocker):
"""Test that the default handler calls the set() method"""
class MockEvent:
def __init__(self):
self._is_set = False
def set(self):
raise AttributeError('Raised intentionally')
def is_set(self):
return self._is_set
mocker.patch('ansible_runner.utils.threading.main_thread', return_value='thread0')
mocker.patch('ansible_runner.utils.threading.current_thread', return_value='thread0')
mocker.patch('ansible_runner.utils.threading.Event', MockEvent)
mock_signal = mocker.patch('ansible_runner.utils.signal.signal')
signal_handler()
with pytest.raises(AttributeError, match='Raised intentionally'):
mock_signal.call_args[0][1]('number', 'frame')
class TestBase64IO:
def test_init_fails(self):
with pytest.raises(TypeError, match='Base64IO wrapped object must have attributes'):
Base64IO(None)
def test__passthrough_interactive_check_bad_method(self):
obj = Base64IO(io.StringIO('test'))
assert not obj._passthrough_interactive_check('invalid_method')
def test_write(self, tmp_path):
tmpfile = tmp_path / "TestBase64IO_test_write.txt"
tmpfile.touch()
with tmpfile.open(mode='br') as t:
obj = Base64IO(t)
with pytest.raises(IOError, match='Stream is not writable'):
obj.write(b'')
obj.close()
with pytest.raises(ValueError, match='I/O operation on closed file.'):
obj.write(b'')
def test__read_additional_data_removing_whitespace(self):
obj = Base64IO(io.StringIO(''))
data = _to_bytes('te s t')
assert obj._read_additional_data_removing_whitespace(data, 4) == b'test'
|