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:
objectAn in-memory APIC that answers the SDK’s HTTP traffic — tests without a fabric.
The fake is an
httpxhandler 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()), throughtransportfor anhttpxclient of your own, or throughhandle()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 itsdn.Like every controller it always holds the policy universe, a
polUniatunithat 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 transport: MockTransport¶
An
httpxtransport 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
Niwakiclient 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 asNiwakirefuses it.- Returns:
The client, inert until entered.
- Raises:
TypeError – An option the client does not accept.
- Return type:
Example:
with fake.client() as aci: tenant("prod").bd("web").push(aci)
- async_client(**kwargs)[source]¶
An
AsyncNiwakiclient 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:
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, orNonewhen 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
Nonefor 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
dnattribute, 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 inrequestsand never triggers an injected failure.- Parameters:
payload (JsonObject) – An APIC envelope,
{"<class>": {"attributes": {...}, "children": [...]}}. Seed afaultInstunder 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
dnwhose RN the naming properties do not compute, a childdnnot 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.snapshotcaptured.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.takeagainst the new fake, at the same scope, serialises to the same bytes — so a capture of a real fabric becomes a test fixture.- Parameters:
- 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,
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) withapic_codeandapic_messageset.- Parameters:
dn (str) – The Distinguished Name to fail.
code (str) – The APIC error
codeto answer.text (str) – The APIC error
textto answer.status (int) – The HTTP status (400 to 599).
method (str | None) – Narrow to one HTTP verb (
"GET","POST","DELETE"), orNonefor all three.times (int | None) – How many matching requests fail before the failure is spent, or
Noneto fail every one untilclear_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")
- 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
httpxrequest (its body already read).- Returns:
The APIC answer – an
imdataenvelope, 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:
objectOne 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
dictof attributes.- 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
dnis not repeated here. Read-only: assigning an item raisesTypeError.- Type:
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.