David Dahan
David Dahan

Reputation: 11172

Python mock patch syntax trouble with different arguments number

## tests file
@mock.patch('profiles.models.create_stripe_charge', StripeMocks._mock_raises_stripe_error)
def my_test(self):
    #  ... stuff


## logic file
def create_stripe_charge(customer, amount_in_cents, capture=True):
    # ... stuff

## mocks file
class StripeMocks:
    def _mock_raises_stripe_error(self):
        raise stripe.error.StripeError

When running my test, I got a _mock_raises_stripe_error() takes 1 positional argument but 3 were given' error.

I understand that I'm trying to mock a 3-args method with a 1-arg method, but what if I just want to tell Python: please, no matter how many arguments my create_stripe_charge method has, I just want to simulate that it raises an Exception.

What is the correct syntax to do this? Thanks.

Upvotes: 0

Views: 1327

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123510

To raise an exception when a mock is called, set the side_effect attribute to an exception:

@mock.patch('profiles.models.create_stripe_charge',
            side_effect=stripe.error.StripeError)
def my_test(self, mock_create_stripe_charge):
    # ...

You replaced create_stripe_charge() entirely, with a function that only takes one argument (self). You could use *args to capture additional arguments (and since you used an unbound method, there is no need to use self at all), but using a new function is not really a good idea.

Using a proper mock to replace the function also lets you assert that the mock was called properly, and you can make assertions about what arguments were passed in. You can't do that when you use your own function instead.

Upvotes: 5

Related Questions