【问题标题】:speed up test with asyncio使用 asyncio 加速测试
【发布时间】:2021-11-04 16:37:29
【问题描述】:

这是我的代码

@pytest.mark.asyncio
async def test_async():
    res = []
    for file_id in range(100):
        result = await get_files_async(file_id)
        res.append(result)
    assert res == [200 for _ in range(100)]


async def get_files_async(file_id):
    kwargs = {"verify": False, "cert": (cert, key)}
    resp = requests.request('GET', url, **kwargs)
    return resp.status_code

pytest 的时间显示需要 118 秒才能完成,这与按顺序向 url 发送请求的测试非常接近。 有什么改进可以加快这个测试吗?谢谢。

【问题讨论】:

    标签: pytest python-asyncio pytest-asyncio


    【解决方案1】:

    您无法使用异步加速此过程,因为您使用的是 requests,这是一个同步 pkg,因此每次调用都会停止偶数循环。

    您可以切换到在线程中运行请求,也可以切换到异步 pkg,例如 httpx 或 aiohttp

    如果您确实切换到不同的 pkg,请将 test_async 更改为此以并行运行请求

    @pytest.mark.asyncio
    async def test_async():
        tasks = []
        for file_id in range(100):
            tasks.append(asyncio.create_task(get_files_async(file_id)))
        res = await asyncio.gather(*tasks)
        assert res == [200 for _ in range(100)]
    

    【讨论】:

    • 感谢您的回答。我切换到 aiohttp,它确实加快了测试速度。
    猜你喜欢
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    相关资源
    最近更新 更多