python - 您可以将 self.assertRaises 用作异步上下文管理器吗?

标签 python unit-testing python-3.x python-asyncio

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

async with self.assertRaises(TestExceptionType):
    await my_func()

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

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

所以我的问题是:这可行吗?如果不是,断言失败的异步函数的最佳方法是什么?

最佳答案

只需在 await 调用周围使用经典的旧好 with 即可:

with self.assertRaises(TestExceptionType):
    await my_func()

有效。

关于python - 您可以将 self.assertRaises 用作异步上下文管理器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39492402/

相关文章:

python - 如何通过python将数据存储到MySQL数据库中

python - Spyder 快捷方式的目标文件是什么?

visual-studio - 从NuGet安装NUnit之后,如何强制TestDriven.Net使用NuGet引用的NUnit dll?

c++ - 在现有项目中创建 CPPUnit 测试需要哪些 .cpp 和 .h 文件?

python - 成员函数装饰器和 self 参数

python - 如何在 Python 中只调用一次函数

python - Matplotlib 设置 x 轴上的频率

javascript - 实习生 - 窗口未定义

Python (3) readline 无论文件中有什么内容都返回空字符串

python - 使用模型继承并遇到不可为空的字段错误