python - 在修补导入的模块时模拟返回 ImportError

标签 python unit-testing mocking

我在模拟函数时遇到了一些问题。所述函数已导入并在 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/

相关文章:

python - Tensorflow 训练损失在不同的运行中具有宏观相似性

node.js - 如何测试sequelize查询(where)逻辑?

python - Pandas:通过比较 2 个不同数据框中的 2 列来创建新列

python - 在 Python 中统一列表的最快方法

Python 打印变量时出现 Unicode 错误

AngularJS+ Jasmine : $httpBackend not working as expected

java - 使用 Junit 4.4 或更高版本运行 Eclipse Junit 插件测试——为什么没有检测到测试?

php - 何时使用 stub /模拟以及何时在单元测试中使用真实对象?

c# - 单元测试使用外部 dll 的方法

ruby-on-rails-4 - 使用 rails 4 和 rspec 3 被 verify_partial_doubles 绊倒