Testing — an in-memory APIC

Test your automation without a fabric — an in-memory APIC that speaks the SDK’s HTTP.

FakeApic answers the requests a Niwaki client sends — login, design pushes, deletes, reads with the full query grammar — from a DN-indexed store, and refuses loudly whatever it cannot answer faithfully. StoredObject is the read-only view of what it holds.

Nothing here is imported by import niwaki; import niwaki.testing from your tests. A pytest fixture is available as an opt-in plugin:

# conftest.py
pytest_plugins = ["niwaki.testing.pytest"]

# test_provisioning.py
def test_push(fake_apic):
    with fake_apic.client() as aci:
        build_shop("acme").push(aci)
    assert fake_apic.get("uni/tn-acme") is not None

Example:

from niwaki.design import tenant
from niwaki.testing import FakeApic

fake = FakeApic()
with fake.client() as aci:
    tenant("prod").bd("web", unicast_routing=True).push(aci)
    assert aci.tenant("prod").bd("web").read().unicast_routing is True

The guide page Testing your automation walks through it.

The fake

class niwaki.testing.FakeApic(*, host='https://fake-apic.invalid')[source]

Bases: object

An in-memory APIC that answers the SDK’s HTTP traffic — tests without a fabric.

The fake is an httpx handler over a DN-indexed object store. Writes (POST, DELETE) change the store; reads (GET) answer from it with the APIC’s own query grammar — scoping, response subtrees, property selection, ordering, paging and evaluated filters. Anything it cannot answer faithfully is refused with an APIC error whose text starts with "FakeApic:": never a silent, wrong answer.

Wire it in through a ready client (client(), async_client()), through transport for an httpx client of your own, or through handle() as a callback for an HTTP-mocking library.

It mimics what the APIC does to what it is given: a bitmask comes back in a different order than written, a named number is stored by its name (port 80 → "http"), and every returned object carries its dn.

Like every controller it always holds the policy universe, a polUni at uni that cannot be deleted.

What it is not: no RBAC (every login succeeds), no WebSocket subscriptions, no policy validation and no containment check (a design the controller would refuse, an object under a parent that cannot hold it, is stored), and no fault raising — a fault exists only when you seed one, and a failure only when you inject it with fail().

Parameters:

host (str) – The base URL the fake answers as (its clients connect to it). The default is a reserved, never-resolvable name.

Example:

from niwaki.design import tenant
from niwaki.testing import FakeApic

fake = FakeApic()
with fake.client() as aci:
    tenant("prod").bd("web").push(aci)
    assert aci.tenant("prod").bd("web").read().name == "web"
assert fake.get("uni/tn-prod/BD-web") is not None
property host: str

The base URL this fake answers as (https://fake-apic.invalid by default).

property transport: MockTransport

An httpx transport answered by this fake, for a client you build yourself.

Example:

http = httpx.Client(base_url=fake.host, transport=fake.transport)
with Niwaki.with_client(http, fake.host, "ops", "anything") as aci:
    ...
property requests: tuple[Request, ...]

Every request received, in order — login, refresh and refused ones included.

A snapshot of the log at the moment you read it. Seeding is not a request and never appears here.

Example:

posts = [r for r in fake.requests if r.method == "POST"]
client(**kwargs)[source]

A Niwaki client wired to this fake, not yet connected.

Entering it logs in with placeholder credentials the fake answers inline. The store belongs to the fake, not to a client: several clients, one after the other or side by side, see the same objects.

Parameters:

**kwargs (object) – Relayed untouched to the client constructor (retry, refresh_threshold, …) — so an option the sync client does not take (max_concurrent) is refused exactly as Niwaki refuses it.

Returns:

The client, inert until entered.

Raises:

TypeError – An option the client does not accept.

Return type:

Niwaki

Example:

with fake.client() as aci:
    tenant("prod").bd("web").push(aci)
async_client(**kwargs)[source]

An AsyncNiwaki client wired to this fake, not yet connected.

Parameters:

**kwargs (object) – Relayed untouched to the client constructor (max_concurrent, retry, …).

Returns:

The client, inert until entered with async with.

Raises:
  • TypeError – An option the client does not accept.

  • ValueError – An option the client refuses (max_concurrent=0).

Return type:

AsyncNiwaki

Example:

async with fake.async_client() as aci:
    await tenant("prod").bd("web").push(aci)
get(dn)[source]

The object stored at dn, as a detached read-only view.

Parameters:

dn (str) – A Distinguished Name.

Returns:

A StoredObject, or None when nothing is stored there.

Return type:

StoredObject | None

Example:

bd = fake.get("uni/tn-prod/BD-web")
assert bd is not None and bd.attributes["arpFlood"] == "yes"
objects(aci_class=None)[source]

Every stored object (or every object of one exact class), in DN order.

Parameters:

aci_class (str | None) – A wire class name to keep, or None for everything.

Returns:

Detached read-only views, sorted by DN.

Return type:

tuple[StoredObject, …]

Example:

assert [o.dn for o in fake.objects("fvBD")] == ["uni/tn-prod/BD-web"]
seed(payload)[source]

Load objects into the store, exactly as a POST would — without a request.

A top-level object lands at its explicit dn attribute, else at its own RN from the root (polUni → uni, fabricTopology → topology); children nest under it. The APIC’s storage mimicry applies (named numbers, bitmask order). Seeding is not logged in requests and never triggers an injected failure.

Parameters:

payload (JsonObject) – An APIC envelope, {"<class>": {"attributes": {...}, "children": [...]}}. Seed a faultInst under an object to give it a fault.

Raises:

ValueError – The envelope is malformed, names an unknown class or property, or places an object in contradiction with itself (an explicit dn whose RN the naming properties do not compute, a child dn not directly under its parent). Nothing is stored then: a seed is atomic.

Example:

fake.seed({"fvTenant": {"attributes": {"dn": "uni/tn-prod", "name": "prod"}}})
classmethod from_snapshot(snapshot, *, host='https://fake-apic.invalid')[source]

A fresh fake holding the objects a niwaki.snapshot captured.

Every captured object is rebuilt at its DN (the snapshot’s scope plus the RN chain of its tree), with its captured attributes. A snapshot.take against the new fake, at the same scope, serialises to the same bytes — so a capture of a real fabric becomes a test fixture.

Parameters:
  • snapshot (Snapshot) – The capture to replay. An empty capture gives an empty fake.

  • host (str) – The base URL the new fake answers as.

Returns:

A new, independent fake (an empty request log).

Raises:

ValueError – The snapshot tree is malformed.

Return type:

Self

Example:

captured = snapshot.take(aci, "uni/tn-prod")
replayed = FakeApic.from_snapshot(captured)
fail(
dn,
*,
code='400',
text='FakeApic: injected failure',
status=400,
method=None,
times=None,
)[source]

Make the next requests that target dn answer an APIC error.

A request targets dn when it is a GET or a DELETE of /api/mo/<dn>.json, or a POST that would write dn — posted at dn, or dn materialised anywhere inside the posted envelope. A class query or a read of an ancestor’s subtree does not target it. A failed write changes nothing: an APIC POST is atomic.

Through the SDK the answer surfaces as its typed error — APIError (or the subclass the HTTP status selects) with apic_code and apic_message set.

Parameters:
  • dn (str) – The Distinguished Name to fail.

  • code (str) – The APIC error code to answer.

  • text (str) – The APIC error text to answer.

  • status (int) – The HTTP status (400 to 599).

  • method (str | None) – Narrow to one HTTP verb ("GET", "POST", "DELETE"), or None for all three.

  • times (int | None) – How many matching requests fail before the failure is spent, or None to fail every one until clear_failures().

Raises:

ValueError – status is not an error status, method is not a verb the fake serves, or times is below 1.

Example:

fake.fail("uni/tn-prod/BD-web", code="103", text="boom", method="POST")
clear_failures()[source]

Drop every pending injected failure.

handle(request)[source]

Answer one HTTP request — the handler behind transport.

Host-agnostic: only the path, method, query string and body are read, so it can serve as the callback of an HTTP-mocking library for code that names its own APIC host. Every request is logged in requests, whatever the answer.

Parameters:

request (Request) – The httpx request (its body already read).

Returns:

The APIC answer – an imdata envelope, or an APIC error envelope (HTTP 400 and a text starting with "FakeApic:" for a request the fake refuses; the injected status for an injected failure).

Return type:

Response

Example:

response = fake.handle(httpx.Request("GET", "https://apic/api/class/fvBD.json"))

Store views

class niwaki.testing.StoredObject(dn, aci_class, attributes)[source]

Bases: object

One object held by a FakeApic, as a read-only value.

A view is detached: it is built at the moment you ask for it, and a later write to the fake never changes a view already handed out. It compares by value — against another view, or against one you build yourself with a plain dict of attributes.

dn

The object’s Distinguished Name.

Type:

str

aci_class

Its wire class name ("fvBD").

Type:

str

attributes

Its wire attributes, exactly as stored — values in the APIC’s own spelling (a named number by its name, a bitmask in the fabric’s order). The dn is not repeated here. Read-only: assigning an item raises TypeError.

Type:

collections.abc.Mapping[str, str]

Example:

stored = fake.get("uni/tn-prod/BD-web")
assert stored == StoredObject(
    dn="uni/tn-prod/BD-web", aci_class="fvBD", attributes={"name": "web"}
)

The pytest plugin

The opt-in pytest plugin of niwaki.testing — a fresh fake APIC per test.

Installing niwaki registers no pytest plugin: opt in from your root conftest.py:

pytest_plugins = ["niwaki.testing.pytest"]

Then request the fake_apic fixture by name. This is the only module of the SDK that imports pytest.

The plugin defines one fixture, fake_apic: a fresh, empty FakeApic for each test that requests it.