文件名称:在单元测试中给对象打补丁-python cookbook(第3版)高清中文完整版
文件大小:4.84MB
文件格式:PDF
更新时间:2024-06-29 23:06:50
python cookbook 第3版 高清 中文完整版
14.2 在单元测试中给对象打补丁 问题 You’re writing unit tests and need to apply patches to selected objects in order to make assertions about how they were used in the test (e.g., assertions about being called with certain parameters, access to selected attributes, etc.). 解决方案 The unittest.mock.patch() function can be used to help with this problem. It’s a little unusual, but patch() can be used as a decorator, a context manager, or stand-alone. For example, here’s an example of how it’s used as a decorator: from unittest.mock import patch import example @patch(‘example.func’) def test1(x, mock_func): example.func(x) # Uses patched example.func mock_func.assert_called_with(x) It can also be used as a context manager: with patch(‘example.func’) as mock_func: example.func(x) # Uses patched example.func mock_func.assert_called_with(x) Last, but not least, you can use it to patch things manually: p = patch(‘example.func’) mock_func = p.start() example.func(x) mock_func.assert_called_with(x) p.stop() If necessary, you can stack decorators and context managers to patch multiple objects. For example: