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

时间:2018-04-12 13:57:11

标签: python mocking patch python-unittest python-decorators

我为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)

这是主要功能:

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)

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

Unhandled exception occurred::'NoneType' object has no attribute 'client'

补丁修饰器似乎相互影响。

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

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

0 个答案:

没有答案