【问题标题】:Can you use self.assertRaises as an async context manager?你可以使用 self.assertRaises 作为异步上下文管理器吗?
【发布时间】:2016-09-14 13:59:42
【问题描述】:

我想测试 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__

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

【问题讨论】:

  • 这里为什么需要异步上下文管理器? with self.assertRaises(TestExceptionType): 在这里应该足够了,因为 assertRaises 没有异步执行任何操作。

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


【解决方案1】:

只需使用经典老好with 左右await 调用:

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

有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-10
    • 1970-01-01
    相关资源
    最近更新 更多