gpt4 book ai didi

Python Mocking - 如何模拟 Google 的 storage.client?

转载 作者:行者123 更新时间:2023-12-04 15:36:48 25 4
gpt4 key购买 nike

有人可以帮助 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 的身份验证,但没有成功。任何援助将不胜感激。

最佳答案

一种可能的解决方案:将 GOOGLE_APPLICATION_CREDENTIALS 模拟为 os 模块中的 env 变量。我认为 GOOGLE_APPLICATION_CREDENTIALS 是 dict,所以 mock dict 可能会帮助你。

e.g.这里

关于Python Mocking - 如何模拟 Google 的 storage.client?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59469612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com