Files
napalm-redfish/tests/conftest.py
T
Christian Manivong daa7dc9726
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 13s
driver / types (pull_request) Successful in 58s
driver / test (3.12) (pull_request) Failing after 58s
driver / test (3.13) (pull_request) Failing after 55s
driver / lowest (pull_request) Failing after 30s
driver / build (pull_request) Successful in 27s
driver / security (pull_request) Successful in 1m4s
CI / driver (pull_request) Failing after 2m29s
driver / publish (pull_request) Skipped
feat(time-sync): the BMC's NTP servers through TimeSyncMixin
netOrk keeps one list of NTP servers per site and aligns a device that
differs (NetOrk/netork#2360). A BMC takes part through Redfish's
ManagerNetworkProtocol: NTP.NTPServers is read, and written with a
PATCH that carries the resource's @odata.etag as If-Match, so a change
made on the BMC in between is refused instead of overwritten.

BMCs give the array a fixed length and show the unused slots as empty
strings (three on an iDRAC 9, two on an iLO 5). Such an array is filled
up with its empty value, and more servers than slots are refused before
anything is written. Servers of a disabled NTP are not in use: they read
as none, and the write turns NTP on. Servers the BMC already uses are
not written again, so a poll that aligns it every time does not churn.
get_ntp_servers() follows the same rule.

A BMC runs on UTC or an offset (DateTimeLocalOffset), not a zone, so
time_sync_writes is {"ntp_servers"} and the zone is read only where the
manager names an IANA zone (TimeZoneName). A BMC whose Redfish has no
NTP block (the Supermicro X10's v1_0_0) raises rather than claiming it
has no servers. The bmc driver has it over Redfish only; ipmi has none.

Needs napalm-device-types 4.35.0.

Refs NetOrk/netork#2367
2026-11-11 15:20:35 +01:00

140 lines
4.6 KiB
Python

"""Shared helpers for loading the recorded Redfish responses under tests/fixtures/."""
import json
import re
from collections.abc import Callable
from pathlib import Path
from urllib.parse import urlsplit
import pytest
import responses
FIXTURES = Path(__file__).parent / "fixtures"
PREFIX = "/redfish/v1"
def fixture_file(mockup: str, path: str) -> Path:
"""Map a request path to its file: /redfish/v1/X/Y -> <mockup>/X/Y/index.json."""
path = path.split("#", 1)[0].split("?", 1)[0].rstrip("/")
if not path.startswith(PREFIX):
raise ValueError(f"not a Redfish path: {path}")
relative = path[len(PREFIX) :].lstrip("/")
return FIXTURES / mockup / relative / "index.json"
def load(mockup: str, path: str) -> dict:
return json.loads(fixture_file(mockup, path).read_text())
@pytest.fixture
def rackmount():
"""Loader for the DMTF public-rackmount1 mockup."""
return lambda path: load("dmtf-public-rackmount1", path)
@pytest.fixture
def localstorage():
"""Loader for the DMTF public-localstorage mockup."""
return lambda path: load("dmtf-public-localstorage", path)
@pytest.fixture
def telemetry():
"""Loader for the DMTF public-telemetry mockup."""
return lambda path: load("dmtf-public-telemetry", path)
BASE_URL = "https://bmc.example.net"
SESSIONS = "/redfish/v1/SessionService/Sessions"
SESSION_PATH = SESSIONS + "/0123456789abcdef"
TOKEN = "secret-session-token"
class MockupServer:
"""Serve a fixture mockup over mocked HTTP, plus a SessionService that hands out one token.
Unknown paths return a Redfish error body with 404, like a real service. ``override``
replaces the answer for one method and path (the path may include a query string);
``answer`` does so with a callback that takes the request and returns ``(status, body)``.
"""
def __init__(self, rsps, mockup: str):
self.rsps = rsps
self.mockup = mockup
self.overrides: dict[tuple[str, str], tuple[int, dict, dict]] = {}
self.callbacks: dict[tuple[str, str], Callable] = {}
anything = re.compile(re.escape(BASE_URL) + r"/.*")
for method in (responses.GET, responses.POST, responses.PATCH, responses.DELETE):
rsps.add_callback(method, anything, callback=self._handle)
def override(
self,
method: str,
path: str,
status: int,
body: dict | str | None = None,
headers: dict | None = None,
):
self.overrides[(method, path)] = (status, body if body is not None else {}, headers or {})
def answer(self, method: str, path: str, callback: Callable):
self.callbacks[(method, path)] = callback
@staticmethod
def _reply(status, body, headers=None):
if isinstance(body, str):
text = body
else:
text = json.dumps(body) if body != {} or status != 204 else ""
return status, {"Content-Type": "application/json", **(headers or {})}, text
def _handle(self, request):
parts = urlsplit(request.url)
for key in ((request.method, f"{parts.path}?{parts.query}"), (request.method, parts.path)):
if key in self.callbacks:
return self._reply(*self.callbacks[key](request))
if key in self.overrides:
return self._reply(*self.overrides[key])
if request.method == "POST" and parts.path == SESSIONS:
return self._reply(
201,
{"@odata.id": SESSION_PATH, "Id": "0123456789abcdef"},
{"X-Auth-Token": TOKEN, "Location": BASE_URL + SESSION_PATH},
)
if request.method == "DELETE" and parts.path == SESSION_PATH:
return self._reply(204, {})
if request.method == "GET":
try:
return self._reply(200, load(self.mockup, parts.path))
except (FileNotFoundError, ValueError):
pass
return self._reply(
404,
{
"error": {
"code": "Base.1.0.ResourceMissingAtURI",
"message": f"{parts.path} not found",
}
},
)
def calls(self, method: str | None = None, path: str | None = None):
return [
c
for c in self.rsps.calls
if (method is None or c.request.method == method)
and (path is None or urlsplit(c.request.url).path == path)
]
@pytest.fixture
def http():
with responses.RequestsMock(assert_all_requests_are_fired=False) as rsps:
yield rsps
@pytest.fixture
def server(http):
"""The public-rackmount1 mockup served on BASE_URL."""
return MockupServer(http, "dmtf-public-rackmount1")