【发布时间】:2015-10-26 19:17:54
【问题描述】:
看看这个网页:http://www.toptal.com/python/an-introduction-to-mocking-in-python——作者谈到了 Python 中的 Mocking 和 Patching,并给出了一个非常可靠的“真实世界”示例。让我感到困惑的部分是了解单元测试框架如何知道哪个模拟对象被传递到哪个补丁。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import os.path
def rm(filename):
if os.path.isfile(filename):
os.remove(filename)
代码示例很容易理解。对操作系统库/模块的硬编码依赖。首先使用os.path.isfile()方法检查文件是否存在,如果存在,使用os.remove()删除它
测试/模拟代码如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from mymodule import rm
import mock
import unittest
class RmTestCase(unittest.TestCase):
@mock.patch('mymodule.os.path')
@mock.patch('mymodule.os')
def test_rm(self, mock_os, mock_path):
# set up the mock
mock_path.isfile.return_value = False
rm("any path")
# test that the remove call was NOT called.
self.assertFalse(mock_os.remove.called, "Failed to not remove the file if not present.")
# make the file 'exist'
mock_path.isfile.return_value = True
rm("any path")
mock_os.remove.assert_called_with("any path")
我想让我感到困惑的是测试中有 2 个 @Patch 调用和 2 个参数。单元测试框架如何知道mymodule.os.path 正在修补os.path 并映射到mock_path? mymodule.os.path 在哪里定义?
(似乎有很多“魔法”在发生,我没有关注它。)
【问题讨论】:
标签: python unit-testing mocking