Ir para o conteúdo

tempest_fastapi_sdk.testing

Helpers de teste para quem consome o SDK: app, banco, cliente e fixtures.

« Web, UI e utilitários


ModelFactory

ModelFactory(session: AsyncSession, model: type[ModelT], **defaults: Any)

Bases: Generic[ModelT]

Build and persist BaseModel instances with shared defaults.

Bind a model and its default column values to a session once, then call :meth:build (unsaved), :meth:create (persisted) or :meth:create_many. Per-call keyword arguments override the defaults. A default (or override) that is callable is invoked with the row's auto-incrementing index, which is how unique fields are generated — see :func:seq.

Attributes:

Name Type Description
session AsyncSession

The session rows are added to.

model type[ModelT]

The model class built.

Initialize the factory.

Parameters:

Name Type Description Default
session AsyncSession

The async session to persist into.

required
model type[ModelT]

The BaseModel subclass to build.

required
**defaults Any

Default column values. A callable value is called with the row index (see :func:seq) to produce a per-row value.

{}

Raises:

Type Description
TypeError

When model is not a BaseModel subclass.

build

build(**overrides: Any) -> ModelT

Return an unsaved instance (defaults + overrides).

Parameters:

Name Type Description Default
**overrides Any

Field values overriding the defaults.

{}

Returns:

Name Type Description
ModelT ModelT

A new, un-persisted model instance.

create async

create(**overrides: Any) -> ModelT

Build, add + flush an instance, and return it refreshed.

Uses flush (not commit) so the row is visible within the test's transaction while leaving commit/rollback to the harness.

Parameters:

Name Type Description Default
**overrides Any

Field values overriding the defaults.

{}

Returns:

Name Type Description
ModelT ModelT

The persisted, refreshed instance.

create_many async

create_many(count: int, **overrides: Any) -> list[ModelT]

Create count rows sharing overrides (unique per index).

Parameters:

Name Type Description Default
count int

How many rows to create.

required
**overrides Any

Field values overriding the defaults; a callable override still receives each row's index.

{}

Returns:

Type Description
list[ModelT]

list[ModelT]: The persisted, refreshed instances.

seq

seq(template: str, *, start: int = 0) -> Callable[[int], str]

Return an index generator formatting template with {n}.

Use as a factory default to produce unique string values — email=seq("user{n}@x.com") yields user0@x.com, user1@x.com, … one per built row.

Parameters:

Name Type Description Default
template str

A format string containing {n}.

required
start int

The first index value. Defaults to 0.

0

Returns:

Type Description
Callable[[int], str]

Callable[[int], str]: A function mapping the row index to the

Callable[[int], str]

formatted string.

make_test_database async

make_test_database(
    database_url: str = "sqlite+aiosqlite:///:memory:",
    *,
    metadata: MetaData | None = None,
) -> AsyncGenerator[async_sessionmaker[AsyncSession], None]

Yield a session factory backed by a freshly created database.

Setup creates every table, teardown drops them and disposes the engine. Use as an async with block in test setups that need a clean database per scope. The name does not start with test, so importing it into a test module does not make pytest collect it as a test.

Parameters:

Name Type Description Default
database_url str

SQLAlchemy URL.

'sqlite+aiosqlite:///:memory:'
metadata MetaData | None

The metadata to apply. Defaults to :attr:BaseModel.metadata.

None

Yields:

Type Description
AsyncGenerator[async_sessionmaker[AsyncSession], None]

async_sessionmaker[AsyncSession]: A session factory ready to use.

make_test_session async

make_test_session(
    database_url: str = "sqlite+aiosqlite:///:memory:",
    *,
    metadata: MetaData | None = None,
) -> AsyncGenerator[AsyncSession, None]

Yield a single :class:AsyncSession backed by a fresh database.

Convenience wrapper around :func:make_test_database for tests that only need one session. The name does not start with test, so importing it into a test module does not make pytest collect it as a test.

Parameters:

Name Type Description Default
database_url str

SQLAlchemy URL.

'sqlite+aiosqlite:///:memory:'
metadata MetaData | None

The metadata to apply.

None

Yields:

Name Type Description
AsyncSession AsyncGenerator[AsyncSession, None]

A live session — closed automatically on exit.

assert_subject_graph_valid

assert_subject_graph_valid(graph: SubjectGraph) -> None

Fail when the schema would break erasure of a data subject.

Call it from a test so a foreign key added without ON DELETE CASCADE toward a table of the subject's closure (or an unjustified SET NULL) fails CI instead of failing the first erasure request in production.

Example:

>>> def test_subject_graph() -> None:
...     assert_subject_graph_valid(SubjectGraph(Base.metadata, root="users"))

Parameters:

Name Type Description Default
graph SubjectGraph

The graph to check.

required

Raises:

Type Description
AssertionError

Listing every line of :meth:SubjectGraph.violations when there is at least one.

admin_login async

admin_login(
    client: AsyncFormClient[ResponseT],
    identifier: str,
    password: str,
    *,
    prefix: str = "/admin",
    headers: dict[str, str] | None = None,
) -> ResponseT

Sign in through the admin login form with an async client.

Parameters:

Name Type Description Default
client AsyncFormClient[ResponseT]

A client bound to the app — httpx.AsyncClient or httpx2.AsyncClient; it keeps the cookies between the two requests.

required
identifier str

The e-mail to submit.

required
password str

The password to submit.

required
prefix str

Where the admin router is mounted.

'/admin'
headers dict[str, str] | None

Extra headers for the submit, e.g. a trusted client-IP header.

None

Returns:

Name Type Description
ResponseT ResponseT

The POST {prefix}/login response, of the client's

ResponseT

own response type, not followed — 303 on success, the

ResponseT

re-rendered form otherwise.

admin_login_sync

admin_login_sync(
    client: SyncFormClient[ResponseT],
    identifier: str,
    password: str,
    *,
    prefix: str = "/admin",
    headers: dict[str, str] | None = None,
) -> ResponseT

Sign in through the admin login form with a sync client.

The fastapi.testclient.TestClient counterpart of :func:admin_login.

Parameters:

Name Type Description Default
client SyncFormClient[ResponseT]

A TestClient, httpx.Client or httpx2.Client; it keeps the cookies between the two requests.

required
identifier str

The e-mail to submit.

required
password str

The password to submit.

required
prefix str

Where the admin router is mounted.

'/admin'
headers dict[str, str] | None

Extra headers for the submit.

None

Returns:

Name Type Description
ResponseT ResponseT

The POST {prefix}/login response, of the client's

ResponseT

own response type, not followed.

admin_csrf_token

admin_csrf_token(html: str) -> str

Extract the csrf_token hidden field from an admin page.

Parameters:

Name Type Description Default
html str

A rendered admin page carrying a form.

required

Returns:

Name Type Description
str str

The token value.

Raises:

Type Description
ValueError

When the page has no csrf_token field — usually because it is not a form page, or the request was redirected.

SyncFormClient

Bases: Protocol

A sync HTTP client that loads a page and posts a form.

httpx.Client, httpx2.Client and Starlette's TestClient all satisfy it. The URL is positional-only, so an implementation is free to name it as it likes; the optional parameters are named, as they can only be passed by keyword.

get

get(url: str) -> ResponseT

Load url.

Parameters:

Name Type Description Default
url str

The path or URL to load.

required

Returns:

Name Type Description
ResponseT ResponseT

The response.

post

post(
    url: str,
    /,
    *,
    data: Mapping[str, str] | None = None,
    headers: Mapping[str, str] | None = None,
    follow_redirects: bool = False,
) -> ResponseT

Post a form to url.

Parameters:

Name Type Description Default
url str

The path or URL to post to.

required
data Mapping[str, str] | None

The form fields.

None
headers Mapping[str, str] | None

Extra request headers.

None
follow_redirects bool

Whether to follow a redirect.

False

Returns:

Name Type Description
ResponseT ResponseT

The response.

AsyncFormClient

Bases: Protocol

The async counterpart of :class:SyncFormClient.

httpx.AsyncClient and httpx2.AsyncClient satisfy it. The members return Awaitable rather than being async def, which accepts both a coroutine function and a method returning any other awaitable.

get

get(url: str) -> Awaitable[ResponseT]

Load url.

Parameters:

Name Type Description Default
url str

The path or URL to load.

required

Returns:

Type Description
Awaitable[ResponseT]

Awaitable[ResponseT]: The response, once awaited.

post

post(
    url: str,
    /,
    *,
    data: Mapping[str, str] | None = None,
    headers: Mapping[str, str] | None = None,
    follow_redirects: bool = False,
) -> Awaitable[ResponseT]

Post a form to url.

Parameters:

Name Type Description Default
url str

The path or URL to post to.

required
data Mapping[str, str] | None

The form fields.

None
headers Mapping[str, str] | None

Extra request headers.

None
follow_redirects bool

Whether to follow a redirect.

False

Returns:

Type Description
Awaitable[ResponseT]

Awaitable[ResponseT]: The response, once awaited.

FormResponse

Bases: Protocol

The part of an HTTP response the login helpers read.

text property

text: str

Return the decoded body.

Returns:

Name Type Description
str str

The response body as text.

assert_schema_metadata

assert_schema_metadata(module: ModuleType) -> None

Fail when an exported schema field is missing its documentation.

Parameters:

Name Type Description Default
module ModuleType

A module or package, usually the project's schemas package.

required

Raises:

Type Description
AssertionError

Listing one line per undocumented field.

schema_metadata_findings

schema_metadata_findings(module: ModuleType) -> list[SchemaMetadataFinding]

Check every field of every schema a module exports.

Parameters:

Name Type Description Default
module ModuleType

A module or package, usually the project's schemas package.

required

Returns:

Type Description
list[SchemaMetadataFinding]

list[SchemaMetadataFinding]: One finding per undocumented field,

list[SchemaMetadataFinding]

each on the class declaring it, sorted by schema and field. Empty

list[SchemaMetadataFinding]

when every field is documented.

SchemaMetadataFinding dataclass

SchemaMetadataFinding(schema: str, field: str, missing: tuple[str, ...])

One field that is missing part of its documentation.

Attributes:

Name Type Description
schema str

module.ClassName of the class declaring the field.

field str

The field name.

missing tuple[str, ...]

The metadata it lacks, in :data:LEAF_METADATA order.

render

render() -> str

Format the finding as module.Class.field: missing a, b.

Returns:

Name Type Description
str str

The one-line report.

LEAF_METADATA module-attribute

LEAF_METADATA: tuple[str, ...] = ('title', 'description', 'examples')

What a field holding a plain value must declare.

NESTED_METADATA module-attribute

NESTED_METADATA: tuple[str, ...] = ('title', 'description')

What a field holding another schema must declare.