python - 用方法补丁(装饰器)覆盖类补丁

标签 python unit-testing tdd python-unittest python-unittest.mock

我在一个类中有几种测试方法,这些方法使用一种类型的对象修补程序,因此我使用类装饰器进行了修补。对于另一个方法,我想以不同的方式修补同一对象。我尝试了以下方法,但是尽管方法本身使用了不同的补丁来装饰,但作为类装饰器制作的补丁仍然有效。我希望方法补丁能覆盖类补丁。为什么不是这样?

在这种特殊情况下,我可以删除类补丁并修补单个方法,但这将是重复的。如何实现这种覆盖(方法覆盖类补丁)机制?

from unittest TestCase
from unittest import mock

@mock.patch('my_module.cls.method', mock.Mock(side_effect=RuntimeError('testing'))
class SwitchViewTest(TestCase):

    def test_use_class_patching(self):
        # several other methods like this
        # test code ..

    @mock.patch('my_module.cls.method', mock.Mock(side_effect=RuntimeError('custom'))
    def test_override_class_patching(self):
        # test code ...

最佳答案

使用with:

def test_override_class_patching(self):
    with mock.patch('my_module.cls.method') as mock_object:
        mock_object.side_effect = RuntimeError('custom')
        # test code ...

关于python - 用方法补丁(装饰器)覆盖类补丁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39651686/

相关文章:

assembly - 是否有任何组装测试框架?

TDD 和 JPEG 压缩

javascript - Spidermonkey 中的 JSON 序列化

python - 预计 volv1d_1 的形状是多少

python - 如何使用 openpyxl 使用列表写入 Excel 单元格范围?

python - 如何从具有特定字符串格式的字典中减去

php - 在 Laravel 8 中运行多个 PHPUnit 测试时出错

c# - 删除测试驱动开发中的重复

javascript - 如何对 DOM 操作进行单元测试(使用 jasmine)

python - 是否可以在不指定数据库的情况下使用 SQLAlchemy 连接到 postgres 服务器?