[英]Mock doesn't work in unittest for Python 2.7
I have a project structure like this:我有一个这样的项目结构:
py_test
|
+---my_module
| |
| +--- __init__.py (empty)
| |
| +--- futil.py
|
+---test
|
+--- __init__.py (empty)
|
+--- futil_test.py
In futil.py I have the following:在futil.py我有以下内容:
from os import path
def check_exists(file_path):
return path.exists(file_path)
In futil_test.py I'm trying to implement a unit test like this:在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()
When I try to launch the unit test, it fails with the error:当我尝试启动单元测试时,它失败并显示错误:
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
In the example here the similar construction seems to be working.在这里的示例中,类似的结构似乎正在起作用。 What am I doing wrong?我究竟做错了什么?
"from os import path", will make path function part of futil. “from os import path”,将使路径功能成为无效的一部分。 Instead of mocking "my_module.futil.os.path'" just mock "my_module.futil.path'", that should work.与其模拟“my_module.futil.os.path'”,不如模拟“my_module.futil.path'”,这应该可行。
I have found this article very useful in the past http://alexmarandon.com/articles/python_mock_gotchas/我发现这篇文章过去非常有用http://alexmarandon.com/articles/python_mock_gotchas/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.