Member-only story

Simplify your Python tests with dirty equals

Kevin Tewouda
5 min readAug 27, 2023

--

Photo by Stormseeker on Unsplash

Imagine this scenario, you have created a Todo API and you return this payload when requesting a single todo.

{
"created_at": "2023-08-27T17:31:14.355813",
"done": False,
"id": "70592516-24d5-4582-8d80-54b2c70b5ab1",
"metadata": {
"foo": "bar",
"text": "bla bla"
},
"name": "Learn Python",
"updated_at": None
}

How will you test this payload? Especially the datetime and uuid objects.

For the uuid, my strategy was to use a unittest mock utility or to write a function testing if I could get a uuid.UUID object and returns a boolean.

For the datetime, I use freezegun to freeze the date to a particular value. You can also use another package like time-machine (discovered recently). Thus I ended up with a test code like the following:

import uuid

from fastapi.testclient import TestClient
from freezegun import freeze_time

from api import app

client = TestClient(app)


def is_uuid(value: str) -> bool:
try:
uuid.UUID(value)
return True
except ValueError:
return False


@freeze_time('2023-08-27 18:00')
def test_get_todo():
response = client.get('/')
assert response.status_code == 200
data = response.json()

assert is_uuid(data['id'])
assert data['created_at'] ==…

--

--

Kevin Tewouda
Kevin Tewouda

Written by Kevin Tewouda

Déserteur camerounais résidant désormais en France. Passionné de programmation, sport, de cinéma et mangas. J’écris en français et en anglais dû à mes origines.

No responses yet