HOME BLOG

Archive for the ‘Testing’ Category

How to mock Python functions with Pytest

Posted on: June 8th, 2022 by Olu No Comments

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

How to do mocking in setUp in Python

Posted on: August 29th, 2020 by Olu No Comments

Hi folks,

In this post I will talk about how to mock functions in Python across all methods of your test class.

To do this, all you have to do is perform your mocking in the setUp method of your test class.

A way to do this is to create a patch object using code like:

mock_item_patch = mock.patch('some.module.path.item')

 

Next, call start() on the patch object to create your mock using code like

mock_item = mock_item_patch.start()

 

Once you do this, you can set return_value or side_effect as needed. E.g.

mock_item.foo.return_value = 'bar'

 

Don’t forget to add a call to stop the patch on clean-up using code

self.addCleanup(mock_item_patch.stop)

 

Below is code showing all these in action.

 

from unittest import mock, TestCase


class YourTestClass(TestCase):
    def setUp(self):
        mock_item_patch = mock.patch('some.module.path.item')
        mock_item = mock_item_patch.start()
        mock_item.foo.return_value = 'bar'
        self.addCleanup(mock_item_patch.stop)


    def test_something(self):
        ...

 

That’s all for now. Happy software development.