【问题标题】:How to mock a function that is not part of any class using monkeypatch in Python?python - 如何在Python中使用monkeypatch模拟不属于任何类的函数?
【发布时间】:2021-10-06 20:25:53
【问题描述】:

考虑一个函数:

def some_function():
    print("some function")

它是模拟函数:

def some_function_dummy():
    print("some function")

如何使用monkeypath.setattr() 模拟some_function() 函数?

类似于:

monkeypatch.setattr(<class name>, "some_function", dummy_function)

不确定这里的<class name> 应该是什么。

【问题讨论】:

    标签: python unit-testing mocking monkeypatching


    【解决方案1】:

    obj 应该是当前模块:

    import sys
    
    # Get the current module
    this = sys.modules[__name__]
    
    monkeypatch.setattr(this, "some_function", dummy_function)
    

    如果some_function 位于另一个文件中,则需要将此文件导入当前模块:

    import another_file
    
    monkeypatch.setattr(another_file, "some_function", dummy_function)
    

    【讨论】:

    • 谢谢。如果some_function 在包含monkeypatch 的测试文件以外的文件中怎么办?
    • 我已经更新了我的答案,看看是否可行。
    猜你喜欢
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多