如何在 Python 中使用 monkeypatch 模拟不属于任何 class 的函数?

How to mock a function that is not part of any class using monkeypatch in Python?

考虑一个函数:

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> 应该是什么。

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)