有人可以帮助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的身份验证,但没有成功。任何帮助都将不胜感激。
发布于 2019-12-24 21:39:01
一种可能的解决方案是:将GOOGLE_APPLICATION_CREDENTIALS模拟为os模块中的环境变量。我认为GOOGLE_APPLICATION_CREDENTIALS是dict,所以mocking dict可能会对你有帮助。
e.g.在这里
https://stackoverflow.com/questions/59469612
复制相似问题