Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading