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 @@
1
+ """Testing helpers for netherframe.core."""
@@ -0,0 +1,628 @@
1
+ """Run FakeCloud (a local AWS emulator) for tests and give each test its own AWS account in it.
2
+
3
+ Every test suite shares one FakeCloud container, started with ``docker run`` by
4
+ :func:`start_fakecloud_container` and coordinated by :func:`shared_fakecloud` so that
5
+ concurrent test runs and their xdist workers start it once and the last one out stops it.
6
+ Tests do not share state: :func:`create_fakecloud_account` makes a fresh account (random
7
+ 12-digit id, admin user and access key) and FakeCloud resolves the account of every request
8
+ from its access key. The pytest fixtures in :mod:`netherframe.testing.pytest_fakecloud`
9
+ wrap all of this.
10
+
11
+ pytest options (:mod:`netherframe.testing.options`):
12
+
13
+ - ``--nf-use-fakecloud`` / ``--no-nf-use-fakecloud``: run FakeCloud-backed tests (default
14
+ depends on the suite)
15
+ - ``--nf-fakecloud-autostart`` / ``--no-nf-fakecloud-autostart``: start the container when it
16
+ is not running (default on)
17
+
18
+ Environment overrides of the container (FakeCloud's, not Netherframe's):
19
+
20
+ - ``FAKECLOUD_ENDPOINT``: where FakeCloud listens (default ``http://localhost:4566``)
21
+ - ``FAKECLOUD_CONTAINER_NAME``: the container's name (default ``nf-fakecloud``)
22
+ - ``FAKECLOUD_IMAGE``: the image to run (default ``ghcr.io/faiscadev/fakecloud:0.51.0``)
23
+ - ``FAKECLOUD_REGION``, ``FAKECLOUD_ACCOUNT_ID``, ``FAKECLOUD_LOG``: passed to the container
24
+
25
+ Run ``python -m netherframe.testing.fakecloud start|stop|status`` to manage the
26
+ container by hand, for example to keep it running across test runs.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import json
32
+ import os
33
+ import secrets
34
+ import subprocess
35
+ import tempfile
36
+ import time
37
+ from contextlib import contextmanager
38
+ from dataclasses import dataclass
39
+ from pathlib import Path
40
+ from typing import TYPE_CHECKING, Any
41
+ from urllib.parse import urlsplit
42
+
43
+ import requests
44
+
45
+ from netherframe.core.logging import get_logger
46
+ from netherframe.testing.options import option
47
+ from collections.abc import Generator
48
+
49
+ if TYPE_CHECKING:
50
+ from collections.abc import Callable
51
+
52
+ logger = get_logger(__name__)
53
+
54
+ DEFAULT_FAKECLOUD_ENDPOINT = "http://localhost:4566"
55
+ DEFAULT_FAKECLOUD_REGION = "us-east-1"
56
+ DEFAULT_FAKECLOUD_CONTAINER_NAME = "nf-fakecloud"
57
+ DEFAULT_FAKECLOUD_IMAGE = "ghcr.io/faiscadev/fakecloud:0.51.0"
58
+ FAKECLOUD_CONTAINER_PORT = 4566
59
+
60
+ FAKECLOUD_ENDPOINT = os.getenv("FAKECLOUD_ENDPOINT", DEFAULT_FAKECLOUD_ENDPOINT)
61
+ FAKECLOUD_REGION = os.getenv("FAKECLOUD_REGION", DEFAULT_FAKECLOUD_REGION)
62
+ FAKECLOUD_CONTAINER_NAME = os.getenv(
63
+ "FAKECLOUD_CONTAINER_NAME",
64
+ DEFAULT_FAKECLOUD_CONTAINER_NAME,
65
+ )
66
+ FAKECLOUD_IMAGE = os.getenv("FAKECLOUD_IMAGE", DEFAULT_FAKECLOUD_IMAGE)
67
+
68
+ # Services whose state FakeCloud 0.45.1 can reset for a single account
69
+ # (POST /_fakecloud/reset/{service}/{account_id}). IAM goes last: once its state is
70
+ # gone the account's access key no longer resolves.
71
+ FAKECLOUD_ACCOUNT_RESET_SERVICES = (
72
+ "acm",
73
+ "acm-pca",
74
+ "apigateway",
75
+ "application-autoscaling",
76
+ "athena",
77
+ "bedrock",
78
+ "bedrock-agent",
79
+ "bedrock-agent-runtime",
80
+ "cloudformation",
81
+ "cloudfront",
82
+ "cloudwatch",
83
+ "cognito",
84
+ "config",
85
+ "dynamodb",
86
+ "ecr",
87
+ "ecs",
88
+ "elasticache",
89
+ "events",
90
+ "firehose",
91
+ "glue",
92
+ "kinesis",
93
+ "kms",
94
+ "lambda",
95
+ "logs",
96
+ "rds",
97
+ "route53",
98
+ "route53resolver",
99
+ "s3",
100
+ "scheduler",
101
+ "secretsmanager",
102
+ "ses",
103
+ "sns",
104
+ "sqs",
105
+ "ssm",
106
+ "stepfunctions",
107
+ "wafv2",
108
+ "iam",
109
+ )
110
+
111
+ # Endpoint keys of the hashicorp/aws provider pointed at FakeCloud by FakeCloudAccount.provider_config().
112
+ FAKECLOUD_PROVIDER_ENDPOINTS = (
113
+ "acm",
114
+ "apigateway",
115
+ "cloudformation",
116
+ "cloudwatch",
117
+ "dynamodb",
118
+ "ec2",
119
+ "ecr",
120
+ "ecs",
121
+ "elasticache",
122
+ "events",
123
+ "iam",
124
+ "kinesis",
125
+ "kms",
126
+ "lambda",
127
+ "logs",
128
+ "rds",
129
+ "route53",
130
+ "s3",
131
+ "scheduler",
132
+ "secretsmanager",
133
+ "sfn",
134
+ "sns",
135
+ "sqs",
136
+ "ssm",
137
+ "sts",
138
+ )
139
+
140
+
141
+ def use_fakecloud(default: bool = True) -> bool:
142
+ """Whether FakeCloud-backed tests run: ``--nf-use-fakecloud`` / ``--no-nf-use-fakecloud``, else ``default`` (the suite's)."""
143
+ given = option("--nf-use-fakecloud")
144
+ return default if given is None else bool(given)
145
+
146
+
147
+ def fakecloud_autostart() -> bool:
148
+ """Whether tests may start FakeCloud: off with ``--no-nf-fakecloud-autostart``."""
149
+ return bool(option("--nf-fakecloud-autostart"))
150
+
151
+
152
+ def _load_fakecloud_sync() -> type[Any]:
153
+ try:
154
+ from fakecloud import FakeCloudSync
155
+ except ImportError as exc: # pragma: no cover - exercised via callers
156
+ raise RuntimeError(
157
+ "FakeCloud-backed tests require the 'fakecloud' Python package. Install the workspace dev dependencies or add 'fakecloud' to your environment.",
158
+ ) from exc
159
+
160
+ return FakeCloudSync
161
+
162
+
163
+ def _fakecloud_sdk_errors() -> tuple[type[Exception], ...]:
164
+ """Return the exceptions the fakecloud SDK raises for API and transport failures."""
165
+ import httpx
166
+ from fakecloud.client import FakeCloudError
167
+
168
+ return (FakeCloudError, httpx.HTTPError)
169
+
170
+
171
+ def fakecloud_sdk_available() -> bool:
172
+ """Return whether the fakecloud Python SDK is importable."""
173
+ try:
174
+ _load_fakecloud_sync()
175
+ except RuntimeError:
176
+ return False
177
+ return True
178
+
179
+
180
+ def get_fakecloud_client(endpoint_url: str = FAKECLOUD_ENDPOINT) -> Any:
181
+ """Create a synchronous FakeCloud SDK client."""
182
+ return _load_fakecloud_sync()(endpoint_url)
183
+
184
+
185
+ def _request_fakecloud_health(
186
+ endpoint_url: str = FAKECLOUD_ENDPOINT,
187
+ ) -> dict[str, Any] | None:
188
+ try:
189
+ response = requests.get(f"{endpoint_url}/_fakecloud/health", timeout=5)
190
+ response.raise_for_status()
191
+ except requests.RequestException:
192
+ return None
193
+ return response.json()
194
+
195
+
196
+ def get_fakecloud_health(
197
+ endpoint_url: str = FAKECLOUD_ENDPOINT,
198
+ ) -> dict[str, Any] | None:
199
+ """Return FakeCloud health metadata when available."""
200
+ if fakecloud_sdk_available():
201
+ try:
202
+ with get_fakecloud_client(endpoint_url) as client:
203
+ health = client.health()
204
+ except _fakecloud_sdk_errors() as exc:
205
+ logger.debug("FakeCloud SDK health check failed, falling back to HTTP: %s", exc)
206
+ return _request_fakecloud_health(endpoint_url)
207
+ return {
208
+ "status": health.status,
209
+ "version": health.version,
210
+ "services": list(health.services),
211
+ }
212
+
213
+ return _request_fakecloud_health(endpoint_url)
214
+
215
+
216
+ def is_fakecloud_healthy(endpoint_url: str = FAKECLOUD_ENDPOINT) -> bool:
217
+ """Return True when FakeCloud responds on its health endpoint."""
218
+ return get_fakecloud_health(endpoint_url) is not None
219
+
220
+
221
+ def get_fakecloud_health_services(
222
+ endpoint_url: str = FAKECLOUD_ENDPOINT,
223
+ ) -> dict[str, str]:
224
+ """Return FakeCloud service health metadata normalized to status strings."""
225
+ health = get_fakecloud_health(endpoint_url)
226
+ if not health:
227
+ return {}
228
+
229
+ services = health.get("services", [])
230
+ if isinstance(services, dict):
231
+ return {str(name): "running" for name, enabled in services.items() if enabled not in {False, None}}
232
+
233
+ if isinstance(services, list):
234
+ return {str(service): "running" for service in services}
235
+
236
+ return {}
237
+
238
+
239
+ def fakecloud_supports_service(
240
+ service: str,
241
+ endpoint_url: str = FAKECLOUD_ENDPOINT,
242
+ ) -> bool:
243
+ """Return whether FakeCloud advertises support for a service on its health endpoint."""
244
+ services = get_fakecloud_health_services(endpoint_url)
245
+ return services.get(service) == "running"
246
+
247
+
248
+ def reset_fakecloud_state(endpoint_url: str = FAKECLOUD_ENDPOINT) -> bool:
249
+ """Reset all FakeCloud state, in every account."""
250
+ if fakecloud_sdk_available():
251
+ try:
252
+ with get_fakecloud_client(endpoint_url) as client:
253
+ client.reset()
254
+ return True
255
+ except _fakecloud_sdk_errors() as exc:
256
+ logger.warning("Failed to reset FakeCloud state at %s: %s", endpoint_url, exc)
257
+ return False
258
+
259
+ try:
260
+ response = requests.post(f"{endpoint_url}/_reset", timeout=5)
261
+ response.raise_for_status()
262
+ except requests.RequestException as exc:
263
+ logger.warning("Failed to reset FakeCloud state at %s: %s", endpoint_url, exc)
264
+ return False
265
+ return True
266
+
267
+
268
+ def reset_fakecloud_service(
269
+ service: str,
270
+ endpoint_url: str = FAKECLOUD_ENDPOINT,
271
+ ) -> bool:
272
+ """Reset a single FakeCloud service, in every account."""
273
+ if fakecloud_sdk_available():
274
+ try:
275
+ with get_fakecloud_client(endpoint_url) as client:
276
+ client.reset_service(service)
277
+ return True
278
+ except _fakecloud_sdk_errors() as exc:
279
+ logger.warning("Failed to reset FakeCloud service %s at %s: %s", service, endpoint_url, exc)
280
+ return False
281
+
282
+ try:
283
+ response = requests.post(
284
+ f"{endpoint_url}/_fakecloud/reset/{service}",
285
+ timeout=5,
286
+ )
287
+ response.raise_for_status()
288
+ except requests.RequestException as exc:
289
+ logger.warning("Failed to reset FakeCloud service %s at %s: %s", service, endpoint_url, exc)
290
+ return False
291
+ return True
292
+
293
+
294
+ # -- Per-test accounts --------------------------------------------------------------------
295
+
296
+
297
+ @dataclass(frozen=True)
298
+ class FakeCloudAccount:
299
+ """An AWS account in FakeCloud and the access key of its admin user.
300
+
301
+ FakeCloud resolves the account of each request from its access key, so everything
302
+ created with these credentials lives in this account and nothing else sees it.
303
+ S3 bucket names are the exception: as in AWS, they are unique across all accounts
304
+ (use :meth:`unique_name`).
305
+ """
306
+
307
+ account_id: str
308
+ access_key_id: str
309
+ secret_access_key: str
310
+ endpoint_url: str = FAKECLOUD_ENDPOINT
311
+ region: str = FAKECLOUD_REGION
312
+
313
+ def boto_config(self, region: str | None = None) -> dict[str, Any]:
314
+ """Keyword arguments for ``boto3.client(service, **config)`` in this account."""
315
+ return {
316
+ "endpoint_url": self.endpoint_url,
317
+ "region_name": region or self.region,
318
+ "aws_access_key_id": self.access_key_id,
319
+ "aws_secret_access_key": self.secret_access_key,
320
+ }
321
+
322
+ def client(self, service_name: str, region: str | None = None) -> Any:
323
+ """A boto3 client for ``service_name`` in this account."""
324
+ import boto3
325
+
326
+ return boto3.client(service_name, **self.boto_config(region))
327
+
328
+ def provider_config(self, region: str | None = None) -> dict[str, Any]:
329
+ """Keyword arguments for the hashicorp/aws provider (``AwsProvider(**config)``) in this account.
330
+
331
+ Every service endpoint in :data:`FAKECLOUD_PROVIDER_ENDPOINTS` points at FakeCloud. The
332
+ provider skips looking up the account id: once it knows it, it reads S3 bucket tags
333
+ through S3 Control, which FakeCloud does not serve. Build ARNs with :meth:`arn`.
334
+ """
335
+ return {
336
+ "region": region or self.region,
337
+ "access_key": self.access_key_id,
338
+ "secret_key": self.secret_access_key,
339
+ "skip_credentials_validation": True,
340
+ "skip_requesting_account_id": True,
341
+ "skip_metadata_api_check": "true",
342
+ "s3_use_path_style": True,
343
+ "endpoints": [dict.fromkeys(FAKECLOUD_PROVIDER_ENDPOINTS, self.endpoint_url)],
344
+ }
345
+
346
+ def arn(self, service: str, resource: str, *, region: str = "") -> str:
347
+ """An ARN in this account, e.g. ``arn("iam", "role/deployer")``."""
348
+ return f"arn:aws:{service}:{region}:{self.account_id}:{resource}"
349
+
350
+ def unique_name(self, prefix: str) -> str:
351
+ """``<prefix>-<account id>``: a name unique across accounts, as S3 bucket names must be."""
352
+ return f"{prefix}-{self.account_id}"
353
+
354
+
355
+ def random_account_id() -> str:
356
+ """A random 12-digit AWS account id (no leading zero, never the default account)."""
357
+ default_account = os.getenv("FAKECLOUD_ACCOUNT_ID", "123456789012")
358
+ while True:
359
+ account_id = str(secrets.randbelow(9 * 10**11) + 10**11)
360
+ if account_id != default_account:
361
+ return account_id
362
+
363
+
364
+ def create_fakecloud_account(
365
+ endpoint_url: str = FAKECLOUD_ENDPOINT,
366
+ *,
367
+ region: str = FAKECLOUD_REGION,
368
+ account_id: str | None = None,
369
+ user_name: str = "nf-test-admin",
370
+ ) -> FakeCloudAccount:
371
+ """Create an account (random id unless given) with an admin user, and return its credentials.
372
+
373
+ Uses FakeCloud's ``POST /_fakecloud/iam/create-admin``, which creates the account's IAM
374
+ state, an admin user with an ``Allow *`` policy and an access key for it.
375
+ """
376
+ account_id = account_id or random_account_id()
377
+ response = requests.post(
378
+ f"{endpoint_url}/_fakecloud/iam/create-admin",
379
+ json={"accountId": account_id, "userName": user_name},
380
+ timeout=10,
381
+ )
382
+ response.raise_for_status()
383
+ body = response.json()
384
+ return FakeCloudAccount(
385
+ account_id=body["accountId"],
386
+ access_key_id=body["accessKeyId"],
387
+ secret_access_key=body["secretAccessKey"],
388
+ endpoint_url=endpoint_url,
389
+ region=region,
390
+ )
391
+
392
+
393
+ def reset_fakecloud_account(
394
+ account: FakeCloudAccount,
395
+ services: tuple[str, ...] = FAKECLOUD_ACCOUNT_RESET_SERVICES,
396
+ ) -> bool:
397
+ """Drop the account's state in ``services`` (per-account reset; other accounts keep theirs).
398
+
399
+ Returns False, after logging why, when any service could not be reset.
400
+ """
401
+ ok = True
402
+ with requests.Session() as session:
403
+ for service in services:
404
+ try:
405
+ response = session.post(
406
+ f"{account.endpoint_url}/_fakecloud/reset/{service}/{account.account_id}",
407
+ timeout=10,
408
+ )
409
+ response.raise_for_status()
410
+ except requests.RequestException as exc:
411
+ logger.warning("Failed to reset FakeCloud service %s for account %s: %s", service, account.account_id, exc)
412
+ ok = False
413
+ return ok
414
+
415
+
416
+ @contextmanager
417
+ def temporary_fakecloud_account(
418
+ endpoint_url: str = FAKECLOUD_ENDPOINT,
419
+ *,
420
+ region: str = FAKECLOUD_REGION,
421
+ ) -> Generator[FakeCloudAccount]:
422
+ """Yield a fresh FakeCloud account and reset its state afterwards."""
423
+ account = create_fakecloud_account(endpoint_url, region=region)
424
+ try:
425
+ yield account
426
+ finally:
427
+ reset_fakecloud_account(account)
428
+
429
+
430
+ # -- The container ------------------------------------------------------------------------
431
+
432
+
433
+ def fakecloud_docker_run_command(endpoint_url: str = FAKECLOUD_ENDPOINT) -> list[str]:
434
+ """The ``docker run`` command that starts the FakeCloud container for ``endpoint_url``."""
435
+ host_port = urlsplit(endpoint_url).port or FAKECLOUD_CONTAINER_PORT
436
+ environment = {
437
+ "FAKECLOUD_LOG": os.getenv("FAKECLOUD_LOG", "info"),
438
+ "FAKECLOUD_REGION": FAKECLOUD_REGION,
439
+ }
440
+ if account_id := os.getenv("FAKECLOUD_ACCOUNT_ID"):
441
+ environment["FAKECLOUD_ACCOUNT_ID"] = account_id
442
+ return [
443
+ "docker",
444
+ "run",
445
+ "--detach",
446
+ "--rm",
447
+ "--name",
448
+ FAKECLOUD_CONTAINER_NAME,
449
+ "--publish",
450
+ f"{host_port}:{FAKECLOUD_CONTAINER_PORT}",
451
+ # Lambda Invoke runs functions in sibling containers, which reach FakeCloud through
452
+ # host.docker.internal; native-Linux Docker needs that name mapped explicitly.
453
+ "--volume",
454
+ "/var/run/docker.sock:/var/run/docker.sock",
455
+ "--add-host",
456
+ "host.docker.internal:host-gateway",
457
+ # The image ships no curl or wget; FakeCloud has its own probe.
458
+ "--health-cmd",
459
+ "fakecloud healthcheck",
460
+ "--health-interval",
461
+ "10s",
462
+ "--health-timeout",
463
+ "5s",
464
+ "--health-retries",
465
+ "5",
466
+ *(arg for name, value in environment.items() for arg in ("--env", f"{name}={value}")),
467
+ FAKECLOUD_IMAGE,
468
+ ]
469
+
470
+
471
+ def _docker(*args: str) -> subprocess.CompletedProcess[str]:
472
+ return subprocess.run(["docker", *args], capture_output=True, text=True, check=False)
473
+
474
+
475
+ def _container_status() -> str | None:
476
+ """The FakeCloud container's status (``running``, ``exited``, ...), or None if there is none."""
477
+ result = _docker("container", "inspect", "--format", "{{.State.Status}}", FAKECLOUD_CONTAINER_NAME)
478
+ return result.stdout.strip() if result.returncode == 0 else None
479
+
480
+
481
+ def wait_for_fakecloud(endpoint_url: str = FAKECLOUD_ENDPOINT, timeout: float = 60) -> bool:
482
+ """Wait until FakeCloud answers its health endpoint; False on timeout."""
483
+ deadline = time.monotonic() + timeout
484
+ while True:
485
+ if is_fakecloud_healthy(endpoint_url):
486
+ return True
487
+ if time.monotonic() >= deadline:
488
+ return False
489
+ time.sleep(0.25)
490
+
491
+
492
+ def start_fakecloud_container(endpoint_url: str = FAKECLOUD_ENDPOINT, timeout: float = 60) -> bool:
493
+ """Start the FakeCloud container unless FakeCloud already answers, and wait until it is healthy.
494
+
495
+ Returns False, after logging why, when Docker is missing or the container does not come up.
496
+ """
497
+ if is_fakecloud_healthy(endpoint_url):
498
+ return True
499
+ try:
500
+ status = _container_status()
501
+ if status != "running":
502
+ if status is not None: # a stopped leftover would block the name
503
+ _docker("rm", "--force", FAKECLOUD_CONTAINER_NAME)
504
+ logger.info("Starting FakeCloud container %s (%s)", FAKECLOUD_CONTAINER_NAME, FAKECLOUD_IMAGE)
505
+ result = subprocess.run(fakecloud_docker_run_command(endpoint_url), capture_output=True, text=True, check=False)
506
+ if result.returncode != 0:
507
+ logger.error("Failed to start FakeCloud: %s", result.stderr.strip())
508
+ return False
509
+ except FileNotFoundError:
510
+ logger.error("Failed to start FakeCloud: docker is not installed")
511
+ return False
512
+ if not wait_for_fakecloud(endpoint_url, timeout):
513
+ logger.error("FakeCloud did not become healthy at %s within %ss", endpoint_url, timeout)
514
+ return False
515
+ return True
516
+
517
+
518
+ def stop_fakecloud_container() -> None:
519
+ """Stop (and so remove, it runs with ``--rm``) the FakeCloud container."""
520
+ try:
521
+ result = _docker("rm", "--force", FAKECLOUD_CONTAINER_NAME)
522
+ except FileNotFoundError:
523
+ return
524
+ if result.returncode != 0 and "No such container" not in result.stderr:
525
+ logger.warning("Failed to stop FakeCloud: %s", result.stderr.strip())
526
+
527
+
528
+ # -- Sharing the container between test runs ----------------------------------------------
529
+
530
+
531
+ def _coordination_dir() -> Path:
532
+ """Where test processes on this machine coordinate their use of the container."""
533
+ path = Path(tempfile.gettempdir()) / f"netherframe-{FAKECLOUD_CONTAINER_NAME}"
534
+ path.mkdir(exist_ok=True)
535
+ return path
536
+
537
+
538
+ def _process_alive(pid: int) -> bool:
539
+ try:
540
+ os.kill(pid, 0)
541
+ except ProcessLookupError:
542
+ return False
543
+ except PermissionError:
544
+ return True
545
+ return True
546
+
547
+
548
+ @contextmanager
549
+ def _locked_users(directory: Path) -> Generator[dict[str, Any]]:
550
+ """Hold the lock and yield the shared state: the pids using FakeCloud and whether tests started it."""
551
+ import fcntl # noqa: PLC0415 - POSIX-only; imported only when a test run uses FakeCloud
552
+
553
+ state_path = directory / "users.json"
554
+ with (directory / "lock").open("w") as lock:
555
+ fcntl.flock(lock, fcntl.LOCK_EX)
556
+ state: dict[str, Any] = json.loads(state_path.read_text()) if state_path.exists() else {"pids": [], "started": False}
557
+ # A test process that died without cleaning up no longer holds the container.
558
+ state["pids"] = [pid for pid in state["pids"] if _process_alive(pid)]
559
+ try:
560
+ yield state
561
+ finally:
562
+ state_path.write_text(json.dumps(state))
563
+
564
+
565
+ @contextmanager
566
+ def shared_fakecloud(
567
+ *,
568
+ autostart: bool = True,
569
+ endpoint_url: str = FAKECLOUD_ENDPOINT,
570
+ start: Callable[[], bool] | None = None,
571
+ stop: Callable[[], None] | None = None,
572
+ ) -> Generator[None]:
573
+ """Make FakeCloud available while the block runs, sharing one container between test processes.
574
+
575
+ Use it around the ``yield`` of a session fixture. Every xdist worker, and every test run
576
+ on the machine, registers its pid under a lock in the system temp directory: the first
577
+ one starts the container when FakeCloud is down, and the last one out stops it, but only
578
+ if tests started it (a container started by hand keeps running). Processes that died are
579
+ dropped from the list. Skips when FakeCloud is down and ``autostart`` is off, or when it
580
+ fails to start.
581
+ """
582
+ import pytest # noqa: PLC0415 - test-only dependency
583
+
584
+ start = start or (lambda: start_fakecloud_container(endpoint_url))
585
+ stop = stop or stop_fakecloud_container
586
+ directory = _coordination_dir()
587
+ pid = os.getpid()
588
+ with _locked_users(directory) as state:
589
+ if not is_fakecloud_healthy(endpoint_url):
590
+ if not autostart:
591
+ pytest.skip("FakeCloud is not running and autostart is disabled (--no-nf-fakecloud-autostart)")
592
+ if not start():
593
+ pytest.skip("Failed to start FakeCloud")
594
+ state["started"] = True
595
+ state["pids"].append(pid)
596
+ try:
597
+ yield
598
+ finally:
599
+ with _locked_users(directory) as state:
600
+ if pid in state["pids"]:
601
+ state["pids"].remove(pid)
602
+ if not state["pids"] and state["started"]:
603
+ stop()
604
+ state["started"] = False
605
+
606
+
607
+ def main(argv: list[str] | None = None) -> int:
608
+ """``python -m netherframe.testing.fakecloud start|stop|status``."""
609
+ import argparse
610
+
611
+ parser = argparse.ArgumentParser(description="Manage the FakeCloud container that tests use.")
612
+ parser.add_argument("command", choices=["start", "stop", "status"])
613
+ args = parser.parse_args(argv)
614
+ if args.command == "start":
615
+ if not start_fakecloud_container():
616
+ return 1
617
+ print(f"FakeCloud is running at {FAKECLOUD_ENDPOINT}")
618
+ elif args.command == "stop":
619
+ stop_fakecloud_container()
620
+ else:
621
+ health = get_fakecloud_health()
622
+ print(f"FakeCloud at {FAKECLOUD_ENDPOINT}: {'version ' + str(health.get('version')) if health else 'not running'}")
623
+ return 0 if health else 1
624
+ return 0
625
+
626
+
627
+ if __name__ == "__main__":
628
+ raise SystemExit(main())