使用 pytest-ansible 完成模块 UT 并输出覆盖率。
解读
国内一线互联网、金融云及运营商的自动化平台,普遍要求“代码即基础设施”必须可测试、可度量。
面试官抛出该题,核心想验证三件事:
- 你是否真的把 Ansible 模块当成 Python 包来写,而不是堆 Shell 脚本;
- 能否用 pytest-ansible 的 ansible_adhoc、mocker、capsys 等 fixture 在本地 CI(GitLab-CI / GitHub Actions)里快速跑 UT;
- 是否知道怎么把覆盖率落到 行覆盖率 ≥ 80 % 的硬指标,并生成 Cobertura XML 给 SonarQube 门禁。
现场节奏很快,往往要求 5 分钟内给出目录结构、核心用例、命令行、覆盖率报告截图,否则直接挂。
知识点
- pytest-ansible 插件加载顺序:pytest_ansible→pytest_collection→fixtures(ansible_adhoc、ansible_module、ansible_facts)
- 模块入口规范:AnsibleModule 构造参数 argument_spec、supports_check_mode、mutually_exclusive
- 单元测试隔离:monkeypatch.setattr 打桩 AnsibleModule.run_command 或 module.fail_json
- 覆盖率统计范围:--cov=plugins/modules 只统计业务代码,排除 test/、molecule/
- 国内 CI 门禁:GitLab-CI 的 coverage: '/TOTAL.*\s+(\d+%)/' 正则解析,合并请求需 ≥ 80 %
- 坑点:模块里如果用了 from ansible.module_utils.basic import *》,会被 coverage 误判为未执行,需要在 .coveragerc 里 exclude_lines = pragma: no cover, from ansible.module_utils
答案
- 目录结构(符合国内基建规范)
my_collection/
├── plugins/
│ └── modules/
│ └── nginx_config.py
├── tests/
│ └── unit/
│ └── test_nginx_config.py
├── .coveragerc
├── pytest.ini
└── requirements-dev.txt
- 被测模块片段(plugins/modules/nginx_config.py)
from ansible.module_utils.basic import AnsibleModule
def main():
args = dict(
path=dict(type='str', required=True),
state=dict(type='str', choices=['present', 'absent'], default='present')
)
module = AnsibleModule(argument_spec=args, supports_check_mode=True)
path = module.params['path']
if module.check_mode:
module.exit_json(changed=True, msg="would create {}".format(path))
# 真实逻辑省略
module.exit_json(changed=True, msg="{} created".format(path))
if __name__ == '__main__':
main()
- 单元测试(tests/unit/test_nginx_config.py)
import json
import pytest
from unittest.mock import patch
from ansible.module_utils import basic
from plugins.modules import nginx_config
@pytest.fixture
def mock_module():
with patch.object(basic.AnsibleModule, 'run_command') as rc:
rc.return_value = (0, '', '')
yield basic.AnsibleModule
def test_present_check_mode(mock_module, capsys):
"""check_mode 下应返回 changed=True"""
test_args = ['nginx_config.py', 'path=/etc/nginx/conf.d/a.conf', 'state=present', '_ansible_check_mode=True']
with patch('sys.argv', test_args):
nginx_config.main()
out, err = capsys.readouterr()
result = json.loads(out)
assert result['changed'] is True
assert 'would create' in result['msg']
- 运行与覆盖率(本地 & CI 同一套命令)
python -m venv venv && source venv/bin/activate
pip install -r requirements-dev.txt # 包含 pytest-ansible>=2.2.4, pytest-cov, coverage[toml]
pytest tests/unit \
--ansible-inventory=inventories/test.ini \
--cov=plugins/modules \
--cov-report=term-missing \
--cov-report=xml \
--cov-fail-under=80 \
-v
终端输出:
plugins/modules/nginx_config.py 35 7 80% 46-52
TOTAL 35 7 80%
同时生成 coverage.xml,可被 SonarQube 直接读取。
- GitLab-CI 片段(国内镜像加速)
unit-test:
stage: test
image: registry.cn-hangzhou.aliyuncs.com/acs/ansible-python:3.9
script:
- pip install -r requirements-dev.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
- pytest tests/unit --cov=plugins/modules --cov-report=xml --cov-fail-under=80
coverage: '/TOTAL.*\s+(\d+%)/'
artifacts:
reports:
coverage_report:
coverage_format: cobertura
path: coverage.xml
拓展思考
- 如果模块里调了 fetch_url 或 ansible_collections.community.crypto.openssl_privatekey,需要写 requests_mock 或 ansible.module_utils.urls.fetch_url 的 side_effect 桩,否则覆盖率会掉。
- 国内银行信创环境要求 SM2/SM3 国密算法,模块里一旦引入 gmssl,需在 tox.ini 里加 py39-sm 因子,并 mock 掉硬件加密卡调用,保证 UT 在 x86 容器里也能跑到 80 %。
- 当集合(collection)越来越大,用 pytest-xdist 做并发,--cov-append 合并覆盖率,10 分钟跑完 800 条用例,是二线云厂商的及格线。