Python 3.x “如何嘲笑”;与“异步”;声明?
我试图为一个使用“async with”语句的方法编写测试(在本例中是aioredis的连接池),我想模拟到redis的连接,但我很难弄清楚如何进行 以下是我目前掌握的情况:Python 3.x “如何嘲笑”;与“异步”;声明?,python-3.x,mocking,pytest,python-asyncio,Python 3.x,Mocking,Pytest,Python Asyncio,我试图为一个使用“async with”语句的方法编写测试(在本例中是aioredis的连接池),我想模拟到redis的连接,但我很难弄清楚如何进行 以下是我目前掌握的情况: from asyncio import Future from unittest.mock import MagicMock import pytest # The thing i'm trying to test async def set_value(redis, value): # Do things
from asyncio import Future
from unittest.mock import MagicMock
import pytest
# The thing i'm trying to test
async def set_value(redis, value):
# Do things
async with redis.get() as conn:
await conn.set("key", value)
#My Mock classes
class MockRedis():
def get(self):
return MockAsyncPool()
class MockAsyncPool(MagicMock):
async def __aenter__(self):
conn = MagicMock()
f = Future()
f.set_result(True)
conn.set = MagicMock(return_value=f)
return conn
def __aexit__(self, exc_type, exc_val, exc_tb):
pass
# The actual test
@pytest.mark.asyncio
async def test_get_token():
redis = MockRedis()
token = await set_value(redis, 'something')
assert token is not None
我用以下方法运行它:
py.test path/to/file.py
我得到一个错误:
>等待连接设置(“键”,值)
E TypeError:对象非类型不能用于“等待”表达式
\uuuu aexit\uuuu
也需要异步:
如果不是异步的,它将返回None
,而不是一个协程,因此它会引发一个错误,正如我创建的错误消息所指出的,错误消息需要修复一样
async def __aexit__(self, exc_type, exc_val, exc_tb):
pass