python - 避免在单元测试中运行顶级模块代码

标签 python unit-testing monkeypatching

我正在尝试对一些导入模块的 Python 3 代码进行单元测试。不幸的是,模块的编写方式,简单地导入它会产生令人不快的副作用,这对测试并不重要。我正在尝试使用 unitest.mock.patch绕过它,但运气不佳。
这是一个说明性示例的结构:

.
└── work
    ├── __init__.py
    ├── test_work.py
    ├── work.py
    └── work_caller.py
__init__.py是一个空文件
工作.py
import os


def work_on():
    path = os.getcwd()
    print(f"Working on {path}")
    return path

def unpleasant_side_effect():
    print("I am an unpleasant side effect of importing this module")

# Note that this is called simply by importing this file
unpleasant_side_effect()
work_caller.py
from work.work import work_on

class WorkCaller:
    def call_work(self):
        # Do important stuff that I want to test here

        # This call I don't care about in the test, but it needs to be called
        work_on()
测试工作.py
from unittest import TestCase, mock

from work.work_caller import WorkCaller


class TestWorkMockingModule(TestCase):
    def test_workcaller(self):
        with mock.patch("work.work.unpleasant_side_effect") as mocked_function:
            sut = WorkCaller()
            sut.call_work()
work_caller.py我只想测试开始代码,而不是对 work_on() 的调用.当我运行测试时,我得到以下输出:
paul-> python -m unittest
I am an unpleasant side effect of importing this module
Working on /Users/paul/src/patch-test
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
我期待这条线 I am an unpleasant side effect of importing this module不会打印,因为函数 unpleasant_side_effect会被 mock 。我可能哪里出错了?

最佳答案

unpleasant_side_effect运行有两个原因。首先,因为导入是在测试用例开始之前处理的,因此在导入时不会被模拟。其次,因为 mocking 本身导入了 work.py因此运行 unpleasant_side_effect即使work_caller.py没有进口。
导入问题可以通过mock模块work.py来解决本身。这可以在测试模块或测试用例本身中全局完成。这里我给它分配了 MagicMock ,可以导入,调用等。
测试工作.py

from unittest import TestCase, mock


class TestWorkMockingModule(TestCase):
    def test_workcaller(self):
        import sys
        sys.modules['work.work'] = mock.MagicMock()
        from work.work_caller import WorkCaller

        sut = WorkCaller()
        sut.call_work()
缺点是 work_on 也被 mock ,我不确定你的情况是否有问题。
不可能不运行导入时整个模块,因为函数和类也是语句,因此模块执行必须在返回到调用者之前完成,调用者想要更改导入的模块。

关于python - 避免在单元测试中运行顶级模块代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58433358/

相关文章:

python - 如何使用 django-admin.py?

c++ - 在 Visual Studio Code 中对 native C++ 进行单元测试

javascript - 使用 johnpapa vm 风格的 Angular Bootstrap 模态的单元测试解析

python - gevent猴子补丁和断点

python - 如何避免将开发包放入 requirements.txt

python - 在 Azure Devops 中使用 API 创建变量组

python - 如何获得适用于 Windows 的 python-dev?

c - C 中的测试单元用于服务器监听功能。避免监听阻塞调用

JavaScript 袖珍引用,第 14 页121 : How is this "monkey-patching" method supposed to work?

python - 使用 Try 和 Except 时如何在 Python 中单元测试错误