I am having issues mocking an exception in my python unit unit test I have simplified the code and the test here
session = botocore.session.get_session()
client = session.create_client('stepfunctions', region_name='us-east-1')
def execute(event, context):
try:
# some code here setting the parameters for start_execution
response = client.start_execution(
stateMachineArn=SM_ARN,
input=json.dumps(queue_event),
name=invocation_name
)
except client.exceptions.ExecutionAlreadyExists as e:
error_message = f'Execution {invocation_name} already exists'
logger.info(f"{error_message}. Details: {e}")
raise Exception("Exception already exists")
and the test I have written which passes, but when debugging is not entering the except client.exceptions.ExecutionAlreadyExists as e: block of code is this
@mock.patch('lib.lambdas.my_lambda.index.client.start_execution')
def test_execute_execution_already_exists(self, mock_start_execution):
from lib.lambdas.my_lambda.index import execute
# Set the side effect of the mock to raise the ExecutionAlreadyExists exception
exception = client.exceptions.ExecutionAlreadyExists(operation_name='StartExecution', error_response={
'Error': {'Code': 'ExecutionAlreadyExists', 'Message': 'Execution already exists'}})
mock_start_execution.side_effect = exception
mock_start_execution.return_value = {'ResponseMetadata': {'HTTPStatusCode': 400}}
# Call the execute function and verify that it raises an exception with the expected message
with self.assertRaises(Exception) as cm:
execute(self.event, get_lambda_context())
expected_message = "Execution already exists"
actual_message = str(cm.exception)
self.assertIn(expected_message, actual_message)