简体   繁体   English

不能monkeypatch导入的模块

[英]Can not monkeypatch imported module

I have a very simple Google Cloud Function written in Python and it makes a reference to Google's Secret manager via their Python library.我有一个用 Python 编写的非常简单的Google Cloud Function ,它通过他们的 Python 库引用了 Google 的 Secret 管理器。

The code is very simple and it looks like this:代码非常简单,如下所示:

import os
from google.cloud import secretmanager
import logging

client = secretmanager.SecretManagerServiceClient()
secret_name = "my-secret"
project_id = os.environ.get('GCP_PROJECT')
resource_name = "projects/{}/secrets/{}/versions/latest".format(project_id, secret_name)
response = client.access_secret_version(resource_name)
secret_string = response.payload.data.decode('UTF-8')

def new_measures_handler(data, context):
    logging.info(secret_string)
    print('File: {}.'.format(data['name']))

and then I have my simple unit test which is trying to take advantage of monkey patching :然后我有我的简单单元测试,它试图利用猴子补丁

import main

def test_print(capsys, monkeypatch):
    # arrange
    monkeypatch.setenv("GCP_PROJECT", "TestingUser")
    monkeypatch.setattr(secretmanager, "SecretManagerServiceClient", lambda: 1)

    name = 'test'
    data = {'name': name}

    # act
    main.new_measures_handler(data, None)
    out, err = capsys.readouterr()

    #assert
    assert out == 'File: {}.\n'.format(name)

Everything goes well with the mock for the environment variable but I can not mock secretmanager .环境变量的模拟一切顺利,但我无法模拟secretmanager It keeps on trying to call the actual API.它不断尝试调用实际的 API。 My ultimate goal is to mock secretmanager.SecretManagerServiceClient() and make it return an object which later on can be used by: client.access_secret_version(resource_name) (which I will need to mock as well, I think)我的最终目标是模拟secretmanager.SecretManagerServiceClient()并使其返回一个对象,稍后可以使用该对象: client.access_secret_version(resource_name) (我认为我也需要模拟)

有关使用unittest修补和模拟来模拟 Google API 调用并返回模拟结果的工作示例,请参阅我对此问题的回答: How to Mock a Google API Library with Python 3.7 for Unit Testing

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM