Search code examples
pythonmockingpython-mockmagicmock

Configure return value mock with decorator only


Is there a way to capture the following logic in the patch decorator instead of having to pass the mock into the function:

@patch('boto3.client')
def test_playing_with_saml(self, boto3_client):
    boto3_client.return_value.assume_role_with_saml = lambda *args, **kwargs: ('foo', 'bar')
    self.assertEqual(playing_with_saml(), 'expected')

Solution

  • No, not really, not without speccing out the rest of boto3_client, which is not going to be clearer or more readable.

    I'd not use a lambda here, I'd set the return value of the mock instead:

    boto3_client.return_value.assume_role_with_saml.return_value = ('foo', 'bar')
    

    Now you can make assertions about the boto3_client.return_value.assume_role_with_saml method (like asserting it has been called).