如何测试 google Drive API python 客户端

chi*_*imo 5 python-3.x google-drive-realtime-api python-unittest

目前,我的 django 项目中有一个 google Drive API 客户端,可以按预期工作。

import unittest
from unittest import mock

DRIVE_API_VERSION = "v3"
DRIVE_API_SERVICE_NAME = "drive"
DRIVE_AUTHORIZED_USER_FILE = "path/to/secrets/json/file"
DRIVE_SCOPES = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file ', 'https://www.googleapis.com/auth/drive.appdata']

def construct_drive_service():
    try:
        drive_credentials = google.oauth2.credentials.Credentials.from_authorized_user_file(
            DRIVE_AUTHORIZED_USER_FILE, scopes=DRIVE_SCOPES)
    except FileNotFoundError:
        print('Drive credentials not created')
        pass
    if drive_credentials:
        return build(DRIVE_API_SERVICE_NAME, DRIVE_API_VERSION, credentials=drive_credentials, cache_discovery=False)
    else:
        return None
Run Code Online (Sandbox Code Playgroud)

现在我面临的挑战是为这个函数编写测试。但我不知道该使用什么策略。我试过这个

class TestAPICalls(unittest.TestCase):

    @mock.patch('api_calls.google.oauth2.credentials', autospec=True)
    def setUp(self, mocked_drive_cred):
        self.mocked_drive_cred = mocked_drive_cred

    @mock.patch('api_calls.DRIVE_AUTHORIZED_USER_FILE')
    def test_drive_service_creation(self, mocked_file):
        mocked_file.return_value = "some/file.json"
        self.mocked_drive_cred.Credentials.return_value = mock.sentinel.Credentials
        construct_drive_service()
        self.mocked_drive_cred.Credentials.from_authorized_user_file.assert_called_with(mocked_file)
Run Code Online (Sandbox Code Playgroud)

但我的测试失败并出现以下错误

    with io.open(filename, 'r', encoding='utf-8') as json_file:
ValueError: Cannot open console output buffer for reading
Run Code Online (Sandbox Code Playgroud)

我知道客户端正在尝试读取文件,但得到的是mock object。问题是我不知道如何解决这个问题。

我一直在阅读图书馆的mock资料,但整个事情仍然很模糊。