提问人:Aastha Jha 提问时间:11/2/2023 更新时间:11/2/2023 访问量:47
TypeError:对象 AsyncMock 不能在“await”表达式中使用
TypeError: object AsyncMock can't be used in 'await' expression
问:
我为一个函数创建了一个pytest,但是当我尝试运行它时出现以下错误:
> return await cntrl.get_function_by_topic_by_method(url, method, *args, query_params=query_params, action=action, **kwargs)
E TypeError: object AsyncMock can't be used in 'await' expression
我对为什么会发生这种情况感到困惑,因为只能等待异步函数,并且由于我使用了 AsyncMock(),它应该可以工作。
该函数如下所述,它位于:app/folder_market/controller/DQR.py
import traceback
import logging
import httpx
from .utils.ApiHelper import ApiHelper
logger = logging.getLogger(__name__)
class DQR(object):
def __init__(self, config, *args, **kwargs):
self.methods = ['GET', 'PUT']
self.config = config
self.args = args
self.kwargs = kwargs
self.cai_usage = config['cai_usage']
self.topic = "DQR"
async def retrieve_something(self, *args, query_params=None, **kwargs):
try:
action = 'retrievSomething'
cntrl = ApiHelper(self.config)
url, method = cntrl.get_url_and_method(self.topic, action=action)
return await cntrl.get_function_by_topic_by_method(url, method, *args, query_params=query_params, action=action, **kwargs)
except (httpx.RequestError, httpx.TimeoutException, httpx.ConnectError, httpx.NetworkError, httpx.TransportError) as error:
# Log the full exception traceback for debugging
traceback.print_exc()
msg = "Error in " + __name__ + ", retrieve_data_collection_requests: " + str(error)
print(msg)
logger.error(msg)
函数的测试位于:app/tests/controller/test_DQR.py
from unittest.mock import AsyncMock
import os
import sys
import pytest
sys.path.insert(0, os.path.abspath("."))
from folder_market.controller.DQR import DQR
from folder_market.utils.ConfigHelper import load_config
from folder_market.controller.utils.ConfigHelper import config_validator
from pytest_mock import MockerFixture
config = load_config('marketplace/config.yaml')
config_validator(config)
instance_data_collection = DQR(config=config)
# Helper function to assert response data
def assert_response_data(response_data):
assert len(response_data['objects']) > 1
assert all(item.get('id') for item in response_data['objects'])
@pytest.mark.asyncio
async def test_retrieve_something_param_id_success(mocker: MockerFixture):
# Create a mock of the 'ApiHelper' instance
mock_api_helper = mocker.patch(
"folder_market.controller.DQR.ApiHelper"
)
api_helper_instance = mock_api_helper.return_value
api_helper_instance.get_url_and_method.return_value = ("https://mocked-api-url", "GET")
expected_response_data = {
"processingTime": 486,
"offset": 0,
"limit": 50,
"totalCount": 1,
"objects": [
{
"id": "407225ad-7870-4678-8169-43829d80c4bc",
"refId": "d90574a4-417d-4c34-b9f1-4f2da5fc997a"
}]}
mock_http_client = AsyncMock()
mock_http_client.get.return_value.status_code = 200
mock_http_client.get.return_value.json.return_value = expected_response_data
api_helper_instance.get_function_by_topic_by_method.return_value = mock_http_client
requestId = "407225ad-7870-4678-8169-43829d80c4bc"
get_data_collection_request = await instance_data_collection.retrieve_data_collection_requests(query_params={"requestIds": requestId})
assert get_data_collection_request.status_code == 200
response_data = get_data_collection_request.json()
assert_response_data(response_data)
assert response_data['objects'][0]['id'] == requestId
答: 暂无答案
评论