Skip to content

9 - dirty-equals

A fresh testing library from Samuel Colvin who is also the author of pydantic. dirty-equals makes it possible to assert full payloads without a requirement for knowing the exact values of all the keys in the payload. Handy for testing JSON APIs, for example.

TODO

Read more
The code
import datetime as dt
import random
from typing import Any

from dirty_equals import Contains, IsList, IsNow, IsPositiveFloat
from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()


@app.post("/order")
async def create_order() -> dict[str, Any]:
    # Just a dummy payload for demonstration
    return {
        "price": random.random() * 100,
        "products": ["milk", "coke", "pasta"],
        "created_at": dt.datetime.now().isoformat(),
        "created_by": "Jerry",
    }


def test_order_api() -> None:
    client = TestClient(app)

    response = client.post("/order")

    assert response.json() == {
        "price": IsPositiveFloat(),
        "products": IsList(length=3) & Contains("pasta"),
        "created_at": IsNow(iso_string=True),
        "created_by": "Jerry",
    }

tested with:

dirty-equals==0.1
fastapi==0.74.1
requests==2.27.1
pytest==7.0.1