我使用 unittest.mock 為我的 python 代碼構建測驗。我有一個我正在嘗試測驗的方法,它包含對另一個函式的異步呼叫。我想修補那個異步呼叫,這樣我就可以讓 Mock 回傳一個測驗值asset id,而不是實際呼叫異步方法。我已經嘗試了很多我在網上找到的東西,但到目前為止都沒有奏效。
下面的簡化示例:
測驗.py
import pytest
from app.create.creations import generate_new_asset
from app.fakeapi.utils import create_asset
from unittest.mock import Mock, patch
@patch("app.fakeapi.utils.create_asset")
@pytest.mark.anyio
async def test_generate_new_asset(mock_create):
mock_create.return_value = 12345678
await generate_new_asset()
...
創作.py
from app.fakeapi.utils import create_asset
...
async def generate_new_asset()
...
# When I run tests this does not return the 12345678 value, but actually calls the `create_asset` method.
return await create_asset(...)
uj5u.com熱心網友回復:
測驗異步代碼有點棘手。如果您使用的是python3.8或更高版本AsyncMock可用。
注意:它僅適用于Python > 3.8
我認為在您的情況下缺少事件回圈。這是應該作業的代碼,您可能需要做一些調整。您可能還需要安裝pytest-mock. 將它作為夾具將允許您模擬不同的值來測驗不同的場景。
import asyncio
from unittest.mock import AsyncMock, Mock
@pytest.fixture(scope="module")
def mock_create_asset(mocker):
async_mock = AsyncMock()
mocker.patch('app.fakeapi.utils.create_asset', side_effect=async_mock)
return async_mock
@pytest.fixture(scope="module")
def event_loop():
return asyncio.get_event_loop()
@pytest.mark.asyncio
async def test_generate_new_asset(mock_create_asset):
mock_create_asset.return_value = 12345678
await generate_new_asset()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/513962.html
標籤:Python单元测试嘲弄
