alata.

Testing

Test your Alata application with pytest, HTTP test cases, fluent JSON assertions, and database transaction examples.

Alata is built to be tested. The framework ships first-class testing utilities — an HTTP test case that drives your application through its real kernel, a fluent assertion API for JSON responses, and database transaction helpers — all designed to plug straight into pytest.

Getting Started

Alata's testing tools build on pytest and pytest-asyncio. A scaffolded project already includes them as dev dependencies, together with httpx (which powers the HTTP test client):

pyproject.toml
[dependency-groups]
dev = [
    "pytest>=8.0.0",
    "pytest-asyncio>=0.25.0",
    "httpx>=0.28.0",
    "ruff>=0.16.0",
]

Enable pytest-asyncio's automatic mode so plain async def test functions run without decorating each one:

pyproject.toml
[tool.pytest.ini_options]
testpaths = ["tests"]
asyncio_mode = "auto"

With asyncio_mode = "auto", any async test function is collected and awaited automatically — no @pytest.mark.asyncio needed.

The conftest pattern

Create a dedicated database for tests and configure it in .env.testing. Application boot loads .env first and then this overlay, so an early os.environ["DB_DATABASE"] assignment alone is not enough.

.env.testing
APP_ENV=testing
ENVIRONMENT=local
DB_DATABASE=myapp_test
CACHE_STORE=memory
QUEUE_CONNECTION=sync
LOG_CHANNEL=null

Set the test database host, port, user, and password here as well if they differ from development. Prepare its schema before running the suite:

./alata migrate --env testing

Select this environment before pytest imports any application modules. Loading the overlay here also covers tests that use the module-level boot() helper:

tests/conftest.py
import os
from pathlib import Path

import pytest
from dotenv import load_dotenv

from alata.container import ServiceContainer


TEST_ENV = Path(__file__).resolve().parents[1] / ".env.testing"
if not TEST_ENV.is_file():
    raise pytest.UsageError("Create .env.testing with a dedicated test database first.")
load_dotenv(TEST_ENV, override=True)
os.environ["APP_ENV"] = "testing"


@pytest.fixture
def fresh_container():
    """An isolated container for unit tests that register their own services."""
    previous = ServiceContainer.get_instance()
    isolated = ServiceContainer()
    ServiceContainer.set_instance(isolated)
    try:
        yield isolated
    finally:
        isolated.flush()
        ServiceContainer.set_instance(previous)

Use the isolated container for unit tests:

tests/test_container_wiring.py
def test_singleton_returns_same_instance(fresh_container):
    fresh_container.singleton("svc", lambda: object())

    assert fresh_container.make("svc") is fresh_container.make("svc")

For integration tests, use the application's kernel and lifecycle as shown below. Do not flush the shared application after each test: importing bootstrap.application again returns its existing Python module and application object.

HTTP Tests

HttpTestCase runs requests against your application's ASGI kernel in-process — no server, no sockets. Subclass it once per project and implement get_application():

tests/test_api_base.py
from typing import TYPE_CHECKING

from alata.http.testing import HttpTestCase

if TYPE_CHECKING:
    from alata.application import Application


class ApiTestCase(HttpTestCase):
    def get_application(self) -> "Application":
        from bootstrap.application import app

        return app

    async def asyncSetUp(self):
        app = self.get_application().fastapi
        self._lifespan = app.router.lifespan_context(app)
        await self._lifespan.__aenter__()
        await super().asyncSetUp()

    async def asyncTearDown(self):
        try:
            await super().asyncTearDown()
        finally:
            await self._lifespan.__aexit__(None, None, None)

HttpTestCase creates the HTTP client; the base class above also runs application startup and shutdown, including async provider hooks. Every test class that extends your ApiTestCase gets an httpx.AsyncClient wired to the kernel, plus async helper methods for each verb — get, post, put, patch, and delete — that each return a TestResponse:

tests/test_users.py
class TestUsers(ApiTestCase):
    async def test_index_lists_users(self):
        response = await self.get("/api/v1/users")

        response.assert_ok()

    async def test_store_creates_a_user(self):
        response = await self.post("/api/v1/users", json={"name": "Bedu"})

        response.assert_created()

The helpers accept every keyword argument the underlying httpx client does — json=, params=, headers=, and so on. And because TestResponse transparently forwards unknown attributes to the wrapped httpx.Response, you can still read response.status_code, response.headers, or call response.json() directly whenever an assertion helper doesn't fit.

Response assertions

All assertion methods return the TestResponse, so they chain:

response.assert_ok().assert_json_structure({"users": {"*": ["id", "name"]}})
MethodAsserts
assert_status(code)The response has the given status code (failure messages include the body).
assert_ok()Status is 200.
assert_created()Status is 201.
assert_no_content()Status is 204.
assert_json(callback)Fluent assertions against the JSON body (see below).
assert_json(exact={...})The decoded JSON body equals exact exactly.
assert_json_structure(structure)The body contains the given key structure.
assert_contents(*substrings)The (buffered) text body contains each substring.
assert_stream(*chunks)A streamed body equals the given content or exact chunk sequence.
assert_stream_contains(*substrings)The streamed content contains each substring.

Asserting JSON structure

assert_json_structure verifies that keys exist, without caring about values. Use a list for leaf keys, a dict to nest, and a "*" key to apply a structure to every element of a list:

response.assert_json_structure({
    "teams": {"*": ["name", "sport"]},
})

Fluent JSON assertions

For value-level assertions, pass a callback to assert_json. The callback receives an AssertableJson scoped to the body:

response.assert_json(lambda json: (
    json.where("id", 1)
        .where("name", "Bedu")
        .where("active", lambda v: v is True)
        .has("profile", lambda profile: (
            profile.where("email", "a@b.com").etc()
        ))
        .etc()
))

The full API:

MethodAsserts
where(key, expected)key equals a literal value, or satisfies a predicate callable.
where_not(key, expected)key does not equal the value / pass the predicate.
where_all({key: expected, ...})Each pair, via where.
where_type(key, "string")key is one of the JSON type names string, integer, double, number, boolean, array, object, null. Accepts "string|null" or a list.
where_all_type({key: type, ...})Each pair, via where_type.
where_contains(key, expected)The list (or string) at key contains expected.
has(key)key exists.
has(key, 3)key is a sized collection of length 3.
has(key, callback)Scope into key and run nested assertions.
has(key, 3, callback)Both length and a nested scope.
has_all("a", "b")Every key exists (also accepts a list).
has_any("a", "b")At least one key exists.
missing(key) / missing_all(...)The key(s) are absent.
count(key, n)The collection at key has exactly n items.
first(callback)Scope into the first child element.
each(callback)Run the callback against every child element in its own scope.
etc()Acknowledge any remaining, un-asserted keys in this scope.

Keys support dot notation for deep access, including list indexes — where("meta.page", 1) or has("users.0.name") both work.

The fluent API enforces a strict interaction model: when a scope closes, every property of the object must have been asserted against — otherwise the test fails with the list of unexpected keys. This catches responses that quietly grow extra fields. Call .etc() in a scope to opt out and acknowledge the remaining keys.

Testing streamed responses

Server-Sent Events endpoints get their own assertion family. is_stream() reports whether the response is text/event-stream, stream_chunks() returns the individual data: payloads, and stream_content() concatenates them:

response = await self.post("/api/v1/chat", json={"message": "Hi"})

# Assert the concatenated stream content:
response.assert_stream("Hello there!")

# Or assert the exact chunk sequence:
response.assert_stream("Hello", " there!")

# Or just look for substrings anywhere in the stream:
response.assert_stream_contains("Hello")

assert_stream and assert_stream_contains fail fast if the response is not actually a stream — use assert_contents for buffered bodies.

Database Testing

Rolling back test writes

Add DatabaseTransaction before your API test base class to roll back test writes automatically:

tests/test_signup.py
from alata.db.testing import DatabaseTransaction

from tests.test_api_base import ApiTestCase


class TestSignup(DatabaseTransaction, ApiTestCase):
    async def test_signup_creates_a_user(self):
        response = await self.post("/api/v1/signup", json={
            "name": "Bedu",
            "email": "bedu@example.com",
        })
        response.assert_created()

The mixin wraps the default async connection. Call await super().asyncSetUp() before creating test data and await super().asyncTearDown() after custom teardown. Rollback also runs when setup, the test, or teardown fails.

Writes through sync sessions, other connections, independent tasks or processes, or code that commits the outer transaction need separate cleanup. See transactions.

A dedicated test database

Use the .env.testing setup from the conftest pattern, even when using transaction rollbacks. Check the resolved database before any test setup that changes the schema:

from alata.db import get_engine
from bootstrap.application import app

assert app.env == "testing"
assert get_engine().url.database == "myapp_test"

Run migrations against that database explicitly. migrate:fresh drops its tables; it should not be an automatic consequence of importing test modules or starting pytest.

Swapping Services with Fakes

Because your code resolves services through the container, tests can substitute implementations without patching imports. Bind an instance over the real binding and the entire application — routes, tasks, commands — sees the fake:

class FakeMailer:
    def __init__(self):
        self.sent = []

    def send(self, to, subject, body):
        self.sent.append((to, subject, body))


async def test_signup_sends_welcome_mail(fresh_container):
    mailer = FakeMailer()
    fresh_container.instance("mailer", mailer)   # override the real binding

    await register_user(name="Bedu", email="bedu@example.com")

    assert len(mailer.sent) == 1

container.instance() registers a pre-built object, replacing whatever factory or singleton was bound under that name. The isolated container fixture discards the fake afterwards and restores the previous container.

If you fake often, a tiny helper fixture keeps tests tidy:

tests/conftest.py
@pytest.fixture
def fake(fresh_container):
    """Register fake bindings: fake("storage", MockStorage())."""
    def _fake(name: str, factory_or_value) -> None:
        if callable(factory_or_value):
            fresh_container.bind(name, factory_or_value)
        else:
            fresh_container.instance(name, factory_or_value)

    return _fake

Testing Queued Tasks

Call a decorated task directly to test its logic without dispatching it. Await an async def task as below; call a synchronous def task without await:

tests/test_email_tasks.py
from app.tasks.email_tasks import send_welcome_email


async def test_welcome_email_builds_the_right_message():
    result = await send_welcome_email(user_id=1)   # runs inline, no broker

    assert result["subject"] == "Welcome!"

To assert that code dispatches a task — without actually enqueueing anything — replace the task's kiq method with an AsyncMock:

tests/test_signup_dispatch.py
from unittest.mock import AsyncMock, patch

from app.services.registration import register_user
from app.tasks.email_tasks import send_welcome_email


async def test_signup_dispatches_welcome_email():
    with patch.object(send_welcome_email, "kiq", new=AsyncMock()) as kiq:
        await register_user(name="Bedu", email="bedu@example.com")

        kiq.assert_awaited_once_with(user_id=1)

The same approach works for console commands: they are ordinary classes, so instantiate the command, stub out any collaborators through the container, and call its logic directly.

Testing Time-Dependent Code

Use freeze_time() to give Alata date helpers, model timestamps, and scheduled tasks a predictable clock:

from alata.support.dates import utc_now
from alata.testing import freeze_time

with freeze_time("2026-10-06T09:00:00+09:00"):
    user = User.create({"name": "Bedu", "email": "bedu@example.com"})
    assert user.created_at == utc_now()

The previous clock is restored when the block exits. Nested scopes and independently frozen async tasks are isolated. See dates and timezones for the clock's scope.

Running the Suite

./alata test                 # the whole suite
./alata test tests/test_users.py -v
./alata test -k "signup"      # by keyword

In CI, generate .env.testing with the isolated database credentials before running migrations and pytest.

On this page