Skip to main content

Pytest Clerk Mock

A pytest plugin that serves the Clerk Backend API from memory. Your code keeps using the real clerk-backend-api SDK: it builds and sends each request, parses each response and raises its own errors, while an httpx transport answers from the fixture's in-memory state.

Features

  • A real clerk-backend-api Clerk over an in-memory httpx transport: mock_clerk.sdk() and mock_clerk.transport, plus mock_clerk.route(httpx_mock) for default clients.
  • Users, organizations, memberships, email addresses, actor tokens, sessions, sign-in tokens, invitations and the JWKS, answered with Clerk's response and error bodies.
  • Faults and recorded requests: fail, fail_connection, clear_faults and requests.
  • The SDK's retry loop on a virtual clock, with each wait in retry_waits.
  • Signed Clerk v2 session tokens, a matching public key and an httpx.Auth for the active identity.

Examples

The mock_clerk fixture holds the state. mock_clerk.sdk() returns a real Clerk whose sync and async httpx clients send every request to mock_clerk.transport:

def test_create_user(mock_clerk):
    clerk = mock_clerk.sdk()

    user = clerk.users.create(email_address=["person@example.test"], first_name="Ada")

    assert clerk.users.get(user_id=user.id).first_name == "Ada"

An application that injects its own httpx clients passes the transport instead:

clerk = Clerk(
    client=httpx.Client(transport=mock_clerk.transport),
    async_client=httpx.AsyncClient(transport=mock_clerk.transport),
)

Code that builds Clerk() with default clients is served through pytest-httpx:

def test_default_clients(mock_clerk, httpx_mock):
    mock_clerk.route(httpx_mock)

    assert Clerk(bearer_auth="sk_test").users.list() == []

create_mock_clerk_fixture(default_user_id, default_org_id, default_org_role, autouse) builds a mock_clerk fixture with another starting identity.

Installation

pip install pytest-clerk-mock

For code that builds Clerk() with its default httpx clients, install the httpx-mock extra, which brings in pytest-httpx:

pip install "pytest-clerk-mock[httpx-mock]"

Services And Routes

The transport serves every operation of these SDK services under https://api.clerk.com/v1:

SDK service State on mock_clerk
users mock_clerk.users
organizations mock_clerk.organizations
organization_memberships mock_clerk.organization_memberships
email_addresses stored on the users that hold them
actor_tokens mock_clerk.actor_tokens.issued
sessions mock_clerk.sessions
sign_in_tokens mock_clerk.sign_in_tokens.issued
invitations mock_clerk.invitations.issued
jwks the public key that verifies session tokens

Each service on mock_clerk is the seeding API: its synchronous methods take the SDK's own parameters, apart from the request options (retries, server_url, timeout_ms and http_headers), so a test seeds state with the same calls it makes through the SDK:

user = mock_clerk.users.create(email_address=["person@example.test"])
organization = mock_clerk.organizations.create(request=models.CreateOrganizationRequestBody(name="Acme"))
mock_clerk.organization_memberships.create(
    organization_id=organization.id,
    user_id=user.id,
    role="org:admin",
)

A few helpers seed records the Backend API cannot create, or store them under an ID the test chooses:

  • mock_clerk.users.add(user_id, **fields) takes the keyword parameters of users.create and returns the models.User; an ID already taken raises ValueError.
  • mock_clerk.organizations.add(org_id, name="", slug="") registers an organization.
  • mock_clerk.users.add_biometric_credential(user_id, platform=..., name=None) enrolls a biometric credential, which users.list_biometric_credentials and users.list_trusted_devices return until it is revoked.
  • mock_clerk.sessions.add_reverification(session_id, level=models.Level.FIRST_FACTOR) records a completed reverification that sessions.get_reverification reads back.

Users created or added with email addresses hold them verified, the first one primary, as Clerk does for users the Backend API creates. A created_at RFC 3339 timestamp, as Clerk takes for imported users, becomes the user's creation time, so a test can seed users who signed up days ago:

mock_clerk.users.add("user_imported", created_at="2026-01-05T09:30:00Z")

A failed operation answers with a Clerk {"errors": [...]} body and a status the SDK maps for that operation, so the SDK raises ClerkErrors or SDKError itself: for example, an unknown user is a 404 and a membership in an organization the mock does not hold is refused. Where Clerk documents an error code, as for user_locked and user_merge_not_allowed, the mock sends that code; other refusals carry a code the mock chooses. A request no route serves raises UnroutedClerkRequestError, naming its method and path; the SDK does not retry it.

Faults And Recorded Requests

from http import HTTPStatus

from clerk_backend_api import models

mock_clerk.fail(
    "GET",
    "/v1/users/{user_id}",
    HTTPStatus.SERVICE_UNAVAILABLE,
    [models.ClerkError(code="unavailable", message="Unavailable", long_message="Unavailable")],
    headers={"Retry-After": "2"},
    times=1,
)
mock_clerk.fail_connection("POST", "/v1/users", exception=httpx.ConnectError)
mock_clerk.clear_faults()
  • fail(method, path, status, errors, headers=None, times=None) answers matching requests with a Clerk error body; fail_connection(method, path, exception=httpx.ConnectError, times=None) raises an httpx transport error instead. The path may use SDK placeholders such as {user_id}. A fault lasts until clear_faults() when times is None, or for that many requests.
  • mock_clerk.requests holds every httpx.Request the SDK sent, body included.

Retries Without Waiting

The fixture runs the SDK's retry loop on a virtual clock: it replaces only the time and asyncio names inside clerk_backend_api.utils.retries, so a retry window passes instantly and every wait, backoff or Retry-After, is appended in seconds to mock_clerk.retry_waits. A persistent 5XX exhausts the window and the SDK raises; fail(..., times=1) gives a retry that then succeeds. mock_clerk.sdk() sends no retries unless given a retry_config.

Session Tokens And Auth

A key pair generated once per test session signs RS256 Clerk v2 session tokens that clerk_backend_api.security.authenticate_request verifies:

options = AuthenticateRequestOptions(
    jwt_key=mock_clerk.jwt_public_key,
    authorized_parties=[SESSION_TOKEN_AUTHORIZED_PARTY],
)
  • mock_clerk.session_token(...) returns a token for the active identity, or for the user_id, org_id, org_role, actor, session_id and expires_in given. The organization claim carries the role without its org: prefix, as Clerk's v2 tokens do, so the verified payload's org_role reads admin for an administrator.
  • mock_clerk.auth is an httpx.Auth that sends Authorization: Bearer <token> for the active identity, and no header while nobody is signed in.
  • GET /v1/jwks serves the public key, so verification without jwt_key works through mock_clerk.route(httpx_mock). Sessions' create_token signs with the same key, honors expires_in_seconds and names the session's active organization with the member's role. For a session that is no longer active, after revoke, its user's deletion or mock_clerk.sessions.set_status(session_id, status), the mock returns a 401 error body instead, which the SDK raises as ClerkErrors.
  • Sign-in tokens carry a ticket and its URL, signed with a key of their own, so the session token key never verifies a ticket.

The active identity starts as the fixture's defaults and changes with:

mock_clerk.configure_auth("user_456", org_id="org_789", org_role="org:member", actor="user_admin")
mock_clerk.configure_auth_from_user(MockClerkUser.GUEST)

with mock_clerk.as_user("user_789"):
    ...

MockClerkUser names TEAM_OWNER, TEAM_MEMBER, GUEST and UNAUTHENTICATED.

Local Development

poetry install --all-extras
poetry run pytest --ignore=tests/contract_parity
poetry run pytest tests/contract_parity -m contract
poetry run ruff check .
poetry run black --check .

The contract tests check that every operation of each served SDK service has a route, its _async method included, and a mock method taking the operation's parameters.

License

MIT

Metadata

Release files for pytest-clerk-mock 0.7.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pytest-clerk-mock 0.7.0
File Size Uploaded Provenance Actions
pytest_clerk_mock-0.7.0.tar.gz 39.1 kB With provenance Details for pytest_clerk_mock-0.7.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pytest-clerk-mock 0.7.0
File Interpreter ABI Platform Actions
pytest_clerk_mock-0.7.0-py3-none-any.whl Python 3 none any Details for pytest_clerk_mock-0.7.0-py3-none-any.whl

Total release size: 88.3 kB

Release files / pytest_clerk_mock-0.7.0.tar.gz

Download URL pytest_clerk_mock-0.7.0.tar.gz
Size 39.1 kB
Tags Source
SHA-256 checksum
How to use checksums
99b437eb68de1a3b8db9cc15b69cd2c620ba641e712b54da107cfe6d53c40986
BLAKE2b-256 checksum
How to use checksums
94dfe301a740e4f8f2d9e844598dae01479710bec145ccc2ab617dcc66ebc883
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

Release files / pytest_clerk_mock-0.7.0-py3-none-any.whl

Download URL pytest_clerk_mock-0.7.0-py3-none-any.whl
Size 49.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4d3ae8affdd16a1484354dc4cb6b0d65ab7e8a399dbf56ae879e03fff60c3b38
BLAKE2b-256 checksum
How to use checksums
5e1782e31b42389f762154147fda8bfd8e1bf8b0c334a7932b54c7729ccb4358
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

Security for pytest-clerk-mock 0.7.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for pytest_clerk_mock-0.7.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page