副作用有几个例外的模拟补丁

2024-10-01 02:40:12 发布

您现在位置:Python中文网/ 问答频道 /正文

模拟对象时,有一些工具允许更改函数的结果

比如说,有一门课:

class Worker:

    def do_work(self):
        return perform_operation()

do_work()在不同的情况下引发几个异常时,我想测试一些情况:

@patch(
    'my.package.Worker.do_work',
    Mock(side_effect=[exc.VeryBadError, exc.NotThatBadError]
))
def test_worker_raise_errors():
    worker_user.call_worker()

但是没有办法将几个错误传递给side_effects像上面那样,它只会运行一次,只会在exc.VeryBadError中失败

当我想找到一种方法为每个异常启动test_worker_raise_errors()两次,但不为每个异常创建每个测试函数时

有没有一种方法可以为每个异常启动一个测试几次作为副作用,并在这种情况下看到2个失败


Tags: 工具对象方法testdef情况doside
1条回答
网友
1楼 · 发布于 2024-10-01 02:40:12

这个简单的例子会给你一个提示:

from unittest.mock import Mock

mock = Mock(
    side_effect=[
        AssertionError('Error 1'), 
        AttributeError('Error 2'),
    ]
)

try:
    mock()
except AssertionError as e:     # Catch the exception so that the execution can continue and we can test further.
    print(e)

try:
    mock()
except AttributeError as e:     # Catch the exception so that the execution can continue and we can test further.
    print(e)

输出:

Error 1
Error 2

您可以使用self.assertRaises(...)使它更干净一点

相关问题 更多 >