5

I currently have a google drive API client in my django project that works as expected.

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

The challenge for me now is to write tests for this function. But I don't know what strategy to use. I have tried this

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)

But my tests fail with the below error

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

I know that the client is trying to read a file but is getting a mock object instead. Problem is I have no idea how to go about solving this problem.

I have been reading up on the mock library but the whole thing is still hazy.

chidimo
  • 2,684
  • 3
  • 32
  • 47

0 Answers0