簡體   English   中英

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

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

有人可以幫助 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,所以嘲笑 dict 可能會幫助你。

例如這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM