python - Mock 在 Python 2.7 的单元测试中不起作用
问题描述
我有一个这样的项目结构:
py_test
|
+---my_module
| |
| +--- __init__.py (empty)
| |
| +--- futil.py
|
+---test
|
+--- __init__.py (empty)
|
+--- futil_test.py
在futil.py我有以下内容:
from os import path
def check_exists(file_path):
return path.exists(file_path)
在futil_test.py我试图实现这样的单元测试:
import mock
import unittest
from my_module.futil import check_exists
class TestExists(unittest.TestCase):
@mock.patch('my_module.futil.os.path') # <---leads to error, as well as my_module.os.path
def test_exists(self, mock_path):
mock_path.exists.return_value = True
self.assertTrue(check_exists('ba'))
if __name__ == '__main__':
unittest.main()
当我尝试启动单元测试时,它失败并出现错误:
Error
Traceback (most recent call last):
File "/usr/lib64/python2.7/unittest/case.py", line 367, in run
testMethod()
File "/home/antonio/devel/py/py_test/venv/lib/python2.7/site-packages/mock/mock.py", line 1322, in patched
arg = patching.__enter__()
File "/home/antonio/devel/py/py_test/venv/lib/python2.7/site-packages/mock/mock.py", line 1378, in __enter__
self.target = self.getter()
File "/home/antonio/devel/py/py_test/venv/lib/python2.7/site-packages/mock/mock.py", line 1548, in <lambda>
getter = lambda: _importer(target)
File "/home/antonio/devel/py/py_test/venv/lib/python2.7/site-packages/mock/mock.py", line 1235, in _importer
thing = _dot_lookup(thing, comp, import_path)
File "/home/antonio/devel/py/py_test/venv/lib/python2.7/site-packages/mock/mock.py", line 1224, in _dot_lookup
__import__(import_path)
ImportError: No module named os
在此处的示例中,类似的构造似乎正在起作用。我究竟做错了什么?
解决方案
“from os import path”,将使路径功能成为 futil 的一部分。而不是模拟“my_module.futil.os.path'”只是模拟“my_module.futil.path'”,应该可以。
我发现这篇文章在过去非常有用http://alexmarandon.com/articles/python_mock_gotchas/
推荐阅读
- c# - 窗口窗体最顶层有什么区别?C#
- spring-boot - 在 Apache Kafka java 中实现请求响应
- php - 当多站点为真时,为什么会发生重定向?
- javascript - 如何在 React.js(描述中的沙盒)中制作功能性的火种风格卡片?
- javascript - 使用字符串模板将来自 laravel 的路由值与样式绑定时 Vue 警告错误
- php - 带有 ACF 中继器字段的 PHP 邮件格式
- linux - 使用 awk 在每个“追加”实例中向新变量添加不同的值
- wpf - 与 ItemsSource 的 wpf 绑定问题
- c# - 如何更改模块 FormAndList(又名 UserDefinedTable)中 MsBuildTasks 的包文件夹的路径?
- amcharts - 如何将图表中的所有项目设置为在上午图表中具有相同的颜色 4