如何在导入主模块时模拟函数?

How to mock functions on import of main module?

我有以下问题:

我的 main.py 包含:

from google.cloud import secretmanager    

secret_name = "abc"

def function_1(secret):
    client = secretmanager.SecretManagerServiceClient()
    name = f"projects/123/secrets/{secret}/versions/latest"
    response = client.access_secret_version(name=name)
    return response.payload.data.decode("UTF-8")

def function_2():
    secret = function_1(secret_name)
    return secret

secret = function_2()

我的 test_main.py 有:

def test_function_1():
    import main
    ...

当 运行 这个和 test_main.py 中的其他测试时,我得到一个错误,因为通过导入 main function_2 被调用,例如access_secret_version 方法被称为未模拟。我不想更改我的 main.py,例如将 secret = function_2() 放在 if __name__=="__main__" 下。我想在 test_main.py.

中解决这个问题

我尝试了不同的方法,例如

@patch('main.secretmanager.SecretManagerServiceClient')
@patch('main.secretmanager.SecretManagerServiceClient.access_secret_version')
def test_function_1():
    import main
    ...

但是 import main 总是在调用这些方法时不进行模拟。我怎样才能做到这一点?我如何模拟 function_2 调用的内容?

这里 Mock function called on import OP 找到了类似的解决方法。

提前感谢您的帮助。

@patch 装饰器中的模块应该是 google.cloud 而不是 main,否则你从 main 导入是为了打补丁(它在 function_2 之前运行已打补丁)。

@patch('google.cloud.secretmanager.SecretManagerServiceClient')