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+.
pip install pytest-ansibleVerified import paths — ran on the pinned version, not inferred.
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.
Review and update test assertions to accommodate the new Python object-based result structures and Ansible-style inventory indexing introduced in 2.0.0 and later versions.
Refactor fixtures from `scope=class` to a more appropriate scope (e.g., `module` or `function`) or use alternative patterns for resource setup/teardown within your test suite.
Uninstall `pytest-molecule` and install `pytest-ansible`. Update test configurations to leverage the integrated Molecule scenario testing within `pytest-ansible`.
Ensure your environment uses Python 3.10 or newer and `ansible-core` 2.14 or newer to maintain compatibility and receive full support.
If encountering issues, investigate specific interactions between the two plugins. Consider isolating tests that use `pytest-ansible` from those that use `testinfra` or consult the project's issue tracker for potential workarounds or fixes.
Ensure that your `galaxy.yml` file contains the correct `namespace` and `name` for your collection. Run `pytest` from the collection's root directory, adjacent to the `galaxy.yml` file. If issues persist, try removing `__pycache__` and `.pyc` files.
To resolve this when running `ansible-test units`, you need to explicitly disable the `pytest-ansible` plugin. This can often be done by adding `-p no:pytest_ansible` to the `pytest` command-line arguments.
First, ensure `pytest-ansible` is installed (`pip install pytest-ansible`). For built-in fixtures, ensure your test file is properly recognized by `pytest` (e.g., named `test_*.py` or `*_test.py`). If defining custom fixtures, place them in a `conftest.py` file in the test directory or a parent directory, ensuring `conftest.py` is discoverable. You can run `pytest --fixtures [testpath]` to see available fixtures.
Verify that your inventory file is correctly defined and accessible. Check the `--inventory` and `--host-pattern` arguments for `pytest` or `ansible-playbook` to ensure they match existing hosts and groups in your inventory. Also, examine any `--limit` flags for correct syntax and ensure they don't exclude all desired hosts.