|
| 1 | +import os |
| 2 | + |
| 3 | +import ansible_runner |
| 4 | +import pytest |
| 5 | +import py.path # type: ignore |
| 6 | +import yaml |
| 7 | + |
| 8 | + |
| 9 | +TEST_PLAYBOOKS_PATH = py.path.local(__file__).realpath() / '..' / 'test_playbooks' |
| 10 | + |
| 11 | + |
| 12 | +def find_all_test_playbooks(): |
| 13 | + for playbook in TEST_PLAYBOOKS_PATH.listdir(sort=True): |
| 14 | + playbook = playbook.basename |
| 15 | + if playbook.endswith('.yml'): |
| 16 | + yield playbook.replace('.yml', '') |
| 17 | + |
| 18 | + |
| 19 | +TEST_PLAYBOOKS = list(find_all_test_playbooks()) |
| 20 | + |
| 21 | + |
| 22 | +def pytest_addoption(parser): |
| 23 | + parser.addoption( |
| 24 | + "--testcase", |
| 25 | + action="store", |
| 26 | + default="", |
| 27 | + help="testcase to run", |
| 28 | + ) |
| 29 | + |
| 30 | + |
| 31 | +@pytest.fixture |
| 32 | +def testcase(request): |
| 33 | + return request.config.getoption('testcase') |
| 34 | + |
| 35 | + |
| 36 | +def get_phpipam_url(): |
| 37 | + server_yml = py.path.local(__file__).realpath() / '..' / 'test_playbooks/vars/server.yml' |
| 38 | + with open(server_yml.strpath) as server_yml_file: |
| 39 | + server_yml_content = yaml.safe_load(server_yml_file) |
| 40 | + |
| 41 | + return server_yml_content['phpipam_server_url'] |
| 42 | + |
| 43 | + |
| 44 | +def run_playbook(module, extra_vars=None, limit=None, inventory=None, check_mode=False, extra_env=None): |
| 45 | + # Assemble parameters for playbook call |
| 46 | + os.environ['ANSIBLE_CONFIG'] = os.path.join(os.getcwd(), 'ansible.cfg') |
| 47 | + if extra_env is not None: |
| 48 | + os.environ.update(extra_env) |
| 49 | + kwargs = {} |
| 50 | + kwargs['playbook'] = os.path.join(os.getcwd(), 'tests', 'test_playbooks', '{}.yml'.format(module)) |
| 51 | + if inventory is None: |
| 52 | + inventory = os.path.join(os.getcwd(), 'tests', 'inventory', 'hosts') |
| 53 | + kwargs['inventory'] = inventory |
| 54 | + kwargs['verbosity'] = 4 |
| 55 | + if extra_vars: |
| 56 | + kwargs['extravars'] = extra_vars |
| 57 | + if limit: |
| 58 | + kwargs['limit'] = limit |
| 59 | + if check_mode: |
| 60 | + kwargs['cmdline'] = "--check" |
| 61 | + return ansible_runner.run(**kwargs) |
0 commit comments