Metadata-Version: 2.4
Name: pytest-clerk-mock
Version: 0.7.0
Summary: A pytest plugin for mocking Clerk authentication
License-File: LICENSE
Author: Julien Kmec
Author-email: me@julien.dev
Requires-Python: >=3.11
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Provides-Extra: httpx-mock
Requires-Dist: clerk-backend-api (>=7.1.0)
Requires-Dist: cryptography (>=45.0.0)
Requires-Dist: httpx (>=0.28.0)
Requires-Dist: pydantic (>=2.0.0)
Requires-Dist: pyjwt (>=2.10.0)
Requires-Dist: pytest-httpx (>=0.36.0) ; extra == "httpx-mock"
Project-URL: Repository, https://github.com/julien777z/pytest-clerk-mock
Description-Content-Type: text/markdown

# Pytest Clerk Mock

A pytest plugin that serves the [Clerk](https://clerk.com/) 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`:

```python
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:

```python
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:

```python
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

```bash
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](https://pypi.org/project/pytest-httpx/):

```bash
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:

```python
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:

```python
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

```python
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:

```python
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:

```python
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

```bash
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

