简体   繁体   English

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

[英]Python Mocking - How to mock Google's storage.client?

Could anybody help with GCP API mocking?有人可以帮助 GCP API 模拟吗? Here's the function func.py :这是函数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 

Here's the test:这是测试:

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

When PyTest ran, the following error was received:当 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.

I tried to mock Google's authentication, but was unsuccessful.我试图模拟 Google 的身份验证,但没有成功。 Any assistance would be appreciated.任何援助将不胜感激。

One possible solution: to mock GOOGLE_APPLICATION_CREDENTIALS as env variable in os module.一种可能的解决方案:将 GOOGLE_APPLICATION_CREDENTIALS 模拟为 os 模块中的 env 变量。 I consider GOOGLE_APPLICATION_CREDENTIALS as dict, so mocking dict may help you.我认为 GOOGLE_APPLICATION_CREDENTIALS 是 dict,所以嘲笑 dict 可能会帮助你。

eg here 例如这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM