Skip to content

Using Déjà in tests

You don't need production traffic to use Déjà. A test can drive the app itself on the recording loop, save a recording, and replay it, which is also the quickest way to try Déjà on your own code.

Record and replay in one test

The app, with the race:

wallet.py
"""A FastAPI app with a race: two purchases can both pass the balance check."""

import asyncio

from fastapi import FastAPI, HTTPException

import deja

START = 100


def create_app(directory: str = "deja-recordings") -> FastAPI:
    app = FastAPI()
    wallet = {"balance": START, "charged": 0}

    @app.post("/purchase")
    async def purchase(amount: int = 100):
        balance = wallet["balance"]
        if balance < amount:
            raise HTTPException(402, "insufficient funds")
        await asyncio.sleep(0.01)  # the payment provider's API call
        wallet["balance"] = balance - amount
        wallet["charged"] += amount
        if wallet["charged"] > START:
            deja.flag("charged more than the starting balance")
        return {"balance": wallet["balance"]}

    app.add_middleware(deja.DejaMiddleware, directory=directory)
    return app

The test: two purchases at once on the recording loop, then replay and verify.

record_and_replay.py
"""Record a race in a test, replay it, and check whether it is fixed."""

import asyncio

import httpx

import deja
from deja.replay import replay
from deja.verify import verify

from wallet import create_app


async def two_purchases(directory: str) -> list[str]:
    app = create_app(directory)
    transport = httpx.ASGITransport(app=app)
    async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
        await asyncio.gather(client.post("/purchase"), client.post("/purchase"))
    await asyncio.sleep(0.1)  # recordings are written off the event loop
    return asyncio.get_running_loop().deja.dumps


def main(directory: str = "deja-recordings") -> str:
    # 1. Record: run the requests on the recording loop.
    #    The second purchase calls deja.flag(), which saves a recording.
    saved = asyncio.run(two_purchases(directory), loop_factory=deja.recording_loop)
    recording = saved[0]

    # 2. Replay: the same interleaving, the same answers.
    result = replay(recording, lambda: create_app(directory + "/replay"))
    assert result.followed and result.same_responses, result.summary()

    # 3. Verify: against this (unfixed) code the race is still there.
    verdict = verify(recording, lambda: create_app(directory + "/replay"), times=3)
    assert not verdict.fixed, verdict.summary()
    return recording


if __name__ == "__main__":
    print(main())

What happens:

  1. asyncio.run(..., loop_factory=deja.recording_loop) runs the requests on the recording loop. Both purchases read the balance before either writes it; the second one finds more charged than the wallet held and calls deja.flag(), so the middleware saves a recording. loop.deja.dumps lists the files saved.
  2. replay runs the same requests against a fresh app in the recorded order: followed and same_responses are true.
  3. verify says the race is still there, because the code isn't fixed. After a fix, verdict.fixed becomes true.

Both examples are in the repository under docs/examples/ and run as part of its test suite.

Save a recording without a failure

To record a stretch of activity whether or not anything fails, mark the buffer and dump from the mark:

rec = asyncio.get_running_loop().deja
marker = rec.mark("trial 3")
...                                   # drive the app
rec.dump("trial3.deja", since=marker)

See Recorder.mark and Recorder.dump.

A regression test from a recording

deja export-test turns a recording into a pytest test that fails while the race reproduces (see Fixing a race). The generated test only needs deja installed:

from deja.verify import verify

def test_lost_update_wallet_balance():
    from gallery.wallet import create_app as app_factory

    verdict = verify(RECORDING, app_factory, times=3)
    assert verdict.fixed, verdict.summary()

Tips

  • Use a factory for the app, so each replay gets fresh state.
  • Replaying doesn't write recordings, even though the app still has the middleware.
  • If the recording was made with a fixed PYTHONHASHSEED, run replays with the same value (deja replay does this itself); see Configuration.