python - 多个异步单元测试失败,但一一运行会通过

标签 python pytest fastapi python-3.9 pytest-asyncio

我有两个单元测试,如果我一一运行它们,它们就会通过。如果我在类级别运行它们,一个通过,另一个在 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
我已经尝试了几个小时,请问我错过了什么?

最佳答案

我找到了解决办法。
创建一个名为 conftest.py 的文件下 tests并插入以下内容:

@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()
这将在每次测试后正确结束循环并允许运行多个循环。

关于python - 多个异步单元测试失败,但一一运行会通过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66054356/

相关文章:

python - pytest - 从运行测试的 CLI 命令指定日志级别

python - 使用 ID 创建对象并填充其他字段

python - 读取时避免从 MySQL 数据库中多次加载 json.loads

异步和等待方法的 Python pytest 用例

python - 从两个2D框架获取3D坐标

python - pytest 的 ModuleNotFoundError 问题

fastapi - 如何为 HTTP 400 错误定义单独的 response_model?

python - 如何将 FastAPI UploadFile(zip 文件)以 .zip 格式保存到磁盘?

python - 如何在 pydot 中的两个子图之间添加边?

python - matplotlib 中的 gnuplot linecolor 变量?