You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Sanity与Pytest对Ansible集合开展单元测试及连接测试

用Sanity测试与Pytest验证Ansible连接的实操方法

一、Sanity测试:基础连接合规性校验

Sanity测试主要聚焦Ansible集合的语法、结构合规性,同时可嵌入基础连接配置的校验逻辑:

  • 先确保集合目录结构符合Ansible规范,在集合根目录执行Sanity测试命令:
    ansible-test sanity --docker default
  • 自定义连接配置检查:在集合的tests/sanity/custom目录下编写Python脚本,校验inventory文件中目标主机的连接参数(如ansible_host、ansible_user、ansible_ssh_private_key_file)是否齐全、格式合法,避免因配置缺失导致连接失败。
  • 借助validate-modules检查项:确保角色中调用的模块(比如ping)参数格式正确,排除模块使用错误引发的连接问题。

二、Pytest:Ansible连接单元测试

结合pytest-ansible插件可完成真实或模拟环境下的连接测试:

  1. 安装依赖:
    pip install pytest pytest-ansible
  2. 编写测试用例(放在集合tests/unit目录下,示例命名test_connection.py):
    import pytest
    
    def test_host_connectivity(host):
        # 用ping模块验证实际连接状态
        ping_result = host.ping()
        assert ping_result is True, "Ansible无法与目标主机建立连接"
    
    def test_connection_vars(host):
        # 校验目标主机的连接变量配置
        target_user = host.ansible.get_variables()['ansible_user']
        assert target_user == 'expected_user', "连接用户配置不符合预期"
    
  3. 运行测试:
    • 真实环境测试:确保inventory文件指向测试虚拟机,执行命令:
      pytest tests/unit/test_connection.py --inventory=inventory.ini
    • 模拟环境测试(无需真实主机):用mock功能模拟主机响应,避免依赖真实环境:
      def test_mocked_ping(mocker):
          mock_ping_module = mocker.patch('ansible.modules.ping.PingModule.run')
          mock_ping_module.return_value = {'ping': 'pong'}
          assert mock_ping_module.called, "模拟ping模块未被调用"
      
  4. 角色关联测试:在测试中先验证连接正常,再执行角色任务,确保角色运行的基础连接环境有效。

三、关键注意事项

  • Sanity测试是静态合规检查,无法替代实际连接测试,两者结合才能覆盖更多场景。
  • 真实环境测试务必使用专用测试虚拟机,避免影响生产环境。
  • 可将测试命令集成到CI/CD流程,每次代码提交自动运行测试,保障连接逻辑稳定性。

内容的提问来源于stack exchange,提问作者Mahakaal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 16:36:22