导入时模拟全局函数调用

Mock global function call while importing

假设我有一个名为 a.py 的文件,其代码类似于

import mod1
mod1.a()

def b():
   print("hi")

现在如果我想模拟乐趣 b() 然后 unittest.py 同时在顶部有导入语句

from a import b

在导入时 mod1.a() 将被调用。我如何模拟导入时发生的调用。

考虑从模块顶层删除代码,将其移至受

保护的块
if __name__ == '__main__':
    mod1.a()
    ... # the rest of your top level code

这样,受保护的代码不会在导入时执行,只有在直接 运行 时才会执行。

如果你还需要那里的调用,想mock一下,很简单。 对于这样的文件,

# mod.py

import mod1
mod1.a()

def b():
   print("hi")


# mod1.py

def a():
    print('Running a!')

# test_1.py
# Note: do not call unittest.py to a file.
# That is the name of a module from the Python stdlib,
# you actually need to use it and things will not work,
# because Python tries to load your file not the library you need.

from unittest.mock import patch

with patch('mod1.a') as mock_a:
    ... # configure mock_a here if there is a need, for example
        # to set a fake a call result
    import mod
    ... # the rest of your testing code. Use `mock_a` if you want to
        # inspect `a` calls.

with mod1.a 之外不再被嘲笑。 还有其他启动和停止模拟的方法,您应该查看文档。在学习 mock 之前,请确保您充分了解单元测试的工作原理以及如何组织测试。