小编F F*_*F F的帖子

Python mock.patch装饰器影响同一测试套件中的其他单元测试

我为main_function编写了一个单元测试,并断言它使用类的实例调用其中的函数get_things,并使用patch作为参数进行模拟:

@patch("get_something")
@patch("MyClass.__new__")
def test(self, mock_my_class_instance, mock_get_something):
    # Given
    dummy_my_class_instance = MagicMock()
    mock_my_class_instance.return_value = dummy_my_class_instance

    dummy_my_class_instance.get_things.return_value = {}

    # When
    main_function(parameter)

    # Then
    dummy_my_class_instance.get_things.assert_called_once_with(parameter["key1"], parameter["key2"])
    mock_get_something.assert_called_once_with(dummy_my_class_instance)
Run Code Online (Sandbox Code Playgroud)

这是主要功能:

def main_function(parameter):
    properties = get_properties(parameter)

    my_class_instance = MyClass()

    list_of_things = my_class_instance.get_things(properties["key-1"], properties["key-2"])
    an_object = get_something(my_class_instance)

    return other_function(list_of_things, an_object)
Run Code Online (Sandbox Code Playgroud)

它单独传递,但是当与其他修补MyClass.get_things()的测试一起运行时,它会失败.这是消息:

Unhandled exception occurred::'NoneType' object has no attribute 'client'
Run Code Online (Sandbox Code Playgroud)

似乎修补程序装饰器相互影响.

我试图在测试函数中创建模拟作为变量而不是装饰器,但问题仍然存在.我也尝试创建一个tearDown()来停止补丁,但它似乎不起作用.

在模拟类实例时,有没有办法隔离补丁或成功丢弃它们?

python patch mocking python-decorators python-unittest

5
推荐指数
1
解决办法
409
查看次数