Member-only story

A Short Guide to Mocking in Python Unit Testing

Matt Kornfield
5 min readJan 16, 2025

Patching and mocking and asserting, oh my

Photo by Timothy Dykes on Unsplash

There are a handful of ways to mock things in Python for unit testing, and I thought I’d give a set of ways to mock things, as well as explanations.

Some Given Code

Let’s say I want to test the following contrived code, in a file called

matts_module/request_samples.py

The code relies on the requests library, but we don’t actually want to call out to that, so we’ll learn how we can mock all these request calls.

import requests
from requests import Session
from typing import Tuple


def make_http_request(url: str) -> requests.Response:
resp = requests.get(url)
resp.raise_for_status()
return resp


def make_session_based_request(url: str) -> requests.Response:
with Session() as s:
return s.get(url)


def make_http_request_prepend_https(url: str) -> requests.Response:
return make_http_request("https://" + url)


def make_multiple_http_requests(
url: str) -> Tuple[requests.Response, requests.Response]:
resp = requests.get(url)
resp.raise_for_status()
resp2 = requests.post(url, json={"key": "val"})
resp2.raise_for_status()
return (resp, resp2)

How Patching (basically) Works

--

--

Matt Kornfield
Matt Kornfield

Written by Matt Kornfield

Today's solutions are tomorrow's debugging adventure.

No responses yet