netherframe.testing 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,377 @@
1
+ """Fault-injection scenarios for graph state backends, shared by the in-memory and PostgreSQL test suites.
2
+
3
+ ``FakeCloud`` records every mutating call with its interval, so an execution-history oracle can
4
+ check that no two mutations of one object overlapped. ``drive`` runs one operation the way hybrid
5
+ apply does (reserve, dispatch, call, return, commit) and can crash at any stage; ``abandon``
6
+ leaves an engine as a crashed process would (its lease neither renewed nor released).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import itertools
12
+ import threading
13
+ import time
14
+ from collections.abc import Callable
15
+ from dataclasses import dataclass, field
16
+ from typing import Any
17
+
18
+ from netherframe.core.backends.graph_recovery import Probe
19
+ from netherframe.core.backends.graph_state import (
20
+ CREATE,
21
+ CREATE_DISPATCHED,
22
+ DELETE,
23
+ DELETE_DISPATCHED,
24
+ DISPATCHED,
25
+ MOVE,
26
+ REPLACE,
27
+ UPDATE,
28
+ GraphStateBackend,
29
+ OperationRecord,
30
+ )
31
+ from netherframe.core.backends.graph_state_engine import GraphOperation, GraphStateEngine
32
+ from netherframe.core.backends.state_models import ResourceState
33
+
34
+ STACK = "stack"
35
+ TYPE = "fake_server"
36
+ PROVIDER = "fake"
37
+
38
+ #: Where ``drive`` can crash
39
+ AFTER_RESERVE = "after_reserve"
40
+ AFTER_DISPATCH = "after_dispatch"
41
+ AFTER_CALL = "after_call"
42
+ AFTER_RETURN = "after_return"
43
+ BETWEEN_HALVES = "between_halves"
44
+ CRASH_POINTS = (AFTER_RESERVE, AFTER_DISPATCH, AFTER_CALL, AFTER_RETURN)
45
+
46
+
47
+ class Crash(BaseException): # noqa: N818 - a simulated process death, not an error
48
+ """The simulated death of the process driving an operation."""
49
+
50
+
51
+ def address(name: str) -> str:
52
+ return f"{STACK}.{TYPE}.{name}"
53
+
54
+
55
+ def entry(name: str, attributes: dict[str, Any]) -> ResourceState:
56
+ return ResourceState(type=TYPE, id=name, provider=PROVIDER, attributes=dict(attributes), stack_id=STACK)
57
+
58
+
59
+ @dataclass
60
+ class Call:
61
+ object_id: str
62
+ action: str
63
+ actor: str
64
+ start: float
65
+ end: float | None = None
66
+
67
+
68
+ @dataclass
69
+ class FakeCloud:
70
+ """Objects by id, and every mutating call with its interval (``calls``)."""
71
+
72
+ objects: dict[str, dict[str, Any]] = field(default_factory=dict)
73
+ calls: list[Call] = field(default_factory=list)
74
+ _ids: Any = field(default_factory=lambda: itertools.count(1))
75
+ _lock: threading.Lock = field(default_factory=threading.Lock)
76
+
77
+ def _mutate(self, object_id: str, action: str, actor: str, duration: float, change: Callable[[], dict[str, Any]]) -> dict[str, Any]:
78
+ call = Call(object_id, action, actor, time.monotonic())
79
+ with self._lock:
80
+ self.calls.append(call)
81
+ try:
82
+ if duration:
83
+ time.sleep(duration)
84
+ with self._lock:
85
+ return change()
86
+ finally:
87
+ call.end = time.monotonic()
88
+
89
+ def create(self, actor: str, attributes: dict[str, Any], *, duration: float = 0.0) -> dict[str, Any]:
90
+ object_id = f"srv-{next(self._ids)}"
91
+
92
+ def change() -> dict[str, Any]:
93
+ self.objects[object_id] = {**attributes, "id": object_id}
94
+ return dict(self.objects[object_id])
95
+
96
+ return self._mutate(object_id, CREATE, actor, duration, change)
97
+
98
+ def update(self, actor: str, object_id: str, attributes: dict[str, Any], *, duration: float = 0.0) -> dict[str, Any]:
99
+ def change() -> dict[str, Any]:
100
+ self.objects[object_id] = {**self.objects[object_id], **attributes, "id": object_id}
101
+ return dict(self.objects[object_id])
102
+
103
+ return self._mutate(object_id, UPDATE, actor, duration, change)
104
+
105
+ def delete(self, actor: str, object_id: str, *, duration: float = 0.0) -> dict[str, Any]:
106
+ def change() -> dict[str, Any]:
107
+ self.objects.pop(object_id, None)
108
+ return {}
109
+
110
+ return self._mutate(object_id, DELETE, actor, duration, change)
111
+
112
+ def read(self, object_id: str) -> dict[str, Any] | None:
113
+ with self._lock:
114
+ found = self.objects.get(object_id)
115
+ return dict(found) if found is not None else None
116
+
117
+ def find(self, name: str) -> list[dict[str, Any]]:
118
+ with self._lock:
119
+ return [dict(found) for found in self.objects.values() if found.get("name") == name]
120
+
121
+ def overlapping(self) -> list[tuple[Call, Call]]:
122
+ """Pairs of mutating calls on one object whose intervals overlap (the oracle: none)."""
123
+ pairs = []
124
+ for first, second in itertools.combinations(self.calls, 2):
125
+ if first.object_id != second.object_id:
126
+ continue
127
+ first_end = first.end if first.end is not None else float("inf")
128
+ second_end = second.end if second.end is not None else float("inf")
129
+ if first.start < second_end and second.start < first_end:
130
+ pairs.append((first, second))
131
+ return pairs
132
+
133
+
134
+ class FileCloud(FakeCloud):
135
+ """A ``FakeCloud`` kept in a JSON file, shared by processes (a crashed run's and its recoverer's); calls are timed by the wall clock."""
136
+
137
+ def __init__(self, path: str) -> None:
138
+ super().__init__()
139
+ self.path = path
140
+
141
+ def _locked(self) -> Any:
142
+ import contextlib
143
+ import fcntl
144
+
145
+ @contextlib.contextmanager
146
+ def held() -> Any:
147
+ with open(f"{self.path}.lock", "a+") as lock:
148
+ fcntl.flock(lock, fcntl.LOCK_EX)
149
+ try:
150
+ yield
151
+ finally:
152
+ fcntl.flock(lock, fcntl.LOCK_UN)
153
+
154
+ return held()
155
+
156
+ def _read(self) -> dict[str, Any]:
157
+ import json
158
+ import os
159
+
160
+ if not os.path.exists(self.path):
161
+ return {"objects": {}, "calls": [], "next": 1}
162
+ with open(self.path) as handle:
163
+ return json.load(handle)
164
+
165
+ def _write(self, data: dict[str, Any]) -> None:
166
+ import json
167
+
168
+ with open(self.path, "w") as handle:
169
+ json.dump(data, handle)
170
+
171
+ def _record(self, object_id: str, action: str, actor: str, start: float, end: float | None) -> int:
172
+ with self._locked():
173
+ data = self._read()
174
+ data["calls"].append([object_id, action, actor, start, end])
175
+ self._write(data)
176
+ return len(data["calls"]) - 1
177
+
178
+ def _finish(self, index: int, end: float) -> None:
179
+ with self._locked():
180
+ data = self._read()
181
+ data["calls"][index][4] = end
182
+ self._write(data)
183
+
184
+ def _mutate(self, object_id: str, action: str, actor: str, duration: float, change: Callable[[], dict[str, Any]]) -> dict[str, Any]:
185
+ index = self._record(object_id, action, actor, time.time(), None)
186
+ try:
187
+ if duration:
188
+ time.sleep(duration)
189
+ with self._locked():
190
+ data = self._read()
191
+ self.objects = data["objects"]
192
+ result = change()
193
+ data["objects"] = self.objects
194
+ self._write(data)
195
+ return result
196
+ finally:
197
+ self._finish(index, time.time())
198
+
199
+ def create(self, actor: str, attributes: dict[str, Any], *, duration: float = 0.0) -> dict[str, Any]:
200
+ with self._locked():
201
+ data = self._read()
202
+ object_id = f"srv-{data['next']}"
203
+ data["next"] += 1
204
+ self._write(data)
205
+
206
+ def change() -> dict[str, Any]:
207
+ self.objects[object_id] = {**attributes, "id": object_id}
208
+ return dict(self.objects[object_id])
209
+
210
+ return self._mutate(object_id, CREATE, actor, duration, change)
211
+
212
+ def read(self, object_id: str) -> dict[str, Any] | None:
213
+ with self._locked():
214
+ found = self._read()["objects"].get(object_id)
215
+ return dict(found) if found is not None else None
216
+
217
+ def find(self, name: str) -> list[dict[str, Any]]:
218
+ with self._locked():
219
+ return [dict(found) for found in self._read()["objects"].values() if found.get("name") == name]
220
+
221
+ @property
222
+ def recorded(self) -> list[Call]:
223
+ with self._locked():
224
+ return [Call(object_id, action, actor, start, end) for object_id, action, actor, start, end in self._read()["calls"]]
225
+
226
+ def overlapping(self) -> list[tuple[Call, Call]]:
227
+ self.calls = self.recorded
228
+ return super().overlapping()
229
+
230
+
231
+ class CloudProber:
232
+ """``graph_recovery.Prober`` over a ``FakeCloud``: objects are read by id and located by their ``name`` (a client-chosen identity)."""
233
+
234
+ def __init__(self, cloud: FakeCloud) -> None:
235
+ self.cloud = cloud
236
+
237
+ def refresh(self, record: OperationRecord, before: ResourceState) -> Probe:
238
+ found = self.cloud.read(str(before.attributes.get("id")))
239
+ if found is None:
240
+ return Probe(False)
241
+ refreshed = before.copy()
242
+ refreshed.attributes = found
243
+ return Probe(True, refreshed)
244
+
245
+ def locate(self, record: OperationRecord, template: ResourceState) -> Probe:
246
+ name = template.attributes.get("name")
247
+ if not name:
248
+ return Probe(None, reason="its configuration sets no name to find it by")
249
+ found = self.cloud.find(str(name))
250
+ if len(found) > 1:
251
+ return Probe(None, reason=f"{len(found)} objects are named {name}")
252
+ if not found:
253
+ return Probe(False)
254
+ located = template.copy()
255
+ located.attributes = found[0]
256
+ return Probe(True, located)
257
+
258
+ def import_object(self, record: OperationRecord, template: ResourceState, import_id: str) -> Probe:
259
+ found = self.cloud.read(import_id)
260
+ if found is None:
261
+ return Probe(False)
262
+ imported = template.copy()
263
+ imported.attributes = found
264
+ return Probe(True, imported)
265
+
266
+
267
+ def abandon(engine: GraphStateEngine) -> None:
268
+ """Leave ``engine`` as a crashed process would: its heartbeat stops, its lease is neither renewed nor released."""
269
+ heartbeat, engine._heartbeat = engine._heartbeat, None
270
+ if heartbeat is not None:
271
+ heartbeat.stop()
272
+ engine._ownership = None
273
+
274
+
275
+ def drive(
276
+ engine: GraphStateEngine,
277
+ cloud: FakeCloud,
278
+ name: str,
279
+ action: str,
280
+ *,
281
+ attributes: dict[str, Any] | None = None,
282
+ crash: str | None = None,
283
+ actor: str = "run",
284
+ duration: float = 0.0,
285
+ ) -> GraphOperation:
286
+ """Run one operation on ``name`` as hybrid apply does: reserve (pre-call validation), dispatch, call the cloud, record what returned, commit.
287
+
288
+ ``crash`` stops it at that stage as a dead process would (``Crash`` is raised after
289
+ ``abandon``): nothing after it runs, not even the operation's end.
290
+ """
291
+ key = address(name)
292
+ before = engine.load_state().resources.get(key)
293
+ template = entry(name, attributes or {"name": name})
294
+ # This cloud consumes only its concrete request, never another graph value.
295
+ operation = engine.begin_operation(key, action, provider=PROVIDER, before=before, template=template, inputs=())
296
+ token = engine.enter_operation(operation)
297
+ try:
298
+ if crash == AFTER_RESERVE:
299
+ raise Crash(crash)
300
+ if action == REPLACE:
301
+ if before is None:
302
+ raise ValueError("a replacement needs an object")
303
+ operation.dispatch(DELETE_DISPATCHED)
304
+ cloud.delete(actor, str(before.attributes["id"]), duration=duration)
305
+ operation.returned({})
306
+ engine.record_removal(key)
307
+ if crash == BETWEEN_HALVES:
308
+ raise Crash(crash)
309
+ operation.dispatch(CREATE_DISPATCHED)
310
+ created = cloud.create(actor, template.attributes, duration=duration)
311
+ operation.returned(created)
312
+ engine.record_resource(entry(name, created))
313
+ else:
314
+ operation.dispatch(DISPATCHED)
315
+ if crash == AFTER_DISPATCH:
316
+ raise Crash(crash)
317
+ if action == CREATE:
318
+ result = cloud.create(actor, template.attributes, duration=duration)
319
+ elif action == UPDATE:
320
+ if before is None:
321
+ raise ValueError("an update needs an object")
322
+ result = cloud.update(actor, str(before.attributes["id"]), template.attributes, duration=duration)
323
+ elif action == DELETE:
324
+ if before is None:
325
+ raise ValueError("a delete needs an object")
326
+ result = cloud.delete(actor, str(before.attributes["id"]), duration=duration)
327
+ else:
328
+ raise ValueError(f"cannot drive a {action}")
329
+ if crash == AFTER_CALL:
330
+ raise Crash(crash)
331
+ operation.returned(result)
332
+ if crash == AFTER_RETURN:
333
+ raise Crash(crash)
334
+ if action == DELETE:
335
+ engine.record_removal(key)
336
+ else:
337
+ engine.record_resource(entry(name, result))
338
+ except Crash:
339
+ engine.exit_operation(token)
340
+ abandon(engine)
341
+ raise
342
+ except BaseException as exc:
343
+ engine.exit_operation(token)
344
+ operation.finish(exc)
345
+ raise
346
+ engine.exit_operation(token)
347
+ operation.finish(None)
348
+ return operation
349
+
350
+
351
+ def move(engine: GraphStateEngine, source: str, target: str, *, crash: bool = False) -> None:
352
+ """Move ``source``'s row to ``target`` as ``nf state mv`` does: one operation, both rows in one transaction; ``crash`` dies before the commit."""
353
+ import contextlib
354
+ import math
355
+
356
+ state = engine.load_state()
357
+ moved = state.resources[address(source)].copy()
358
+ moved.id = target
359
+ with contextlib.ExitStack() as stack:
360
+ stack.enter_context(engine.operation(address(source), MOVE, provider=PROVIDER, footprint=[address(target)]))
361
+ with engine.batched_saves(interval=math.inf):
362
+ engine.record_removal(address(source))
363
+ engine.record_resource(moved)
364
+ if crash:
365
+ abandon_pending(engine)
366
+ raise Crash("inside the move")
367
+
368
+
369
+ def abandon_pending(engine: GraphStateEngine) -> None:
370
+ """A crash inside a grouped commit: the group's records are never committed."""
371
+ engine._pending, engine._pending_ops, engine._pending_operations = [], {}, []
372
+ engine._group_depth = 1_000_000
373
+ abandon(engine)
374
+
375
+
376
+ def unresolved(backend: GraphStateBackend) -> list[OperationRecord]:
377
+ return backend.operations(unresolved=True)
@@ -0,0 +1,33 @@
1
+ """Netherframe's logs in a test run: in each test's captured output, not on the terminal.
2
+
3
+ pytest loads plugins before it captures output, and loading this package's (``pytest11``) imports
4
+ ``netherframe.core``, whose modules get their loggers on import: that configures logging with a
5
+ handler writing to the terminal's stderr, at the default level. Its logs then print between the
6
+ test progress dots, for passing tests too. :func:`log_to_captured_stderr` configures logging
7
+ again, writing to whatever ``sys.stderr`` is when a record is logged: in a test, the stream pytest
8
+ captures, so a log shows with the test that wrote it, and only if that test fails.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import sys
14
+
15
+ from netherframe.core.logging_setup import configure_logging, reset_logging
16
+
17
+ #: The level tests log at unless ``pytest --nf-test-log-level`` says otherwise
18
+ DEFAULT_TEST_LOG_LEVEL = "ERROR"
19
+
20
+
21
+ def _write_to_current_stderr(message: str) -> None:
22
+ sys.stderr.write(message)
23
+
24
+
25
+ def log_to_captured_stderr(level: str = DEFAULT_TEST_LOG_LEVEL) -> None:
26
+ """Log to the stderr pytest captures, at ``level`` (``pytest --nf-test-log-level``, default ``ERROR``).
27
+
28
+ Call it from a ``pytest_configure`` hook. pytest swaps ``sys.stderr`` for each test, and back
29
+ between tests, so the handler looks it up for each record, and writes it in the thread that
30
+ logged it (not enqueued for a writer thread, which could write between tests).
31
+ """
32
+ reset_logging()
33
+ configure_logging(level=level, sink=_write_to_current_stderr, enqueue=False, multiprocess_safe=False)
@@ -0,0 +1,124 @@
1
+ """The ``--nf-*`` pytest options: what only a test run decides, readable wherever test code runs.
2
+
3
+ Netherframe's own settings are flags and ``[tool.nf.config]`` (:mod:`netherframe.core.config`),
4
+ and nothing reads the environment. What only a test run decides (whether container or FakeCloud
5
+ tests run, where qualification evidence goes, the tools some tests need) is a pytest
6
+ command-line option, named ``--nf-...``::
7
+
8
+ uv run pytest --nf-use-containers --nf-graph-conformance-results evidence/
9
+
10
+ :mod:`~netherframe.testing.pytest_workspace` registers :data:`WORKSPACE_OPTIONS` and
11
+ :mod:`~netherframe.testing.pytest_fakecloud` registers :data:`FAKECLOUD_OPTIONS`. Both
12
+ record the run's parsed command line here (before the initial conftests load, and again at
13
+ ``pytest_configure``), so fixtures, helpers, conftests and module-level ``skipif`` conditions
14
+ read an option with :func:`option`, in xdist workers too. Outside pytest (a script, a process a
15
+ test starts) :func:`option` returns the option's default: give such a process what it needs on
16
+ its command line instead.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ from dataclasses import dataclass
23
+ from typing import TYPE_CHECKING, Any
24
+
25
+ if TYPE_CHECKING:
26
+ from collections.abc import Iterable
27
+
28
+ import pytest
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class RunOption:
33
+ """A ``--nf-*`` pytest option: ``boolean`` ones also take ``--no-nf-*``."""
34
+
35
+ flag: str
36
+ help: str
37
+ default: Any = None
38
+ boolean: bool = False
39
+ choices: tuple[str, ...] | None = None
40
+ metavar: str | None = None
41
+
42
+ @property
43
+ def dest(self) -> str:
44
+ return self.flag.removeprefix("--").replace("-", "_")
45
+
46
+
47
+ def _results(flag: str, what: str) -> RunOption:
48
+ return RunOption(flag, f"directory to keep {what} in (default: the test's temporary directory, or none kept)", metavar="DIR")
49
+
50
+
51
+ FAKECLOUD_OPTIONS = (
52
+ RunOption("--nf-use-fakecloud", "run FakeCloud-backed tests (default: on for netherframe.core's integration tests, off elsewhere)", boolean=True),
53
+ RunOption("--nf-fakecloud-autostart", "start the shared FakeCloud container when it is not running (default: on)", default=True, boolean=True),
54
+ )
55
+
56
+ WORKSPACE_OPTIONS = (
57
+ RunOption("--nf-test-log-level", "level of Netherframe's logs captured with each test (default: ERROR)", default="ERROR", metavar="LEVEL"),
58
+ RunOption("--nf-anyio-backend", "AnyIO backend of netherframe.core's anyio tests (default: asyncio)", default="asyncio", choices=("asyncio", "trio")),
59
+ RunOption("--nf-use-containers", "run tests that start Docker containers: PostgreSQL, Keycloak, proxies (default: off)", default=False, boolean=True),
60
+ RunOption("--nf-run-terraform-integration", "run the integration tests that also apply with Terraform (default: off)", default=False, boolean=True),
61
+ RunOption(
62
+ "--nf-test-hybrid-state-backend",
63
+ "state backend of netherframe.core's AWS integration tests: local, or postgresql graph state in a PostgreSQL container it starts (default: local)",
64
+ default="local",
65
+ choices=("local", "postgresql"),
66
+ ),
67
+ RunOption("--nf-update-golden", "rewrite golden files from the current output instead of comparing with them (default: off)", default=False, boolean=True),
68
+ RunOption("--nf-terraform-plugin-cache-dir", "Terraform plugin cache shared by test runs (default: ~/.nf/terraform-plugin-cache)", metavar="DIR"),
69
+ RunOption("--nf-test-java", "a java binary with keytool beside it, for the TLS bundle tests that need Java (default: those tests skip)", metavar="PATH"),
70
+ RunOption("--nf-test-helm-ngc", "run the public NGC Helm chart lookup probe (default: off)", default=False, boolean=True),
71
+ RunOption("--nf-go-bin", "Go binary that builds the runtime provider (default: go on PATH)", metavar="PATH"),
72
+ RunOption("--nf-runtime-provider-repo", "terraform-provider-runtime checkout for the runtime provider tests (default: they skip)", metavar="DIR"),
73
+ RunOption("--nf-consul-test-address", "host:port of a real Consul server for the Consul integration tests (default: they skip)", metavar="HOST:PORT"),
74
+ RunOption("--nf-consul-test-scheme", "scheme of --nf-consul-test-address (default: http)", default="http", choices=("http", "https")),
75
+ RunOption("--nf-consul-test-token-file", "file holding an ACL token for the Consul ACL test (default: it skips)", metavar="PATH"),
76
+ RunOption("--nf-keycloak-test-image", "Keycloak image of the Keycloak container tests", default="quay.io/keycloak/keycloak:26.0.8", metavar="IMAGE"),
77
+ RunOption("--nf-keycloak-test-provider-version", "keycloak/keycloak provider version of the Keycloak codify tests", default="5.10.0", metavar="VERSION"),
78
+ RunOption("--nf-graph-file-effect-index", "replay index of the graph file-effect metrics test (default: its archived qualification index)", metavar="PATH"),
79
+ RunOption("--nf-graph-fallback-pair-fixtures", "captures of the graph planning fallback-pair test (default: its archived qualification captures)", metavar="DIR"),
80
+ RunOption("--nf-graph-rpc-audit-dir", "directory to write each graph test's provider RPC audit to (default: none written)", metavar="DIR"),
81
+ _results("--nf-graph-conformance-results", "graph conformance evidence"),
82
+ _results("--nf-graph-broad-creation-evidence", "graph broad-creation evidence"),
83
+ _results("--nf-graph-broad-update-evidence", "graph broad-update evidence"),
84
+ _results("--nf-graph-chunk-results", "graph publication-chunk results"),
85
+ _results("--nf-graph-commit-disconnect-evidence", "graph commit-disconnect evidence"),
86
+ _results("--nf-graph-eligibility-results", "graph identity eligibility results"),
87
+ _results("--nf-graph-fallback-pair-results", "graph planning fallback-pair results"),
88
+ _results("--nf-graph-index-results", "graph planning index results"),
89
+ _results("--nf-graph-pair-results", "graph planning pair results"),
90
+ _results("--nf-graph-payload-cache-results", "graph payload-cache results"),
91
+ _results("--nf-graph-payload-reuse-results", "graph payload-reuse results"),
92
+ _results("--nf-graph-saved-retention-results", "graph saved-plan retention results"),
93
+ _results("--nf-graph-shadow-results", "graph planning shadow results"),
94
+ _results("--nf-graph-transport-results", "graph benchmark transport results"),
95
+ _results("--nf-graph-value-cap-results", "graph planning value-cap results"),
96
+ _results("--nf-graph-write-cost-results", "graph write-cost results"),
97
+ _results("--nf-domain-proto-results", "graph domain prototype results"),
98
+ )
99
+
100
+ _REGISTERED = {item.flag: item for item in (*FAKECLOUD_OPTIONS, *WORKSPACE_OPTIONS)}
101
+ _parsed: argparse.Namespace | None = None
102
+
103
+
104
+ def add_options(parser: pytest.Parser, options: Iterable[RunOption]) -> None:
105
+ """Register ``options`` with pytest (from a ``pytest_addoption`` hook)."""
106
+ group = parser.getgroup("netherframe", "Netherframe test runs")
107
+ for item in options:
108
+ if item.boolean:
109
+ group.addoption(item.flag, action=argparse.BooleanOptionalAction, default=item.default, dest=item.dest, help=item.help)
110
+ else:
111
+ group.addoption(item.flag, default=item.default, dest=item.dest, choices=item.choices, metavar=item.metavar, help=item.help)
112
+
113
+
114
+ def remember_options(parsed: argparse.Namespace) -> None:
115
+ """Record the run's parsed command line (``config.option``, or ``known_args_namespace`` early on)."""
116
+ global _parsed # noqa: PLW0603 - one test run per process
117
+ _parsed = parsed
118
+
119
+
120
+ def option(flag: str) -> Any:
121
+ """The value of the ``--nf-*`` option ``flag`` in this test run, else its default."""
122
+ item = _REGISTERED[flag]
123
+ value = getattr(_parsed, item.dest, None) if _parsed is not None else None
124
+ return item.default if value is None else value
@@ -0,0 +1,17 @@
1
+ """Helpers for patching attributes in tests without type noise."""
2
+
3
+ from typing import Any, cast
4
+
5
+
6
+ def patch_attr[T](obj: object, attr: str, value: T) -> T:
7
+ """Assign an attribute on an object and return the assigned value."""
8
+ target = cast("Any", obj)
9
+ setattr(target, attr, value)
10
+ return value
11
+
12
+
13
+ def patch_attrs(obj: object, **attrs: Any) -> None:
14
+ """Assign multiple attributes on an object."""
15
+ target = cast("Any", obj)
16
+ for name, value in attrs.items():
17
+ setattr(target, name, value)
@@ -0,0 +1,53 @@
1
+ """A stand-in for the HTTP that provider installation does, for tests that need a registry's or a mirror's answers without a network.
2
+
3
+ ``FakeHttp(answer)`` answers each request with ``answer(url)``: ``(status, document)``, the
4
+ document JSON (a dict or list) or bytes, or None for a 404. Service discovery is answered for
5
+ every host (``providers.v1`` at ``/v1/providers/``) unless ``answer`` answers it. Give it to an
6
+ ``Installation``::
7
+
8
+ http = FakeHttp(lambda url: (200, {"versions": [{"version": "1.0.0"}]}) if url.endswith("/versions") else None)
9
+ installation = Installation(http=http)
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ from collections.abc import Callable
16
+ from email.message import Message
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ from netherframe.core.providers.installation.credentials import Credentials
21
+ from netherframe.core.providers.installation.discovery import DISCOVERY_PATH
22
+ from netherframe.core.providers.installation.http import HttpError, Response
23
+
24
+ type Answer = Callable[[str], tuple[int, Any] | None]
25
+
26
+
27
+ class FakeHttp:
28
+ def __init__(self, answer: Answer, *, credentials: Credentials | None = None) -> None:
29
+ self.answer = answer
30
+ self.credentials = credentials or Credentials()
31
+ #: The URLs asked, discovery documents aside
32
+ self.requested: list[str] = []
33
+ self.discovered: list[str] = []
34
+
35
+ def get(self, url: str, **_options: Any) -> Response:
36
+ answered = self.answer(url)
37
+ if url.endswith(DISCOVERY_PATH):
38
+ self.discovered.append(url)
39
+ if answered is None:
40
+ answered = (200, {"providers.v1": "/v1/providers/"})
41
+ else:
42
+ self.requested.append(url)
43
+ status, document = answered if answered is not None else (404, {"errors": ["Not Found"]})
44
+ body = document if isinstance(document, bytes) else json.dumps(document).encode()
45
+ headers = Message()
46
+ headers["Content-Type"] = "application/octet-stream" if isinstance(document, bytes) else "application/json"
47
+ return Response(status, headers, body, url)
48
+
49
+ def download(self, url: str, destination: Path, **_options: Any) -> None:
50
+ response = self.get(url)
51
+ if response.status != 200:
52
+ raise HttpError(f"{url} answered {response.status}")
53
+ destination.write_bytes(response.body)
@@ -0,0 +1,33 @@
1
+ """Shared helpers for provider protocol tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+ from unittest.mock import Mock
7
+
8
+ from netherframe.core.providers.provider_session_models import ProviderConnection
9
+
10
+
11
+ def attach_mock_connection(
12
+ client: Any,
13
+ *,
14
+ stub: Mock | None = None,
15
+ channel: Mock | None = None,
16
+ process: Mock | None = None,
17
+ controller_stub: Mock | None = None,
18
+ stdio_stub: Mock | None = None,
19
+ protocol_version: int = 6,
20
+ ) -> ProviderConnection:
21
+ """Attach a mock provider session connection to a client under test."""
22
+ connection = ProviderConnection(
23
+ process=process or Mock(),
24
+ channel=channel or Mock(),
25
+ stub=stub or Mock(),
26
+ controller_stub=controller_stub or Mock(),
27
+ stdio_stub=stdio_stub or Mock(),
28
+ protocol_version=protocol_version,
29
+ stderr_thread=None,
30
+ stdio_stream_thread=None,
31
+ )
32
+ client._session._connection = connection # noqa: SLF001 - test helper
33
+ return connection
File without changes