pytest-varar 0.5.0__tar.gz

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,32 @@
1
+ node_modules
2
+ dist
3
+ .DS_Store
4
+ *.tsbuildinfo
5
+ coverage
6
+ *.timestamp-*
7
+ .superpowers
8
+ .var/
9
+
10
+ # varar.lock.json baselines written by var-cli integration tests (temp fixtures)
11
+ typescript/packages/cli/tests/fixtures/run-basic/varar.lock.json
12
+ typescript/packages/cli/tests/fixtures/drift-tmp-*/
13
+ # varar.lock.json written by the Python conformance dogfood command
14
+ python/varar.lock.json
15
+ # varar.lock.json written into the Kotest fixture roots on every test run
16
+ # (the drift fixture's baseline IS committed and is not listed here)
17
+ java/kotest/src/test/resources/kotest-smoke/varar.lock.json
18
+ java/kotest/src/test/resources/kotest-failing/varar.lock.json
19
+ .claude/*
20
+ !.claude/skills/
21
+
22
+ # Python
23
+ .venv/
24
+ __pycache__/
25
+ *.pyc
26
+ .pytest_cache/
27
+ .ruff_cache/
28
+ .coverage
29
+ htmlcov/
30
+ coverage.lcov
31
+
32
+ release/dist/
@@ -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,17 @@
1
+ [project]
2
+ name = "pytest-varar"
3
+ version = "0.5.0"
4
+ description = "pytest plugin for Markdown-native BDD"
5
+ requires-python = ">=3.11"
6
+ license = "MIT"
7
+ dependencies = ["varar==0.5.0", "varar-config==0.5.0", "varar-core==0.5.0", "varar-runner==0.5.0", "pytest>=8"]
8
+
9
+ [project.entry-points.pytest11]
10
+ var = "varar_pytest.plugin"
11
+
12
+ [build-system]
13
+ requires = ["hatchling"]
14
+ build-backend = "hatchling.build"
15
+
16
+ [tool.hatch.build.targets.wheel]
17
+ packages = ["src/varar_pytest"]
@@ -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)
@@ -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
@@ -0,0 +1,77 @@
1
+ """test_async.py — verify that async def step handlers work through the plugin.
2
+
3
+ The var core drives coroutines via asyncio.run() in execute.py, so no plugin
4
+ change is expected. This test confirms end-to-end transparency.
5
+ """
6
+
7
+ VAR_CONFIG = """\
8
+ {"docs": {"include": ["features/**/*.md"], "exclude": []},
9
+ "steps": ["steps/**/*.steps.py"]}
10
+ """
11
+
12
+ # An action that is async def, returns a partial state dict.
13
+ # A sensor that is async def, returns its single slot bare so the core can compare it.
14
+ ASYNC_STEPS = """\
15
+ import asyncio
16
+ from varar import steps
17
+
18
+ param, stimulus, sensor = steps(lambda: {"value": 0})
19
+
20
+
21
+ @stimulus("I asynchronously add {int}")
22
+ async def _(state, n):
23
+ await asyncio.sleep(0) # yield to event loop once
24
+ return {"value": state["value"] + n}
25
+
26
+
27
+ @sensor("the async total is {int}")
28
+ async def _(state, expected):
29
+ await asyncio.sleep(0)
30
+ return state["value"]
31
+ """
32
+
33
+ ASYNC_SPEC = """\
34
+ # Async feature
35
+
36
+ ## adds two values asynchronously
37
+
38
+ I asynchronously add 3
39
+ I asynchronously add 4
40
+ the async total is 7
41
+ """
42
+
43
+ ASYNC_WRONG_SPEC = """\
44
+ # Async feature
45
+
46
+ ## async mismatch is detected
47
+
48
+ I asynchronously add 3
49
+ the async total is 99
50
+ """
51
+
52
+
53
+ def _write_fixture(pytester, spec_content: str, steps_content: str) -> None:
54
+ (pytester.path / "varar.config.json").write_text(VAR_CONFIG, encoding="utf-8")
55
+ (pytester.path / "steps").mkdir(exist_ok=True)
56
+ (pytester.path / "steps" / "async_calc.steps.py").write_text(
57
+ steps_content.strip(), encoding="utf-8"
58
+ )
59
+ (pytester.path / "features").mkdir(exist_ok=True)
60
+ (pytester.path / "features" / "async.md").write_text(spec_content, encoding="utf-8")
61
+
62
+
63
+ def test_async_handler_example_passes(pytester):
64
+ """An async def action and async def sensor are driven to completion by the core."""
65
+ _write_fixture(pytester, ASYNC_SPEC, ASYNC_STEPS)
66
+ result = pytester.runpytest("-v")
67
+ result.assert_outcomes(passed=1)
68
+ result.stdout.fnmatch_lines(["*async*PASSED*"])
69
+
70
+
71
+ def test_async_mismatch_is_detected(pytester):
72
+ """A mismatch in an async sensor is still caught and reported as a failure."""
73
+ _write_fixture(pytester, ASYNC_WRONG_SPEC, ASYNC_STEPS)
74
+ result = pytester.runpytest("-v")
75
+ result.assert_outcomes(failed=1)
76
+ # render_failure emits "expected: 99, actual: 3" — confirm it's a real cell-mismatch.
77
+ result.stdout.fnmatch_lines(["*expected*99*"])
@@ -0,0 +1,77 @@
1
+ STEPS = '''
2
+ from varar import steps
3
+ param, stimulus, sensor = steps(lambda: {"n": 0})
4
+ @stimulus("I add {int}")
5
+ def _(state, n):
6
+ return {"n": state["n"] + n}
7
+ @sensor("the total is {int}")
8
+ def _(state, total):
9
+ assert state["n"] == total, f"expected {total} got {state['n']}"
10
+ '''
11
+ VAR_CONFIG = """\
12
+ {"docs": {"include": ["features/**/*.md"], "exclude": []},
13
+ "steps": ["steps/**/*.steps.py"]}
14
+ """
15
+ # Steps must be in the same paragraph (single newline, not blank line) so the
16
+ # structurer groups them into one example per ## section.
17
+ SPEC = "# Calc\n\n## adds two\n\nI add 2\nthe total is 2\n\n## adds wrong\n\nI add 2\nthe total is 9\n"
18
+
19
+
20
+ def _write_varar_config(pytester):
21
+ (pytester.path / "varar.config.json").write_text(VAR_CONFIG, encoding="utf-8")
22
+
23
+
24
+ def _write_steps(pytester):
25
+ (pytester.path / "steps").mkdir(exist_ok=True)
26
+ (pytester.path / "steps/calc.steps.py").write_text(STEPS.strip(), encoding="utf-8")
27
+
28
+
29
+ def test_one_item_per_example_pass_and_fail(pytester):
30
+ _write_varar_config(pytester)
31
+ _write_steps(pytester)
32
+ (pytester.path / "features").mkdir()
33
+ (pytester.path / "features/calc.md").write_text(SPEC, encoding="utf-8")
34
+ result = pytester.runpytest("-v")
35
+ result.assert_outcomes(passed=1, failed=1)
36
+ result.stdout.fnmatch_lines(["*features/calc.md::adds two*PASSED*"])
37
+
38
+
39
+ def test_k_selection(pytester):
40
+ _write_varar_config(pytester)
41
+ _write_steps(pytester)
42
+ (pytester.path / "features").mkdir()
43
+ (pytester.path / "features/calc.md").write_text(SPEC, encoding="utf-8")
44
+ # pytest 9 uses expression syntax; "adds and two" matches items whose
45
+ # keywords include both "adds" and "two" — uniquely identifies "adds two".
46
+ result = pytester.runpytest("-k", "adds and two")
47
+ result.assert_outcomes(passed=1)
48
+
49
+
50
+ def test_duplicate_heading_items_get_unique_node_ids(pytester):
51
+ """Two blank-line-separated paragraphs under the same ## heading must not
52
+ produce colliding pytest node IDs. First paragraph passes, second fails."""
53
+ # Two paragraphs under the same heading — the structurer emits two examples
54
+ # with identical scope_stack[-1] ("same heading").
55
+ spec = (
56
+ "# Calc\n\n"
57
+ "## same heading\n\n"
58
+ "I add 2\nthe total is 2\n\n"
59
+ "## same heading\n\n"
60
+ "I add 2\nthe total is 9\n"
61
+ )
62
+ _write_varar_config(pytester)
63
+ _write_steps(pytester)
64
+ (pytester.path / "features").mkdir()
65
+ (pytester.path / "features/dup.md").write_text(spec, encoding="utf-8")
66
+ result = pytester.runpytest("-v")
67
+ result.assert_outcomes(passed=1, failed=1)
68
+ # First example keeps the bare heading; second gets the [1] suffix.
69
+ result.stdout.fnmatch_lines(["*features/dup.md::same heading*"])
70
+ result.stdout.fnmatch_lines(["*features/dup.md::same heading[[]1[]]*"])
71
+
72
+
73
+ def test_non_matching_md_is_ignored(pytester):
74
+ _write_varar_config(pytester)
75
+ (pytester.path / "README.md").write_text("# not a spec\n", encoding="utf-8")
76
+ result = pytester.runpytest()
77
+ result.assert_outcomes() # nothing collected, no error
@@ -0,0 +1,105 @@
1
+ """test_dogfood_bundles.py — integration tests running real conformance bundles.
2
+
3
+ Each test copies a bundle's example.md and <name>.steps.py into the pytester
4
+ tree, runs pytest with a varar.config.json pointing at them, and asserts the
5
+ outcome matches the bundle's intent as documented by its golden trace.json.
6
+
7
+ Bundles exercised:
8
+ - 01-roman-numerals : happy-path example → PASSED
9
+ - 03-expected-failure: example declared expected_outcome=fail, step throws the
10
+ expected error → the core inverts the outcome (run() does
11
+ NOT raise) → pytest reports PASSED
12
+ - 07-row-check-mismatch: sensor returns wrong cell value → FAILED with a
13
+ markdown-anchored cell-mismatch message
14
+
15
+ Bundles directory is resolved robustly relative to this file:
16
+ python/packages/pytest/tests/ → parents[4] → repo root
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from pathlib import Path
22
+
23
+ # ---------------------------------------------------------------------------
24
+ # Bundle directory
25
+ # ---------------------------------------------------------------------------
26
+
27
+ _BUNDLES = Path(__file__).resolve().parents[4] / "conformance" / "bundles"
28
+ assert _BUNDLES.is_dir(), f"bundles dir not found: {_BUNDLES}"
29
+
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # Helpers
33
+ # ---------------------------------------------------------------------------
34
+
35
+
36
+ def _setup_bundle(pytester, bundle_name: str, steps_filename: str) -> None:
37
+ """Copy bundle's example.md and steps file into the pytester tree."""
38
+ bundle_dir = _BUNDLES / bundle_name
39
+ example_md = (bundle_dir / "example.md").read_text(encoding="utf-8")
40
+ steps_py = (bundle_dir / steps_filename).read_text(encoding="utf-8")
41
+
42
+ (pytester.path / "varar.config.json").write_text(
43
+ '{"docs": {"include": ["specs/**/*.md"], "exclude": []},'
44
+ ' "steps": ["steps/**/*.steps.py"]}',
45
+ encoding="utf-8",
46
+ )
47
+ (pytester.path / "specs").mkdir()
48
+ (pytester.path / "specs" / "example.md").write_text(example_md, encoding="utf-8")
49
+ (pytester.path / "steps").mkdir()
50
+ (pytester.path / "steps" / steps_filename).write_text(steps_py, encoding="utf-8")
51
+
52
+
53
+ # ---------------------------------------------------------------------------
54
+ # 01 — happy-path example passes
55
+ # ---------------------------------------------------------------------------
56
+
57
+
58
+ def test_bundle_01_roman_numerals_passes(pytester):
59
+ """Happy-path bundle: the single example must be reported PASSED."""
60
+ _setup_bundle(pytester, "01-roman-numerals", "numerals.steps.py")
61
+ result = pytester.runpytest("-v")
62
+ result.assert_outcomes(passed=1)
63
+ result.stdout.fnmatch_lines(["*Converting 1*PASSED*"])
64
+
65
+
66
+ # ---------------------------------------------------------------------------
67
+ # 03 — expected-failure: satisfied → PASSED
68
+ # ---------------------------------------------------------------------------
69
+
70
+
71
+ def test_bundle_03_expected_failure_reports_passed(pytester):
72
+ """Expected-failure bundle: the step throws the expected error.
73
+
74
+ The core inverts the outcome — run() does NOT raise — so pytest reports
75
+ the example as PASSED (the expected failure occurred as intended).
76
+ """
77
+ _setup_bundle(pytester, "03-expected-failure", "division.steps.py")
78
+ result = pytester.runpytest("-v")
79
+ result.assert_outcomes(passed=1)
80
+ result.stdout.fnmatch_lines(["*Dividing by zero is rejected*PASSED*"])
81
+
82
+
83
+ # ---------------------------------------------------------------------------
84
+ # 07 — row-check mismatch: FAILED with markdown-anchored cell diff
85
+ # ---------------------------------------------------------------------------
86
+
87
+
88
+ def test_bundle_07_row_check_mismatch_fails_with_cell_diff(pytester):
89
+ """Cell-mismatch bundle: the sensor returns a wrong score.
90
+
91
+ The example must be reported FAILED, and the failure output must reference
92
+ the mismatched column and its expected/actual values.
93
+ """
94
+ _setup_bundle(pytester, "07-row-check-mismatch", "report.steps.py")
95
+ result = pytester.runpytest("-v")
96
+ result.assert_outcomes(failed=1)
97
+ # Header-bound row examples use the step text as their item name
98
+ # (scope_stack[-1] == "I report the score and grade"), not the ## heading.
99
+ result.stdout.fnmatch_lines(["*I report the score and grade*FAILED*"])
100
+ # The repr_failure output must include the column name and both values.
101
+ result.stdout.fnmatch_lines(["*score*"])
102
+ result.stdout.fnmatch_lines(["*expected*10*"])
103
+ result.stdout.fnmatch_lines(["*actual*99*"])
104
+ # The render_failure output emits "line N | column ..." — assert the exact line.
105
+ result.stdout.fnmatch_lines(["*line 9*"])
@@ -0,0 +1,65 @@
1
+ """Drift gate through the pytest plugin (mirrors the TS var-cli drift tests)."""
2
+ import json
3
+
4
+ STEPS = '''
5
+ from varar import steps
6
+ param, stimulus, sensor = steps(lambda: {"n": 0})
7
+ @stimulus("I add {int}")
8
+ def _(state, n):
9
+ return {"n": state["n"] + n}
10
+ '''
11
+
12
+ VAR_CONFIG = """\
13
+ {"docs": {"include": ["features/**/*.md"], "exclude": []},
14
+ "steps": ["steps/**/*.steps.py"]}
15
+ """
16
+
17
+
18
+ def _project(pytester):
19
+ (pytester.path / "varar.config.json").write_text(VAR_CONFIG, encoding="utf-8")
20
+ (pytester.path / "steps").mkdir(exist_ok=True)
21
+ (pytester.path / "steps/calc.steps.py").write_text(STEPS.strip(), encoding="utf-8")
22
+ (pytester.path / "features").mkdir(exist_ok=True)
23
+
24
+
25
+ def _write_baseline(pytester, examples):
26
+ lock = {
27
+ "version": 1,
28
+ "specs": {"features/vault.md": {"sourceHash": "fnv1a:0", "examples": examples}},
29
+ }
30
+ (pytester.path / "varar.lock.json").write_text(json.dumps(lock), encoding="utf-8")
31
+
32
+
33
+ def _lock(pytester):
34
+ return json.loads((pytester.path / "varar.lock.json").read_text(encoding="utf-8"))
35
+
36
+
37
+ def test_first_run_records_the_baseline_and_passes(pytester):
38
+ _project(pytester)
39
+ (pytester.path / "features/calc.md").write_text("I add 2\n", encoding="utf-8")
40
+ result = pytester.runpytest("-v")
41
+ result.assert_outcomes(passed=1)
42
+ lock = _lock(pytester)
43
+ assert lock["specs"]["features/calc.md"]["examples"] == [{"name": "I add 2", "line": 1}]
44
+
45
+
46
+ def test_a_paragraph_that_stopped_matching_drifts_and_fails(pytester):
47
+ _project(pytester)
48
+ # Prose now; the baseline says it was an example.
49
+ (pytester.path / "features/vault.md").write_text("The vault is sealed.\n", encoding="utf-8")
50
+ _write_baseline(pytester, [{"name": "The vault is sealed", "line": 1}])
51
+ before = (pytester.path / "varar.lock.json").read_text(encoding="utf-8")
52
+ result = pytester.runpytest("-v")
53
+ result.assert_outcomes(failed=1)
54
+ result.stdout.fnmatch_lines(["*var:drift*"])
55
+ # Unacknowledged drift leaves the baseline untouched.
56
+ assert (pytester.path / "varar.lock.json").read_text(encoding="utf-8") == before
57
+
58
+
59
+ def test_var_update_accepts_drift(pytester):
60
+ _project(pytester)
61
+ (pytester.path / "features/vault.md").write_text("The vault is sealed.\n", encoding="utf-8")
62
+ _write_baseline(pytester, [{"name": "The vault is sealed", "line": 1}])
63
+ result = pytester.runpytest("--var-update")
64
+ result.assert_outcomes()
65
+ assert _lock(pytester)["specs"]["features/vault.md"]["examples"] == []
@@ -0,0 +1,133 @@
1
+ """test_failures.py — pytester-based tests for VarItem.repr_failure.
2
+
3
+ Tests:
4
+ - Cell-mismatch failure renders line number + expected/actual diff.
5
+ - A paragraph whose sentences match no step definition is silently ignored.
6
+ """
7
+
8
+ VAR_CONFIG = """\
9
+ {"docs": {"include": ["features/**/*.md"], "exclude": []},
10
+ "steps": ["steps/**/*.steps.py"]}
11
+ """
12
+
13
+ # ---------------------------------------------------------------------------
14
+ # Cell-mismatch fixtures (mirrors conformance bundle 07-row-check-mismatch)
15
+ # ---------------------------------------------------------------------------
16
+
17
+ CELL_MISMATCH_SPEC = """\
18
+ # Scoring
19
+
20
+ ## A wrong score is caught
21
+
22
+ I report the score and grade.
23
+
24
+ | score | grade |
25
+ | ----- | ----- |
26
+ | 10 | A |
27
+ """
28
+
29
+ CELL_MISMATCH_STEPS = """\
30
+ from varar import steps
31
+ param, stimulus, sensor = steps(lambda: {})
32
+
33
+ @sensor("I report the score and grade")
34
+ def _(state, row=None):
35
+ return {"score": "99", "grade": "A"}
36
+ """
37
+
38
+ # ---------------------------------------------------------------------------
39
+ # Prose-paragraph fixtures (no matching step defs → silently ignored)
40
+ # ---------------------------------------------------------------------------
41
+
42
+ # A spec with one real example AND one prose paragraph that matches no step def.
43
+ PROSE_AND_REAL_SPEC = """\
44
+ # My Feature
45
+
46
+ ## Prose paragraph
47
+
48
+ This sentence matches no step definition at all.
49
+
50
+ ## A real example
51
+
52
+ I report the score and grade.
53
+
54
+ | score | grade |
55
+ | ----- | ----- |
56
+ | 99 | A |
57
+ """
58
+
59
+ # A spec with ONLY a prose paragraph — the whole file has no matched steps.
60
+ PROSE_ONLY_SPEC = """\
61
+ # My Feature
62
+
63
+ ## Prose paragraph
64
+
65
+ This sentence matches no step definition at all.
66
+ """
67
+
68
+ PROSE_STEPS = """\
69
+ from varar import steps
70
+ param, stimulus, sensor = steps(lambda: {})
71
+
72
+ @sensor("I report the score and grade")
73
+ def _(state, row=None):
74
+ return {"score": "99", "grade": "A"}
75
+ """
76
+
77
+ # Steps that register NO defs at all.
78
+ EMPTY_STEPS = """\
79
+ from varar import steps
80
+ param, stimulus, sensor = steps(lambda: {})
81
+ """
82
+
83
+
84
+ # ---------------------------------------------------------------------------
85
+ # Helpers
86
+ # ---------------------------------------------------------------------------
87
+
88
+
89
+ def _write_fixture(pytester, spec_content: str, steps_content: str) -> None:
90
+ (pytester.path / "varar.config.json").write_text(VAR_CONFIG, encoding="utf-8")
91
+ (pytester.path / "steps").mkdir(exist_ok=True)
92
+ (pytester.path / "steps" / "spec.steps.py").write_text(
93
+ steps_content.strip(), encoding="utf-8"
94
+ )
95
+ (pytester.path / "features").mkdir(exist_ok=True)
96
+ (pytester.path / "features" / "spec.md").write_text(spec_content, encoding="utf-8")
97
+
98
+
99
+ # ---------------------------------------------------------------------------
100
+ # Tests
101
+ # ---------------------------------------------------------------------------
102
+
103
+
104
+ def test_cell_mismatch_repr_failure_shows_line_and_diff(pytester):
105
+ """repr_failure for CellMismatchError must include the markdown line number,
106
+ the column name, and the expected/actual values."""
107
+ _write_fixture(pytester, CELL_MISMATCH_SPEC, CELL_MISMATCH_STEPS)
108
+ result = pytester.runpytest("-v")
109
+ result.assert_outcomes(failed=1)
110
+ # render_failure output: "line N | column 'score' — expected: '10', actual: '99'"
111
+ result.stdout.fnmatch_lines(["*score*"])
112
+ result.stdout.fnmatch_lines(["*expected*10*"])
113
+ result.stdout.fnmatch_lines(["*actual*99*"])
114
+ # A line-number reference must appear somewhere in the output.
115
+ assert any("line" in line for line in result.stdout.lines)
116
+
117
+
118
+ def test_prose_paragraph_with_no_matching_steps_is_silently_ignored(pytester):
119
+ """A paragraph whose sentences match no step definition must NOT be collected
120
+ as a test item — it is plain prose and is silently dropped by the planner."""
121
+ _write_fixture(pytester, PROSE_ONLY_SPEC, EMPTY_STEPS)
122
+ result = pytester.runpytest("-v")
123
+ # No items collected, no failures.
124
+ result.assert_outcomes(passed=0, failed=0)
125
+
126
+
127
+ def test_prose_paragraph_does_not_pollute_real_examples(pytester):
128
+ """A spec that mixes a prose paragraph (no matches) with a real example must
129
+ collect only the real example — no extra failing item for the prose."""
130
+ _write_fixture(pytester, PROSE_AND_REAL_SPEC, PROSE_STEPS)
131
+ result = pytester.runpytest("-v")
132
+ # Only the one real example should be collected and should pass.
133
+ result.assert_outcomes(passed=1, failed=0)
@@ -0,0 +1,107 @@
1
+ """test_fixtures.py — pytester-based tests for the fixture bridge.
2
+
3
+ Tests:
4
+ - A step handler can receive pytest fixtures (``db``, ``tmp_path``) via extra
5
+ parameters after the captured args; the captured ``{int}`` is still bound
6
+ positionally, not confused with fixtures.
7
+ - Classification pins: one handler has BOTH a captured arg AND a fixture,
8
+ asserting that the bridge correctly separates positional captures from
9
+ fixture injections.
10
+ """
11
+
12
+ VAR_CONFIG = """\
13
+ {"docs": {"include": ["features/**/*.md"], "exclude": []},
14
+ "steps": ["steps/**/*.steps.py"]}
15
+ """
16
+
17
+ # ---------------------------------------------------------------------------
18
+ # Steps: action uses db + tmp_path fixtures; sensor uses db fixture only.
19
+ # The {int} capture is the positional arg; db and tmp_path are fixtures.
20
+ # ---------------------------------------------------------------------------
21
+
22
+ STEPS = """\
23
+ from varar import steps
24
+ param, stimulus, sensor = steps(lambda: {})
25
+
26
+ @stimulus("I save {int}")
27
+ def _(state, n, db, tmp_path):
28
+ db.append((n, str(tmp_path)))
29
+
30
+ @sensor("db has {int} entries")
31
+ def _(state, count, db):
32
+ return len(db)
33
+ """
34
+
35
+ SPEC = """\
36
+ # Fixture Bridge
37
+
38
+ ## saves to db and tmp_path
39
+
40
+ I save 1
41
+ I save 2
42
+ db has 2 entries
43
+ """
44
+
45
+ def _write_fixture(pytester, spec_content: str, steps_content: str) -> None:
46
+ (pytester.path / "varar.config.json").write_text(VAR_CONFIG, encoding="utf-8")
47
+ (pytester.path / "steps").mkdir(exist_ok=True)
48
+ (pytester.path / "steps" / "spec.steps.py").write_text(
49
+ steps_content.strip(), encoding="utf-8"
50
+ )
51
+ (pytester.path / "features").mkdir(exist_ok=True)
52
+ (pytester.path / "features" / "spec.md").write_text(spec_content, encoding="utf-8")
53
+
54
+
55
+ # Also create a conftest with a custom db fixture
56
+ CONFTEST = """\
57
+ import pytest
58
+
59
+ @pytest.fixture
60
+ def db():
61
+ return []
62
+ """
63
+
64
+
65
+ def test_fixtures_injected_into_step_handlers(pytester):
66
+ """db and tmp_path fixtures are injected; {int} capture stays positional."""
67
+ pytester.makeconftest(CONFTEST)
68
+ _write_fixture(pytester, SPEC, STEPS)
69
+ result = pytester.runpytest("-v")
70
+ result.assert_outcomes(passed=1)
71
+
72
+
73
+ # ---------------------------------------------------------------------------
74
+ # Classification pin: one handler with BOTH a captured arg AND a fixture.
75
+ # ``n`` is positional (from {int}), ``db`` is a fixture.
76
+ # ---------------------------------------------------------------------------
77
+
78
+ CLASSIFICATION_STEPS = """\
79
+ from varar import steps
80
+ param, stimulus, sensor = steps(lambda: {})
81
+
82
+ @stimulus("I store {int} in db")
83
+ def _(state, n, db):
84
+ db.append(n)
85
+
86
+ @sensor("db contains {int}")
87
+ def _(state, expected, db):
88
+ assert db == [expected], f"expected [{expected}], got {db}"
89
+ return expected
90
+ """
91
+
92
+ CLASSIFICATION_SPEC = """\
93
+ # Classification
94
+
95
+ ## captured arg and fixture coexist
96
+
97
+ I store 42 in db
98
+ db contains 42
99
+ """
100
+
101
+
102
+ def test_classification_captured_and_fixture(pytester):
103
+ """n is bound from {int} capture; db is injected as fixture — they coexist."""
104
+ pytester.makeconftest(CONFTEST)
105
+ _write_fixture(pytester, CLASSIFICATION_SPEC, CLASSIFICATION_STEPS)
106
+ result = pytester.runpytest("-v")
107
+ result.assert_outcomes(passed=1)