跳转至内容

测试集合内面向用户的角色

Molecule

要设置 molecule,请在您的集合中创建一个名为 extensions 的新目录,然后在该目录中运行molecule init scenario以创建默认场景。

mkdir extensions
cd extensions
molecule init scenario

更新 molecule.yml 以了解集合路径。

provisioner:
  name: ansible
  config_options:
    defaults:
      collections_path: ${ANSIBLE_COLLECTIONS_PATH}

并在 shell 中设置集合路径。

export ANSIBLE_COLLECTIONS_PATH=/home/user/working/collections

请注意,这应该是根collections目录,而不是其中的ansible_collections目录。我们将此设置为环境变量,以便以后可以移动集合而无需更新集合内部的硬编码目录。

最后,更新 converge.yml 以包含来自您集合的角色

---
- name: Include a role from a collection
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Testing role
      ansible.builtin.include_role:
        name: foo.bar.my_role
        tasks_from: main.yml

或剧本

---
- name: Include a playbook from a collection
  ansible.builtin.import_playbook: foo.bar.my_playbook

这告诉 molecule 测试时要运行什么。现在您可以使用molecule test运行它。

pytest-ansible

通过向 tests/integration 添加特殊测试,您可以使用 pytest-ansible 将您的 molecule 测试与单元测试一起运行。

"""Tests for molecule scenarios."""
from __future__ import absolute_import, division, print_function

from pytest_ansible.molecule import MoleculeScenario


def test_integration(molecule_scenario: MoleculeScenario) -> None:
    """Run molecule for each scenario.

    :param molecule_scenario: The molecule scenario object
    """
    proc = molecule_scenario.test()
    assert proc.returncode == 0

调用 pytest 现在将您的 molecule 场景作为 pytest 作业运行。

请参考pytest-ansible 文档以查看更多选项。

tox-ansible

tox-ansible 自动在许多不同的 Python 和 Ansible 版本上运行您的 pytest 测试。

首先,在您的集合根目录中创建一个空的 tox-ansible.ini 文件。

touch tox-ansible.ini

这将是 tox-ansible 的配置文件。我们总是从空文件开始,以避免无意中覆盖 tox-ansible 环境配置。

列出生成的运行环境
tox list --ansible -c tox-ansible.ini
default environments:
...
integration-py3.11-2.14      -> Integration tests using ansible-core 2.16 and python 3.12
integration-py3.11-devel     -> Integration tests using ansible-core devel and python 3.12
integration-py3.11-milestone -> Integration tests using ansible-core milestone and python 3.12
...
sanity-py3.11-2.14           -> Sanity tests using ansible-core 2.16 and python 3.12
sanity-py3.11-devel          -> Sanity tests using ansible-core devel and python 3.12
sanity-py3.11-milestone      -> Sanity tests using ansible-core milestone and python 3.12
...
unit-py3.11-2.14             -> Unit tests using ansible-core 2.16 and python 3.12
unit-py3.11-devel            -> Unit tests using ansible-core devel and python 3.12
unit-py3.11-milestone        -> Unit tests using ansible-core milestone and python 3.12

这仅限于支持的组合,因此测试可能在 Python 3.8 与ansible-core 2.12 一起运行,但在ansible-core 2.14 中则不行。可以通过配置文件配置要跳过的 ansible-core 版本。

tox-ansible.ini
[ansible]
skip =
    2.9
    devel

这将避免使用 ansible-core 2.9 或 devel 运行测试。

请参考tox-ansible 文档以查看更多选项。