python - 如何在使用 inlineCallbacks 的试用测试用例中使用 assertRaises

标签 python twisted trial

我正在尝试弄清楚如何编写断言引发异常的试验测试用例。

目前我有两种简单的方法来测试(成功和失败)。每个方法都返回一个已经被回调或错误返回的延迟。测试成功方法工作正常。在测试失败方法时,我希望能够断言引发了异常(使用 assertRaises)。

但是测试用例失败了,我得到:

twisted.trial.unittest.FailTest: ConnectionRefusedError not raised (<Deferred at 0x920e28c current result: <twisted.python.failure.Failure <class 'twisted.internet.error.ConnectionRefusedError'>>> returned)

代码如下:

from twisted.trial.unittest import TestCase
from twisted.internet.defer import inlineCallbacks, succeed, fail
from twisted.internet.error import ConnectionRefusedError

class MyObject:
    def success(self):
        return succeed(True)

    def failure(self):
        return fail(ConnectionRefusedError())


class TestErrBack(TestCase):
    def setUp(self):
        self.o = MyObject()

    @inlineCallbacks
    def test_success(self):
        result = yield self.o.success()
        self.assertTrue(result)

    @inlineCallbacks
    def test_failure(self):
        # this test case is failing !
        yield self.assertRaises(ConnectionRefusedError, self.o.failure)

我在 test_failure 中使用了正确的方法吗? 我可以使用 try...catch 绕过对 self.o.failure 的调用,但我认为这种方法不如使用 assertRaises 好。

最佳答案

改用TestCase.assertFailure:

yield self.assertFailure(self.o.failure(), ConnectionRefusedError)

从 Twisted 12.3 开始,还有一个 TestCase.failureResultOf 助手:

self.failureResultOf(self.o.failure()).trap(ConnectionRefusedError)

从 13.1 开始,此 API 接受一个额外的参数并为您执行类型检查:

self.failureResultOf(self.o.failure(), ConnectionRefusedError)

这对于您知道 Deferred 已经触发并产生结果的测试很有用。如果 Deferred 在调用时没有失败结果,failureResultOf 会引发测试失败异常而不是返回失败。

这适用于您的示例代码并且应该适用于大多数单元测试。如果您正在使用试用来编写功能测试或集成测试,其中有实际的异步工作正在进行并且您不知道 Deferred 何时触发,那么您需要坚持使用第一个 API,断言失败

关于python - 如何在使用 inlineCallbacks 的试用测试用例中使用 assertRaises,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9840884/

相关文章:

python - sklearn 使用 prob_a 进行逻辑二元分类

python - sqlite3,python,创建表 - 靠近 "/": syntax error

用于任务管道的 Python 模式

python - 模板+脚本反向代理?

同时使用 Twisted Web 服务器和 Autobahn WebSocket,使用相同的端口

Python:运行脚本 A 处理脚本 B 中的 argparser

python - 使用twisted框架将文件发送到客户端

python - 在扭曲试验中超时后没有调用 tearDown?

.net - VB.NET程序试用版的制作

c# - 带试用期的 PayPal 定期付款