首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python Mocking -如何模仿谷歌的storage.client?

Python Mocking -如何模仿谷歌的storage.client?
EN

Stack Overflow用户
提问于 2019-12-24 21:34:47
回答 1查看 1.5K关注 0票数 3

有人可以帮助GCP API模拟吗?下面是函数func.py

代码语言:javascript
运行
复制
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 

下面是测试结果:

代码语言:javascript
运行
复制
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运行时,收到以下错误:

代码语言:javascript
运行
复制
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的身份验证,但没有成功。任何帮助都将不胜感激。

EN

回答 1

Stack Overflow用户

发布于 2019-12-24 21:39:01

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

e.g.在这里

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59469612

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档