Initial commit

This commit is contained in:
Jon Ervine
2021-03-03 11:36:53 +08:00
parent a5dc995324
commit 4cdbe9a6d5
137 changed files with 12374 additions and 2 deletions
View File
+30
View File
@@ -0,0 +1,30 @@
import pytest
from distutils.version import LooseVersion
import pkg_resources
import os
@pytest.fixture(autouse=True)
def mock_env_user(monkeypatch):
monkeypatch.setenv("ANSIBLE_DEVEL_WARNING", "False")
@pytest.fixture(scope='session')
def is_pre_ansible28():
try:
if LooseVersion(pkg_resources.get_distribution('ansible').version) < LooseVersion('2.8'):
return True
except pkg_resources.DistributionNotFound:
# ansible-base (e.g. ansible 2.10 and beyond) is not accessible in this way
pass
@pytest.fixture(scope='session')
def skipif_pre_ansible28(is_pre_ansible28):
if is_pre_ansible28:
pytest.skip("Valid only on Ansible 2.8+")
@pytest.fixture
def test_data_dir():
return os.path.join(os.path.dirname(__file__), 'data')
+1
View File
@@ -0,0 +1 @@
host_1
+1
View File
@@ -0,0 +1 @@
host_2
+6
View File
@@ -0,0 +1,6 @@
---
- hosts: all
gather_facts: false
connection: local
tasks:
- debug: msg='Hello world!'
+7
View File
@@ -0,0 +1,7 @@
1_ok
2_skipped
3_changed
4_failed
5_ignored
6_rescued
7_unreachable
@@ -0,0 +1,5 @@
---
- hosts: all
gather_facts: false
tasks:
- include: gen_host_status_base.yml
@@ -0,0 +1,41 @@
---
- name: A debug msg all hosts will show except for skipped ones
debug:
msg: "Playing {{ ansible_host }}"
when: "'_skipped' not in ansible_host"
- name: Hosts haven't really changed, but we will say they have
debug:
msg: "I am a changed host."
changed_when: true
when: "'_changed' in ansible_host"
- name: All failhosts aboard the failboat
fail:
msg: "I did nothing to deserve this."
when: "'_failed' in ansible_host"
- name: Ignore this failure for some hosts
fail:
msg: "<insert inspirational quote about failure>"
ignore_errors: true
when: "'_ignored' in ansible_host"
- name: Fail and rescue - collection of tasks
block:
- fail:
msg: "HALP!!!"
when: "'_rescued' in ansible_host"
rescue:
- debug: msg="ε-(´・`) フ"
- name: Set unreachable fact
set_fact:
unreachable: true
when: "'_unreachable' in ansible_host"
- name: Reach out to the unreachable hosts
ping:
vars:
ansible_host: 'invalid.invalid'
when: unreachable is defined and unreachable
@@ -0,0 +1,8 @@
---
- hosts: all
gather_facts: false
tasks:
- include: gen_host_status_base.yml
loop:
- 1
- 2
+6
View File
@@ -0,0 +1,6 @@
---
- hosts: localhost
connection: local
gather_facts: false
tasks:
- debug: msg="{{ lookup('env', 'FOO') }}"
@@ -0,0 +1,21 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.action import ActionBase
import os
class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=None):
result = super(ActionModule, self).run(tmp, task_vars)
result['changed'] = result['failed'] = False
result['msg'] = ''
env_dict = dict(os.environ)
result['printenv'] = '\n'.join(
'{0}={1}'.format(k, v) for k, v in env_dict.items()
)
result['environment'] = env_dict
result['cwd'] = os.getcwd()
return result
@@ -0,0 +1,6 @@
---
- hosts: localhost
gather_facts: false
connection: local
tasks:
- look_at_environment:
+11
View File
@@ -0,0 +1,11 @@
---
- name: Sleep playbook for testing things while process is running
hosts: localhost
gather_facts: false
connection: local
vars:
sleep_interval: 30
tasks:
- name: sleep for a specified interval
command: 'sleep {{ sleep_interval }}'
@@ -0,0 +1,14 @@
from ansible.plugins.callback import CallbackBase
class CallbackModule(CallbackBase):
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'aggregate'
CALLBACK_NAME = 'other_callback'
def v2_playbook_on_play_start(self, play):
pass
def v2_runner_on_ok(self, result):
pass
+73
View File
@@ -0,0 +1,73 @@
import os
import shutil
import pytest
import pexpect
from ansible_runner.runner_config import RunnerConfig
@pytest.fixture(scope='function')
def rc(tmpdir):
rc = RunnerConfig(str(tmpdir))
rc.suppress_ansible_output = True
rc.expect_passwords = {
pexpect.TIMEOUT: None,
pexpect.EOF: None
}
rc.cwd = str(tmpdir)
rc.env = {}
rc.job_timeout = 10
rc.idle_timeout = 0
rc.pexpect_timeout = 2.
rc.pexpect_use_poll = True
return rc
# TODO: determine if we want to add docker / podman
# to zuul instances in order to run these tests
@pytest.fixture(scope="session", autouse=True)
def container_runtime_available():
import subprocess
import warnings
runtimes_available = True
for runtime in ('docker', 'podman'):
try:
subprocess.run([runtime, '-v'])
except FileNotFoundError:
warnings.warn(UserWarning(f"{runtime} not available"))
runtimes_available = False
return runtimes_available
# TODO: determine if we want to add docker / podman
# to zuul instances in order to run these tests
@pytest.fixture(scope="session")
def container_runtime_installed():
import subprocess
for runtime in ('podman', 'docker'):
try:
subprocess.run([runtime, '-v'])
return runtime
except FileNotFoundError:
pass
pytest.skip('No container runtime is available.')
@pytest.fixture(scope='session')
def clear_integration_artifacts(request):
'''Fixture is session scoped to allow parallel runs without error
'''
if 'PYTEST_XDIST_WORKER' in os.environ:
# we never want to clean artifacts if running parallel tests
# because we cannot know when all processes are finished and it is
# safe to clean up
return
def rm_integration_artifacts():
path = "test/integration/artifacts"
if os.path.exists(path):
shutil.rmtree(path)
request.addfinalizer(rm_integration_artifacts)
@@ -0,0 +1,71 @@
import json
import os
import subprocess
import yaml
from tempfile import NamedTemporaryFile
import pytest
@pytest.fixture
def tmp_file_maker():
"""Fixture to return temporary file maker."""
def tmp_file(text):
with NamedTemporaryFile(delete=False) as tempf:
tempf.write(bytes(text, 'UTF-8'))
return tempf.name
return tmp_file
class CompletedProcessProxy(object):
def __init__(self, result):
self.result = result
def __getattr__(self, attr):
return getattr(self.result, attr)
@property
def json(self):
try:
response_json = json.loads(self.stdout)
except json.JSONDecodeError:
pytest.fail(
f"Unable to convert the response to a valid json - stdout: {self.stdout}, stderr: {self.stderr}"
)
return response_json
@property
def yaml(self):
return yaml.safe_load(self.stdout)
@pytest.fixture(scope='function')
def cli(request):
def run(args, *a, **kw):
if not kw.pop('bare', None):
args = ['ansible-runner',] + args
kw['encoding'] = 'utf-8'
if 'check' not in kw:
# By default we want to fail if a command fails to run. Tests that
# want to skip this can pass check=False when calling this fixture
kw['check'] = True
if 'stdout' not in kw:
kw['stdout'] = subprocess.PIPE
if 'stderr' not in kw:
kw['stderr'] = subprocess.PIPE
kw.setdefault('env', os.environ.copy()).update({
'LANG': 'en_US.UTF-8'
})
try:
ret = CompletedProcessProxy(subprocess.run(' '.join(args), shell=True, *a, **kw))
except subprocess.CalledProcessError as err:
pytest.fail(
f"Running {err.cmd} resulted in a non-zero return code: {err.returncode} - stdout: {err.stdout}, stderr: {err.stderr}"
)
return ret
return run
@@ -0,0 +1 @@
localhost
@@ -0,0 +1,38 @@
---
- hosts: localhost
gather_facts: true
vars:
cgroup_search_terms: docker\|lxc\|podman\|oci
is_container: false
is_podman: false
is_docker: false
tasks:
- debug: msg="Test if we are in a container!"
- name: 'Look for container env var defined in /proc/1/environ'
shell: "grep 'container=' /proc/1/environ"
register: container_proc_environ
ignore_errors: true
- name: 'Look for container info defined in /proc/1/cgroup'
shell: "grep '{{ cgroup_search_terms}}' /proc/1/cgroup"
register: container_proc_cgroup
ignore_errors: true
- name: 'Found evidence that we are in docker container'
set_fact:
is_docker: true
when: (('container' in ansible_env and ansible_env.container == 'docker') or ansible_virtualization_type == 'docker')
- name: 'Found evidence that we are in podman container'
set_fact:
is_podman: true
when: ('container' in ansible_env and ansible_env.container == 'podman')
- name: 'Found evidence that we are in a container'
set_fact:
is_container: true
when: is_docker or is_podman or container_proc_environ.rc == 0 or container_proc_cgroup.rc == 0
- fail:
when: not (is_container)
@@ -0,0 +1,73 @@
# -*- coding: utf-8 -*-
import os
import pytest
HERE = os.path.abspath(os.path.dirname(__file__))
@pytest.fixture
def skip_if_no_podman(container_runtime_installed):
if container_runtime_installed != 'podman':
pytest.skip('podman container runtime(s) not available')
@pytest.mark.serial
def test_module_run(cli, skip_if_no_podman):
r = cli(['run', '-m', 'ping','--hosts', 'localhost', os.path.join(HERE, 'priv_data')])
assert '"ping": "pong"' in r.stdout
@pytest.mark.serial
def test_playbook_run(cli, skip_if_no_podman):
r = cli(['run', os.path.join(HERE,'priv_data'), '-p', 'test-container.yml'])
assert 'PLAY RECAP *******' in r.stdout
assert 'failed=0' in r.stdout
@pytest.mark.serial
def test_provide_env_var(cli, skip_if_no_podman, test_data_dir):
r = cli(['run', os.path.join(test_data_dir, 'job_env'), '-p', 'printenv.yml'])
assert 'gifmyvqok2' in r.stdout, r.stdout
@pytest.mark.serial
def test_adhoc_localhost_setup(cli, skip_if_no_podman, container_runtime_installed):
r = cli(
[
'adhoc',
'--private-data-dir', os.path.join(HERE,'priv_data'),
'--container-runtime', container_runtime_installed,
'localhost', '-m', 'setup'
]
)
# TODO: look for some fact that indicates we are in container?
assert '"ansible_facts": {' in r.stdout
@pytest.mark.serial
def test_playbook_with_private_data_dir(cli, skip_if_no_podman, container_runtime_installed):
# tests using a private_data_dir in conjunction with an absolute path
r = cli(
[
'playbook',
'--private-data-dir', os.path.join(HERE,'priv_data'),
'--container-runtime', container_runtime_installed,
os.path.join(HERE, 'priv_data/project/test-container.yml')
]
)
assert 'PLAY RECAP *******' in r.stdout
assert 'failed=0' in r.stdout
@pytest.mark.serial
def test_playbook_with_relative_path(cli, skip_if_no_podman, container_runtime_installed):
r = cli(
[
'playbook',
'--container-runtime', container_runtime_installed,
'test/integration/containerized/priv_data/project/test-container.yml'
]
)
assert 'PLAY RECAP *******' in r.stdout
assert 'failed=0' in r.stdout
@@ -0,0 +1,72 @@
import os
import shutil
import time
import pytest
from ansible_runner.interface import run
def is_running(cli, container_runtime_installed, container_name):
cmd = [container_runtime_installed, 'ps', '-aq', '--filter', 'name=ansible_runner_foo_bar']
r = cli(cmd, bare=True)
output = '{}{}'.format(r.stdout, r.stderr)
print(' '.join(cmd))
print(output)
return output.strip()
class CancelStandIn:
def __init__(self, runtime, cli, delay=0.2):
self.runtime = runtime
self.cli = cli
self.delay = 0.2
self.checked_running = False
self.start_time = None
def cancel(self):
# Avoid checking for some initial delay to allow container startup
if not self.start_time:
self.start_time = time.time()
if time.time() - self.start_time < self.delay:
return False
# guard against false passes by checking for running container
if not self.checked_running:
for i in range(5):
if is_running(self.cli, self.runtime, 'ansible_runner_foo_bar'):
break
time.sleep(0.2)
else:
print(self.cli([self.runtime, 'ps', '-a'], bare=True).stdout)
raise Exception('Never spawned expected container')
self.checked_running = True
# Established that container was running, now we cancel job
return True
@pytest.mark.serial
def test_cancel_will_remove_container(test_data_dir, container_runtime_installed, cli):
private_data_dir = os.path.join(test_data_dir, 'sleep')
env_dir = os.path.join(private_data_dir, 'env')
if os.path.exists(env_dir):
shutil.rmtree(env_dir)
cancel_standin = CancelStandIn(container_runtime_installed, cli)
res = run(
private_data_dir=private_data_dir,
playbook='sleep.yml',
settings={
'process_isolation_executable': container_runtime_installed,
'process_isolation': True
},
cancel_callback=cancel_standin.cancel,
ident='foo?bar' # question mark invalid char, but should still work
)
assert res.rc == 254, res.stdout.read()
assert res.status == 'canceled'
assert not is_running(
cli, container_runtime_installed, 'ansible_runner_foo_bar'
), 'Found a running container, they should have all been stopped'
+7
View File
@@ -0,0 +1,7 @@
FROM registry.access.redhat.com/ubi8/ubi
RUN yum -y install python3-pip gcc python3-devel openssh-clients
RUN pip3 install https://github.com/ansible/ansible/archive/devel.tar.gz
RUN pip3 install https://github.com/ansible/ansible-runner/archive/devel.tar.gz
+41
View File
@@ -0,0 +1,41 @@
---
- name: Run some basic system automation stuff
hosts: rhel8
tasks:
- name: install some basic packages
yum:
name:
- tmux
- git
- vim-enhanced
- python3
- name: enable journald persistent storage
file:
path: /var/log/journal
state: directory
- name: Get tuned profile
slurp:
src: /etc/tuned/active_profile
register: tuned_active_profile
- debug:
msg: "{{ tuned_active_profile['content'] | b64decode | trim }}"
- name: tuned-adm set throughput-performance
shell: /usr/sbin/tuned-adm profile throughput-performance
when: "tuned_active_profile['content'] | b64decode | trim != 'throughput-performance'"
- name: don't allow password based ssh
lineinfile:
path: /etc/ssh/sshd_config
regexp: '^PasswordAuthentication'
line: "PasswordAuthentication no"
notify: restart sshd
handlers:
- name: restart sshd
service:
name: sshd
state: restarted
+2
View File
@@ -0,0 +1,2 @@
[rhel8]
azure-rhel8 ansible_host=168.62.187.3 ansible_user=admiller ansible_become=yes
+2
View File
@@ -0,0 +1,2 @@
[all]
localhost ansible_connection=local
@@ -0,0 +1,2 @@
[all]
localhost ansible_connection=local ansible_python_interpreter-"/usr/bin/env python"
+6
View File
@@ -0,0 +1,6 @@
---
- hosts: all
tasks:
- debug: msg="Before!"
- shell: sleep 90
- debug: msg="After!"
@@ -0,0 +1 @@
{install_date: 'Mon Aug 20 13:21:07 2018', version: master}
@@ -0,0 +1,13 @@
---
galaxy_info:
author: Ben Thomasson
description: Hello World role
company: Red Hat
license: Apache
min_ansible_version: 1.2
galaxy_tags:
- hello
dependencies: []
@@ -0,0 +1,2 @@
---
- debug:
+5
View File
@@ -0,0 +1,5 @@
---
- hosts: all
gather_facts: false
roles:
- name: benthomasson.hello_role
+249
View File
@@ -0,0 +1,249 @@
import os
import sys
import uuid
import json
import random
import string
import tempfile
import shutil
from pytest import raises
from unittest.mock import patch
from ansible_runner.__main__ import main
def random_string():
return ''.join(random.choice(string.ascii_uppercase + string.digits)
for _ in range(random.randint(3, 20)))
def random_json(keys=None):
data = dict()
if keys:
for key in keys:
data[key] = random_string()
else:
for _ in range(0, 5):
data[random_string()] = random_string()
return json.dumps(data)
def cmdline(command, *args):
cmdline = ['ansible-runner', command]
cmdline.extend(args)
sys.argv = cmdline
def test_main_bad_private_data_dir():
tmpfile = os.path.join('/tmp', str(uuid.uuid4().hex))
open(tmpfile, 'w').write(random_string())
cmdline('run', tmpfile, '-p', 'fake')
try:
with raises(OSError):
main()
finally:
os.remove(tmpfile)
def run_role(options, private_data_dir=None, expected_rc=0):
try:
private_data_dir = private_data_dir or tempfile.mkdtemp()
args = ['run', private_data_dir]
args.extend(options)
with patch('ansible_runner.interface.run') as mock_run:
with raises(SystemExit) as exc:
main()
assert exc.type == SystemExit
assert exc.value.code == expected_rc
finally:
shutil.rmtree(private_data_dir)
return mock_run
def test_cmdline_role_defaults():
"""Run a role directly with all command line defaults
"""
private_data_dir = tempfile.mkdtemp()
options = ['-r' , 'test']
playbook = [{'hosts': 'all', 'gather_facts': True, 'roles': [{'role': 'test'}]}]
run_options = {
'private_data_dir': private_data_dir,
'playbook': playbook
}
result = run_role(options, private_data_dir)
result.called_with_args([run_options])
def test_cmdline_role_skip_facts():
"""Run a role directly and set --role-skip-facts option
"""
private_data_dir = tempfile.mkdtemp()
options = ['-r' , 'test', '--role-skip-facts']
playbook = [{'hosts': 'all', 'gather_facts': False, 'roles': [{'role': 'test'}]}]
run_options = {
'private_data_dir': private_data_dir,
'playbook': playbook
}
result = run_role(options, private_data_dir)
result.called_with_args([run_options])
def test_cmdline_role_inventory():
"""Run a role directly and set --inventory option
"""
private_data_dir = tempfile.mkdtemp()
options = ['-r' , 'test', '--inventory hosts']
playbook = [{'hosts': 'all', 'gather_facts': False, 'roles': [{'role': 'test'}]}]
run_options = {
'private_data_dir': private_data_dir,
'playbook': playbook,
'inventory': 'hosts'
}
result = run_role(options, private_data_dir)
result.called_with_args([run_options])
def test_cmdline_role_vars():
"""Run a role directly and set --role-vars option
"""
private_data_dir = tempfile.mkdtemp()
options = ['-r' , 'test', '--role-vars "foo=bar"']
playbook = [{
'hosts': 'all',
'gather_facts': False,
'roles': [{
'role': 'test',
'vars': {'foo': 'bar'}
}]
}]
run_options = {
'private_data_dir': private_data_dir,
'playbook': playbook
}
result = run_role(options, private_data_dir)
result.called_with_args([run_options])
def test_cmdline_roles_path():
"""Run a role directly and set --roles-path option
"""
private_data_dir = tempfile.mkdtemp()
options = ['-r' , 'test', '--roles-path /tmp/roles']
playbook = [{'hosts': 'all', 'gather_facts': False, 'roles': [{'role': 'test'}]}]
run_options = {
'private_data_dir': private_data_dir,
'playbook': playbook,
'envvars': {'ANSIBLE_ROLES_PATH': '/tmp/roles'}
}
result = run_role(options, private_data_dir)
result.called_with_args([run_options])
def test_cmdline_role_with_playbook_option():
"""Test error is raised with invalid command line option '-p'
"""
cmdline('run', 'private_data_dir', '-r', 'fake', '-p', 'fake')
with raises(SystemExit) as exc:
main()
assert exc == 1
def test_cmdline_playbook(is_pre_ansible28):
try:
private_data_dir = tempfile.mkdtemp()
play = [{'hosts': 'all', 'tasks': [{'debug': {'msg': random_string()}}]}]
path = os.path.join(private_data_dir, 'project')
os.makedirs(path)
playbook = os.path.join(path, 'main.yaml')
with open(playbook, 'w') as f:
f.write(json.dumps(play))
path = os.path.join(private_data_dir, 'inventory')
os.makedirs(path)
inventory = os.path.join(path, 'hosts')
with open(inventory, 'w') as f:
if is_pre_ansible28:
f.write('[all]\nlocalhost ansible_connection=local ansible_python_interpreter="/usr/bin/env python"')
else:
f.write('[all]\nlocalhost ansible_connection=local')
cmdline('run', private_data_dir, '-p', playbook, '--inventory', inventory)
assert main() == 0
with open(playbook) as f:
assert json.loads(f.read()) == play
finally:
shutil.rmtree(private_data_dir)
def test_cmdline_playbook_hosts():
"""Test error is raised with trying to pass '--hosts' with '-p'
"""
cmdline('run', 'private_data_dir', '-p', 'fake', '--hosts', 'all')
with raises(SystemExit) as exc:
main()
assert exc == 1
def test_cmdline_includes_one_option():
"""Test error is raised if not '-p', '-m' or '-r'
"""
cmdline('run', 'private_data_dir')
with raises(SystemExit) as exc:
main()
assert exc == 1
def test_cmdline_cmdline_override(is_pre_ansible28):
try:
private_data_dir = tempfile.mkdtemp()
play = [{'hosts': 'all', 'tasks': [{'debug': {'msg': random_string()}}]}]
path = os.path.join(private_data_dir, 'project')
os.makedirs(path)
playbook = os.path.join(path, 'main.yaml')
with open(playbook, 'w') as f:
f.write(json.dumps(play))
path = os.path.join(private_data_dir, 'inventory')
os.makedirs(path)
inventory = os.path.join(path, 'hosts')
with open(inventory, 'w') as f:
if is_pre_ansible28:
f.write('[all]\nlocalhost ansible_connection=local ansible_python_interpreter="/usr/bin/env python"')
else:
f.write('[all]\nlocalhost ansible_connection=local')
# privateip: removed --hosts command line option from test beause it is
# not a supported combination of cli options
#cmdline('run', private_data_dir, '-p', playbook, '--hosts', 'all', '--cmdline', '-e foo=bar')
cmdline('run', private_data_dir, '-p', playbook, '--cmdline', '-e foo=bar')
assert main() == 0
finally:
shutil.rmtree(private_data_dir)
+422
View File
@@ -0,0 +1,422 @@
from __future__ import absolute_import
import json
import os
import yaml
import six
from ansible import __version__ as ANSIBLE_VERSION
from ansible_runner.interface import init_runner
import pytest
HERE = os.path.abspath(os.path.dirname(__file__))
@pytest.fixture()
def executor(tmpdir, request, is_pre_ansible28):
private_data_dir = six.text_type(tmpdir.mkdir('foo'))
playbooks = request.node.callspec.params.get('playbook')
playbook = list(playbooks.values())[0]
envvars = request.node.callspec.params.get('envvars')
if envvars is None:
envvars = {}
# warning messages create verbose events and interfere with assertions
envvars["ANSIBLE_DEPRECATION_WARNINGS"] = "False"
# python interpreter used is not of much interest, we really want to silence warnings
envvars['ANSIBLE_PYTHON_INTERPRETER'] = 'auto_silent'
if is_pre_ansible28:
inventory = 'localhost ansible_connection=local ansible_python_interpreter="/usr/bin/env python"'
else:
inventory = 'localhost ansible_connection=local'
r = init_runner(
private_data_dir=private_data_dir,
inventory=inventory,
envvars=envvars,
playbook=yaml.safe_load(playbook)
)
return r
@pytest.mark.parametrize('event', ['playbook_on_start',
'playbook_on_play_start',
'playbook_on_task_start', 'runner_on_ok',
'playbook_on_stats'])
@pytest.mark.parametrize('playbook', [
{'helloworld.yml': '''
- name: Hello World Sample
connection: local
hosts: all
gather_facts: no
tasks:
- name: Hello Message
debug:
msg: "Hello World!"
'''}, # noqa
{'results_included.yml': '''
- name: Run module which generates results list
connection: local
hosts: all
gather_facts: no
vars:
results: ['foo', 'bar']
tasks:
- name: Generate results list
debug:
var: results
'''} # noqa
], ids=['helloworld.yml', 'results_included.yml'])
@pytest.mark.parametrize('envvars', [
{'ANSIBLE_CALLBACK_PLUGINS': os.path.join(HERE, 'callback')},
{'ANSIBLE_CALLBACK_PLUGINS': ''}],
ids=['local-callback-plugin', 'no-callback-plugin']
)
def test_callback_plugin_receives_events(executor, event, playbook, envvars):
executor.run()
assert len(list(executor.events))
assert event in [task['event'] for task in executor.events]
@pytest.mark.parametrize('playbook', [
{'no_log_on_ok.yml': '''
- name: args should not be logged when task-level no_log is set
connection: local
hosts: all
gather_facts: no
tasks:
- shell: echo "SENSITIVE"
no_log: true
'''}, # noqa
{'no_log_on_fail.yml': '''
- name: failed args should not be logged when task-level no_log is set
connection: local
hosts: all
gather_facts: no
tasks:
- shell: echo "SENSITIVE"
no_log: true
failed_when: true
ignore_errors: true
'''}, # noqa
{'no_log_on_skip.yml': '''
- name: skipped task args should be suppressed with no_log
connection: local
hosts: all
gather_facts: no
tasks:
- shell: echo "SENSITIVE"
no_log: true
when: false
'''}, # noqa
{'no_log_on_play.yml': '''
- name: args should not be logged when play-level no_log set
connection: local
hosts: all
gather_facts: no
no_log: true
tasks:
- shell: echo "SENSITIVE"
'''}, # noqa
{'async_no_log.yml': '''
- name: async task args should suppressed with no_log
connection: local
hosts: all
gather_facts: no
no_log: true
tasks:
- async: 10
poll: 1
shell: echo "SENSITIVE"
no_log: true
'''}, # noqa
{'with_items.yml': '''
- name: with_items tasks should be suppressed with no_log
connection: local
hosts: all
gather_facts: no
tasks:
- shell: echo {{ item }}
no_log: true
with_items: [ "SENSITIVE", "SENSITIVE-SKIPPED", "SENSITIVE-FAILED" ]
when: item != "SENSITIVE-SKIPPED"
failed_when: item == "SENSITIVE-FAILED"
ignore_errors: yes
'''}, # noqa, NOTE: with_items will be deprecated in 2.9
{'loop.yml': '''
- name: loop tasks should be suppressed with no_log
connection: local
hosts: all
gather_facts: no
tasks:
- shell: echo {{ item }}
no_log: true
loop: [ "SENSITIVE", "SENSITIVE-SKIPPED", "SENSITIVE-FAILED" ]
when: item != "SENSITIVE-SKIPPED"
failed_when: item == "SENSITIVE-FAILED"
ignore_errors: yes
'''}, # noqa
])
def test_callback_plugin_no_log_filters(executor, playbook):
executor.run()
assert len(list(executor.events))
assert 'SENSITIVE' not in json.dumps(list(executor.events))
@pytest.mark.parametrize('playbook', [
{'no_log_on_ok.yml': '''
- name: args should not be logged when no_log is set at the task or module level
connection: local
hosts: all
gather_facts: no
tasks:
- shell: echo "PUBLIC"
- shell: echo "PRIVATE"
no_log: true
- uri: url=https://example.org url_username="PUBLIC" url_password="PRIVATE"
'''}, # noqa
])
def test_callback_plugin_task_args_leak(executor, playbook, skipif_pre_ansible28):
executor.run()
events = list(executor.events)
assert events[0]['event'] == 'playbook_on_start'
assert events[1]['event'] == 'playbook_on_play_start'
# task 1
assert events[2]['event'] == 'playbook_on_task_start'
assert events[3]['event'] == 'runner_on_start'
assert events[4]['event'] == 'runner_on_ok'
# task 2 no_log=True
assert events[5]['event'] == 'playbook_on_task_start'
assert events[6]['event'] == 'runner_on_start'
assert events[7]['event'] == 'runner_on_ok'
assert 'PUBLIC' in json.dumps(events), events
for event in events:
assert 'PRIVATE' not in json.dumps(event), event
# make sure playbook was successful, so all tasks were hit
assert not events[-1]['event_data']['failures'], 'Unexpected playbook execution failure'
@pytest.mark.parametrize('playbook', [
{'loop_with_no_log.yml': '''
- name: playbook variable should not be overwritten when using no log
connection: local
hosts: all
gather_facts: no
tasks:
- command: "{{ item }}"
register: command_register
no_log: True
with_items:
- "echo helloworld!"
- debug: msg="{{ command_register.results|map(attribute='stdout')|list }}"
'''}, # noqa
])
def test_callback_plugin_censoring_does_not_overwrite(executor, playbook, skipif_pre_ansible28):
executor.run()
events = list(executor.events)
assert events[0]['event'] == 'playbook_on_start'
assert events[1]['event'] == 'playbook_on_play_start'
# task 1
assert events[2]['event'] == 'playbook_on_task_start'
# Ordering of task and item events may differ randomly
assert set(['runner_on_start', 'runner_item_on_ok', 'runner_on_ok']) == set([data['event'] for data in events[3:6]])
# task 2 no_log=True
assert events[6]['event'] == 'playbook_on_task_start'
assert events[7]['event'] == 'runner_on_start'
assert events[8]['event'] == 'runner_on_ok'
assert 'helloworld!' in events[8]['event_data']['res']['msg']
@pytest.mark.parametrize('playbook', [
{'strip_env_vars.yml': '''
- name: sensitive environment variables should be stripped from events
connection: local
hosts: all
tasks:
- shell: echo "Hello, World!"
'''}, # noqa
])
def test_callback_plugin_strips_task_environ_variables(executor, playbook):
executor.run()
assert len(list(executor.events))
for event in list(executor.events):
assert os.environ['PATH'] not in json.dumps(event)
@pytest.mark.parametrize('playbook', [
{'custom_set_stat.yml': '''
- name: custom set_stat calls should persist to the local disk so awx can save them
connection: local
hosts: all
tasks:
- set_stats:
data:
foo: "bar"
'''}, # noqa
])
def test_callback_plugin_saves_custom_stats(executor, playbook, skipif_pre_ansible28):
executor.run()
for event in executor.events:
event_data = event.get('event_data', {})
if 'artifact_data' in event_data:
assert event_data['artifact_data'] == {'foo': 'bar'}
break
else:
raise Exception('Did not find expected artifact data in event data')
@pytest.mark.parametrize('playbook', [
{'handle_playbook_on_notify.yml': '''
- name: handle playbook_on_notify events properly
connection: local
hosts: all
handlers:
- name: my_handler
debug: msg="My Handler"
tasks:
- debug: msg="My Task"
changed_when: true
notify:
- my_handler
'''}, # noqa
])
@pytest.mark.skipif(ANSIBLE_VERSION < '2.5', reason="v2_playbook_on_notify doesn't work before ansible 2.5")
def test_callback_plugin_records_notify_events(executor, playbook, skipif_pre_ansible28):
executor.run()
assert len(list(executor.events))
notify_events = [x for x in executor.events if x['event'] == 'playbook_on_notify']
assert len(notify_events) == 1
assert notify_events[0]['event_data']['handler'] == 'my_handler'
assert notify_events[0]['event_data']['host'] == 'localhost'
assert notify_events[0]['event_data']['task'] == 'debug'
@pytest.mark.parametrize('playbook', [
{'no_log_module_with_var.yml': '''
- name: ensure that module-level secrets are redacted
connection: local
hosts: all
vars:
- pw: SENSITIVE
tasks:
- uri:
url: https://example.org
url_username: john-jacob-jingleheimer-schmidt
url_password: "{{ pw }}"
'''}, # noqa
])
def test_module_level_no_log(executor, playbook, skipif_pre_ansible28):
# It's possible for `no_log=True` to be defined at the _module_ level,
# e.g., for the URI module password parameter
# This test ensures that we properly redact those
executor.run()
assert len(list(executor.events))
assert 'john-jacob-jingleheimer-schmidt' in json.dumps(list(executor.events))
assert 'SENSITIVE' not in json.dumps(list(executor.events))
def test_output_when_given_invalid_playbook(tmpdir):
# As shown in the following issue:
#
# https://github.com/ansible/ansible-runner/issues/29
#
# There was a lack of output by runner when a playbook that doesn't exist
# is provided. This was fixed in this PR:
#
# https://github.com/ansible/ansible-runner/pull/34
#
# But no test validated it. This does that.
private_data_dir = str(tmpdir)
executor = init_runner(
private_data_dir=private_data_dir,
inventory="localhost ansible_connection=local",
envvars={"ANSIBLE_DEPRECATION_WARNINGS": "False"},
playbook=os.path.join(private_data_dir, 'fake_playbook.yml')
)
executor.run()
stdout = executor.stdout.read()
assert "ERROR! the playbook:" in stdout
assert "could not be found" in stdout
def test_output_when_given_non_playbook_script(tmpdir):
# As shown in the following pull request:
#
# https://github.com/ansible/ansible-runner/pull/256
#
# This ports some functionality that previously lived in awx and allows raw
# lines of stdout to be treated as event lines.
#
# As mentioned in the pull request as well, there were no specs added, and
# this is a retro-active test based on the sample repo provided in the PR:
#
# https://github.com/AlanCoding/ansible-runner-examples/tree/master/non_playbook/sleep_with_writes
private_data_dir = str(tmpdir)
with open(os.path.join(private_data_dir, "args"), 'w') as args_file:
args_file.write("bash sleep_and_write.sh\n")
with open(os.path.join(private_data_dir, "sleep_and_write.sh"), 'w') as script_file:
script_file.write("echo 'hi world'\nsleep 0.5\necho 'goodbye world'\n")
# Update the settings to make this test a bit faster :)
os.mkdir(os.path.join(private_data_dir, "env"))
with open(os.path.join(private_data_dir, "env", "settings"), 'w') as settings_file:
settings_file.write("pexpect_timeout: 0.2")
executor = init_runner(
private_data_dir=private_data_dir,
inventory="localhost ansible_connection=local",
envvars={"ANSIBLE_DEPRECATION_WARNINGS": "False"}
)
executor.run()
stdout = executor.stdout.readlines()
assert stdout[0].strip() == "hi world"
assert stdout[1].strip() == "goodbye world"
events = list(executor.events)
assert len(events) == 2
assert events[0]['event'] == 'verbose'
assert events[0]['stdout'] == 'hi world'
assert events[1]['event'] == 'verbose'
assert events[1]['stdout'] == 'goodbye world'
@pytest.mark.parametrize('playbook', [
{'listvars.yml': '''
- name: List Variables
connection: local
hosts: localhost
gather_facts: false
tasks:
- name: Print a lot of lines
debug:
msg: "{{ ('F' * 150) | list }}"
'''}, # noqa
])
def test_large_stdout_parsing_when_using_json_output(executor, playbook, skipif_pre_ansible28):
# When the json flag is used, it is possible to output more data than
# pexpect's maxread default of 2000 characters. As a result, if not
# handled properly, the stdout can end up being corrupted with partial
# non-event matches with raw "non-json" lines being intermixed with json
# ones.
#
# This tests to confirm we don't polute the stdout output with non-json
# lines when a single event has a lot of output.
if six.PY2:
pytest.skip('Ansible in python2 uses different syntax.')
executor.config.env['ANSIBLE_NOCOLOR'] = str(True)
executor.run()
text = executor.stdout.read()
assert text.count('"F"') == 150
+192
View File
@@ -0,0 +1,192 @@
import pytest
import tempfile
from distutils.spawn import find_executable
import json
import os
from ansible_runner import defaults, run, run_async
@pytest.mark.parametrize('containerized', [True, False])
def test_basic_events(containerized, container_runtime_available, is_pre_ansible28, is_run_async=False, g_facts=False):
if containerized and not container_runtime_available:
pytest.skip('container runtime(s) not available')
tdir = tempfile.mkdtemp()
if is_pre_ansible28:
inventory = 'localhost ansible_connection=local ansible_python_interpreter="/usr/bin/env python"'
else:
inventory = 'localhost ansible_connection=local'
playbook = [{'hosts': 'all', 'gather_facts': g_facts, 'tasks': [{'debug': {'msg': "test"}}]}]
run_args = {'private_data_dir': tdir,
'inventory': inventory,
'envvars': {"ANSIBLE_DEPRECATION_WARNINGS": "False", 'ANSIBLE_PYTHON_INTERPRETER': 'auto_silent'},
'playbook': playbook}
if containerized:
run_args.update({'process_isolation': True,
'process_isolation_executable': 'podman',
'container_image': defaults.default_container_image,
'container_volume_mounts': [f'{tdir}:{tdir}']})
if not is_run_async:
r = run(**run_args)
else:
thread, r = run_async(**run_args)
thread.join() # ensure async run finishes
event_types = [x['event'] for x in r.events if x['event'] != 'verbose']
okay_events = [x for x in filter(lambda x: 'event' in x and x['event'] == 'runner_on_ok',
r.events)]
assert event_types[0] == 'playbook_on_start'
assert "playbook_on_play_start" in event_types
assert "runner_on_ok" in event_types
assert "playbook_on_stats" in event_types
assert r.rc == 0
if not is_run_async:
assert len(okay_events) == 1
else:
assert len(okay_events) == 2
okay_event = okay_events[0]
assert "uuid" in okay_event and len(okay_event['uuid']) == 36
assert "parent_uuid" in okay_event and len(okay_event['parent_uuid']) == 36
assert "stdout" in okay_event and len(okay_event['stdout']) > 0
assert "start_line" in okay_event and int(okay_event['start_line']) > 0
assert "end_line" in okay_event and int(okay_event['end_line']) > 0
assert "event_data" in okay_event and len(okay_event['event_data']) > 0
@pytest.mark.parametrize('containerized', [True, False])
def test_async_events(containerized, container_runtime_available, is_pre_ansible28):
test_basic_events(containerized, container_runtime_available, is_pre_ansible28, is_run_async=True,g_facts=True)
def test_basic_serializeable(is_pre_ansible28):
tdir = tempfile.mkdtemp()
if is_pre_ansible28:
inv = 'localhost ansible_connection=local ansible_python_interpreter="/usr/bin/env python"'
else:
inv = 'localhost ansible_connection=local'
r = run(private_data_dir=tdir,
inventory=inv,
playbook=[{'hosts': 'all', 'gather_facts': False, 'tasks': [{'debug': {'msg': "test"}}]}])
events = [x for x in r.events]
json.dumps(events)
def test_event_omission(is_pre_ansible28):
tdir = tempfile.mkdtemp()
if is_pre_ansible28:
inv = 'localhost ansible_connection=local ansible_python_interpreter="/usr/bin/env python"'
else:
inv = 'localhost ansible_connection=local'
r = run(private_data_dir=tdir,
inventory=inv,
omit_event_data=True,
playbook=[{'hosts': 'all', 'gather_facts': False, 'tasks': [{'debug': {'msg': "test"}}]}])
assert not any([x['event_data'] for x in r.events])
def test_event_omission_except_failed(is_pre_ansible28):
tdir = tempfile.mkdtemp()
if is_pre_ansible28:
inv = 'localhost ansible_connection=local ansible_python_interpreter="/usr/bin/env python"'
else:
inv = 'localhost ansible_connection=local'
r = run(private_data_dir=tdir,
inventory=inv,
only_failed_event_data=True,
playbook=[{'hosts': 'all', 'gather_facts': False, 'tasks': [{'fail': {'msg': "test"}}]}])
all_event_datas = [x['event_data'] for x in r.events if x['event_data']]
assert len(all_event_datas) == 1
def test_runner_on_start(rc, skipif_pre_ansible28):
tdir = tempfile.mkdtemp()
r = run(private_data_dir=tdir,
inventory="localhost ansible_connection=local",
playbook=[{'hosts': 'all', 'gather_facts': False, 'tasks': [{'debug': {'msg': "test"}}]}])
start_events = [x for x in filter(lambda x: 'event' in x and x['event'] == 'runner_on_start',
r.events)]
assert len(start_events) == 1
def test_playbook_on_stats_summary_fields(test_data_dir, is_pre_ansible28):
if is_pre_ansible28:
pytest.skip('Test is for post 2.8 status types.')
private_data_dir = os.path.join(test_data_dir, 'host_status')
res = run(
private_data_dir=private_data_dir,
playbook='gen_host_status.yml'
)
assert res.rc != 0, res.stdout.read()
EXPECTED_SUMMARY_FIELDS = ('changed', 'dark', 'failures', 'ignored', 'ok', 'rescued', 'skipped')
runner_stats = res.stats
for stat in EXPECTED_SUMMARY_FIELDS:
assert stat in runner_stats
assert runner_stats[stat] # expected at least 1 host in each stat type
def test_include_role_events(clear_integration_artifacts):
r = run(
private_data_dir=os.path.abspath('test/integration'),
playbook='use_role.yml'
)
role_events = [event for event in r.events if event.get('event_data', {}).get('role', '') == "benthomasson.hello_role"]
assert 'runner_on_ok' in [event['event'] for event in role_events]
for event in role_events:
event_data = event['event_data']
assert not event_data.get('warning', False) # role use should not contain warnings
if event['event'] == 'runner_on_ok':
assert event_data['res']['msg'] == 'Hello world!'
@pytest.mark.skipif(find_executable('cgexec') is None,
reason="cgexec not available")
def test_profile_data(skipif_pre_ansible28):
tdir = tempfile.mkdtemp()
try:
r = run(private_data_dir=tdir,
inventory="localhost ansible_connection=local",
resource_profiling=True,
resource_profiling_base_cgroup='ansible-runner',
playbook=[{'hosts': 'all', 'gather_facts': False, 'tasks': [{'debug': {'msg': "test"}}]}])
assert r.config.env['ANSIBLE_CALLBACK_WHITELIST'] == 'cgroup_perf_recap'
assert r.config.env['CGROUP_CONTROL_GROUP'].startswith('ansible-runner/')
expected_datadir = os.path.join(tdir, 'profiling_data')
assert r.config.env['CGROUP_OUTPUT_DIR'] == expected_datadir
assert r.config.env['CGROUP_OUTPUT_FORMAT'] == 'json'
assert r.config.env['CGROUP_CPU_POLL_INTERVAL'] == '0.25'
assert r.config.env['CGROUP_MEMORY_POLL_INTERVAL'] == '0.25'
assert r.config.env['CGROUP_PID_POLL_INTERVAL'] == '0.25'
assert r.config.env['CGROUP_FILE_PER_TASK'] == 'True'
assert r.config.env['CGROUP_WRITE_FILES'] == 'True'
assert r.config.env['CGROUP_DISPLAY_RECAP'] == 'False'
data_files = [f for f in os.listdir(expected_datadir)
if os.path.isfile(os.path.join(expected_datadir, f))]
# Ensure each type of metric is represented in the results
for metric in ('cpu', 'memory', 'pids'):
assert len([f for f in data_files if '{}.json'.format(metric) in f]) == 1
# Ensure each file consists of a list of json dicts
for file in data_files:
with open(os.path.join(expected_datadir, file)) as f:
for line in f:
line = line[1:-1] # strip RS and LF (see https://tools.ietf.org/html/rfc7464#section-2.2)
try:
json.loads(line)
except json.JSONDecodeError as e:
pytest.fail("Failed to parse {}: '{}'"
.format(os.path.join(expected_datadir, file), e))
except RuntimeError:
pytest.skip(
'this test requires a cgroup to run e.g., '
'sudo cgcreate -a `whoami` -t `whoami` -g cpuacct,memory,pids:ansible-runner'
) # noqa
+136
View File
@@ -0,0 +1,136 @@
import os
import pytest
import shutil
from ansible_runner.interface import run, run_async
def test_run():
r = run(module='debug', host_pattern='localhost')
assert r.status == 'successful'
def test_run_async():
thread, r = run_async(module='debug', host_pattern='localhost')
thread.join()
assert r.status == 'successful'
@pytest.fixture
def printenv_example(test_data_dir):
private_data_dir = os.path.join(test_data_dir, 'printenv')
# TODO: remove if main code can handle this for us
# https://github.com/ansible/ansible-runner/issues/493
# for now, necessary to prevent errors on re-run
env_dir = os.path.join(private_data_dir, 'env')
if os.path.exists(env_dir):
shutil.rmtree(env_dir)
return private_data_dir
def get_env_data(res):
for event in res.events:
found = bool(
event['event'] == 'runner_on_ok' and event.get(
'event_data', {}
).get('task_action', None) == 'look_at_environment'
)
if found:
return event['event_data']['res']
else:
print('output:')
print(res.stdout.read())
raise RuntimeError('Count not find look_at_environment task from playbook')
def test_env_accuracy(request, printenv_example):
os.environ['SET_BEFORE_TEST'] = 'MADE_UP_VALUE'
def remove_test_env_var():
if 'SET_BEFORE_TEST' in os.environ:
del os.environ['SET_BEFORE_TEST']
request.addfinalizer(remove_test_env_var)
res = run(
private_data_dir=printenv_example,
playbook='get_environment.yml',
inventory=None,
envvars={'FROM_TEST': 'FOOBAR'},
)
assert res.rc == 0, res.stdout.read()
actual_env = get_env_data(res)['environment']
assert actual_env == res.config.env
@pytest.mark.serial
def test_env_accuracy_inside_container(request, printenv_example, container_runtime_installed):
os.environ['SET_BEFORE_TEST'] = 'MADE_UP_VALUE'
def remove_test_env_var():
if 'SET_BEFORE_TEST' in os.environ:
del os.environ['SET_BEFORE_TEST']
request.addfinalizer(remove_test_env_var)
res = run(
private_data_dir=printenv_example,
project_dir='/tmp',
playbook='get_environment.yml',
inventory=None,
envvars={'FROM_TEST': 'FOOBAR'},
settings={
'process_isolation_executable': container_runtime_installed,
'process_isolation': True
}
)
assert res.rc == 0, res.stdout.read()
env_data = get_env_data(res)
actual_env = env_data['environment']
expected_env = res.config.env.copy()
# NOTE: the reported environment for containerized jobs will not account for
# all environment variables, particularly those set by the entrypoint script
for key, value in expected_env.items():
assert key in actual_env
assert actual_env[key] == value, 'Reported value wrong for {0} env var'.format(key)
assert env_data['cwd'] == res.config.cwd
def test_multiple_inventories(test_data_dir):
private_data_dir = os.path.join(test_data_dir, 'debug')
res = run(
private_data_dir=private_data_dir,
playbook='debug.yml',
)
stdout = res.stdout.read()
assert res.rc == 0, stdout
# providing no inventory should cause <private_data_dir>/inventory
# to be used, reading both inventories in the directory
assert 'host_1' in stdout
assert 'host_2' in stdout
def test_inventory_absolute_path(test_data_dir):
private_data_dir = os.path.join(test_data_dir, 'debug')
res = run(
private_data_dir=private_data_dir,
playbook='debug.yml',
inventory=[
os.path.join(private_data_dir, 'inventory', 'inv_1'),
],
)
stdout = res.stdout.read()
assert res.rc == 0, stdout
# hosts can be down-selected to one inventory out of those available
assert 'host_1' in stdout
assert 'host_2' not in stdout
+327
View File
@@ -0,0 +1,327 @@
# -*- coding: utf-8 -*-
from __future__ import print_function
from ansible_runner.__main__ import main
import os
import codecs
import multiprocessing
import shutil
import yaml
import tempfile
import time
from contextlib import contextmanager
import pytest
from ansible_runner.exceptions import AnsibleRunnerException
HERE = os.path.abspath(os.path.dirname(__file__))
def ensure_directory(directory):
if not os.path.exists(directory):
os.makedirs(directory)
def ensure_removed(path):
if os.path.exists(path):
if os.path.isfile(path):
os.unlink(path)
elif os.path.isdir(path):
shutil.rmtree(path)
@contextmanager
def temp_directory(files=None):
temp_dir = tempfile.mkdtemp()
print(temp_dir)
try:
yield temp_dir
shutil.rmtree(temp_dir)
except BaseException:
if files is not None:
for file in files:
if os.path.exists(file):
with open(file) as f:
print(f.read())
raise
def test_temp_directory():
context = dict()
def will_fail():
with temp_directory() as temp_dir:
context['saved_temp_dir'] = temp_dir
assert False
def will_pass():
with temp_directory() as temp_dir:
context['saved_temp_dir'] = temp_dir
assert True
with pytest.raises(AssertionError):
will_fail()
assert os.path.exists(context['saved_temp_dir'])
shutil.rmtree(context['saved_temp_dir'])
will_pass()
assert not os.path.exists(context['saved_temp_dir'])
def test_help():
with pytest.raises(SystemExit) as exc:
main([])
assert exc.value.code == 2, 'Should raise SystemExit with return code 2'
def test_module_run():
try:
rc = main(['run', '-m', 'ping',
'--hosts', 'localhost',
'ping'])
assert os.path.exists('./ping')
assert os.path.exists('./ping/artifacts')
assert rc == 0
finally:
if os.path.exists('./ping'):
shutil.rmtree('./ping')
def test_module_run_debug():
try:
rc = main(['run', '-m', 'ping',
'--hosts', 'localhost',
'--debug',
'ping'])
assert os.path.exists('./ping')
assert os.path.exists('./ping/artifacts')
assert rc == 0
finally:
if os.path.exists('./ping'):
shutil.rmtree('./ping')
def test_module_run_clean():
with temp_directory() as temp_dir:
rc = main(['run', '-m', 'ping',
'--hosts', 'localhost',
temp_dir])
assert rc == 0
def test_role_run(skipif_pre_ansible28, clear_integration_artifacts):
rc = main(['run', '-r', 'benthomasson.hello_role',
'--hosts', 'localhost',
'--roles-path', 'test/integration/roles',
"test/integration"])
assert rc == 0
def test_role_run_abs():
with temp_directory() as temp_dir:
rc = main(['run', '-r', 'benthomasson.hello_role',
'--hosts', 'localhost',
'--roles-path', os.path.join(HERE, 'project/roles'),
temp_dir])
assert rc == 0
def test_role_logfile(skipif_pre_ansible28, clear_integration_artifacts):
rc = main(['run', '-r', 'benthomasson.hello_role',
'--hosts', 'localhost',
'--roles-path', 'test/integration/project/roles',
'--logfile', 'new_logfile',
'test/integration'])
assert os.path.exists('new_logfile')
assert rc == 0
def test_role_logfile_abs():
try:
with temp_directory() as temp_dir:
rc = main(['run', '-r', 'benthomasson.hello_role',
'--hosts', 'localhost',
'--roles-path', os.path.join(HERE, 'project/roles'),
'--logfile', 'new_logfile',
temp_dir])
assert os.path.exists('new_logfile')
assert rc == 0
finally:
ensure_removed("new_logfile")
def test_role_bad_project_dir():
with open("bad_project_dir", 'w') as f:
f.write('not a directory')
try:
with pytest.raises(OSError):
main(['run', '-r', 'benthomasson.hello_role',
'--hosts', 'localhost',
'--roles-path', os.path.join(HERE, 'project/roles'),
'--logfile', 'new_logfile',
'bad_project_dir'])
finally:
os.unlink('bad_project_dir')
ensure_removed("new_logfile")
def test_role_run_clean(skipif_pre_ansible28, clear_integration_artifacts):
rc = main(['run', '-r', 'benthomasson.hello_role',
'--hosts', 'localhost',
'--roles-path', 'test/integration/roles',
"test/integration"])
assert rc == 0
def test_role_run_cmd_line_abs():
with temp_directory() as temp_dir:
rc = main(['run', '-r', 'benthomasson.hello_role',
'--hosts', 'localhost',
'--roles-path', os.path.join(HERE, 'project/roles'),
temp_dir])
assert rc == 0
def test_role_run_artifacts_dir(skipif_pre_ansible28, clear_integration_artifacts):
rc = main(['run', '-r', 'benthomasson.hello_role',
'--hosts', 'localhost',
'--roles-path', 'test/integration/roles',
'--artifact-dir', 'otherartifacts',
"test/integration"])
assert rc == 0
def test_role_run_artifacts_dir_abs(skipif_pre_ansible28):
try:
with temp_directory() as temp_dir:
rc = main(['run', '-r', 'benthomasson.hello_role',
'--hosts', 'localhost',
'--roles-path', os.path.join(HERE, 'project/roles'),
'--artifact-dir', 'otherartifacts',
temp_dir])
assert os.path.exists(os.path.join('.', 'otherartifacts'))
assert rc == 0
finally:
shutil.rmtree(os.path.join('.', 'otherartifacts'))
@pytest.mark.parametrize('envvars', [
{'msg': 'hi'},
{
'msg': u'utf-8-䉪ቒ칸ⱷ?噂폄蔆㪗輥',
u'蔆㪗輥': u'䉪ቒ칸'
}],
ids=['regular-text', 'utf-8-text']
)
def test_role_run_env_vars(envvars):
with temp_directory() as temp_dir:
ensure_directory(os.path.join(temp_dir, 'env'))
with codecs.open(os.path.join(temp_dir, 'env/envvars'), 'w', encoding='utf-8') as f:
f.write(yaml.dump(envvars))
rc = main(['run', '-r', 'benthomasson.hello_role',
'--hosts', 'localhost',
'--roles-path', os.path.join(HERE, 'project/roles'),
temp_dir])
assert rc == 0
def test_role_run_args():
with temp_directory() as temp_dir:
rc = main(['run', '-r', 'benthomasson.hello_role',
'--hosts', 'localhost',
'--roles-path', os.path.join(HERE, 'project/roles'),
'--role-vars', 'msg=hi',
temp_dir])
assert rc == 0
def test_role_run_inventory(is_pre_ansible28):
inv = 'inventory/localhost_preansible28' if is_pre_ansible28 else 'inventory/localhost'
with temp_directory() as temp_dir:
ensure_directory(os.path.join(temp_dir, 'inventory'))
shutil.copy(os.path.join(HERE, inv), os.path.join(temp_dir, 'inventory/localhost'))
rc = main(['run', '-r', 'benthomasson.hello_role',
'--hosts', 'localhost',
'--roles-path', os.path.join(HERE, 'project/roles'),
'--inventory', os.path.join(temp_dir, 'inventory/localhost'),
temp_dir])
assert rc == 0
def test_role_run_inventory_missing(is_pre_ansible28):
inv = 'inventory/localhost_preansible28' if is_pre_ansible28 else 'inventory/localhost'
with temp_directory() as temp_dir:
ensure_directory(os.path.join(temp_dir, 'inventory'))
shutil.copy(os.path.join(HERE, inv), os.path.join(temp_dir, 'inventory/localhost'))
with pytest.raises(AnsibleRunnerException):
main(['run', '-r', 'benthomasson.hello_role',
'--hosts', 'localhost',
'--roles-path', os.path.join(HERE, 'project/roles'),
'--inventory', 'does_not_exist',
temp_dir])
def test_role_start():
with temp_directory() as temp_dir:
p = multiprocessing.Process(target=main,
args=[['start', '-r', 'benthomasson.hello_role',
'--hosts', 'localhost',
'--roles-path', os.path.join(HERE, 'project/roles'),
temp_dir]])
p.start()
p.join()
def test_playbook_start(skipif_pre_ansible28):
inv = 'inventory/localhost'
with temp_directory() as temp_dir:
project_dir = os.path.join(temp_dir, 'project')
ensure_directory(project_dir)
shutil.copy(os.path.join(HERE, 'project/hello.yml'), project_dir)
ensure_directory(os.path.join(temp_dir, 'inventory'))
shutil.copy(os.path.join(HERE, inv), os.path.join(temp_dir,'inventory/localhost'))
# privateip: removed --hosts command line option from test beause it is
# not a supported combination of cli options
p = multiprocessing.Process(target=main,
args=[['start', '-p', 'hello.yml',
'--inventory', os.path.join(HERE, 'inventory/localhost'),
#'--hosts', 'localhost',
temp_dir]])
p.start()
time.sleep(5)
assert os.path.exists(os.path.join(temp_dir, 'pid'))
rc = main(['is-alive', temp_dir])
assert rc == 0
rc = main(['stop', temp_dir])
assert rc == 0
time.sleep(1)
rc = main(['is-alive', temp_dir])
assert rc == 1
ensure_removed(os.path.join(temp_dir, 'pid'))
rc = main(['stop', temp_dir])
assert rc == 1
+279
View File
@@ -0,0 +1,279 @@
# -*- coding: utf-8 -*-
import json
import os
import re
import pytest
import six
import sys
try:
from unittest.mock import MagicMock
except ImportError:
from unittest.mock import MagicMock
from ansible_runner import Runner
from ansible_runner.exceptions import AnsibleRunnerException
@pytest.mark.serial
def test_password_prompt(rc):
rc.command = [sys.executable, '-c' 'import time; print(input("Password: "))']
rc.expect_passwords[re.compile(r'Password:\s*?$', re.M)] = '1234'
status, exitcode = Runner(config=rc).run()
assert status == 'successful'
assert exitcode == 0
with open(os.path.join(rc.artifact_dir, 'stdout')) as f:
assert '1234' in f.read()
def test_run_command(rc):
rc.command = ['sleep', '1']
status, exitcode = Runner(config=rc).run()
assert status == 'successful'
assert exitcode == 0
with open(os.path.join(rc.artifact_dir, 'command')) as f:
data = json.load(f)
assert data.get('command') == ['sleep','1']
assert 'cwd' in data
assert isinstance(data.get('env'), dict)
def test_run_command_with_unicode(rc):
expected = '"utf-8-䉪ቒ칸ⱷ?噂폄蔆㪗輥"'
if six.PY2:
expected = expected.decode('utf-8')
rc.command = ['echo', '"utf-8-䉪ቒ칸ⱷ?噂폄蔆㪗輥"']
rc.envvars = {"䉪ቒ칸": "蔆㪗輥"}
rc.prepare_env()
status, exitcode = Runner(config=rc).run()
assert status == 'successful'
assert exitcode == 0
with open(os.path.join(rc.artifact_dir, 'command')) as f:
data = json.load(f)
assert data.get('command') == ['echo', expected]
assert 'cwd' in data
assert isinstance(data.get('env'), dict)
assert u"䉪ቒ칸" in data.get('env')
def test_run_command_finished_callback(rc):
finished_callback = MagicMock()
rc.command = ['sleep','1']
runner = Runner(config=rc, finished_callback=finished_callback)
status, exitcode = runner.run()
assert status == 'successful'
assert exitcode == 0
finished_callback.assert_called_with(runner)
def test_run_command_explosive_finished_callback(rc):
def boom(*args):
raise Exception('boom')
rc.command = ['sleep','1']
runner = Runner(config=rc, finished_callback=boom)
with pytest.raises(Exception):
runner.run()
def test_run_command_explosive_cancel_callback(rc):
def boom(*args):
raise Exception('boom')
rc.command = ['sleep','1']
runner = Runner(config=rc, cancel_callback=boom)
with pytest.raises(Exception):
runner.run()
def test_run_command_cancel_callback(rc):
def cancel(*args):
return True
rc.command = ['sleep','1']
runner = Runner(config=rc, cancel_callback=cancel)
status, exitcode = runner.run()
assert status == 'canceled'
assert exitcode == 254
def test_run_command_job_timeout(rc):
rc.command = ['sleep', '1']
rc.job_timeout = 0.0000001
runner = Runner(config=rc)
status, exitcode = runner.run()
assert status == 'timeout'
assert exitcode == 254
def test_run_command_idle_timeout(rc):
rc.command = ['sleep', '1']
rc.idle_timeout = 0.0000001
runner = Runner(config=rc)
status, exitcode = runner.run()
assert status == 'timeout'
assert exitcode == 254
def test_run_command_failed(rc):
rc.command = ['false']
runner = Runner(config=rc)
status, exitcode = runner.run()
assert status == 'failed'
assert exitcode == 1
def test_executable_not_found(rc):
rc.command = ['supercalifragilistic']
runner = Runner(config=rc)
status, exitcode = runner.run()
assert status == 'failed'
assert exitcode == 127
events = list(runner.events)
assert len(events) == 1
assert 'The command was not found or was not executable: supercalifragilistic' in events[0]['stdout'] # noqa
def test_run_command_long_running(rc):
rc.command = ['yes']
runner = Runner(config=rc)
status, exitcode = runner.run()
assert status == 'timeout'
assert exitcode == 254
def test_run_command_long_running_children(rc):
rc.command = ['bash', '-c', "(yes)"]
runner = Runner(config=rc)
status, exitcode = runner.run()
assert status == 'timeout'
assert exitcode == 254
def test_run_command_events_missing(rc):
rc.command = ['sleep','1']
runner = Runner(config=rc)
status, exitcode = runner.run()
assert status == 'successful'
assert exitcode == 0
assert list(runner.events) == []
def test_run_command_stdout_missing(rc):
rc.command = ['sleep','1']
runner = Runner(config=rc)
status, exitcode = runner.run()
assert status == 'successful'
assert exitcode == 0
os.unlink(os.path.join(runner.config.artifact_dir, 'stdout'))
with pytest.raises(AnsibleRunnerException):
list(runner.stdout)
def test_run_command_no_stats(rc):
rc.command = ['sleep','1']
runner = Runner(config=rc)
status, exitcode = runner.run()
assert status == 'successful'
assert exitcode == 0
assert runner.stats is None
def test_run_command_ansible(rc):
rc.module = "debug"
rc.host_pattern = "localhost"
rc.prepare()
runner = Runner(config=rc)
status, exitcode = runner.run()
assert status == 'successful'
assert exitcode == 0
assert list(runner.events) != []
assert runner.stats != {}
assert list(runner.host_events('localhost')) != []
stdout = runner.stdout
assert stdout.read() != ""
def test_run_command_ansible_event_handler(rc):
event_handler = MagicMock()
status_handler = MagicMock()
rc.module = "debug"
rc.host_pattern = "localhost"
rc.prepare()
runner = Runner(config=rc, event_handler=event_handler, status_handler=status_handler)
status, exitcode = runner.run()
assert status == 'successful'
assert exitcode == 0
event_handler.assert_called()
status_handler.assert_called()
def test_run_command_ansible_event_handler_failure(rc):
def event_handler(*args):
raise IOError()
rc.module = "debug"
rc.host_pattern = "localhost"
rc.prepare()
runner = Runner(config=rc, event_handler=event_handler)
status, exitcode = runner.run()
assert status == 'successful'
assert exitcode == 0
def test_run_command_ansible_rotate_artifacts(rc):
rc.module = "debug"
rc.host_pattern = "localhost"
rc.prepare()
rc.rotate_artifacts = 1
runner = Runner(config=rc)
status, exitcode = runner.run()
assert status == 'successful'
assert exitcode == 0
runner = Runner(config=rc)
status, exitcode = runner.run()
assert status == 'successful'
assert exitcode == 0
def test_get_fact_cache(rc):
assert os.path.basename(rc.fact_cache) == 'fact_cache'
rc.module = "setup"
rc.host_pattern = "localhost"
rc.prepare()
runner = Runner(config=rc)
status, exitcode = runner.run()
assert status == 'successful'
assert exitcode == 0
print(rc.cwd)
assert os.path.exists(os.path.join(rc.artifact_dir, 'fact_cache'))
assert os.path.exists(os.path.join(rc.artifact_dir, 'fact_cache', 'localhost'))
data = runner.get_fact_cache('localhost')
assert data
def test_set_fact_cache(rc):
assert os.path.basename(rc.fact_cache) == 'fact_cache'
rc.module = "debug"
rc.module_args = "var=message"
rc.host_pattern = "localhost"
rc.prepare()
runner = Runner(config=rc)
runner.set_fact_cache('localhost', dict(message='hello there'))
status, exitcode = runner.run()
assert status == 'successful'
assert exitcode == 0
print(rc.cwd)
assert os.path.exists(os.path.join(rc.artifact_dir, 'fact_cache'))
assert os.path.exists(os.path.join(rc.artifact_dir, 'fact_cache', 'localhost'))
data = runner.get_fact_cache('localhost')
assert data['message'] == 'hello there'
def test_set_extra_vars(rc):
rc.module = "debug"
rc.module_args = "var=test_extra_vars"
rc.host_pattern = "localhost"
rc.extra_vars = dict(test_extra_vars='hello there')
rc.prepare()
runner = Runner(config=rc)
status, exitcode = runner.run()
with open(os.path.join(rc.artifact_dir, 'stdout')) as f:
assert 'hello there' in f.read()
@@ -0,0 +1,216 @@
import io
import os
import socket
import concurrent.futures
import time
import pytest
import json
from ansible_runner import run
from ansible_runner.streaming import Transmitter, Worker, Processor
import ansible_runner.interface # AWX import pattern
class TestStreamingUsage:
@pytest.fixture(autouse=True)
def reset_self_props(self):
self.status_data = None
def status_handler(self, status_data, runner_config=None):
self.status_data = status_data
def get_job_kwargs(self, job_type):
"""For this test scenaro, the ansible-runner interface kwargs"""
if job_type == 'run':
job_kwargs = dict(playbook='debug.yml')
else:
job_kwargs = dict(module='setup', host_pattern='localhost')
# also test use of user env vars
job_kwargs['envvars'] = dict(MY_ENV_VAR='bogus')
return job_kwargs
def check_artifacts(self, process_dir, job_type):
assert set(os.listdir(process_dir)) == {'artifacts',}
events_dir = os.path.join(process_dir, 'artifacts', 'job_events')
events = []
for file in os.listdir(events_dir):
with open(os.path.join(events_dir, file), 'r') as f:
if file in ('status', 'rc'):
continue
content = f.read()
events.append(json.loads(content))
stdout = '\n'.join(event['stdout'] for event in events)
if job_type == 'run':
assert 'Hello world!' in stdout
else:
assert '"ansible_facts"' in stdout
@pytest.mark.parametrize("job_type", ['run', 'adhoc'])
def test_remote_job_interface(self, tmpdir, test_data_dir, job_type):
transmit_dir = os.path.join(test_data_dir, 'debug')
worker_dir = str(tmpdir.mkdir('for_worker'))
process_dir = str(tmpdir.mkdir('for_process'))
job_kwargs = self.get_job_kwargs(job_type)
outgoing_buffer = io.BytesIO()
transmitter = Transmitter(_output=outgoing_buffer, private_data_dir=transmit_dir, **job_kwargs)
for key, value in job_kwargs.items():
assert transmitter.kwargs.get(key, '') == value
status, rc = transmitter.run()
assert rc in (None, 0)
assert status == 'unstarted'
outgoing_buffer.seek(0) # rewind so we can start reading
sent = outgoing_buffer.getvalue()
assert sent # should not be blank at least
assert b'zipfile' in sent
incoming_buffer = io.BytesIO()
worker = Worker(_input=outgoing_buffer, _output=incoming_buffer, private_data_dir=worker_dir)
worker.run()
assert set(os.listdir(worker_dir)) == {'artifacts', 'inventory', 'project', 'env'}, outgoing_buffer.getvalue()
incoming_buffer.seek(0) # again, be kind, rewind
processor = Processor(_input=incoming_buffer, private_data_dir=process_dir)
processor.run()
self.check_artifacts(process_dir, job_type)
@pytest.mark.parametrize("job_type", ['run', 'adhoc'])
def test_remote_job_by_sockets(self, tmpdir, test_data_dir, container_runtime_installed, job_type):
"""This test case is intended to be close to how the AWX use case works
the process interacts with receptorctl with sockets
sockets are used here, but worker is manually called instead of invoked by receptor
"""
transmit_dir = os.path.join(test_data_dir, 'debug')
worker_dir = str(tmpdir.mkdir('for_worker'))
process_dir = str(tmpdir.mkdir('for_process'))
job_kwargs = self.get_job_kwargs(job_type)
def transmit_method(transmit_sockfile_write):
return ansible_runner.interface.run(
streamer='transmit',
_output=transmit_sockfile_write,
private_data_dir=transmit_dir, **job_kwargs)
def worker_method(transmit_sockfile_read, results_sockfile_write):
return ansible_runner.interface.run(
streamer='worker',
_input=transmit_sockfile_read, _output=results_sockfile_write,
private_data_dir=worker_dir, **job_kwargs)
def process_method(results_sockfile_read):
return ansible_runner.interface.run(
streamer='process', quiet=True,
_input=results_sockfile_read,
private_data_dir=process_dir, status_handler=self.status_handler, **job_kwargs)
transmit_socket_write, transmit_socket_read = socket.socketpair()
results_socket_write, results_socket_read = socket.socketpair()
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
transmit_future = executor.submit(transmit_method, transmit_socket_write.makefile('wb'))
# In real AWX implementation, worker is done via receptorctl
executor.submit(worker_method, transmit_socket_read.makefile('rb'), results_socket_write.makefile('wb'))
while True:
if transmit_future.done():
break
time.sleep(0.05) # additionally, AWX calls cancel_callback()
res = transmit_future.result()
assert res.rc in (None, 0)
assert res.status == 'unstarted'
process_future = executor.submit(process_method, results_socket_read.makefile('rb'))
while True:
if process_future.done():
break
time.sleep(0.05) # additionally, AWX calls cancel_callback()
for s in (transmit_socket_write, transmit_socket_read, results_socket_write, results_socket_read):
s.close()
assert self.status_data is not None
if 'result_traceback' in self.status_data:
raise Exception(self.status_data['result_traceback'])
assert self.status_data.get('status') == 'successful'
assert set(os.listdir(worker_dir)) == {'artifacts', 'inventory', 'project', 'env'}
self.check_artifacts(process_dir, job_type)
def test_missing_private_dir_transmit(tmpdir):
outgoing_buffer = io.BytesIO()
# Transmit
with pytest.raises(ValueError) as excinfo:
run(
streamer='transmit',
_output=outgoing_buffer,
private_data_dir='/foo/bar/baz',
playbook='debug.yml',
)
assert "private_data_dir path is either invalid or does not exist" in str(excinfo.value)
def test_garbage_private_dir_worker(tmpdir):
worker_dir = str(tmpdir.mkdir('for_worker'))
incoming_buffer = io.BytesIO(
b'{"kwargs": {"playbook": "debug.yml"}}\n{"zipfile": 5}\n\x01\x02\x03\x04\x05{"eof": true}\n')
outgoing_buffer = io.BytesIO()
# Worker
run(
streamer='worker',
_input=incoming_buffer,
_output=outgoing_buffer,
private_data_dir=worker_dir,
)
sent = outgoing_buffer.getvalue()
assert b'"status": "error"' in sent
def test_unparsable_private_dir_worker(tmpdir):
worker_dir = str(tmpdir.mkdir('for_worker'))
incoming_buffer = io.BytesIO(b'')
outgoing_buffer = io.BytesIO()
# Worker
run(
streamer='worker',
_input=incoming_buffer,
_output=outgoing_buffer,
private_data_dir=worker_dir,
)
sent = outgoing_buffer.getvalue()
assert b'"status": "error"' in sent
def test_unparsable_private_dir_processor(tmpdir):
process_dir = str(tmpdir.mkdir('for_process'))
incoming_buffer = io.BytesIO(b'')
processor = run(
streamer='process',
_input=incoming_buffer,
private_data_dir=process_dir,
)
assert processor.status == 'error'
View File
+200
View File
@@ -0,0 +1,200 @@
import pytest
import base64
import json
from io import StringIO
from six.moves import xrange
from ansible_runner.utils import OutputEventFilter
MAX_WIDTH = 78
EXAMPLE_UUID = '890773f5-fe6d-4091-8faf-bdc8021d65dd'
def write_encoded_event_data(fileobj, data):
b64data = base64.b64encode(json.dumps(data).encode('utf-8')).decode()
# pattern corresponding to OutputEventFilter expectation
fileobj.write(u'\x1b[K')
for offset in xrange(0, len(b64data), MAX_WIDTH):
chunk = b64data[offset:offset + MAX_WIDTH]
escaped_chunk = u'{}\x1b[{}D'.format(chunk, len(chunk))
fileobj.write(escaped_chunk)
fileobj.write(u'\x1b[K')
@pytest.fixture
def fake_callback():
return []
@pytest.fixture
def fake_cache():
return {}
@pytest.fixture
def wrapped_handle(job_event_callback):
# Preliminary creation of resources usually done in tasks.py
return OutputEventFilter(StringIO(), job_event_callback)
@pytest.fixture
def job_event_callback(fake_callback, fake_cache):
def method(event_data):
print('fake callback called')
if 'uuid' in event_data:
cache_event = fake_cache.get(':1:ev-{}'.format(event_data['uuid']), None)
if cache_event is not None:
event_data.update(cache_event)
fake_callback.append(event_data)
return method
def test_event_recomb(fake_callback, fake_cache, wrapped_handle):
# Pretend that this is done by the Ansible callback module
fake_cache[':1:ev-{}'.format(EXAMPLE_UUID)] = {'event': 'foo'}
write_encoded_event_data(wrapped_handle, {
'uuid': EXAMPLE_UUID
})
wrapped_handle.write(u'\r\nTASK [Gathering Facts] *********************************************************\n')
wrapped_handle.write(u'\u001b[0;33mchanged: [localhost]\u001b[0m\n')
write_encoded_event_data(wrapped_handle, {})
# stop pretending
assert len(fake_callback) == 1
recomb_data = fake_callback[0]
assert 'event' in recomb_data
assert recomb_data['event'] == 'foo'
def test_separate_verbose_events(fake_callback, wrapped_handle):
# Pretend that this is done by the Ansible callback module
wrapped_handle.write(u'Using /etc/ansible/ansible.cfg as config file\n')
wrapped_handle.write(u'SSH password: \n')
write_encoded_event_data(wrapped_handle, { # associated with _next_ event
'uuid': EXAMPLE_UUID
})
# stop pretending
assert len(fake_callback) == 2
for event_data in fake_callback:
assert 'event' in event_data
assert event_data['event'] == 'verbose'
def test_large_data_payload(fake_callback, fake_cache, wrapped_handle):
# Pretend that this is done by the Ansible callback module
fake_cache[':1:ev-{}'.format(EXAMPLE_UUID)] = {'event': 'foo'}
event_data_to_encode = {
'uuid': EXAMPLE_UUID,
'host': 'localhost',
'role': 'some_path_to_role'
}
assert len(json.dumps(event_data_to_encode)) > MAX_WIDTH
write_encoded_event_data(wrapped_handle, event_data_to_encode)
wrapped_handle.write(u'\r\nTASK [Gathering Facts] *********************************************************\n')
wrapped_handle.write(u'\u001b[0;33mchanged: [localhost]\u001b[0m\n')
write_encoded_event_data(wrapped_handle, {})
# stop pretending
assert len(fake_callback) == 1
recomb_data = fake_callback[0]
assert 'role' in recomb_data
assert recomb_data['role'] == 'some_path_to_role'
assert 'event' in recomb_data
assert recomb_data['event'] == 'foo'
def test_event_lazy_parsing(fake_callback, fake_cache, wrapped_handle):
# Pretend that this is done by the Ansible callback module
fake_cache[':1:ev-{}'.format(EXAMPLE_UUID)] = {'event': 'foo'}
buff = StringIO()
event_data_to_encode = {
'uuid': EXAMPLE_UUID,
'host': 'localhost',
'role': 'some_path_to_role'
}
write_encoded_event_data(buff, event_data_to_encode)
# write the data to the event filter in chunks to test lazy event matching
buff.seek(0)
start_token_chunk = buff.read(1) # \x1b
start_token_remainder = buff.read(2) # [K
body = buff.read(15) # next 15 bytes of base64 data
remainder = buff.read() # the remainder
for chunk in (start_token_chunk, start_token_remainder, body, remainder):
wrapped_handle.write(chunk)
wrapped_handle.write(u'\r\nTASK [Gathering Facts] *********************************************************\n')
wrapped_handle.write(u'\u001b[0;33mchanged: [localhost]\u001b[0m\n')
write_encoded_event_data(wrapped_handle, {})
# stop pretending
assert len(fake_callback) == 1
recomb_data = fake_callback[0]
assert 'role' in recomb_data
assert recomb_data['role'] == 'some_path_to_role'
assert 'event' in recomb_data
assert recomb_data['event'] == 'foo'
@pytest.mark.timeout(1)
def test_large_stdout_blob():
def _callback(*args, **kw):
pass
f = OutputEventFilter(StringIO(), _callback)
for x in range(1024 * 10):
f.write(u'x' * 1024)
def test_verbose_line_buffering():
events = []
def _callback(event_data):
events.append(event_data)
f = OutputEventFilter(StringIO(), _callback)
f.write(u'one two\r\n\r\n')
assert len(events) == 2
assert events[0]['start_line'] == 0
assert events[0]['end_line'] == 1
assert events[0]['stdout'] == 'one two'
assert events[1]['start_line'] == 1
assert events[1]['end_line'] == 2
assert events[1]['stdout'] == ''
f.write(u'three')
assert len(events) == 2
f.write(u'\r\nfou')
# three is not pushed to buffer until its line completes
assert len(events) == 3
assert events[2]['start_line'] == 2
assert events[2]['end_line'] == 3
assert events[2]['stdout'] == 'three'
f.write(u'r\r')
f.write(u'\nfi')
assert events[3]['start_line'] == 3
assert events[3]['end_line'] == 4
assert events[3]['stdout'] == 'four'
f.write(u've')
f.write(u'\r\n')
assert len(events) == 5
assert events[4]['start_line'] == 4
assert events[4]['end_line'] == 5
assert events[4]['stdout'] == 'five'
f.close()
from pprint import pprint
pprint(events)
assert len(events) == 6
assert events[5]['event'] == 'EOF'
+133
View File
@@ -0,0 +1,133 @@
from io import BytesIO
from pytest import raises, fixture
from unittest.mock import patch
from six import string_types
import ansible_runner.loader
from ansible_runner.exceptions import ConfigurationError
@fixture
def loader():
return ansible_runner.loader.ArtifactLoader('/tmp')
def test__load_json_success(loader):
res = loader._load_json('{"test": "string"}')
assert isinstance(res, dict)
assert res['test'] == 'string'
def test__load_json_failure(loader):
res = loader._load_json('---\ntest: string')
assert res is None
res = loader._load_json('test string')
assert res is None
def test__load_yaml_success(loader):
res = loader._load_yaml('---\ntest: string')
assert isinstance(res, dict)
assert res['test'] == 'string'
res = loader._load_yaml('{"test": "string"}')
assert isinstance(res, dict)
assert res['test'] == 'string'
def test__load_yaml_failure(loader):
res = loader._load_yaml('---\ntest: string:')
assert res is None
def test_abspath(loader):
res = loader.abspath('/test')
assert res == '/test'
res = loader.abspath('test')
assert res == '/tmp/test'
res = loader.abspath('~/test')
assert res.startswith('/')
def test_load_file_text(loader):
with patch.object(ansible_runner.loader.ArtifactLoader, 'get_contents') as mock_get_contents:
mock_get_contents.return_value = 'test\nstring'
assert not loader._cache
# cache miss
res = loader.load_file('/tmp/test', string_types)
assert mock_get_contents.called
assert mock_get_contents.called_with_args('/tmp/test')
assert res == b'test\nstring'
assert '/tmp/test' in loader._cache
mock_get_contents.reset_mock()
# cache hit
res = loader.load_file('/tmp/test', string_types)
assert not mock_get_contents.called
assert res == b'test\nstring'
assert '/tmp/test' in loader._cache
def test_load_file_json(loader):
with patch.object(ansible_runner.loader.ArtifactLoader, 'get_contents') as mock_get_contents:
mock_get_contents.return_value = '---\ntest: string'
assert not loader._cache
res = loader.load_file('/tmp/test')
assert mock_get_contents.called
assert mock_get_contents.called_with_args('/tmp/test')
assert '/tmp/test' in loader._cache
assert res['test'] == 'string'
def test_load_file_type_check(loader):
with patch.object(ansible_runner.loader.ArtifactLoader, 'get_contents') as mock_get_contents:
mock_get_contents.return_value = '---\ntest: string'
assert not loader._cache
# type check passes
res = loader.load_file('/tmp/test', dict)
assert res is not None
mock_get_contents.reset_mock()
mock_get_contents.return_value = 'test string'
loader._cache = {}
# type check fails
with raises(ConfigurationError):
res = loader.load_file('/tmp/test', dict)
assert res is not None
def test_get_contents_ok(loader):
with patch('codecs.open') as mock_open:
handler = BytesIO()
handler.write(b"test string")
handler.seek(0)
mock_open.return_value.__enter__.return_value = handler
res = loader.get_contents('/tmp')
assert res == b'test string'
def test_get_contents_invalid_path(loader):
with raises(ConfigurationError):
loader.get_contents('/tmp/invalid')
def test_get_contents_exception(loader):
with raises(ConfigurationError):
loader.get_contents('/tmp')
+143
View File
@@ -0,0 +1,143 @@
# -*- coding: utf-8 -*-
import codecs
import os
import json
from unittest import mock
import pexpect
import pytest
import six
import sys
from ansible_runner import Runner
from ansible_runner.exceptions import CallbackError
from ansible_runner.runner_config import RunnerConfig
HERE, FILENAME = os.path.split(__file__)
@pytest.fixture(scope='function')
def rc(request, tmpdir):
rc = RunnerConfig(str(tmpdir))
rc.suppress_ansible_output = True
rc.expect_passwords = {
pexpect.TIMEOUT: None,
pexpect.EOF: None
}
rc.cwd = str(tmpdir)
rc.env = {}
rc.job_timeout = .5
rc.idle_timeout = 0
rc.pexpect_timeout = .1
rc.pexpect_use_poll = True
return rc
@pytest.fixture(autouse=True)
def mock_sleep(request):
# the handle_termination process teardown mechanism uses `time.sleep` to
# wait on processes to respond to SIGTERM; these are tests and don't care
# about being nice
m = mock.patch('time.sleep')
m.start()
request.addfinalizer(m.stop)
def test_simple_spawn(rc):
rc.command = ['ls', '-la']
status, exitcode = Runner(config=rc).run()
assert status == 'successful'
assert exitcode == 0
def test_error_code(rc):
rc.command = ['ls', '--nonsense']
status, exitcode = Runner(config=rc).run()
assert status == 'failed'
assert exitcode > 0
# TODO: matt does not like this test
def test_job_timeout(rc):
rc.command = [sys.executable, '-c', 'import time; time.sleep(5)']
runner = Runner(config=rc)
status, exitcode = runner.run()
assert status == 'timeout'
assert runner.timed_out is True
def test_cancel_callback(rc):
rc.command = [sys.executable, '-c', 'print(input("Password: "))']
status, exitcode = Runner(config=rc, cancel_callback=lambda: True).run()
assert status == 'canceled'
def test_cancel_callback_error(rc):
def kaboom():
raise Exception('kaboom')
rc.command = [sys.executable, '-c', 'print(input("Password: "))']
with pytest.raises(CallbackError):
Runner(config=rc, cancel_callback=kaboom).run()
def test_verbose_event_created_time(rc):
rc.command = ['echo', 'helloworld']
runner = Runner(config=rc)
status, exitcode = runner.run()
assert status == 'successful'
assert exitcode == 0
for event in runner.events:
assert 'created' in event, event
@pytest.mark.parametrize('value', ['abc123', six.u('Iñtërnâtiônàlizætiøn')])
def test_env_vars(rc, value):
rc.command = [sys.executable, '-c', 'import os; print(os.getenv("X_MY_ENV"))']
rc.env = {'X_MY_ENV': value}
status, exitcode = Runner(config=rc).run()
assert status == 'successful'
assert exitcode == 0
with codecs.open(os.path.join(rc.artifact_dir, 'stdout'), 'r', encoding='utf-8') as f:
assert value in f.read()
def test_event_callback_interface_has_ident(rc):
rc.ident = "testident"
runner = Runner(config=rc, remove_partials=False)
runner.event_handler = mock.Mock()
with mock.patch('codecs.open', mock.mock_open(read_data=json.dumps(dict(event="test")))):
with mock.patch('os.chmod', mock.Mock()) as chmod:
with mock.patch('os.mkdir', mock.Mock()):
runner.event_callback(dict(uuid="testuuid", counter=0))
assert runner.event_handler.call_count == 1
runner.event_handler.assert_called_with(dict(
runner_ident='testident', counter=0, uuid='testuuid', event='test',
created=mock.ANY
))
chmod.assert_called_once()
runner.status_callback("running")
def test_event_callback_interface_calls_event_handler_for_verbose_event(rc):
rc.ident = "testident"
event_handler = mock.Mock()
runner = Runner(config=rc, event_handler=event_handler)
with mock.patch('os.mkdir', mock.Mock()):
runner.event_callback(dict(uuid="testuuid", event='verbose', counter=0))
assert event_handler.call_count == 1
event_handler.assert_called_with(dict(
runner_ident='testident', counter=0, uuid='testuuid', event='verbose',
created=mock.ANY
))
def test_status_callback_interface(rc):
runner = Runner(config=rc)
assert runner.status == 'unstarted'
runner.status_handler = mock.Mock()
runner.status_callback("running")
assert runner.status_handler.call_count == 1
runner.status_handler.assert_called_with(dict(status='running', runner_ident=str(rc.ident)), runner_config=runner.config)
assert runner.status == 'running'
+655
View File
@@ -0,0 +1,655 @@
# -*- coding: utf-8 -*-
from functools import partial
from io import StringIO
import os
import re
import six
from pexpect import TIMEOUT, EOF
import pytest
from unittest.mock import (Mock, patch, PropertyMock)
from ansible_runner.runner_config import RunnerConfig, ExecutionMode
from ansible_runner.interface import init_runner
from ansible_runner.loader import ArtifactLoader
from ansible_runner.exceptions import ConfigurationError
try:
Pattern = re._pattern_type
except AttributeError:
# Python 3.7
Pattern = re.Pattern
def load_file_side_effect(path, value=None, *args, **kwargs):
if args[0] == path:
if value:
return value
raise ConfigurationError
def test_runner_config_init_defaults():
rc = RunnerConfig('/')
assert rc.private_data_dir == '/'
assert rc.ident is not None
assert rc.playbook is None
assert rc.inventory is None
assert rc.limit is None
assert rc.module is None
assert rc.module_args is None
assert rc.artifact_dir == os.path.join('/artifacts/%s' % rc.ident)
assert isinstance(rc.loader, ArtifactLoader)
def test_runner_config_with_artifact_dir():
rc = RunnerConfig('/', artifact_dir='/this-is-some-dir')
assert rc.artifact_dir == os.path.join('/this-is-some-dir', rc.ident)
def test_runner_config_init_with_ident():
rc = RunnerConfig('/', ident='test')
assert rc.private_data_dir == '/'
assert rc.ident == 'test'
assert rc.playbook is None
assert rc.inventory is None
assert rc.limit is None
assert rc.module is None
assert rc.module_args is None
assert rc.artifact_dir == os.path.join('/artifacts/test')
assert isinstance(rc.loader, ArtifactLoader)
def test_runner_config_project_dir():
rc = RunnerConfig('/', project_dir='/another/path')
assert rc.project_dir == '/another/path'
rc = RunnerConfig('/')
assert rc.project_dir == '/project'
def test_prepare_environment_vars_only_strings():
rc = RunnerConfig(private_data_dir="/", envvars=dict(D='D'))
value = dict(A=1, B=True, C="foo")
envvar_side_effect = partial(load_file_side_effect, 'env/envvars', value)
with patch.object(rc.loader, 'load_file', side_effect=envvar_side_effect):
rc.prepare_env()
assert 'A' in rc.env
assert isinstance(rc.env['A'], six.string_types)
assert 'B' in rc.env
assert isinstance(rc.env['B'], six.string_types)
assert 'C' in rc.env
assert isinstance(rc.env['C'], six.string_types)
assert 'D' in rc.env
assert rc.env['D'] == 'D'
def test_prepare_env_ad_hoc_command():
rc = RunnerConfig(private_data_dir="/")
value = {'AD_HOC_COMMAND_ID': 'teststring'}
envvar_side_effect = partial(load_file_side_effect, 'env/envvars', value)
with patch.object(rc.loader, 'load_file', side_effect=envvar_side_effect):
rc.prepare_env()
assert rc.cwd == '/'
def test_prepare_environment_pexpect_defaults():
rc = RunnerConfig(private_data_dir="/")
rc.prepare_env()
assert len(rc.expect_passwords) == 2
assert TIMEOUT in rc.expect_passwords
assert rc.expect_passwords[TIMEOUT] is None
assert EOF in rc.expect_passwords
assert rc.expect_passwords[EOF] is None
def test_prepare_env_passwords():
rc = RunnerConfig(private_data_dir='/')
value = {'^SSH [pP]assword.*$': 'secret'}
password_side_effect = partial(load_file_side_effect, 'env/passwords', value)
with patch.object(rc.loader, 'load_file', side_effect=password_side_effect):
rc.prepare_env()
rc.expect_passwords.pop(TIMEOUT)
rc.expect_passwords.pop(EOF)
assert len(rc.expect_passwords) == 1
assert isinstance(list(rc.expect_passwords.keys())[0], Pattern)
assert 'secret' in rc.expect_passwords.values()
def test_prepare_env_extra_vars_defaults():
rc = RunnerConfig('/')
rc.prepare_env()
assert rc.extra_vars is None
def test_prepare_env_settings_defaults():
rc = RunnerConfig('/')
rc.prepare_env()
assert rc.settings == {}
def test_prepare_env_settings():
rc = RunnerConfig('/')
value = {'test': 'string'}
settings_side_effect = partial(load_file_side_effect, 'env/settings', value)
with patch.object(rc.loader, 'load_file', side_effect=settings_side_effect):
rc.prepare_env()
assert rc.settings == value
def test_prepare_env_sshkey_defaults():
rc = RunnerConfig('/')
rc.prepare_env()
assert rc.ssh_key_data is None
def test_prepare_env_sshkey():
rc = RunnerConfig('/')
value = '01234567890'
sshkey_side_effect = partial(load_file_side_effect, 'env/ssh_key', value)
with patch.object(rc.loader, 'load_file', side_effect=sshkey_side_effect):
rc.prepare_env()
assert rc.ssh_key_data == value
def test_prepare_env_defaults():
with patch('os.path.exists') as path_exists:
path_exists.return_value=True
rc = RunnerConfig('/')
rc.prepare_env()
assert rc.idle_timeout is None
assert rc.job_timeout is None
assert rc.pexpect_timeout == 5
assert rc.cwd == '/project'
def test_prepare_env_directory_isolation():
with patch('os.path.exists') as path_exists:
path_exists.return_value=True
rc = RunnerConfig('/')
rc.directory_isolation_path = '/tmp/foo'
rc.prepare_env()
assert rc.cwd == '/tmp/foo'
@patch('os.path.exists', return_value=True)
def test_prepare_inventory(path_exists):
rc = RunnerConfig(private_data_dir='/')
rc.prepare_inventory()
assert rc.inventory == '/inventory'
rc.inventory = '/tmp/inventory'
rc.prepare_inventory()
assert rc.inventory == '/tmp/inventory'
rc.inventory = 'localhost,anotherhost,'
rc.prepare_inventory()
assert rc.inventory == 'localhost,anotherhost,'
path_exists.return_value = False
rc.inventory = None
rc.prepare_inventory()
assert rc.inventory is None
def test_generate_ansible_command():
rc = RunnerConfig(private_data_dir='/', playbook='main.yaml')
with patch('os.path.exists') as path_exists:
path_exists.return_value=True
rc.prepare_inventory()
rc.extra_vars = None
cmd = rc.generate_ansible_command()
assert cmd == ['ansible-playbook', '-i', '/inventory', 'main.yaml']
rc.extra_vars = dict(test="key")
cmd = rc.generate_ansible_command()
assert cmd == ['ansible-playbook', '-i', '/inventory', '-e', '{"test":"key"}', 'main.yaml']
with patch.object(rc.loader, 'isfile', side_effect=lambda x: True):
cmd = rc.generate_ansible_command()
assert cmd == ['ansible-playbook', '-i', '/inventory', '-e', '@/env/extravars', '-e', '{"test":"key"}', 'main.yaml']
rc.extra_vars = '/tmp/extravars.yml'
cmd = rc.generate_ansible_command()
assert cmd == ['ansible-playbook', '-i', '/inventory', '-e', '@/env/extravars', '-e', '@/tmp/extravars.yml', 'main.yaml']
rc.extra_vars = None
cmd = rc.generate_ansible_command()
assert cmd == ['ansible-playbook', '-i', '/inventory', '-e', '@/env/extravars', 'main.yaml']
rc.extra_vars = None
rc.inventory = "localhost,"
cmd = rc.generate_ansible_command()
assert cmd == ['ansible-playbook', '-i', 'localhost,', 'main.yaml']
rc.inventory = ['thing1', 'thing2']
cmd = rc.generate_ansible_command()
assert cmd == ['ansible-playbook', '-i', 'thing1', '-i', 'thing2', 'main.yaml']
rc.inventory = []
cmd = rc.generate_ansible_command()
assert cmd == ['ansible-playbook', 'main.yaml']
rc.inventory = None
with patch('os.path.exists', return_value=False) as path_exists:
rc.prepare_inventory()
cmd = rc.generate_ansible_command()
assert cmd == ['ansible-playbook', 'main.yaml']
rc.verbosity = 3
with patch('os.path.exists', return_value=True) as path_exists:
rc.prepare_inventory()
cmd = rc.generate_ansible_command()
assert cmd == ['ansible-playbook', '-i', '/inventory', '-vvv', 'main.yaml']
rc.verbosity = None
rc.limit = 'hosts'
cmd = rc.generate_ansible_command()
assert cmd == ['ansible-playbook', '-i', '/inventory', '--limit', 'hosts', 'main.yaml']
rc.limit = None
rc.module = 'setup'
cmd = rc.generate_ansible_command()
assert cmd == ['ansible', '-i', '/inventory', '-m', 'setup']
rc.module = None
rc.module = 'setup'
rc.module_args = 'test=string'
cmd = rc.generate_ansible_command()
assert cmd == ['ansible', '-i', '/inventory', '-m', 'setup', '-a', 'test=string']
rc.module_args = None
rc.module = None
rc.forks = 5
cmd = rc.generate_ansible_command()
assert cmd == ['ansible-playbook', '-i', '/inventory', '--forks', '5', 'main.yaml']
def test_generate_ansible_command_with_api_extravars():
rc = RunnerConfig(private_data_dir='/', playbook='main.yaml', extravars={"foo":"bar"})
with patch('os.path.exists') as path_exists:
path_exists.return_value=True
rc.prepare_inventory()
cmd = rc.generate_ansible_command()
assert cmd == ['ansible-playbook', '-i', '/inventory', '-e', '{"foo":"bar"}', 'main.yaml']
def test_generate_ansible_command_with_dict_extravars():
rc = RunnerConfig(private_data_dir='/', playbook='main.yaml', extravars={"foo":"test \n hello"})
with patch('os.path.exists') as path_exists:
path_exists.return_value=True
rc.prepare_inventory()
cmd = rc.generate_ansible_command()
assert cmd == ['ansible-playbook', '-i', '/inventory', '-e', '{"foo":"test \\n hello"}', 'main.yaml']
@pytest.mark.parametrize('cmdline,tokens', [
(u'--tags foo --skip-tags', ['--tags', 'foo', '--skip-tags']),
(u'--limit "䉪ቒ칸ⱷ?噂폄蔆㪗輥"', ['--limit', '䉪ቒ칸ⱷ?噂폄蔆㪗輥']),
])
def test_generate_ansible_command_with_cmdline_args(cmdline, tokens):
rc = RunnerConfig(private_data_dir='/', playbook='main.yaml')
with patch('os.path.exists') as path_exists:
path_exists.return_value = True
rc.prepare_inventory()
rc.extra_vars = {}
cmdline_side_effect = partial(load_file_side_effect, 'env/cmdline', cmdline)
with patch.object(rc.loader, 'load_file', side_effect=cmdline_side_effect):
cmd = rc.generate_ansible_command()
assert cmd == ['ansible-playbook'] + tokens + ['-i', '/inventory', 'main.yaml']
def test_prepare_command_defaults():
rc = RunnerConfig('/')
cmd_side_effect = partial(load_file_side_effect, 'args')
def generate_side_effect():
return StringIO(u'test "string with spaces"')
with patch.object(rc.loader, 'load_file', side_effect=cmd_side_effect):
with patch.object(rc, 'generate_ansible_command', side_effect=generate_side_effect):
rc.prepare_command()
rc.command == ['test', '"string with spaces"']
def test_prepare_with_defaults():
rc = RunnerConfig('/')
rc.prepare_inventory = Mock()
rc.prepare_env = Mock()
rc.prepare_command = Mock()
rc.ssh_key_data = None
rc.artifact_dir = '/'
rc.env = {}
with pytest.raises(ConfigurationError) as exc:
rc.prepare()
assert str(exc.value) == 'No executable for runner to run'
@patch.dict('os.environ', {'PYTHONPATH': '/python_path_via_environ',
'AWX_LIB_DIRECTORY': '/awx_lib_directory_via_environ'})
def test_prepare():
rc = RunnerConfig('/')
rc.prepare_inventory = Mock()
rc.prepare_env = Mock()
rc.prepare_command = Mock()
rc.ssh_key_data = None
rc.artifact_dir = '/'
rc.env = {}
rc.execution_mode = ExecutionMode.ANSIBLE_PLAYBOOK
rc.playbook = 'main.yaml'
rc.prepare()
assert rc.prepare_inventory.called
assert rc.prepare_env.called
assert rc.prepare_command.called
assert not hasattr(rc, 'ssh_key_path')
assert not hasattr(rc, 'command')
assert rc.env['ANSIBLE_STDOUT_CALLBACK'] == 'awx_display'
assert rc.env['ANSIBLE_RETRY_FILES_ENABLED'] == 'False'
assert rc.env['ANSIBLE_HOST_KEY_CHECKING'] == 'False'
assert rc.env['AWX_ISOLATED_DATA_DIR'] == '/'
assert rc.env['PYTHONPATH'] == '/python_path_via_environ:/awx_lib_directory_via_environ', \
"PYTHONPATH is the union of the env PYTHONPATH and AWX_LIB_DIRECTORY"
del rc.env['PYTHONPATH']
os.environ['PYTHONPATH'] = "/foo/bar/python_path_via_environ"
rc.prepare()
assert rc.env['PYTHONPATH'] == "/foo/bar/python_path_via_environ:/awx_lib_directory_via_environ", \
"PYTHONPATH is the union of the explicit env['PYTHONPATH'] override and AWX_LIB_DIRECTORY"
@patch('ansible_runner.runner_config.open_fifo_write')
def test_prepare_with_ssh_key(open_fifo_write_mock):
rc = RunnerConfig('/')
rc.prepare_inventory = Mock()
rc.prepare_env = Mock()
rc.prepare_command = Mock()
rc.wrap_args_with_ssh_agent = Mock()
rc.ssh_key_data = None
rc.artifact_dir = '/'
rc.env = {}
rc.execution_mode = ExecutionMode.ANSIBLE_PLAYBOOK
rc.playbook = 'main.yaml'
rc.ssh_key_data = '01234567890'
rc.command = 'ansible-playbook'
with patch.dict('os.environ', {'AWX_LIB_DIRECTORY': '/'}):
rc.prepare()
assert rc.ssh_key_path == '/ssh_key_data'
assert rc.wrap_args_with_ssh_agent.called
assert open_fifo_write_mock.called
def test_wrap_args_with_ssh_agent_defaults():
rc = RunnerConfig('/')
res = rc.wrap_args_with_ssh_agent(['ansible-playbook', 'main.yaml'], '/tmp/sshkey')
assert res == [
'ssh-agent',
'sh', '-c',
"trap 'rm -f /tmp/sshkey' EXIT && ssh-add /tmp/sshkey && rm -f /tmp/sshkey && ansible-playbook main.yaml"
]
def test_wrap_args_with_ssh_agent_with_auth():
rc = RunnerConfig('/')
res = rc.wrap_args_with_ssh_agent(['ansible-playbook', 'main.yaml'], '/tmp/sshkey', '/tmp/sshauth')
assert res == [
'ssh-agent', '-a', '/tmp/sshauth',
'sh', '-c',
"trap 'rm -f /tmp/sshkey' EXIT && ssh-add /tmp/sshkey && rm -f /tmp/sshkey && ansible-playbook main.yaml"
]
def test_wrap_args_with_ssh_agent_silent():
rc = RunnerConfig('/')
res = rc.wrap_args_with_ssh_agent(['ansible-playbook', 'main.yaml'], '/tmp/sshkey', silence_ssh_add=True)
assert res == [
'ssh-agent',
'sh', '-c',
"trap 'rm -f /tmp/sshkey' EXIT && ssh-add /tmp/sshkey 2>/dev/null && rm -f /tmp/sshkey && ansible-playbook main.yaml"
]
@patch('ansible_runner.runner_config.RunnerConfig.prepare')
@patch('ansible_runner.interface.sys')
@patch('ansible_runner.utils.subprocess')
@pytest.mark.parametrize('executable_present', [True, False])
def test_process_isolation_executable_not_found(mock_subprocess, mock_sys, mock_prepare, executable_present):
# Mock subprocess.Popen indicates if
# process isolation executable is present
mock_proc = Mock()
mock_proc.returncode=(0 if executable_present else 1)
mock_subprocess.Popen.return_value = mock_proc
kwargs = {'process_isolation': True,
'process_isolation_executable': 'fake_executable'}
init_runner(**kwargs)
if executable_present:
assert not mock_sys.exit.called
else:
assert mock_sys.exit.called
def test_bwrap_process_isolation_defaults():
rc = RunnerConfig('/')
rc.artifact_dir = '/tmp/artifacts'
rc.playbook = 'main.yaml'
rc.command = 'ansible-playbook'
rc.process_isolation = True
rc.process_isolation_executable = 'bwrap'
with patch('os.path.exists') as path_exists:
path_exists.return_value=True
rc.prepare()
assert rc.command == [
'bwrap',
'--die-with-parent',
'--unshare-pid',
'--dev-bind', '/', '/',
'--proc', '/proc',
'--bind', '/', '/',
'--chdir', '/project',
'ansible-playbook', '-i', '/inventory', 'main.yaml',
]
@patch('os.makedirs', return_value=True)
@patch('shutil.copytree', return_value=True)
@patch('tempfile.mkdtemp', return_value="/tmp/dirisolation/foo")
@patch('os.chmod', return_value=True)
@patch('shutil.rmtree', return_value=True)
def test_bwrap_process_isolation_and_directory_isolation(mock_makedirs, mock_copytree, mock_mkdtemp,
mock_chmod, mock_rmtree):
def new_exists(path):
if path == "/project":
return False
return True
rc = RunnerConfig('/')
rc.artifact_dir = '/tmp/artifacts'
rc.directory_isolation_path = '/tmp/dirisolation'
rc.playbook = 'main.yaml'
rc.command = 'ansible-playbook'
rc.process_isolation = True
rc.process_isolation_executable = 'bwrap'
with patch('os.path.exists', new=new_exists):
rc.prepare()
assert rc.command == [
'bwrap',
'--die-with-parent',
'--unshare-pid',
'--dev-bind', '/', '/',
'--proc', '/proc',
'--bind', '/', '/',
'--chdir', os.path.realpath(rc.directory_isolation_path),
'ansible-playbook', '-i', '/inventory', 'main.yaml',
]
def test_process_isolation_settings():
rc = RunnerConfig('/')
rc.artifact_dir = '/tmp/artifacts'
rc.playbook = 'main.yaml'
rc.command = 'ansible-playbook'
rc.process_isolation = True
rc.process_isolation_executable = 'not_bwrap'
rc.process_isolation_hide_paths = ['/home', '/var']
rc.process_isolation_show_paths = ['/usr']
rc.process_isolation_ro_paths = ['/venv']
rc.process_isolation_path = '/tmp'
with patch('os.path.exists') as path_exists:
path_exists.return_value=True
rc.prepare()
assert rc.command[0:8] == [
'not_bwrap',
'--die-with-parent',
'--unshare-pid',
'--dev-bind', '/', '/',
'--proc', '/proc',
]
# hide /home
assert rc.command[8] == '--bind'
assert 'ansible_runner_pi' in rc.command[9]
assert rc.command[10] == os.path.realpath('/home') # needed for Mac
# hide /var
assert rc.command[11] == '--bind'
assert 'ansible_runner_pi' in rc.command[12]
assert rc.command[13] == '/var' or rc.command[13] == '/private/var'
# read-only bind
assert rc.command[14:17] == ['--ro-bind', '/venv', '/venv']
# root bind
assert rc.command[17:20] == ['--bind', '/', '/']
# show /usr
assert rc.command[20:23] == ['--bind', '/usr', '/usr']
# chdir and ansible-playbook command
assert rc.command[23:] == ['--chdir', '/project', 'ansible-playbook', '-i', '/inventory', 'main.yaml']
@patch('os.mkdir', return_value=True)
def test_profiling_plugin_settings(mock_mkdir):
rc = RunnerConfig('/')
rc.playbook = 'main.yaml'
rc.command = 'ansible-playbook'
rc.resource_profiling = True
rc.resource_profiling_base_cgroup = 'ansible-runner'
rc.prepare()
expected_command_start = [
'cgexec',
'--sticky',
'-g',
'cpuacct,memory,pids:ansible-runner/{}'.format(rc.ident),
'ansible-playbook'
]
for index, element in enumerate(expected_command_start):
assert rc.command[index] == element
assert 'main.yaml' in rc.command
assert rc.env['ANSIBLE_CALLBACK_WHITELIST'] == 'cgroup_perf_recap'
assert rc.env['CGROUP_CONTROL_GROUP'] == 'ansible-runner/{}'.format(rc.ident)
assert rc.env['CGROUP_OUTPUT_DIR'] == os.path.normpath(os.path.join(rc.private_data_dir, 'profiling_data'))
assert rc.env['CGROUP_OUTPUT_FORMAT'] == 'json'
assert rc.env['CGROUP_CPU_POLL_INTERVAL'] == '0.25'
assert rc.env['CGROUP_MEMORY_POLL_INTERVAL'] == '0.25'
assert rc.env['CGROUP_PID_POLL_INTERVAL'] == '0.25'
assert rc.env['CGROUP_FILE_PER_TASK'] == 'True'
assert rc.env['CGROUP_WRITE_FILES'] == 'True'
assert rc.env['CGROUP_DISPLAY_RECAP'] == 'False'
@patch('os.mkdir', return_value=True)
def test_profiling_plugin_settings_with_custom_intervals(mock_mkdir):
rc = RunnerConfig('/')
rc.playbook = 'main.yaml'
rc.command = 'ansible-playbook'
rc.resource_profiling = True
rc.resource_profiling_base_cgroup = 'ansible-runner'
rc.resource_profiling_cpu_poll_interval = '.5'
rc.resource_profiling_memory_poll_interval = '.75'
rc.resource_profiling_pid_poll_interval = '1.5'
rc.prepare()
assert rc.env['CGROUP_CPU_POLL_INTERVAL'] == '.5'
assert rc.env['CGROUP_MEMORY_POLL_INTERVAL'] == '.75'
assert rc.env['CGROUP_PID_POLL_INTERVAL'] == '1.5'
def test_container_volume_mounting_with_Z(tmpdir):
rc = RunnerConfig(str(tmpdir))
rc.container_volume_mounts = ['project_path:project_path:Z']
rc.container_name = 'foo'
rc.env = {}
new_args = rc.wrap_args_for_containerization(['ansible-playbook', 'foo.yml'])
assert new_args[0] == 'podman'
for i, entry in enumerate(new_args):
if entry == '-v':
mount = new_args[i + 1]
if mount.endswith(':project_path:Z'):
break
else:
raise Exception('Could not find expected mount, args: {}'.format(new_args))
@pytest.mark.parametrize('container_runtime', ['docker', 'podman'])
def test_containerization_settings(tmpdir, container_runtime):
with patch('ansible_runner.runner_config.RunnerConfig.containerized', new_callable=PropertyMock) as mock_containerized:
rc = RunnerConfig(tmpdir)
rc.ident = 'foo'
rc.playbook = 'main.yaml'
rc.command = 'ansible-playbook'
rc.process_isolation = True
rc.process_isolation_executable=container_runtime
rc.container_image = 'my_container'
rc.container_volume_mounts=['/host1:/container1', 'host2:/container2']
mock_containerized.return_value = True
rc.prepare()
extra_container_args = []
if container_runtime == 'podman':
extra_container_args = ['--quiet']
else:
extra_container_args = ['--user={os.getuid()}']
expected_command_start = [container_runtime, 'run', '--rm', '--tty', '--interactive', '--workdir', '/runner/project'] + \
['-v', '{}:/runner:Z'.format(rc.private_data_dir)] + \
['-v', '/host1:/container1', '-v', 'host2:/container2'] + \
['--env-file', '{}/env.list'.format(rc.artifact_dir)] + \
extra_container_args + \
['--name', 'ansible_runner_foo'] + \
['my_container', 'ansible-playbook', '-i', '/runner/inventory/hosts', 'main.yaml']
for index, element in enumerate(expected_command_start):
if '--user' in element:
assert '--user=' in rc.command[index]
else:
assert rc.command[index] == element
+224
View File
@@ -0,0 +1,224 @@
import json
import shutil
import tempfile
import pytest
from unittest.mock import patch
from ansible_runner.utils import (
isplaybook,
isinventory,
dump_artifacts,
args2cmdline,
sanitize_container_name
)
def test_isplaybook():
for obj in ('foo', {}, {'foo': 'bar'}, True, False, None):
assert isplaybook(obj) is False, obj
for obj in (['foo'], []):
assert isplaybook(obj) is True, obj
def test_isinventory():
for obj in (__file__, {}, {'foo': 'bar'}):
assert isinventory(obj) is True, obj
for obj in ([], ['foo'], True, False, None):
assert isinventory(obj) is False, obj
def test_dump_artifacts_private_data_dir():
data_dir = tempfile.gettempdir()
kwargs = {'private_data_dir': data_dir}
dump_artifacts(kwargs)
assert kwargs['private_data_dir'] == data_dir
kwargs = {'private_data_dir': None}
dump_artifacts(kwargs)
assert kwargs['private_data_dir'].startswith(tempfile.gettempdir())
shutil.rmtree(kwargs['private_data_dir'])
with pytest.raises(ValueError):
data_dir = '/foo'
kwargs = {'private_data_dir': data_dir}
dump_artifacts(kwargs)
def test_dump_artifacts_playbook():
with patch('ansible_runner.utils.dump_artifact') as mock_dump_artifact:
# playbook as a native object
pb = [{'playbook': [{'hosts': 'all'}]}]
kwargs = {'private_data_dir': '/tmp', 'playbook': pb}
dump_artifacts(kwargs)
assert mock_dump_artifact.call_count == 1
data, fp, fn = mock_dump_artifact.call_args[0]
assert data == json.dumps(pb)
assert fp == '/tmp/project'
assert fn == 'main.json'
mock_dump_artifact.reset_mock()
# playbook as a path
pb = 'test.yml'
kwargs = {'private_data_dir': '/tmp', 'playbook': pb}
dump_artifacts(kwargs)
assert mock_dump_artifact.call_count == 0
assert mock_dump_artifact.called is False
mock_dump_artifact.reset_mock()
# invalid playbook structures
for obj in ({'foo': 'bar'}, None, True, False, 'foo', []):
mock_dump_artifact.reset_mock()
kwargs = {'private_data_dir': '/tmp', 'playbook': obj}
dump_artifacts(kwargs)
assert mock_dump_artifact.call_count == 0
assert mock_dump_artifact.called is False
def test_dump_artifacts_roles():
with patch('ansible_runner.utils.dump_artifact') as mock_dump_artifact:
kwargs = dict(private_data_dir="/tmp",
role="test",
playbook=[{'playbook': [{'hosts': 'all'}]}])
dump_artifacts(kwargs)
assert mock_dump_artifact.call_count == 2
data, envpath, fp = mock_dump_artifact.call_args[0]
assert fp == "envvars"
data = json.loads(data)
assert "ANSIBLE_ROLES_PATH" in data
assert data['ANSIBLE_ROLES_PATH'] == "/tmp/roles"
mock_dump_artifact.reset_mock()
kwargs = dict(private_data_dir="/tmp",
role="test",
roles_path="/tmp/altrole",
playbook=[{'playbook': [{'hosts': 'all'}]}])
dump_artifacts(kwargs)
assert mock_dump_artifact.call_count == 2
data, envpath, fp = mock_dump_artifact.call_args[0]
assert fp == "envvars"
data = json.loads(data)
assert "ANSIBLE_ROLES_PATH" in data
assert data['ANSIBLE_ROLES_PATH'] == "/tmp/altrole:/tmp/roles"
def test_dump_artifacts_inventory():
with patch('ansible_runner.utils.dump_artifact') as mock_dump_artifact:
# inventory as a string (INI)
inv = '[all]\nlocalhost'
kwargs = {'private_data_dir': '/tmp', 'inventory': inv}
dump_artifacts(kwargs)
assert mock_dump_artifact.call_count == 1
data, fp, fn = mock_dump_artifact.call_args[0]
assert data == inv
assert fp == '/tmp/inventory'
assert fn == 'hosts'
mock_dump_artifact.reset_mock()
# inventory as a path
inv = '/tmp'
kwargs = {'private_data_dir': '/tmp', 'inventory': inv}
dump_artifacts(kwargs)
assert mock_dump_artifact.call_count == 0
assert mock_dump_artifact.called is False
assert kwargs['inventory'] == inv
mock_dump_artifact.reset_mock()
# inventory as a native object
inv = {'foo': 'bar'}
kwargs = {'private_data_dir': '/tmp', 'inventory': inv}
dump_artifacts(kwargs)
assert mock_dump_artifact.call_count == 1
data, fp, fn = mock_dump_artifact.call_args[0]
assert data == json.dumps(inv)
assert fp == '/tmp/inventory'
assert fn == 'hosts.json'
def test_dump_artifacts_extravars():
with patch('ansible_runner.utils.dump_artifact') as mock_dump_artifact:
extravars = {'foo': 'bar'}
kwargs = {'private_data_dir': '/tmp', 'extravars': extravars}
dump_artifacts(kwargs)
assert mock_dump_artifact.call_count == 1
data, fp, fn = mock_dump_artifact.call_args[0]
assert data == json.dumps(extravars)
assert fp == '/tmp/env'
assert fn == 'extravars'
assert 'extravars' not in kwargs
def test_dump_artifacts_passwords():
with patch('ansible_runner.utils.dump_artifact') as mock_dump_artifact:
passwords = {'foo': 'bar'}
kwargs = {'private_data_dir': '/tmp', 'passwords': passwords}
dump_artifacts(kwargs)
assert mock_dump_artifact.call_count == 1
data, fp, fn = mock_dump_artifact.call_args[0]
assert data == json.dumps(passwords)
assert fp == '/tmp/env'
assert fn == 'passwords'
assert 'passwords' not in kwargs
def test_dump_artifacts_settings():
with patch('ansible_runner.utils.dump_artifact') as mock_dump_artifact:
settings = {'foo': 'bar'}
kwargs = {'private_data_dir': '/tmp', 'settings': settings}
dump_artifacts(kwargs)
assert mock_dump_artifact.call_count == 1
data, fp, fn = mock_dump_artifact.call_args[0]
assert data == json.dumps(settings)
assert fp == '/tmp/env'
assert fn == 'settings'
assert 'settings' not in kwargs
def test_dump_artifacts_ssh_key():
with patch('ansible_runner.utils.dump_artifact') as mock_dump_artifact:
ssh_key = '1234567890'
kwargs = {'private_data_dir': '/tmp', 'ssh_key': ssh_key}
dump_artifacts(kwargs)
assert mock_dump_artifact.call_count == 1
data, fp, fn = mock_dump_artifact.call_args[0]
assert data == ssh_key
assert fp == '/tmp/env'
assert fn == 'ssh_key'
assert 'ssh_key' not in kwargs
def test_dump_artifacts_cmdline():
with patch('ansible_runner.utils.dump_artifact') as mock_dump_artifact:
cmdline = '--tags foo --skip-tags'
kwargs = {'private_data_dir': '/tmp', 'cmdline': cmdline}
dump_artifacts(kwargs)
assert mock_dump_artifact.call_count == 1
data, fp, fn = mock_dump_artifact.call_args[0]
assert data == cmdline
assert fp == '/tmp/env'
assert fn == 'cmdline'
assert 'cmdline' not in kwargs
def test_fifo_write():
pass
def test_args2cmdline():
res = args2cmdline('ansible', '-m', 'setup', 'localhost')
assert res == 'ansible -m setup localhost'
@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):
sanitize_container_name(str(container_name)) == expected_name