首页 > 解决方案 > 测试 A 模拟被带到测试 B

问题描述

我在 Python 中有以下单元测试(使用 Python 3.8):

def test_Wrapper_permanent_cookie_OK_True(self):
    # Some stuff

    mock_3 = PermanentCookie
    mock_3.create_permanent_cookies_response = mock.Mock(return_value=response)

    # The following line uses this mock on its execution
    result = permanentcookies.Wrapper_permanent_cookie(Input)
    
    # Test passes (response gets defined previously)
    self.assertTrue(result == (response, None))

执行以下测试时问题开始。这是对我之前模拟的功能的测试。

def test_create_permanent_cookies_response(self):

     permanentcookies = PermanentCookie()
     result = permanentcookies.create_permanent_cookies_response(status2, error2)

     # Test does not pass because "result" is not the execution of the function but the mock from the previous test (response gets defined previously)
     self.assertTrue(result == response)

关于如何完全删除以前的模拟/将每个测试与其他测试隔离/...的任何建议?

提前致谢!

-------------------------------------------------- -----编辑-------------------------------------

我的测试功能是使用补丁方法。但是在这些补丁中,有一个类是我需要测试功能的。也许我缺少一些关于修补类的基本知识......我的代码:


    @mock.patch('src.servicios.permanent_cookies.PermanentCookie')
    @mock.patch('src.servicios.permanent_cookies.utilities.get_current_datetime')
    @mock.patch('src.servicios.permanent_cookies.queries.query_permanent_cookie')
    def test_Wrapper_permanent_cookie_OK_True(self, mock_1, mock_2, mock_3):

         # The following line is not sending my return_value expectation to function usage
         mock_3.create_permanent_cookies_response.return_value = 'test'


        # This is the usage of the class I mocked on the patch above
        permanentcookies = PermanentCookie()
        # Unexpected outcome as the method I passed the return_value method did not return that value.
        result = permanentcookies.Wrapper_permanent_cookie(Input)

标签: pythonunit-testingmockingpython-unittestpatch

解决方案


你实际上并没有patch在任何地方使用。它正在使用在测试结束时删除模拟的补丁。

patch()充当函数装饰器、类装饰器或上下文管理器。在函数体或 with 语句内部,目标被一个对象修补。当 function/with 语句退出时,补丁被撤消。


推荐阅读