'How to save json dumps of responses in python google api client?
In the python google api documentation regarding mocks it is stated:
As you develop and test your application, it is a good idea to save actual API responses in files like books-discovery.json or books-android.json for use in testing.
Where do I get these json from? In particular the response to mock the build() command.
EDIT:
The class I want to test, calendar.py:
from google.oauth2 import service_account
from googleapiclient.discovery import build
class Calendar:
def __init__(self, credentials_file, calendar_id) -> None:
credentials = service_account.Credentials.from_service_account_file(
credentials_file, scopes=["https://www.googleapis.com/auth/calendar"]
)
self.service = build("calendar", "v3", credentials=credentials)
self._id = calendar_id
How to retrive the json response of build to save it in calendar-discovery.json?
Modified class to simplify mocking
import google_auth_httplib2
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.http import build_http
class Calendar:
def __init__(self, credentials_file, calendar_id) -> None:
credentials = service_account.Credentials.from_service_account_file(
credentials_file, scopes=["https://www.googleapis.com/auth/calendar"]
)
http = google_auth_httplib2.AuthorizedHttp(credentials, http=build_http())
self.service = build("calendar", "v3", http=http)
self._id = calendar_id
The test:
def test_calendar_initialization(mocker):
mock = mocker.patch("meal_planner.calendar.build_http")
mock.return_value = HttpMock("calendar-discovery.json", {"status": 200})
calendar = Calendar(credentials_file="credential.json", calendar_id="id")
Solution 1:[1]
- List all the discovery APIs: https://discovery.googleapis.com/discovery/v1/apis
- Search for
"name": "calendar" - Look for
"discoveryRestUrl": "https://calendar-json.googleapis.com/$discovery/rest?version=v3" - Get the calendar discovery document
curl https://calendar-json.googleapis.com/$discovery/rest?version=v3 > calendar-discovery.json`
Reference: https://developers.google.com/discovery
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Simone Gaiarin |
