我在模拟函数时遇到了一些问题。所述函数已导入并在 run_parsers.py
中使用,我得到了
ImportError: 'No module named run_parsers'
当我尝试 mock.patch
run_parsers.py
时。
这是我在 test_run_parsers.py
中的测试代码
from .. import run_parsers # Used in all my other tests.
def test_node_data_parser_throws_exception(self):
def parser():
return NotImplementedError()
with mock.patch("run_parsers.get_node_paths") as node_paths:
node_paths.return_value = "node_1"
run_parsers.get_node_data(parser, "/a/path")
这是我的存储库结构
control_scripts
├── __init__.py
├── README.md
├── run_all_parsers.py
├── run_parsers.py
└── tests
├── __init__.py
├── test_run_parsers.py
According to this tutorial I'm supposed to mock where the function is imported.这就是为什么我试图模拟调用模块而不是定义 get_node_paths 的模块
最佳答案
我不确定这是否与您的设置完全相同,但这是一个对我有用的简单测试用例。
目录设置为:
c:\work
\control
__init__.py
scripts.py
\tests
__inti__.py
mytests.py
and c:\work is on sys.path
在模块scripts.py中:
def identity(x):
return x
def do_identity(x):
return identity(x)
在 mytests.py 中:
import unittest
from unittest.mock import patch
from control import scripts
class MyTest(unittest.TestCase):
def test_patch(self):
with patch('control.scripts.identity') as mymock:
mymock.return_value = 99
self.assertEqual(scripts.do_identity(1), 99)
def test_no_patch(self):
self.assertEqual(scripts.do_identity(1), 1)
if __name__ == "__main__":
unittest.main()
所以我在这里要做的是模拟函数“do_identity”调用的函数“identity”。这两个函数都在“脚本”模块中。此测试运行时没有错误或失败。
我可以从任何目录运行它:
c:\any_directory> python c:\work\control\tests\mytests.py
关于python - 在修补导入的模块时模拟返回 ImportError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34408289/