pytest-varar 0.5.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,11 @@
1
+ Metadata-Version: 2.4
2
+ Name: pytest-varar
3
+ Version: 0.5.0
4
+ Summary: pytest plugin for Markdown-native BDD
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.11
7
+ Requires-Dist: pytest>=8
8
+ Requires-Dist: varar-config==0.5.0
9
+ Requires-Dist: varar-core==0.5.0
10
+ Requires-Dist: varar-runner==0.5.0
11
+ Requires-Dist: varar==0.5.0
@@ -0,0 +1,7 @@
1
+ varar_pytest/__init__.py,sha256=9mvKcUzuBk10Wbtdje8nHxIU38D6C7l3DJ2395MLAGg,52
2
+ varar_pytest/fixtures.py,sha256=T1hl7Z-luHe7BPPYNxJnUFsURjbcoj2pcWcAn1kZHtU,4011
3
+ varar_pytest/plugin.py,sha256=X5jMs3w30JaC0-u663t0VOri3Cl94kKTQ31yoHhrGvA,5393
4
+ pytest_varar-0.5.0.dist-info/METADATA,sha256=xou6n1fJGpc2NmYJRjYpLoSFfr-EEpiDlxIsYdQVWDo,307
5
+ pytest_varar-0.5.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
6
+ pytest_varar-0.5.0.dist-info/entry_points.txt,sha256=516q-3Gyah0RAeqHMcP9ScWp6pi2lKio0qcjlFG7JSE,37
7
+ pytest_varar-0.5.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [pytest11]
2
+ var = varar_pytest.plugin
@@ -0,0 +1,3 @@
1
+ """pytest plugin for var."""
2
+
3
+ __version__ = "0.0.0"
@@ -0,0 +1,110 @@
1
+ """fixtures.py — pytest fixture bridge for var-pytest.
2
+
3
+ Provides:
4
+ - ``_active_request``: a ContextVar holding the current ``FixtureRequest``.
5
+ - ``get_active_request()``: retrieves it (raises RuntimeError if unset).
6
+ - ``wrap_registry_for_fixtures(registry, get_request) -> Registry``: returns a
7
+ new Registry whose step handlers resolve fixture parameters dynamically via
8
+ ``get_request().getfixturevalue(name)``.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import inspect
13
+ from contextvars import ContextVar
14
+ from dataclasses import replace
15
+ from typing import Any, Callable
16
+
17
+ from varar_core.registry import Registry
18
+
19
+ # ---------------------------------------------------------------------------
20
+ # Per-item active request contextvar
21
+ # ---------------------------------------------------------------------------
22
+
23
+ _active_request: ContextVar[Any] = ContextVar("_active_request")
24
+
25
+
26
+ def get_active_request() -> Any:
27
+ """Return the FixtureRequest for the currently-running VarItem.
28
+
29
+ Raises RuntimeError if called outside a VarItem runtest.
30
+ """
31
+ try:
32
+ return _active_request.get()
33
+ except LookupError as exc:
34
+ raise RuntimeError(
35
+ "No active pytest fixture request — "
36
+ "are you calling a fixture-using step outside a VarItem.runtest?"
37
+ ) from exc
38
+
39
+
40
+ # ---------------------------------------------------------------------------
41
+ # Fixture parameter classification
42
+ # ---------------------------------------------------------------------------
43
+
44
+
45
+ def _fixture_param_names(fn: Callable[..., Any], n_positional_passed: int) -> list[str]:
46
+ """Return the names of parameters that should be resolved as fixtures.
47
+
48
+ Parameters AFTER the first ``1 + n_positional_passed`` positional params
49
+ (i.e. after ``state`` plus the args the core passes) that are
50
+ ``POSITIONAL_OR_KEYWORD`` or ``KEYWORD_ONLY`` are treated as fixture names.
51
+ """
52
+ params = list(inspect.signature(fn).parameters.values())
53
+ tail = params[1 + n_positional_passed :]
54
+ return [
55
+ p.name
56
+ for p in tail
57
+ if p.kind in (p.POSITIONAL_OR_KEYWORD, p.KEYWORD_ONLY)
58
+ ]
59
+
60
+
61
+ # ---------------------------------------------------------------------------
62
+ # Handler wrapper
63
+ # ---------------------------------------------------------------------------
64
+
65
+
66
+ def _wrap_handler(
67
+ original: Callable[..., Any],
68
+ get_request: Callable[[], Any],
69
+ ) -> Callable[..., Any]:
70
+ """Return a wrapper that resolves fixture params and delegates to *original*.
71
+
72
+ The wrapper is called as ``(state, *args)`` where ``args`` are the
73
+ positional captures (and an optional trailing table/doc-string) passed by
74
+ the core. Fixture parameters are classified at call time so that a
75
+ trailing table/doc-string arg is counted as a positional capture and NOT
76
+ mistakenly treated as a fixture name.
77
+ """
78
+
79
+ def wrapper(state: Any, *args: Any) -> Any:
80
+ names = _fixture_param_names(original, len(args))
81
+ if not names:
82
+ return original(state, *args)
83
+ request = get_request()
84
+ resolved = {name: request.getfixturevalue(name) for name in names}
85
+ return original(state, *args, **resolved)
86
+
87
+ return wrapper
88
+
89
+
90
+ # ---------------------------------------------------------------------------
91
+ # Registry wrapper
92
+ # ---------------------------------------------------------------------------
93
+
94
+
95
+ def wrap_registry_for_fixtures(
96
+ registry: Registry,
97
+ get_request: Callable[[], Any],
98
+ ) -> Registry:
99
+ """Return a new Registry whose every step handler resolves fixture params.
100
+
101
+ Each ``StepRegistration`` in the returned registry has its ``handler``
102
+ replaced by a wrapper that calls ``get_request().getfixturevalue(name)``
103
+ for each parameter that appears after the positional captures in the
104
+ original handler's signature.
105
+ """
106
+ wrapped_steps = tuple(
107
+ replace(step, handler=_wrap_handler(step.handler, get_request))
108
+ for step in registry.steps
109
+ )
110
+ return replace(registry, steps=wrapped_steps)
varar_pytest/plugin.py ADDED
@@ -0,0 +1,150 @@
1
+ from __future__ import annotations
2
+
3
+ import dataclasses
4
+ import os
5
+ from pathlib import Path
6
+
7
+ import pytest
8
+
9
+ from varar_config import read_varar_config
10
+ from varar_core.diagnostics import drift_detected
11
+ from varar_core.drift import reconcile_drift
12
+ from varar_runner.baseline_store import create_file_baseline_store
13
+ from varar_runner.discovery import match_spec
14
+ from varar_runner.run import RecordingReporter, examples_with_runs, plan_spec
15
+ from varar_runner.steps import load_steps
16
+ from varar_pytest.fixtures import _active_request, get_active_request, wrap_registry_for_fixtures
17
+
18
+ _STASH: dict = {} # keyed by config id → (VarConfig, LoadedSteps, root, store)
19
+
20
+
21
+ def pytest_addoption(parser: pytest.Parser) -> None:
22
+ parser.addoption(
23
+ "--var-update",
24
+ action="store_true",
25
+ default=False,
26
+ help="Accept drift and re-record varar.lock.json (also via VAR_UPDATE=1).",
27
+ )
28
+
29
+
30
+ def _update_mode(config: pytest.Config) -> bool:
31
+ if config.getoption("--var-update", default=False):
32
+ return True
33
+ return os.environ.get("VAR_UPDATE") in ("1", "true")
34
+
35
+
36
+ def pytest_configure(config: pytest.Config) -> None:
37
+ root = Path(config.rootpath)
38
+ cfg = read_varar_config(root)
39
+ loaded = load_steps(cfg.steps, root)
40
+ wrapped_registry = wrap_registry_for_fixtures(loaded.registry, get_active_request)
41
+ loaded = dataclasses.replace(loaded, registry=wrapped_registry)
42
+ _STASH[id(config)] = (cfg, loaded, root, create_file_baseline_store(root))
43
+
44
+
45
+ def pytest_unconfigure(config: pytest.Config) -> None:
46
+ _STASH.pop(id(config), None)
47
+
48
+
49
+ def pytest_collect_file(file_path: Path, parent: pytest.Collector):
50
+ if file_path.suffix != ".md":
51
+ return None
52
+ cfg, _loaded, root, _store = _STASH[id(parent.config)]
53
+ if not match_spec(file_path, cfg.docs_include, cfg.docs_exclude, root):
54
+ return None
55
+ return VarFile.from_parent(parent, path=file_path)
56
+
57
+
58
+ class VarFile(pytest.File):
59
+ def collect(self):
60
+ _cfg, loaded, root, store = _STASH[id(self.config)]
61
+ source = self.path.read_text(encoding="utf-8")
62
+ execution_plan = plan_spec(self.path.name, source, loaded.registry)
63
+ pairs = examples_with_runs(execution_plan, loaded.create_context, RecordingReporter())
64
+ seen: dict[str, int] = {}
65
+ for example, run in pairs:
66
+ # Use the innermost heading (scope_stack[-1]) as the item name so
67
+ # pytest displays "## adds two" as "adds two"; fall back to the
68
+ # body-derived name when there is no scope.
69
+ base = example.scope_stack[-1] if example.scope_stack else example.name
70
+ idx = seen.get(base, 0)
71
+ seen[base] = idx + 1
72
+ name = base if idx == 0 else f"{base}[{idx}]"
73
+ yield VarItem.from_parent(self, name=name, example=example, run=run, source=source)
74
+
75
+ # Reconcile drift against varar.lock.json: a clean run records/updates the
76
+ # baseline; a paragraph that was an example and no longer matches any
77
+ # step yields a failing item (unless --var-update / VAR_UPDATE accepts).
78
+ try:
79
+ spec_path = self.path.relative_to(root).as_posix()
80
+ except ValueError:
81
+ spec_path = self.path.name
82
+ drifts = reconcile_drift(
83
+ store,
84
+ spec_path,
85
+ source,
86
+ execution_plan.var_doc,
87
+ execution_plan,
88
+ update=_update_mode(self.config),
89
+ )
90
+ for d in drifts:
91
+ yield VarDriftItem.from_parent(
92
+ self,
93
+ name=f"var:drift:{d.line}",
94
+ message=drift_detected(d.name, d.span).message,
95
+ line=d.line,
96
+ )
97
+
98
+
99
+ class VarDriftItem(pytest.Item):
100
+ """A failing item for a drifted paragraph — the pytest surface of the
101
+ drift gate. Accept it with --var-update / VAR_UPDATE=1."""
102
+
103
+ def __init__(self, *, message, line, **kw):
104
+ super().__init__(**kw)
105
+ self._message = message
106
+ self._line = line
107
+
108
+ def runtest(self) -> None:
109
+ raise AssertionError(self._message)
110
+
111
+ def repr_failure(self, excinfo: object) -> str:
112
+ return self._message
113
+
114
+ def reportinfo(self):
115
+ return self.path, self._line - 1, self.name
116
+
117
+
118
+ class VarItem(pytest.Item):
119
+ def __init__(self, *, example, run, source, **kw):
120
+ super().__init__(**kw)
121
+ self._example = example
122
+ self._run = run
123
+ self._source = source
124
+ self._token = None
125
+
126
+ def setup(self) -> None:
127
+ from _pytest.fixtures import TopRequest
128
+
129
+ fm = self.session._fixturemanager
130
+ self._fixtureinfo = fm.getfixtureinfo(node=self, func=None, cls=None)
131
+ self.fixturenames = self._fixtureinfo.names_closure
132
+ self.funcargs: dict = {}
133
+ self._request = TopRequest(self, _ispytest=True) # type: ignore[arg-type]
134
+ self._token = _active_request.set(self._request)
135
+
136
+ def runtest(self) -> None:
137
+ self._run()
138
+
139
+ def teardown(self) -> None:
140
+ if self._token is not None:
141
+ _active_request.reset(self._token)
142
+ self._token = None
143
+
144
+ def repr_failure(self, excinfo: object) -> str:
145
+ from varar_runner.render import render_failure
146
+
147
+ return render_failure(excinfo.value, self._source, str(self.path)) # type: ignore[union-attr]
148
+
149
+ def reportinfo(self):
150
+ return self.path, self._example.span.start_line - 1, self.name