ratiugo
ratiugo

Reputation: 53

'TypeError: catching classes that do not inherit from BaseException is not allowed' when trying to mock an exception

I am trying to test a block of code which interacts with the Amazon Forecast service, which looks very similar to the example provided at https://github.com/aws-samples/amazon-forecast-samples/blob/master/ml_ops/visualization_blog/lambdas/createdataset/dataset.py.

More specifically, I am trying to test that I am handling the exception properly. Assuming 'forecast' is the Amazon Forecast boto3 client, the code is structured as follows:

def example_function(dataset):
    try:
        forecast.describe_dataset(dataset)
        #do some stuff
    except forecast.exceptions.ResourceNotFoundException:
        #do other stuff

I have a test case which looks like this:

from moto.forecast.exceptions import ResourceNotFoundException

@patch('forecast client')
def test(self, mock_forecast):
    mock_forecast.describe_dataset.side_effect = ResourceNotFoundException
    example_function(dataset)

This produces the 'TypeError: catching classes that do not inherit from BaseException is not allowed' which is confusing me, as moto.forecast.exceptions.ResourceNotFoundException inherits the moto class 'AWSError', which in turn inherits 'Exception'.

I am fairly at a loss as to how to test the 'except' block of my code without actually interacting with the forecast service if I am not able to set a side_effect as an Exception. Any ideas would be greatly appreciated!

Upvotes: 4

Views: 4343

Answers (1)

Eqzt111
Eqzt111

Reputation: 590

The problem probably is you overwritten the original forecast object with a mock and it returns a mock object to forecast.exceptions.ResourceNotFoundException in the example function when checking the exception branches.

So you have to modify the test to something like this:

from moto.forecast.exceptions import ResourceNotFoundException

@patch('forecast client')
def test(self, mock_forecast):
    mock_forecast.exceptions.ResourceNotFoundException = ResourceNotFoundException
    mock_forecast.describe_dataset.side_effect = ResourceNotFoundException("Exception message")
    example_function(dataset)

Upvotes: 2

Related Questions