【问题标题】:Python Mocking - How to mock Google's storage.client?Python Mocking - 如何模拟 Google 的 storage.client?
【发布时间】:2019-12-24 13:34:47
【问题描述】:

有人可以帮忙处理 GCP API 模拟吗?这是func.py的函数:

import re
from google.cloud import storage
def is_all_log_entries_sink(sink):
    storage_client = storage.Client()
    if 'filter' not in sink and 'storage.googleapis.com' in sink.get('destination', ''):
        bucket_name = re.search(r'^storage.googleapis.com/([^/]+)$', sink.get('destination')).group(1)  
        bucket = storage_client.lookup_bucket(bucket_name)
        if bucket is not None:
            return True
    return False 

这是测试:

import mock
from mock import patch, MagicMock
with mock.patch('oauth2client.client.GoogleCredentials.get_application_default') as mock_method:
    import func
@patch('func.storage_client')
def test_is_all_log_entries_sink(mock_obj):
    mock_obj.lookup_bucket = MagicMock(return_value='bucket-name')
    sink = {'name': 'testname', 'destination': 'storage.googleapis.com/bucket-name'}
    assert func.is_all_log_entries_sink(sink) == 1
    assert mock_obj.lookup_bucket.called
    sink = {'name': 'testname', 'destination': 'storage.googleapis.com/bucket-name', 'filter': 'testfilter'}
    assert func.is_all_log_entries_sink(sink) == 0
    sink = {'name': 'testname', 'destination': 'storage.googleapis.com/bucket-name'}
    mock_obj.lookup_bucket = MagicMock(return_value=None)
    assert func.is_all_log_entries_sink(sink) == 0

运行 PyTest 时,收到以下错误:

E   google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and
 re-run the application.

我试图模拟 Google 的身份验证,但没有成功。任何帮助将不胜感激。

【问题讨论】:

  • 你不能像那样修补你在函数中定义的变量,你需要修补实际的客户端类
  • 你从哪里运行 Python 代码?
  • @eespinola 本地
  • 如果您模拟客户端,则不需要任何身份验证。然后模拟你想使用的客户端方法。

标签: python google-cloud-platform google-api google-api-client python-mock


【解决方案1】:

一种可能的解决方案:将 GOOGLE_APPLICATION_CREDENTIALS 模拟为 os 模块中的环境变量。我将 GOOGLE_APPLICATION_CREDENTIALS 视为 dict,因此模拟 dict 可能会对您有所帮助。

e.g.这里

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 2022-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多