pytest-ansible
The `pytest-ansible` plugin integrates pytest with Ansible, enabling efficient testing of Ansible-related tasks and scenarios. It facilitates unit testing for Ansible collections, integrates with Molecule scenarios, and allows direct Ansible integration within pytest tests. It supports Python 3.10+ and Ansible-core 2.14+.
Warnings
- breaking Version 2.0.0 introduced major changes to allow Ansible-style inventory indexing and improved results processing, shifting from dictionaries to Python objects. Tests written for older versions might require updates to handle these changes in result structures.
- deprecated Version 1.4.0 started raising `DeprecationWarnings` for `scope=class` fixtures. While they might still function, it's recommended to migrate away from them for future compatibility.
- gotcha The `pytest-molecule` plugin's functionality has been merged into `pytest-ansible`. Users of `pytest-molecule` should migrate to `pytest-ansible` for ongoing support and future updates.
- gotcha `pytest-ansible` only guarantees support for actively maintained versions of Python (>=3.10) and `ansible-core` (>=2.14). Using older versions may lead to unexpected behavior or lack of support.
- gotcha There are reported conflicts when `pytest-ansible` is used alongside `testinfra`. This can lead to unexpected test failures or behavior.
Install
-
pip install pytest-ansible
Imports
- ansible_adhoc
import pytest # Fixtures like ansible_adhoc are made available by the plugin
Quickstart
import pytest
import os
# --- Required Setup: inventory file (e.g., hosts.ini) ---
# [local]
# localhost ansible_connection=local
# ---------------------------------------------------------
def test_local_setup_module(ansible_adhoc):
"""
Tests the 'setup' module on 'localhost' using the ansible_adhoc fixture.
Requires an Ansible inventory file (e.g., hosts.ini) in the current
working directory or specified via `--ansible-inventory` when running pytest.
"""
# Run the 'setup' module on 'localhost'
contacted = ansible_adhoc("setup", host_pattern="localhost")
# Assert that 'localhost' was contacted and 'changed' is not in its result
assert 'localhost' in contacted
assert 'changed' not in contacted['localhost']
assert 'ansible_facts' in contacted['localhost']
def test_ansible_ping_module(ansible_adhoc):
"""
Tests the 'ping' module on 'localhost'.
"""
contacted = ansible_adhoc("ping", host_pattern="localhost")
assert 'localhost' in contacted
assert contacted['localhost']['ping'] == 'pong'
# To run this example:
# 1. Save the above content as 'test_ansible_module.py'.
# 2. Create a file named 'hosts.ini' in the same directory with the content:
# [local]
# localhost ansible_connection=local
# 3. Execute pytest from your terminal: `pytest --ansible-inventory=hosts.ini test_ansible_module.py`