如何用Python unittest库Mock对象值?API测试用例问题求助
解决Mock Redis逻辑触发API 500分支的问题
你的测试用例无法触发目标分支的核心问题是patch的对象错误:cache_purge是test函数内部的局部变量,直接patch它不会对函数内的赋值逻辑产生任何影响。要触发返回500的分支,需要从两个关键逻辑入手:
关键逻辑分析
要进入返回500的分支,必须满足两个条件:
redisconn.exists("url_prefix")返回True,让代码进入缓存清理流程pipeline.execute()返回[0],触发cache_purge != [1]的判断
修正后的测试用例
根据你的代码结构,这里提供两种可行的测试方案:
方案1:直接Mock pipeline.execute的返回值
from unittest.mock import patch @patch('parentmodule.module.views.redisconn.exists', return_value=True) @patch('parentmodule.module.views.pipeline.execute', return_value=[0]) def test_cacheRoles_mock_failure(mock_execute, mock_exists, fetch_eid, client): data = { "eid": fetch_eid["eid"] } resp = client.get( "admin/cacheRoles", query_string=data, headers=fetch_eid["headers"] ) assert resp.status_code == 500
方案2:Mock Redis Pipeline实例(更贴近真实调用链)
如果pipeline是通过redisconn.pipeline()创建的,推荐用这种方式模拟完整调用流程:
from unittest.mock import patch, MagicMock @patch('parentmodule.module.views.redisconn.exists', return_value=True) @patch('parentmodule.module.views.redisconn.pipeline') def test_cacheRoles_mock_failure(mock_pipeline, mock_exists, fetch_eid, client): # 创建Mock Pipeline实例并配置execute返回值 mock_pipeline_obj = MagicMock() mock_pipeline_obj.execute.return_value = [0] mock_pipeline.return_value = mock_pipeline_obj data = { "eid": fetch_eid["eid"] } resp = client.get( "admin/cacheRoles", query_string=data, headers=fetch_eid["headers"] ) assert resp.status_code == 500 # 可选:验证pipeline.delete是否被正确调用 mock_pipeline_obj.delete.assert_called_with("url_prefix")
为什么原测试用例无效?
你原代码中cache_purge = pipeline.execute()是函数内部的局部变量赋值,而你patch的是parentmodule.module.views.test.cache_purge——这是函数对象的一个属性,和函数内部的局部变量完全无关,所以你的mock值根本不会被代码读取到。
内容的提问来源于stack exchange,提问作者Vyshnavi
相关产品推荐
相关产品推荐

