Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get call_count after using pytest mocker.patch

I'm using pytest-mocker to patch a function to mock away what it's doing. But I also want to know how many times it was called and its call args.

Some script:

def do_something():
    x = 42
    return calculate(x)

def calculate(num):
    return num * 2

The test:

def test_do_something(mocker):
    mocker.patch("sb.calculate", return_value=1)
    result = do_something()
    assert result == 1  # Assert calculate is mocked correctly and returned whatever what I set above

This helped me mock away the call but I want to know during the test how many times calculate was called and its call arguments. Struggling to see how to do this.

like image 309
rawr rang Avatar asked Nov 28 '25 04:11

rawr rang


1 Answers

You can do it like this:

mock_calculate = mocker.patch("sb.calculate", return_value=1)
assert mock_calculate.call_count == 1

Or if you want to check what parameters were passed:

mock_calculate = mocker.patch("sb.calculate", return_value=1)
assert mock_calculate.called_once_with(1)
like image 149
Code-Apprentice Avatar answered Nov 29 '25 19:11

Code-Apprentice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!