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,75 @@
1
+ """Pytest fixtures for FakeCloud-backed tests: one shared container, a fresh AWS account per test.
2
+
3
+ Registered as the ``netherframe-fakecloud`` pytest plugin by netherframe.core, so every test
4
+ suite in an environment with netherframe.core installed can request:
5
+
6
+ - ``fakecloud_account``: a :class:`~netherframe.testing.fakecloud.FakeCloudAccount`
7
+ created for the test and reset after it. Use ``account.client("s3")`` for boto3,
8
+ ``AwsProvider(**account.provider_config())`` for hybrid/Terraform stacks,
9
+ ``account.arn(...)`` and ``account.unique_name(...)`` for ARNs and S3 bucket names.
10
+ - ``fakecloud_endpoint``: the session's FakeCloud URL; starts the shared container when needed.
11
+ - ``fakecloud_enabled``: whether FakeCloud tests run (``--nf-use-fakecloud``, off by default).
12
+ A suite that should run them by default overrides it in its conftest.
13
+
14
+ It registers the options ``--nf-use-fakecloud`` / ``--no-nf-use-fakecloud`` and
15
+ ``--nf-fakecloud-autostart`` / ``--no-nf-fakecloud-autostart``
16
+ (:data:`~netherframe.testing.options.FAKECLOUD_OPTIONS`). Tests requesting these fixtures
17
+ are skipped when FakeCloud is disabled, or when it is down and ``--no-nf-fakecloud-autostart``
18
+ is given. See :mod:`netherframe.testing.fakecloud` for the container's environment
19
+ overrides.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from typing import TYPE_CHECKING
25
+
26
+ import pytest
27
+
28
+ if TYPE_CHECKING:
29
+ from collections.abc import Iterator
30
+
31
+ from netherframe.testing.fakecloud import FakeCloudAccount
32
+
33
+ # netherframe.testing.fakecloud is imported inside the fixtures: pytest loads this plugin at
34
+ # startup, before test suites configure logging. (netherframe.testing.options imports
35
+ # nothing of netherframe.)
36
+
37
+
38
+ def pytest_addoption(parser: pytest.Parser) -> None:
39
+ from netherframe.testing.options import FAKECLOUD_OPTIONS, add_options
40
+
41
+ add_options(parser, FAKECLOUD_OPTIONS)
42
+
43
+
44
+ def pytest_configure(config: pytest.Config) -> None:
45
+ from netherframe.testing.options import remember_options
46
+
47
+ remember_options(config.option) # also where the workspace plugin is not loaded
48
+
49
+
50
+ @pytest.fixture(scope="session")
51
+ def fakecloud_enabled() -> bool:
52
+ """Whether FakeCloud-backed tests run: ``--nf-use-fakecloud``, off by default."""
53
+ from netherframe.testing.fakecloud import use_fakecloud
54
+
55
+ return use_fakecloud(default=False)
56
+
57
+
58
+ @pytest.fixture(scope="session")
59
+ def fakecloud_endpoint(fakecloud_enabled: bool) -> Iterator[str]:
60
+ """The FakeCloud URL, with the shared container running for the whole session."""
61
+ from netherframe.testing.fakecloud import FAKECLOUD_ENDPOINT, fakecloud_autostart, shared_fakecloud
62
+
63
+ if not fakecloud_enabled:
64
+ pytest.skip("FakeCloud tests are disabled (run pytest with --nf-use-fakecloud)")
65
+ with shared_fakecloud(autostart=fakecloud_autostart(), endpoint_url=FAKECLOUD_ENDPOINT):
66
+ yield FAKECLOUD_ENDPOINT
67
+
68
+
69
+ @pytest.fixture
70
+ def fakecloud_account(fakecloud_endpoint: str) -> Iterator[FakeCloudAccount]:
71
+ """A fresh FakeCloud account for this test, reset when the test ends."""
72
+ from netherframe.testing.fakecloud import temporary_fakecloud_account
73
+
74
+ with temporary_fakecloud_account(fakecloud_endpoint) as account:
75
+ yield account
@@ -0,0 +1,122 @@
1
+ """pytest setup for every test run in this workspace, wherever pytest starts.
2
+
3
+ Run from the repository root, pytest reads the root pyproject.toml; run from a package with its
4
+ own pytest configuration (``poe test-core``, ``test-cli``, ...), it reads that one and never
5
+ loads the root conftest. Setup kept in a conftest therefore applied to some runs and not
6
+ others: ``poe test-core`` ran integration tests ``poe test`` deselects. Every pytest
7
+ configuration in the workspace loads this plugin instead (``-p
8
+ netherframe.testing.pytest_workspace`` in its ``addopts``). It:
9
+
10
+ - marks tests by where they are: ``integration`` (an ``integration`` directory or file name, or
11
+ ``fakecloud`` in the file name), ``performance`` (``performance`` or ``benchmark``) and
12
+ ``slow`` (``property_based`` files), so ``-m "not integration ..."`` deselects the same tests
13
+ in every run;
14
+ - registers the ``--nf-*`` options of test runs (:data:`~netherframe.testing.options.WORKSPACE_OPTIONS`:
15
+ ``--nf-use-containers``, ``--nf-update-golden``, ``--nf-graph-conformance-results``, ...) and
16
+ records the parsed command line for :func:`~netherframe.testing.options.option`;
17
+ - gives the run its own schema cache (:func:`~netherframe.testing.schema_cache.use_run_schema_cache`)
18
+ and captures netherframe's logs with each test at ``--nf-test-log-level``
19
+ (:func:`~netherframe.testing.log_capture.log_to_captured_stderr`);
20
+ - restores the settings given as flags (``netherframe.core.config.flags``) after each test, so
21
+ a test that sets them (``with flags(...)``, or a CLI run with ``nf --graph-lease-ttl ...``)
22
+ leaves none behind;
23
+ - keeps Terraform from asking HashiCorp for new versions (``CHECKPOINT_DISABLE``) and
24
+ recording the answer in ~/.terraform.d;
25
+ - runs Hypothesis tests with a few examples each, unless ``HYPOTHESIS_PROFILE`` names another
26
+ profile.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import os
32
+ import sys
33
+ import tempfile
34
+ from collections.abc import Iterator
35
+ from pathlib import Path
36
+
37
+ import pytest
38
+
39
+ from netherframe.core.config.flags import flags, set_user_defaults
40
+ from netherframe.testing.log_capture import log_to_captured_stderr
41
+ from netherframe.testing.options import WORKSPACE_OPTIONS, add_options, option, remember_options
42
+ from netherframe.testing.schema_cache import hand_to_worker, use_run_schema_cache
43
+
44
+ MARKERS = {
45
+ "integration": "integration tests (FakeCloud, real providers, Terraform, containers)",
46
+ "performance": "performance benchmarks",
47
+ "slow": "slow tests (property-based)",
48
+ "process": "real process/socket observation tests, run serially by test-ci",
49
+ }
50
+
51
+ try:
52
+ from hypothesis import HealthCheck, settings
53
+ except ImportError: # pragma: no cover - hypothesis is a dev dependency of some packages only
54
+ pass
55
+ else:
56
+ # No deadline: an example's time says how loaded the machine is (the whole suite on every
57
+ # core), not whether the property holds; benchmarks measure speed
58
+ settings.register_profile("fast", max_examples=3, deadline=None, suppress_health_check=(HealthCheck.too_slow,))
59
+ settings.load_profile(os.environ.get("HYPOTHESIS_PROFILE", "fast"))
60
+
61
+
62
+ def pytest_addoption(parser: pytest.Parser) -> None:
63
+ add_options(parser, WORKSPACE_OPTIONS)
64
+
65
+
66
+ @pytest.hookimpl(tryfirst=True)
67
+ def pytest_load_initial_conftests(early_config: pytest.Config) -> None:
68
+ """The options as parsed so far, for conftests that read one as they are imported."""
69
+ remember_options(early_config.known_args_namespace)
70
+
71
+
72
+ @pytest.hookimpl(trylast=True) # after pytest's own, which sets up the base temp directory
73
+ def pytest_configure(config: pytest.Config) -> None:
74
+ remember_options(config.option)
75
+ for name, description in MARKERS.items():
76
+ config.addinivalue_line("markers", f"{name}: {description}")
77
+ os.environ["CHECKPOINT_DISABLE"] = "1" # subprocesses (Terraform) inherit it
78
+ # Not the developer's own nf configuration (~/.config/nf/config.toml): a test of it gives its own
79
+ empty = tempfile.mkdtemp(prefix="nf-user-config-")
80
+ os.environ["XDG_CONFIG_HOME"] = empty
81
+ if sys.platform == "win32":
82
+ os.environ["APPDATA"] = empty
83
+ use_run_schema_cache(config)
84
+ log_to_captured_stderr(option("--nf-test-log-level"))
85
+
86
+
87
+ @pytest.fixture(autouse=True)
88
+ def _nf_settings_flags() -> Iterator[None]:
89
+ """Each test starts with the run's settings given as flags (``netherframe.core.config.flags``), and no user defaults, and leaves them so."""
90
+ set_user_defaults({})
91
+ try:
92
+ with flags():
93
+ yield
94
+ finally:
95
+ set_user_defaults({})
96
+
97
+
98
+ @pytest.hookimpl(optionalhook=True)
99
+ def pytest_configure_node(node: object) -> None:
100
+ """An xdist worker starting: hand it the run's schema cache."""
101
+ hand_to_worker(node)
102
+
103
+
104
+ def markers_for(path: Path) -> list[str]:
105
+ """The markers a test file gets from where it is."""
106
+ parts, name = set(path.parts), path.name
107
+ markers = []
108
+ if "integration" in parts or "integration" in name or "fakecloud" in name:
109
+ markers.append("integration")
110
+ if "performance" in parts or "performance" in name or "benchmark" in name:
111
+ markers.append("performance")
112
+ if "property_based" in name:
113
+ markers.append("slow")
114
+ if name.startswith("test_graph_") and (name.endswith("_observer.py") or name == "test_graph_process_cost.py"):
115
+ markers.append("process")
116
+ return markers
117
+
118
+
119
+ def pytest_collection_modifyitems(items: list[pytest.Item]) -> None:
120
+ for item in items:
121
+ for marker in markers_for(item.path):
122
+ item.add_marker(getattr(pytest.mark, marker))
@@ -0,0 +1,54 @@
1
+ """A provider schema cache for each test run, instead of the developer's ``~/.nf/schema_cache``.
2
+
3
+ Tests store schemas for fake provider binaries in the schema cache, and some clear it. Against
4
+ ``~/.nf/schema_cache`` that wiped the developer's cache and raced with other test runs.
5
+ :func:`use_run_schema_cache` sets the ``schema_cache_dir`` setting
6
+ (``netherframe.core.config.flags``) to ``schema_cache`` in the run's pytest base temp directory
7
+ instead (and a test that runs ``nf`` in a process of its own passes ``--schema-cache-dir``):
8
+
9
+ - xdist workers get it from the controller (:func:`hand_to_worker`, in their ``workerinput``),
10
+ so the workers of a run share one cache: a real provider's schema, such as the AWS provider's
11
+ that the FakeCloud tests need, is fetched once per run rather than once per worker.
12
+ - Runs don't share it, so one run can't clear what another is using, and schemas stored for
13
+ fake binaries don't outlive their run.
14
+ - pytest removes it with the run's temp directory: at the end of a passing run (under
15
+ ``tmp_path_retention_policy = "failed"``), else when later runs rotate old temp directories out.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from pathlib import Path
21
+ from typing import TYPE_CHECKING, Any
22
+
23
+ from netherframe.core.config.flags import flag, set_flags
24
+ from netherframe.core.serialization.schema_cache import CACHE_DIR_SETTING
25
+
26
+ if TYPE_CHECKING:
27
+ import pytest
28
+
29
+ #: The key of the run's cache directory in an xdist worker's ``workerinput``
30
+ WORKER_INPUT_KEY = "nf_schema_cache_dir"
31
+
32
+
33
+ def use_run_schema_cache(config: pytest.Config) -> Path:
34
+ """Point the schema cache at this test run's directory and return it.
35
+
36
+ Call it from a ``pytest_configure`` hook marked ``trylast``: pytest sets up the base temp
37
+ directory in its own ``pytest_configure``.
38
+ """
39
+ inherited = getattr(config, "workerinput", {}).get(WORKER_INPUT_KEY)
40
+ if inherited:
41
+ cache_dir = Path(inherited) # an xdist worker: the controller's run directory
42
+ else:
43
+ # pytest's own factory (a private attribute, which xdist uses the same way): a new one
44
+ # would make another base temp directory
45
+ temp_path_factory: pytest.TempPathFactory = getattr(config, "_tmp_path_factory") # noqa: B009
46
+ cache_dir = temp_path_factory.getbasetemp() / "schema_cache"
47
+ set_flags({CACHE_DIR_SETTING: str(cache_dir)})
48
+ return cache_dir
49
+
50
+
51
+ def hand_to_worker(node: Any) -> None:
52
+ """Give an xdist worker the run's cache directory (from ``pytest_configure_node``)."""
53
+ if directory := flag(CACHE_DIR_SETTING):
54
+ node.workerinput[WORKER_INPUT_KEY] = str(directory)