Search code examples
pythongoogle-apipython-unittestgoogle-api-python-clientpython-unittest.mock

How do you use googles python api mocks?


I need a bit of help using google's api mocks. I am new to using mocks and google's api. Here is the api mock

Here is my code I want to test:

#add_entry_to_calendar.py
#...
try:
    service = build("calendar", "v3", credentials=delegated_credentials)
    event = service.events().insert(calendarId=calendarID, body=entry).execute()
#handle exceptions


#test_add_entry_to_calendar.py
@patch("add_entry_to_calendar.build")
def test_add_entry_to_calendar_400(self, mock_build):
    
    http = HttpMock('tests/config-test.json', {'status' : '400'})
    service = mock_build("calendar", "v3", http=http)

    self.assertEqual(add_entry_to_calendar({"A":"B"}), None)

add_entry_to_calendar is getting the mock object when I run my test.

My question - How do I get add_entry_to_calender to use the HttpMock object that I created in test_add_entry_to_calendar? I need the mock object that is created to ".execute()" with my "HttpMock" that i created in the test as a parameter.


Solution

  • #from googleapiclient.errors import HttpError    
    except HttpError as google_e:
            response = json.loads(google_e.content)
            
            response_header_code = response.get("error").get("code")
            response_header_message = response.get("error").get("message")
            response_string = F"{response_header_code} {response_header_message} {response.get('error').get('errors')[0]}"
    
            if response_header_code == 400:
                logger.warning(F"Failed to add entry to calendar. Missing or invalid field parameter in the request. {response_string}")
    

    Throw an HttpError and then look for the error code.