A Beginner’s Guide to Getting Started with Mocking in Pytest

Jack P
4 min readApr 10, 2024

--

Photo by Chris Ried on Unsplash

As an Engineer you will be expected to know how to write and develop Unit Tests. In Python, a popular and great testing library is Pytest. Pytest offers a very simple syntax, many unique features such as parameterizing, strong assertion tools, fixtures, and much more. Knowledge of Pytest is a great skill to have as a Python Engineer and will help you and your team catch bugs before shipping out releases. Along with Pytest, engineers nowadays should be familiar with Mocking. Mocking is a crucial skill to have in order to run independently of external dependencies such as networking or databases. In this blogpost, I will dive into the basics of Pytest and Pytest Mock libraries as well as walk through an example of a unit test with mocking. This post assumes you have basic Python knowledge and will only scratch the surface of Pytest Mock capabailities.

Let’s dive in and learn more about Unit Testing and Mocking!

So what is Pytest?

The Pytest documentation describes Pytest as the following:

“The pytest framework makes it easy to write small, readable tests, and can scale to support complex functional testing for applications and libraries.”

In other words, Pytest makes unit testing easier, quicker to develop, and more powerful and effective. There are many capabilities of Pytest and we will only scratch the surface of it, I recommend visiting the Pytest documentation after this post to learn more about the many functionalities and capabilities of Pytest.

To start with Pytest, we need to install Pytest into our environment.

I would recommend to have a virtual environment set up for this walk through

To install Pytest, we need to run pip install pytest. And voilà, we have Pytest installed into our local Python virtual environment.

Next we will need to install Pytest-Mock. Pytest-Mock is a plugin for Pytest that provides enhanced support for mocking in tests. It builds upon Python’s built-in unittest.mock module, extending its capabilities and integrating it seamlessly with Pytest’s testing framework. To install Pytest Mock run the following command: pip install pytest-mock.

We are now ready to dive into a Pytest and Pytest Mock example.

Let’s say we have the following function:

# main.py

import requests

def get_data(url: str):
response = requests.get(url)
return response.json()

This simple function takes in a string URL and returns the JSON response. In our unit test we want to ensure we can run the unit test independently of our networking dependency. Our strategy for this test is to patch the requests.get method and have it return a mock object that has a set return value to the JSON method call.

Here is an example of what our test will look like:

# test_main.py

import pytest
from pytest_mock import MockerFixture

from main import get_data


def test_get_data(mocker: MockerFixture):
fake_url = "https://fakeurl.com"

mock_response = mocker.Mock()
mock_response.json.return_value = {"key": "value"}

mock_requests_get = mocker.patch(
"main.requests.get",
return_value=mock_response,
)

result = get_data(url=fake_url)

assert result == {"key": "value"}
mock_requests_get.assert_called_once_with(fake_url)

As we can see we start by importing Pytest and a MockerFixture class from Pytest-Mock. In our test_get_data method, we have access to the MockerFixture, parameter mocker. We then create a dummy parameter, and a Mock Response. The Mock Response is a Mock object that will have a return value dictionary when `.json()` is called from it. Notice how the Mock object is created from a mocker.Mock() call. We then patch the main file’s requests.get method with our mocker MockerFixture and return the Mock Response we created. Once we have our setup complete, we can call get_data(url=fake_url) and make some assertions. Our first assertion verifies that the response is the dictionary we return from our Mock Response and the second assertion verifies that requests.get gets called only once with the fake_url as a parameter.

You can then run the test with the following command: pytest test_main.py.

You will see the test pass with a green indicator.

Congratulations you just wrote your first mocking Pytest!

This blogpost only scratched the surface of the Pytest with the Pytest-Mock plugin. We covered basic information onPytest and Pytest-Mock, as well as covered a simple Pytest-Mock example. This post was not written to explain the endless functionality of pytest, but to merely get you started on your unit testing and mocking journey. I hope you enjoyed this post and are eager to dive more into Pytest and Pytest-Mock and will start building well-tested code going forward.

Happy Coding!

Photo by Pavel Herceg on Unsplash

--

--