Skip to content

Testing your app

Rate limits get in the way of most tests and are the whole point of a few. This page covers both.

The tests below are for the app from Limiting by user, imported as per_user. ALICE is the header a signed-in user sends: {"authorization": "Bearer user-1"}.

Switch the limits off

For a test that is not about rate limits:

def test_a_route_without_meeting_its_limit() -> None:
    with per_user.limiter.disabled(), TestClient(per_user.app) as client:
        replies = [client.get("/me/reports", headers=ALICE) for _ in range(10)]
    assert all(reply.status_code == 200 for reply in replies)

Inside the block every request is allowed, nothing is counted and no rate limit headers are sent. The limiter goes back to how it was afterwards, even if the test fails.

Control the clock

A test of the limit itself should not sleep. Give the limiter a FrozenClock, which only moves when you move it:

def test_the_allowance_comes_back_in_time() -> None:
    clock = FrozenClock()
    app = per_user.create_app(Limiter(clock=clock))
    with TestClient(app) as client:
        replies = [client.get("/me/reports", headers=ALICE) for _ in range(4)]
        assert [reply.status_code for reply in replies] == [200, 200, 200, 429]

        clock.advance(int(replies[-1].headers["retry-after"]))
        assert client.get("/me/reports", headers=ALICE).status_code == 200

Two things make this easy:

  • Build the app in a function that takes the limiter. The examples in this guide all have a create_app(limiter), so a test can hand in a limiter with a clock it controls. Each Limiter() also keeps its own counts, so a new one for each test means no test sees another's requests.
  • Wait for as long as the response says. Advancing the clock by Retry-After works whichever algorithm the limiter uses.

Sign in as anyone

Keys are dependencies, so FastAPI's dependency_overrides works on them and on whatever they depend on:

def test_as_a_user_of_your_choosing() -> None:
    app = per_user.create_app(Limiter())
    app.dependency_overrides[per_user.current_user] = lambda: per_user.User(7)
    with TestClient(app) as client:
        replies = [client.get("/me/reports") for _ in range(4)]  # no token needed
    assert replies[0].json() == {"user": 7}
    assert [reply.status_code for reply in replies] == [200, 200, 200, 429]

The override replaces the authentication, and the limit follows: the requests are counted for user 7.