gpt4 book ai didi

python - 如何在异步单元测试中模拟方法?

转载 作者:行者123 更新时间:2023-12-04 16:46:07 37 4
gpt4 key购买 nike

我有一个名为 database.py 的类,其中有一个名为 generate_token() 的函数。
我想模拟它并返回一个固定值 321 .这样我就可以看到调用了该方法并返回了返回值。
我如何 mock 它?这是我尝试过的。

@pytest.mark.asyncio
async def test_successful_register_returns_device_token(monkeypatch):
async def mock_generate_token():
return "321"

m = AsyncMock(mock_generate_token)
m.return_value = "321"
async with AsyncClient(app=app, base_url="http://127.0.0.1") as ac:
monkeypatch.setattr(database, "generate_token", m)
response = await ac.post(
"/register/",
headers={},
json={},
)
assert response.status_code == 201
assert "device_token" in response.json()
assert response.json()["device_token"] == "321"

最佳答案

它实际上比我想象的要简单得多,来自 from unittest.mock import patch 的普通@patch足够了。它识别异步方法并自动注入(inject) AsyncMock。

@pytest.mark.asyncio
@patch("service.auth_service.AuthService.generate_token")
async def test_successful_register_returns_device_token(self, mock_token):
mock_token.return_value = "321"
async with AsyncClient(app=app, base_url="http://testserver") as ac:
response = await ac.post(
"/register/",
headers={},
json={},
)
assert response.status_code == 201
assert "device_token" in response.json()
assert response.json()["device_token"] == "321"

关于python - 如何在异步单元测试中模拟方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66037643/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com