Hi folks,
In this post I talk about a nice way to mock functions when developing Python applications and using Pytest.
There are many ways of doing mocking in Python. But in this post I will cover how to do it using a nice library called pytest-mock.
To use pytest-mock, you need to install it using a command
pip install pytest-mock
Say you want to mock a function called is_eligible inside a module called application. You just need to use the mocker fixture which is provided by pytest-mock.
So your function can look as follows.
def test_some_function(mocker): mocker.patch('application.is_eligible', return_value=True) assert some_func_using_is_eligible() == True
That’s all for now. Till next time, happy software development.
References
Mocking functions in Python with Pytest Part I. https://www.freblogg.com/pytest-functions-mocking-1