python - 测试 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)
解决方案
你实际上并没有patch
在任何地方使用。它正在使用在测试结束时删除模拟的补丁。
patch()
充当函数装饰器、类装饰器或上下文管理器。在函数体或 with 语句内部,目标被一个新对象修补。当 function/with 语句退出时,补丁被撤消。
推荐阅读
- flutter - Flutter - 如何在所有边缘上获得线性渐变?
- reactjs - 在reactjs中使用来自前端的预签名URL上传文件
- rabbitmq - MassTransit 交换以交换绑定优势
- javascript - 无法设置未定义角度表的属性
- winui - WinUi 3 中的渲染模型是什么?
- django - 在 django 中显示多维数据
- javascript - reactjs(函数组件)中的 setInterval 是如何工作的?
- android - 使用脚本定期从 google-play 导出数据
- google-cloud-platform - 拉取请求上的 GCP Pub/Sub 过滤
- deep-learning - Sonnet 模块中的处理步骤及其输出我必须参考