跳转到主要内容

用于测试异步Python代码的pytest插件

项目描述

pytest-aio

pytest-aio – 是一个简单的 pytest 插件,用于测试任何异步Python代码

Tests Status PYPI Version Python Versions

功能

  • 支持几乎所有最流行的异步Python库: Asyncio, TrioCurio

  • 自动运行你的异步测试

  • 正确处理 contextvars(支持异步/同步固定装置)

  • 支持 trio-asyncio

要求

  • python >= 3.9

安装

pytest-aio 应使用pip安装

pip install pytest-aio

可选额外内容

pip install pytest-aio[curio,trio]

使用

安装后,插件将运行所有你的异步测试函数/固定装置。

async def test_async():
    assert True

不需要标记你的异步测试。只需运行pytest即可。

异步固定装置用于同步测试

如果你计划使用异步固定装置进行同步测试,请确保你已经包括了 aiolib 固定装置

# It's important to add aiolib fixture here
def test_with_async_fixtures(async_fixture, aiolib):
    assert async_fixture == 'value from async fixture'

作为替代,如果你自己进行异步固定装置,你可以在其中添加 aiolib

@pytest.fixture
async def async_fixture(aiolib):
    return 'value from async fixture'

# So for the test we don't need to implicity use `aiolib` anymore
def test_with_async_fixtures(async_fixture):
    assert async_fixture == 'value from async fixture'

自定义异步库

默认情况下,每个测试函数都将使用 asyncio、trio、curio 后端一致运行(仅当安装了 trio/curio 时)。但您可以通过创建全局 fixture 来自定义所有测试的库。

# Run all tests with Asyncio/Trio only
@pytest.fixture(params=['asyncio', 'trio'])
def aiolib(request):
    assert request.param

如果您想为所选后端指定不同的选项,可以通过传递一个包含(后端名称,选项字典)的元组来实现。

@pytest.fixture(params=[
    pytest.param(('asyncio', {'use_uvloop': False}), id='asyncio'),
    pytest.param(('asyncio', {'use_uvloop': True}), id='asyncio+uvloop'),
    pytest.param(('trio', {'trio_asyncio': True}), id='trio+asyncio'),
    pytest.param(('curio', {'debug': True}), id='curio'),
])
def aiolib(request):
    assert request.param

仅设置单个测试的特定后端。

@pytest.mark.parametrize('aiolib', ['asyncio'])
async def only_with_asyncio():
    await asyncio.sleep(1)
    assert True

辅助工具

该插件包含 aiosleep fixture。它是当前运行库的 asyncio.sleeptrio.sleepcurio.sleep 的等效功能。

错误跟踪器

如果您有任何建议、错误报告或不满,请向 https://github.com/klen/asgi-tools/issues 的 issue tracker 报告。

贡献

该项目的开发地点: https://github.com/klen/pytest-aio

许可证

许可协议: MIT 许可协议

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源代码分发

pytest_aio-1.9.0.tar.gz (5.7 kB 查看散列

上传时间 源代码

构建分发

pytest_aio-1.9.0-py3-none-any.whl (6.6 kB 查看散列

上传时间 Python 3

由以下支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面