多个异步单元测试失败,但 运行 它们一个接一个地通过
Multiple async unit tests fail, but running them one by one will pass
我有两个单元测试,如果我 运行 一个一个地测试它们,它们就会通过。如果我 运行 他们在 class 级别,一个通过,另一个在 response = await ac.post(
失败,错误消息:RuntimeError: Event loop is closed
@pytest.mark.asyncio
async def test_successful_register_saves_expiry_to_seven_days(self):
async with AsyncClient(app=app, base_url="http://127.0.0.1") as ac:
response = await ac.post(
"/register/",
headers={},
json={
"device_id": "u1",
"device_type": DeviceType.IPHONE.value,
},
)
query = device.select(whereclause=device.c.id == "u1")
d = await db.fetch_one(query)
assert d.expires_at == datetime.utcnow().replace(
second=0, microsecond=0
) + timedelta(days=7)
@pytest.mark.asyncio
async def test_successful_register_saves_device_type(self):
async with AsyncClient(app=app, base_url="http://127.0.0.1") as ac:
response = await ac.post(
"/register/",
headers={},
json={
"device_id": "u1",
"device_type": DeviceType.ANDROID.value,
},
)
query = device.select(whereclause=device.c.id == "u1")
d = await db.fetch_one(query)
assert d.type == DeviceType.ANDROID.value
我已经尝试了几个小时,请问我遗漏了什么?
我找到了解决方案。
在 tests
下创建一个名为 conftest.py
的文件
并插入以下内容:
@pytest.yield_fixture(scope="session")
def event_loop(request):
"""Create an instance of the default event loop for each test case."""
loop = asyncio.get_event_loop_policy().new_event_loop()
yield loop
loop.close()
这将在每次测试后正确结束循环并允许多个 运行。
我有两个单元测试,如果我 运行 一个一个地测试它们,它们就会通过。如果我 运行 他们在 class 级别,一个通过,另一个在 response = await ac.post(
失败,错误消息:RuntimeError: Event loop is closed
@pytest.mark.asyncio
async def test_successful_register_saves_expiry_to_seven_days(self):
async with AsyncClient(app=app, base_url="http://127.0.0.1") as ac:
response = await ac.post(
"/register/",
headers={},
json={
"device_id": "u1",
"device_type": DeviceType.IPHONE.value,
},
)
query = device.select(whereclause=device.c.id == "u1")
d = await db.fetch_one(query)
assert d.expires_at == datetime.utcnow().replace(
second=0, microsecond=0
) + timedelta(days=7)
@pytest.mark.asyncio
async def test_successful_register_saves_device_type(self):
async with AsyncClient(app=app, base_url="http://127.0.0.1") as ac:
response = await ac.post(
"/register/",
headers={},
json={
"device_id": "u1",
"device_type": DeviceType.ANDROID.value,
},
)
query = device.select(whereclause=device.c.id == "u1")
d = await db.fetch_one(query)
assert d.type == DeviceType.ANDROID.value
我已经尝试了几个小时,请问我遗漏了什么?
我找到了解决方案。
在 tests
conftest.py
的文件
并插入以下内容:
@pytest.yield_fixture(scope="session")
def event_loop(request):
"""Create an instance of the default event loop for each test case."""
loop = asyncio.get_event_loop_policy().new_event_loop()
yield loop
loop.close()
这将在每次测试后正确结束循环并允许多个 运行。