相关疑难解决方法(0)

pytest-asyncio 有一个封闭的事件循环,但仅在运行所有测试时

我有一个测试来验证异步响应是否抛出异常,我正在使用 pytest-asyncio 版本 0.10.0 来运行该测试。

代码基本上是:

class TestThis:
    @pytest.mark.asyncio
    def test_the_thing(self):
       arg1 = "cmd"
       arg2 = "second command"
       with pytest.raises(CustomException):
           await do_thing(arg1, arg2)
Run Code Online (Sandbox Code Playgroud)

现在真正奇怪的是,如果我单独运行这个测试,或者单独运行这个类,这个测试就可以正常工作。但是,当我运行所有测试(项目根目录下的 pytest)时,每次都会失败并出现运行时错误,表示循环已关闭。

pytest python-asyncio pytest-asyncio

23
推荐指数
2
解决办法
2万
查看次数

asyncio 抛出运行时错误并忽略异常

下面是一个收集 URL 长度的简单程序。

import aiohttp
import asyncio
from time import perf_counter


URLS = ['http://www.cnn.com', 'http://www.huffpost.com', 'http://europe.wsj.com',
        'http://www.bbc.co.uk', 'http://failfailfail.com']

async def async_load_url(url, session):
    try:
        async with session.get(url) as resp:
            content = await resp.read()
        print(f"{url!r} is {len(content)} bytes")
    except IOError:
        print(f"failed to load {url}")        

async def main():

    async with aiohttp.ClientSession() as session:
        tasks = [async_load_url(url, session) for url in URLS]
        await asyncio.wait(tasks)

if __name__ == "__main__":
    start = perf_counter()
    asyncio.run(main())
    elapsed = perf_counter() - start
    print(f"\nTook {elapsed} seconds")

Run Code Online (Sandbox Code Playgroud)

为什么以下代码在 python 3.9 中失败并出现运行时错误并忽略异常?如何修复它? …

python-3.x python-asyncio aiohttp

7
推荐指数
1
解决办法
3030
查看次数