有人可以提供有关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的身份验证,但未成功。任何帮助将不胜感激。
答案 0 :(得分:1)
一个可能的解决方案:在os模块中将GOOGLE_APPLICATION_CREDENTIALS模拟为env变量。我认为GOOGLE_APPLICATION_CREDENTIALS是dict,所以嘲笑dict可能会对您有所帮助。
e.g.在这里