FastAPI端点异步函数Mock测试遇RuntimeWarning问题求助
解决Mock异步函数引发的RuntimeWarning问题
问题原因分析
你的代码存在两处关键错误导致警告出现:
- Mock fixture中错误使用
side_effect赋值AsyncMock实例,引发未被await的协程对象残留 - 测试用例中对同步断言方法误用
await,同时存在变量名笔误
修正步骤
1. 修复Mock Fixture
无需给side_effect赋值,直接将目标函数替换为AsyncMock实例即可,同时去掉fixture的async修饰符(patch操作是同步的):
@pytest.fixture(scope="function") def mock_helper_function(mocker): async_mock = AsyncMock() # 直接替换目标函数为AsyncMock实例,不需要side_effect mocker.patch('src.api.endpoint.helper_function', new=async_mock) return async_mock
2. 修正测试用例中的断言
- 修正变量名笔误:
mock_assets_create应为mock_helper_function assert_called()是同步方法,不能用await修饰
修改后的测试用例:
@pytest.mark.parametrize( 'attributes', [('CHECKING_ASSET_ATTRIBUTES')] ) @pytest.mark.asyncio async def test_endpoint_helper_func(api, attributes, borrower_ids, mock_helper_function): caller = 'unauthenticated-user' owners = [borrower_ids[caller]] response = await api.response(owners, [attributes], caller) # 调用端点 assert response.status_code == 200 # 去掉await,修正变量名 mock_helper_function.assert_called()
3. 可选:设置Mock返回值
如果需要让mock返回特定结果,可在fixture或测试用例中配置:
# 在fixture中设置 async_mock.return_value = {"status": "success"} # 或在测试用例中设置 mock_helper_function.return_value = {"status": "success"}
错误根源说明
当你给side_effect赋值为AsyncMock实例时,每次调用helper_function都会触发side_effect,返回async_mock()生成的未被await的协程对象,这直接触发了RuntimeWarning。而直接用new=async_mock替换目标函数,AsyncMock会正确处理异步调用的await逻辑,不会产生未被处理的协程对象。
内容的提问来源于stack exchange,提问作者pjr4lph
相关产品推荐
相关产品推荐

