【问题标题】:pytest async function as the argument for parameterizepytest 异步函数作为参数化的参数
【发布时间】:2023-02-19 03:15:02
【问题描述】:

我有一个 async 函数,它异步计算 url 列表,我想使用 parameterize 为每个 url 生成异步测试,这将断言状态代码。 我想做的是这样的:

@pytest.fixture async def compute_urls():
    urls = await compute_urls_helper()
    return urls

@pytest.mark.asyncio 
@pytest.mark.parameterize('url',await compute_urls()) 
async def test_url(compute_urls,url):
    resp = await get_url(url)
    assert resp.status_code == 200

我知道在参数化中使用“等待”是不可能的,所以我很想听听对这种操作的建议。

【问题讨论】:

    标签: asynchronous pytest fixtures parameterized pytest-asyncio


    【解决方案1】:

    您可以使用 asyncio.run 创建一个事件循环来计算参数:

    import asyncio
    from unittest.mock import AsyncMock
    import pytest
    
    
    async def compute_urls_helper():
        return ["stackoverflow.com", "jooj.com"]
    
    
    async def get_url(url: str) -> AsyncMock:
        return AsyncMock(status_code=200)
    
    
    @pytest.mark.asyncio
    @pytest.mark.parametrize("url", asyncio.run(compute_urls_helper()))
    async def test_url(url):
        resp = await get_url(url)
        assert resp.status_code == 200
    

    但是我不建议经常使用这种方法,因为如in the docs所述:

    这个函数 (asyncio.run) 总是创建一个新的事件循环并在最后关闭它。它应该用作 asyncio 程序的主要入口点,理想情况下应该只调用一次。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-21
      • 2020-12-27
      • 1970-01-01
      • 2019-04-03
      • 2020-06-28
      • 1970-01-01
      • 2022-10-05
      相关资源
      最近更新 更多