我试图模拟一个正在fastapi端点内部调用的异步函数,但我得到了运行时警告,协程_从未等待过。
src.api.endpoint.py
from ..create_utils import helper_function
Router = APIRouter()
@api_route(
Router.post,
'/endpoint',
)
async def endpoint(
inputs: InputModel,
db,
caller,
):
return await helper_function(inputs, db, caller)
tests.api.endpoint.py
import asyncio
import pytest
import json
import unittest
from unittest.mock import AsyncMock, Mock
@pytest.fixture(scope="function")
async def mock_helper_function(mocker):
async_mock = AsyncMock()
sup = mocker.patch('src.api.endpoint.helper_function',
side_effect=async_mock) #where func is being imported not defined
return async_mock
@pytest.fixture(scope="module")
def event_loop():
return asyncio.get_event_loop()
@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) #call to endpoint
assert response.status_code == 200
await mock_assets_create.assert_called()
运行此测试将导致以下错误
RuntimeWarning: coroutine 'AsyncMockMixin._execute_mock_call' was never awaited
规格python: 3.9
似乎这个答案应该解决我的问题,但没有https://stackoverflow.com/a/60094385
我已经在补丁模拟上运行了asyncio.iscoroutinefunction()
,并确认它返回true。在夹具和测试中。
我也遵循了这篇文章的指导https://stackoverflow.com/a/74012507
@pytest.fixture(scope="function")
async def mock_helper_function(mocker):
async_mock = AsyncMock()
async_mock.return_value = None
sup = mocker.patch('src.api.endpoint.helper_function',
side_effect=async_mock) #where func is being imported not defined
return async_mock