pytest-ansible

26.4.0 · active · verified Sun Apr 12

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

Install

Imports

Quickstart

This quickstart demonstrates how to write a basic pytest test using the `ansible_adhoc` fixture provided by `pytest-ansible`. It shows how to execute an Ansible module (like `setup` or `ping`) against a local host and assert its results. A minimal Ansible inventory file (`hosts.ini`) is required for the tests to run successfully, which can be specified via the `--ansible-inventory` pytest option.

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`

view raw JSON →