Search code examples
pythonpytestpytest-mock

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.


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)