您可以使用 self.assertRaises 作为异步上下文管理器吗?

acr*_*bia 7 python unit-testing python-3.x python-asyncio

我想测试 python 3 coro 是否因特定异常而失败,但似乎没有实现此功能。

async with self.assertRaises(TestExceptionType):
    await my_func()
Run Code Online (Sandbox Code Playgroud)

因为单元测试像这样失败:

...
File "/Users/...../tests.py", line 144, in go
    async with self.assertRaises(TestExceptionType):
AttributeError: __aexit__
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:这应该有效吗?如果没有,断言失败的异步功能的最佳方法是什么?

And*_*lov 10

只需withawait通话中使用经典的旧好:

with self.assertRaises(TestExceptionType):
    await my_func()
Run Code Online (Sandbox Code Playgroud)

有用。