【问题标题】:Mock global function call while importing导入时模拟全局函数调用
【发布时间】:2019-12-18 14:46:50
【问题描述】:

假设我有一个名为a.py 的文件,其代码如下

import mod1
mod1.a()

def b():
   print("hi")

现在如果我想模拟有趣的b() 然后unittest.py 而在顶部有 import 语句就像

from a import b

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

【问题讨论】:

    标签: python python-unittest python-mock python-unittest.mock


    【解决方案1】:

    考虑从模块顶层移除代码,将其移动到受保护的块

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

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

    如果你仍然需要那里的调用并想模拟它,那很简单。 有了这样的文件,

    # 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.
    

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

    【讨论】:

    • 我明白,但我希望在导入时调用该函数。
    • 我很确定,在执行patch('mod1.a') 时,模块将被加载以检查它是否包含您要修补的内容,这将在修补之前触发未模拟调用。
    猜你喜欢
    • 2018-11-21
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 2015-04-07
    • 2020-04-18
    相关资源
    最近更新 更多