# Testing your API client

You have written an [ApiClient](../reference/ApiClient.md#dazapiz.ApiClient) subclass for a REST API hosted in Azure behind Entra ID. Its tests should run in CI on every pull request, and CI has no Azure: no `az login`, no service principal you would want to put in a runner, and an API you do not want a test to change. dazapiz's own CI works the same way ([design decision D23](https://github.com/pedrobtz/py-dazapiz/blob/main/.agents/design.md#10-decisions): Azure is tested by hand, CI only with simple mocks): what needs real Azure is checked by hand, and the automated tests touch neither Azure nor the network.

So the tests replace the two things the client talks to:

- **the API**, with [respx](https://lundberg.github.io/respx/), which answers `httpx` requests from routes you declare. [ApiClient](../reference/ApiClient.md#dazapiz.ApiClient) is an `httpx` client, so respx mocks it with no change to the client;
- **the credential**, with [dazapiz.testing.StaticTokenCredential](../reference/testing.StaticTokenCredential.md#dazapiz.testing.StaticTokenCredential), a `TokenCredential` that hands out a fixed token and records the scopes it was asked for. Pass it as `credential=`, which wins over [app_credential()](../reference/app_credential.md#dazapiz.app_credential).

Everything else is the real client: its URL templating, request bodies, parsing, validation, errors and retries.


# The example: the Petstore as an Azure-hosted API

The public Swagger Petstore needs no token, so the example in `examples/azure_petstore.py` pretends it does. It is the Petstore client of the [REST client](rest-client.md) page with an Entra ID scope and its own service-principal variables:

``` python
class AzurePetStoreClient(PetStoreClient):
    """The Petstore client with Entra ID authentication, for the testing guide.

    Every method is `PetStoreClient`'s; only where the token comes from is new.
    """

    scope = "api://00000000-0000-0000-0000-000000000000/.default"
    client_id_env = "PETSTORE_CLIENT_ID"
    client_secret_env = "PETSTORE_CLIENT_SECRET"
```

Its tests are in `examples/tests/` and run in dazapiz's CI. They need `pytest`, `respx` and `pytest-socket` in your dev dependencies:

``` sh
uv add --dev pytest respx pytest-socket
```


# The fixtures: `conftest.py`

Copy this file next to your tests and change the client, the URL and the names:

``` python
@pytest.fixture
def api() -> Iterator[respx.MockRouter]:
    """The fake API: add routes with `api.get("/pet/7").respond(...)`.

    An unmatched request raises instead of going out (`assert_all_mocked`,
    respx's default); routes a test adds but does not call are allowed.
    """
    with respx.mock(base_url=PETSTORE_URL, assert_all_called=False) as router:
        yield router


@pytest.fixture
def credential() -> StaticTokenCredential:
    """A credential that hands out "fake-token" and records the scopes asked for."""
    return StaticTokenCredential()


@pytest.fixture
def store(
    api: respx.MockRouter, credential: StaticTokenCredential
) -> Iterator[AzurePetStoreClient]:
    """The client under test, on the fake API and the fake credential."""
    with AzurePetStoreClient(credential=credential) as client:
        yield client
```

`api` is a respx router for the API's base URL, so routes are written as paths (`api.get("/pet/7")`). `assert_all_called=False` lets a test declare routes it does not end up calling. `credential` is a fresh [StaticTokenCredential](../reference/testing.StaticTokenCredential.md#dazapiz.testing.StaticTokenCredential) per test, so `credential.calls` holds only that test's calls. `store` is the client under test, built on both.


# The tests

Each test scripts the API's answer, calls a method, and checks what came back and what was sent. A successful call returns a validated model, and the request carried the fake token, asked for with the class's scope:

``` python
def test_get_pet_returns_a_validated_pet_and_sends_the_token(
    api: respx.MockRouter, store: AzurePetStoreClient, credential: StaticTokenCredential
) -> None:
    route = api.get("/pet/7").respond(json=PET)

    pet = store.get_pet(7)

    assert pet == Pet(
        id=7, name="Rex", photo_urls=["https://example.com/rex.png"], status="available"
    )
    assert route.call_count == 1
    assert route.calls.last.request.headers["Authorization"] == "Bearer fake-token"
    assert credential.calls == [("api://00000000-0000-0000-0000-000000000000/.default",)]
```

The scope is written out rather than read from the class, so a test fails if the class's scope changes by mistake.

A request body is checked as it was sent, from the recorded request: the model's camelCase aliases, and only the fields that were set.

``` python
def test_add_pet_sends_the_model_as_json(api: respx.MockRouter, store: AzurePetStoreClient) -> None:
    route = api.post("/pet").respond(json=PET)

    store.add_pet(PetCreate(id=7, name="Rex", photo_urls=[HttpUrl("https://example.com/rex.png")]))

    # camelCase, and only the fields that were set: no "status": null.
    sent = json.loads(route.calls.last.request.content)
    assert sent == {"id": 7, "name": "Rex", "photoUrls": ["https://example.com/rex.png"]}
```

Failures are scripted the same way. A body that does not validate is a [ResponseParseError](../reference/ResponseParseError.md#dazapiz.ResponseParseError); a 404 is the client's own domain error, chained to the [ApiError](../reference/ApiError.md#dazapiz.ApiError):

``` python
def test_a_malformed_pet_is_a_parse_error(
    api: respx.MockRouter, store: AzurePetStoreClient
) -> None:
    api.get("/pet/7").respond(json={"id": 7, "photoUrls": []})  # no "name"

    with pytest.raises(ResponseParseError):
        store.get_pet(7)


def test_404_is_pet_not_found(api: respx.MockRouter, store: AzurePetStoreClient) -> None:
    api.get("/pet/7").respond(404, json={"message": "Pet not found"})

    with pytest.raises(PetNotFoundError) as err:
        store.get_pet(7)

    assert isinstance(err.value.__cause__, ApiError)
    assert err.value.__cause__.response.status_code == 404
```

`side_effect` with a list answers each call in turn, which scripts a retry. [ApiClient](../reference/ApiClient.md#dazapiz.ApiClient) retries 429, 503 and connection failures, waiting between attempts with `time.sleep`; its `sleep=` argument takes the function to wait with instead, so `sleep=waits.append` makes the test instant and records the waits:

``` python
def test_503_is_retried(api: respx.MockRouter, credential: StaticTokenCredential) -> None:
    waits: list[float] = []
    route = api.get("/pet/7")
    route.side_effect = [httpx.Response(503), httpx.Response(200, json=PET)]

    # sleep= receives each retry wait instead of time.sleep: no real waiting.
    with AzurePetStoreClient(credential=credential, sleep=waits.append) as store:
        assert store.get_pet(7).id == 7
    assert route.call_count == 2
    assert len(waits) == 1


def test_500_is_not_retried(api: respx.MockRouter, credential: StaticTokenCredential) -> None:
    waits: list[float] = []
    route = api.get("/pet/7").respond(500)

    with (
        AzurePetStoreClient(credential=credential, sleep=waits.append) as store,
        pytest.raises(ApiError),
    ):
        store.get_pet(7)
    assert route.call_count == 1
    assert waits == []
```


# Which credential the client picks

Whether a deployment gets its service principal and a developer their `az login` depends on the environment, and can be tested without signing in: [app_credential()](../reference/app_credential.md#dazapiz.app_credential) only builds the azure-identity credential, it fetches no token until a request is made. Set or clear the variables with `monkeypatch`, build the client, and check `client.credential`, the credential it chose, by type:

``` python
def test_service_principal_when_its_variables_are_set(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.delenv("AZURE_TOKEN_CREDENTIALS", raising=False)
    monkeypatch.setenv("PETSTORE_CLIENT_ID", "00000000-0000-0000-0000-000000000001")
    monkeypatch.setenv("PETSTORE_CLIENT_SECRET", "not-a-secret")
    monkeypatch.setenv("AZURE_TENANT_ID", "00000000-0000-0000-0000-000000000002")

    with AzurePetStoreClient() as client:
        assert isinstance(client.credential, ClientSecretCredential)


def test_your_az_login_when_they_are_not(monkeypatch: pytest.MonkeyPatch) -> None:
    for name in ("AZURE_TOKEN_CREDENTIALS", "PETSTORE_CLIENT_ID", "PETSTORE_CLIENT_SECRET"):
        monkeypatch.delenv(name, raising=False)

    with AzurePetStoreClient() as client:
        credential = client.credential
    assert isinstance(credential, ChainedTokenCredential)
    # Then the device code, but only in an interactive session.
    assert isinstance(credential.credentials[0], AzureCliCredential)
```

Clear `AZURE_TOKEN_CREDENTIALS` too: a value on the runner would choose the mode instead. These tests run with the network blocked (below), so building `ClientSecretCredential` and the `az login` chain is checked to make no connection.


# Offline by construction

Two guards make sure no test reaches the network, even by mistake.

- **respx, for `httpx`.** While the `api` router is active, a request no route matches raises an `AssertionError` ("not mocked") instead of going out: respx's `assert_all_mocked=True`, its default, which the fixture keeps.
- **pytest-socket, for everything else.** An autouse fixture blocks every socket for each test in the directory: MSAL and azure-identity fetching a token, another HTTP client, even a DNS lookup fail with `SocketBlockedError`. Unix sockets stay allowed, for local tooling.

``` python
@pytest.fixture(autouse=True)
def no_network() -> Iterator[None]:
    """Block every socket but Unix ones, for each test in this directory."""
    disable_socket(allow_unix_socket=True)
    yield
    enable_socket()
```

Being a fixture in `conftest.py`, it covers only the tests in that directory; tests elsewhere that need a local server keep their sockets. (`pytest --disable-socket` does the same for a whole run.) Both guards are themselves tested:

``` python
def test_an_unmocked_request_fails(api: respx.MockRouter, store: AzurePetStoreClient) -> None:
    with pytest.raises(AssertionError, match="not mocked"):
        store.get_pet(8)  # no route for /pet/8


def test_any_other_connection_is_blocked() -> None:
    with (
        pytest.raises(SocketBlockedError),
        pytest.warns(UserWarning, match="tried to use socket"),
    ):
        httpx.get("https://petstore3.swagger.io/api/v3/pet/7")
```

pytest-socket also issues a warning when it blocks a socket, which `pytest.warns` expects here; under `filterwarnings = ["error"]` an unexpected block fails the test either way.


# Without respx: `httpx.MockTransport`

If you would rather not add a dependency, `httpx.MockTransport` takes a function from request to response. Pass it as the client's `transport=`:

``` python
import httpx
import pytest

from dazapiz.testing import StaticTokenCredential


@pytest.fixture
def store():
    def handler(request: httpx.Request) -> httpx.Response:
        if request.method == "GET" and request.url.path == "/api/v3/pet/7":
            return httpx.Response(200, json=PET)
        return httpx.Response(404)

    transport = httpx.MockTransport(handler)
    with AzurePetStoreClient(credential=StaticTokenCredential(), transport=transport) as client:
        yield client
```

respx adds the routing, the call recording and the unmocked-request check, and needs no change to how the client is built.


# What stays manual

The fakes stand in for Entra ID and the API, so these tests cannot tell you that the real ones agree. Keep a short live check, run by hand or on a schedule with real credentials, outside the CI suite:

- the scope and the app registration: a real token for `scope` is accepted by the API;
- the service principal, managed identity or workload identity of each deployment signs in;
- the real API still answers in the shape the models expect.

dazapiz does the same with an opt-in live test of the Petstore example (`DAZAPIZ_LIVE_HTTP=1`) and a manual checklist for everything that needs Azure.
