2

我有一个测试来验证异步响应是否引发了异常,我正在使用 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)

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

4

1 回答 1

2

https://pypi.org/project/pytest-asyncio/

您显然可以覆盖 pytest-asyncio 的事件循环夹具版本。他们有这样的:

@pytest.fixture
def event_loop():
    loop = asyncio.get_event_loop()
    yield loop
    loop.close()

我有这样的:

@pytest.fixture
def event_loop():
    loop = asyncio.get_event_loop()
    yield loop
    cleanly_shutdown(loop)

或者在像这样的其他情况下:

@pytest.fixture
def event_loop():
    yield asyncio.get_event_loop()

def pytest_sessionfinish(session, exitstatus):
    asyncio.get_event_loop().close()

这些文档非常有帮助:https ://docs.pytest.org/en/latest/reference/reference.html?highlight=sessionfinish#pytest.hookspec.pytest_sessionfinish

于 2021-04-28T19:52:17.590 回答