如何在FastAPI中Mock python-jenkins调用以进行pytest测试?
测试FastAPI接口中Mock Jenkins对象的方案
核心思路
用Python标准库unittest.mock或pytest-mock插件Mock jenkins.Jenkins类及其方法,绕过真实Jenkins实例调用,按需模拟异常或指定返回数据。
测试第一个接口:触发JenkinsException
针对/jenkins_data接口,Mock jenkins.Jenkins的get_nodes方法,让它抛出JenkinsException,验证接口返回空列表。
测试代码示例
from fastapi.testclient import TestClient import jenkins from your_app_module import app # 替换为你的FastAPI应用模块名 client = TestClient(app) def test_get_jenkins_nodes_exception(mocker): # Mock Jenkins类初始化,避免真实连接 mock_jenkins = mocker.patch("your_app_module.jenkins.Jenkins") # 让get_nodes方法抛出JenkinsException mock_jenkins.return_value.get_nodes.side_effect = jenkins.JenkinsException("Mocked error") response = client.get("/jenkins_data") assert response.status_code == 200 assert response.json() == []
注意:替换
your_app_module为实际定义接口的模块名,Mock路径要和接口中导入Jenkins的路径完全一致。
测试第二个接口:Mock currentExecutable的值
针对/job/{node_name}接口,Mock get_node_info方法,返回包含指定currentExecutable的模拟数据,覆盖两种业务场景。
场景1:模拟有运行中的任务
def test_get_current_job_running(mocker): mock_jenkins = mocker.patch("your_app_module.jenkins.Jenkins") # 构造模拟节点信息 mock_node_info = { "executors": [ { "currentExecutable": { "displayName": "Test Build #456" } } ] } mock_jenkins.return_value.get_node_info.return_value = mock_node_info response = client.get("/job/test-node") assert response.status_code == 200 assert response.json() == "Test Build #456"
场景2:模拟无运行中的任务
def test_get_current_job_not_running(mocker): mock_jenkins = mocker.patch("your_app_module.jenkins.Jenkins") # 构造无任务的节点信息 mock_node_info = { "executors": [ { "currentExecutable": None } ] } mock_jenkins.return_value.get_node_info.return_value = mock_node_info response = client.get("/job/test-node") assert response.status_code == 200 assert response.json() == "No Jobs Running"
关键注意事项
- Mock路径必须准确:要Mock接口代码中实际引用
jenkins.Jenkins的路径,比如接口里用import jenkins则Mockyour_app_module.jenkins.Jenkins,用from jenkins import Jenkins则Mockyour_app_module.Jenkins。 - 用TestClient模拟请求:FastAPI官方的
TestClient可以模拟HTTP请求,直接验证接口的响应状态和返回值。 - pytest-mock简化操作:
pytest-mock封装了unittest.mock,通过mockerfixture能快速创建和配置Mock对象。
内容的提问来源于stack exchange,提问作者Mike Driscoll
相关产品推荐
相关产品推荐

