Home > Software engineering >  How do you get a function that throws an exception when run in a mocked test to only throw from the
How do you get a function that throws an exception when run in a mocked test to only throw from the

Time:06-28

When I instantiate a google Mock in my unit test it instantly throws the exception. I tried to fix the issue with a lambda but I am not sure how to then run the lambda.

How do I create the exception in the test but get only get it to throw from from function I want to test?

#test_add_entry_to_calendar

@patch("add_entry_to_calendar.build")
    def test_add_entry_to_calendar_400(self, mock_build):
        
        #google's mock https://googleapis.github.io/google-api-python-client/docs/mocks.html
        http = HttpMock('tests/config-test.json', {'status' : '400'})
        
        service = build("calendar", "v3", http=http)
        
        mock_service = mock_build("calendar", "v3", http=http)
        mock_service.events.return_value.insert.return_value.execute.return_value = \
        lambda x: service.events().insert(calendarId='primary').execute(http=http)
        self.assertEqual(add_entry_to_calendar({"A":"B"}), None)

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

            #prints <function TestAddEntry.test_add_entry_to_calendar_400.<locals>.<lambda> at 0x7f119a53c310>
            #But I don't even want to get to this point.
            #I want the HttpError 400 to get thrown when I create "event"
            print("event is "   str(event))

    except HTTPError as e:
            print("HTTPError")

CodePudding user response:

Not sure if this is the "pythonic" way or even the correct way but I came to a solution.

    @patch("add_entry_to_calendar.build")
    def test_add_entry_to_calendar_400(self, mock_build):
        self.e = None

        #google's mock https://googleapis.github.io/google-api-python-client/docs/mocks.html
        http = HttpMock('tests/config-test.json', {'status' : '400'})
        
        service = build("calendar", "v3", http=http)
        mock_service = mock_build("calendar", "v3", http=http, side_effect=IndexError)

        try:
            service.events().insert(calendarId='primary').execute(http=http)
        except Exception as e:
            self.e = e

        mock_service.events.return_value.insert.return_value.execute.side_effect = self.e

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