Newer
Older
openstack-caracal-dc-dc / tests / dc-util-hosts-import / fake_netbox.py
"""
In-memory stand-in for the NB client in netbox/dc-util-hosts-import.py.

Implements the three methods the target calls on its client -- .one(), .all(),
.create() -- so the REAL main()/preflight can be driven end-to-end without a live
server. Injected at the get_nb() seam, exactly as tests/dc-rack-mgmt-import/ does.

FIDELITY. .one() issues GET ...?<filter>&limit=1 and takes results[0] -- single-match
by construction, returns the first record whose fields equal the filter, or None. .all()
returns every record on a path (optionally filtered), mirroring the target's limit=1000
list read. .create() records every write so a test can assert a rejected/dry run wrote
NOTHING. The store is keyed by path, so ipam/ip-ranges and ipam/ip-addresses both work.
"""
from __future__ import annotations


class FakeNB:
    def __init__(self, ip_ranges=(), ip_addresses=()):
        self.store = {
            "ipam/ip-ranges": [dict(r) for r in ip_ranges],
            "ipam/ip-addresses": [dict(a) for a in ip_addresses],
        }
        self.creates = []   # (path, payload) for every .create() -- the write ledger
        self._next_id = 2000

    def one(self, path, **flt):
        for rec in self.store.get(path, []):
            if all(str(rec.get(k)) == str(v) for k, v in flt.items()):
                return rec
        return None

    def all(self, path, **flt):
        out = []
        for rec in self.store.get(path, []):
            if all(str(rec.get(k)) == str(v) for k, v in flt.items()):
                out.append(rec)
        return out

    def create(self, path, payload):
        self.creates.append((path, dict(payload)))
        rec = dict(payload)
        rec["id"] = self._next_id
        self._next_id += 1
        self.store.setdefault(path, []).append(rec)
        return rec