入门¶
Ansible 集合的单元测试¶
pytest-ansible 插件允许仅使用 pytest 运行 Ansible 集合的单元测试。它提供了一种专注于测试单个 Ansible 模块的方法。使用此插件,您可以编写和执行专门针对 Ansible 模块的单元测试,确保模块代码的准确性和可靠性。这对于验证模块行为的独立性特别有用。
要使用 pytest-ansible,请按照以下步骤操作
- 使用 [pip] 安装插件
-
确保已安装 Python 3.10 或更高版本、ansible-core 和 pytest。
-
根据您首选的目录结构,您可以将集合克隆到相应的路径。
-
集合树方法:首选方法是将正在开发的集合克隆到其正确的集合树路径。这消除了对任何符号链接的需求,并且可以将其他正在开发的集合克隆到相同的树结构中。
注意:在集合目录的根目录(与集合的
galaxy.yml文件相邻)中运行pytest。 -
浅层树方法:
备注
- 在集合目录的根目录(与集合的
galaxy.yml文件相邻)中运行pytest。 - 将在存储库目录中创建一个集合目录,并将集合内容链接到其中。
- 在集合目录的根目录(与集合的
-
使用 pytest 执行单元测试:
pytest tests
帮助¶
可以将以下内容添加到集合的 pyproject.toml 文件中,以限制警告并设置集合测试的默认路径
[tool.pytest.ini_options]
testpaths = [
"tests",
]
filterwarnings = [
'ignore:AnsibleCollectionFinder has already been configured',
]
galaxy.yml 文件中的信息用于构建 collections 目录结构并链接内容。galaxy.yml 文件应反映正确的集合命名空间和名称。
一种在不运行测试的情况下检测问题的方法是运行
可能会看到以下错误
- 检查
galaxy.yml文件中是否具有准确的命名空间和名称 - 确保从集合的根目录(与
galaxy.yml相邻)运行pytest
Molecule 场景集成¶
此功能有助于使用 pytest 运行 Molecule scenarios。它允许 pytest 发现代码库中的所有 molecule.yml 文件并将其作为 pytest 测试运行。它允许您将 Molecule 场景作为 pytest 测试套件的一部分,从而允许您在不同的场景和环境中彻底测试您的 Ansible 角色和剧本。
使用 pytest 运行 molecule 场景¶
如果安装了 molecule,则可以使用两种不同的方法测试 Molecule 场景。
推荐方法
将 test_integration.py 文件添加到 Ansible 集合的 tests/integration 目录中
"""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
molecule_scenario fixture 提供在集合的 extensions/molecule 目录以及集合中的其他目录中发现的参数化 molecule 场景。
每个场景都将运行 molecule test -s <scenario>,并且 test() 调用将返回已完成的子进程。