Files
napalm-proxmox/tests/pbs_fake.py
T
Christian Manivong f554e2cc79
driver / standard (pull_request) Failing after 17s
driver / lint (pull_request) Successful in 18s
driver / types (pull_request) Successful in 56s
driver / lowest (pull_request) Successful in 37s
driver / test (3.12) (pull_request) Successful in 1m6s
driver / test (3.13) (pull_request) Successful in 1m3s
driver / security (pull_request) Successful in 53s
driver / build (pull_request) Successful in 49s
CI / driver (pull_request) Failing after 2m8s
driver / publish (pull_request) Skipped
feat(login): get_web_login_auth on PVE and PBS, a source per realm, 0.20.0 (NetOrk/netork#662)
A Proxmox login names its realm, so each realm with someone who can log in
is a source of napalm-device-types' WebLoginAuthDict. It asks for a password
and a one-time code when the PVE realm's own tfa is set, or when every
enabled, unexpired user of it has an enabled second factor (/access/tfa);
a password alone when one user has none; OpenID is external.

Both servers list only the caller in /access/users and /access/tfa when the
login may not see the others, so the driver checks /access/permissions
first: Sys.Audit or User.Modify on /access/groups on PVE, Sys.Audit on
/access/users on PBS. Without it the read raises PermissionError rather
than judge the server by one account.

Needs napalm-device-types 4.50.0.
2026-11-29 00:19:52 +01:00

100 lines
3.5 KiB
Python

"""A stand-in for proxmoxer's PBS client, answering from recorded responses.
``tests/fixtures/pbs_api.json`` holds what a real Proxmox Backup Server 4.2
answered (sanitised). Paths a test adds on top -- backup groups, snapshots and
jobs, which that server did not have yet -- follow the shapes of the PBS API
schema (``pbs.proxmox.com/docs/api-viewer``).
"""
from __future__ import annotations
import copy
import json
from pathlib import Path
from typing import Any
from proxmoxer.core import ResourceException
RECORDED: dict[str, Any] = json.loads(
(Path(__file__).parent / "fixtures" / "pbs_api.json").read_text()
)
def _key(path: str, params: dict[str, Any]) -> str:
query = "&".join(f"{k}={params[k]}" for k in sorted(params))
return f"{path.strip('/')}?{query}" if query else path.strip("/")
class _Resource:
"""proxmoxer's chained form: ``api.nodes("localhost").status.get()``."""
def __init__(self, api: FakePbsApi, path: str) -> None:
self._api, self._path = api, path
def __getattr__(self, name: str) -> _Resource:
return _Resource(self._api, f"{self._path}/{name}")
def __call__(self, segment: str) -> _Resource:
return _Resource(self._api, f"{self._path}/{segment}")
def get(self, **params: Any) -> Any:
return self._api.get(self._path, **params)
def post(self, **params: Any) -> Any:
return self._api.post(self._path, **params)
def put(self, **params: Any) -> Any:
return self._api.put(self._path, **params)
class FakePbsApi:
"""``get``/``post``/``put``/``delete`` by path, like ``ProxmoxAPI.get("admin/gc")``,
or chained, like ``ProxmoxAPI.nodes("localhost").status.get()``.
A response is looked up as ``"path?k=v&..."`` first, then as ``"path"``. A
value that is an exception is raised. Every call is recorded in ``calls``.
"""
def __init__(self, **overrides: Any) -> None:
self.responses: dict[str, Any] = copy.deepcopy(RECORDED)
self.responses.update(overrides)
self.calls: list[tuple[str, str, dict[str, Any]]] = []
def _answer(self, method: str, path: str, params: dict[str, Any]) -> Any:
self.calls.append((method, path.strip("/"), params))
for key in (f"{method} {_key(path, params)}", f"{method} {path.strip('/')}"):
if key in self.responses:
return self._value(self.responses[key])
if method == "GET":
for key in (_key(path, params), path.strip("/")):
if key in self.responses:
return self._value(self.responses[key])
raise ResourceException(404, "Not Found", f"no recorded answer for {method} {path}")
@staticmethod
def _value(value: Any) -> Any:
if isinstance(value, Exception):
raise value
return copy.deepcopy(value)
def __getattr__(self, name: str) -> _Resource:
if name.startswith("_"):
raise AttributeError(name)
return _Resource(self, name)
def get(self, path: str, /, **params: Any) -> Any:
return self._answer("GET", path, params)
def post(self, path: str, /, **params: Any) -> Any:
return self._answer("POST", path, params)
def put(self, path: str, /, **params: Any) -> Any:
return self._answer("PUT", path, params)
def delete(self, path: str, /, **params: Any) -> Any:
return self._answer("DELETE", path, params)
def forbidden() -> ResourceException:
return ResourceException(403, "Forbidden", "permission check failed")