【发布时间】:2015-12-22 04:09:06
【问题描述】:
我在模拟函数时遇到了一些问题。所述函数已导入并在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 的模块
【问题讨论】:
-
我看到您在嘲笑“run_parsers.get_node_paths”,但您没有调用该函数,而是调用了“run_parsers.get_node_data”。那是错字吗?还是“run_parsers.get_node_data”调用了“run_parsers.get_node_paths”?
-
另一个问题:您是否尝试(作为测试用例)使用绝对导入“import run_parsers”并确保目录“control_scripts”在您的 sys.path 上?这只是为了首先测试模拟功能是否按预期工作,然后您可以解决导入问题。这就是我通常尝试解决这些问题的方式。
-
@SteveMisuta 这不是错字。我正在尝试测试
get_node_data,get_node_data调用的函数之一是get_node_paths。我还没有检查 control_scripts 是否在路径中。我得去看看,但我很确定不是。 -
run_parser不在您的类路径中,因此补丁无法解决它。改用mock.patch("control_script.run_parsers.get_node_paths") -
github.com/la10736/SimpleScratchExtension/blob/master/scratch/… 第 726 行(我希望如此)。是一个非常接近您的项目结构的示例。
标签: python unit-testing mocking