varar-runner 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,8 @@
1
+ Metadata-Version: 2.4
2
+ Name: varar-runner
3
+ Version: 0.5.0
4
+ Summary: Shared spec discovery + run orchestration for varar runners
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.11
7
+ Requires-Dist: varar-config==0.5.0
8
+ Requires-Dist: varar==0.5.0
@@ -0,0 +1,17 @@
1
+ [project]
2
+ name = "varar-runner"
3
+ version = "0.5.0"
4
+ description = "Shared spec discovery + run orchestration for varar runners"
5
+ requires-python = ">=3.11"
6
+ license = "MIT"
7
+ dependencies = ["varar==0.5.0", "varar-config==0.5.0"]
8
+
9
+ [project.scripts]
10
+ varar = "varar_runner.cli:main"
11
+
12
+ [build-system]
13
+ requires = ["hatchling"]
14
+ build-backend = "hatchling.build"
15
+
16
+ [tool.hatch.build.targets.wheel]
17
+ packages = ["src/varar_runner"]
@@ -0,0 +1,19 @@
1
+ """Shared imperative-shell orchestration for var test runners."""
2
+
3
+ __version__ = "0.0.0"
4
+
5
+ from varar_runner.discovery import find_specs, match_spec
6
+ from varar_runner.render import render_failure
7
+ from varar_runner.run import RecordingReporter, examples_with_runs, plan_spec
8
+ from varar_runner.steps import LoadedSteps, load_steps
9
+
10
+ __all__ = [
11
+ "find_specs",
12
+ "match_spec",
13
+ "load_steps",
14
+ "LoadedSteps",
15
+ "plan_spec",
16
+ "examples_with_runs",
17
+ "RecordingReporter",
18
+ "render_failure",
19
+ ]
@@ -0,0 +1,23 @@
1
+ """baseline_store.py — the Node/CLI-equivalent filesystem BaselineStore.
2
+
3
+ The committed drift baseline lives at the project root as varar.lock.json. The
4
+ core owns the format; this adapter only reads and writes the raw text.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from pathlib import Path
9
+
10
+
11
+ class FileBaselineStore:
12
+ def __init__(self, root: Path | str) -> None:
13
+ self._path = Path(root) / "varar.lock.json"
14
+
15
+ def read(self) -> str | None:
16
+ return self._path.read_text(encoding="utf-8") if self._path.exists() else None
17
+
18
+ def write(self, contents: str) -> None:
19
+ self._path.write_text(contents, encoding="utf-8")
20
+
21
+
22
+ def create_file_baseline_store(root: Path | str) -> FileBaselineStore:
23
+ return FileBaselineStore(root)
@@ -0,0 +1,82 @@
1
+ """The `var` command-line entry point.
2
+
3
+ Today it offers a single sub-command, `varar init`, which scaffolds a new
4
+ project: a `varar.config.json`, one Markdown spec, and its step definitions.
5
+ Specs then run through pytest (`pytest-varar`) or unittest — there is no
6
+ `varar run` in the Python port; the test framework is the runner.
7
+
8
+ The scaffold mirrors the TypeScript CLI (`@varar/varar-cli`) byte-for-byte
9
+ except for the steps file, so a project started with `varar init` looks the same
10
+ in every language. The `01-hello.md` spec is language-neutral.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import sys
16
+ from pathlib import Path
17
+ from typing import Callable
18
+
19
+ _CONFIG = """{
20
+ "docs": { "include": ["varar-examples/**/*.md"], "exclude": [] },
21
+ "steps": ["varar-examples/**/*.steps.py"]
22
+ }
23
+ """
24
+
25
+ _EXAMPLE_MD = """# Hello, BDD
26
+
27
+ Given I greet "world"
28
+ Then the greeting is "Hello, world!"
29
+ """
30
+
31
+ _EXAMPLE_STEPS = '''from varar import steps
32
+
33
+ param, stimulus, sensor = steps(lambda: {"greeting": ""})
34
+
35
+
36
+ @stimulus("I greet {string}")
37
+ def _(state, name):
38
+ return {"greeting": f"Hello, {name}!"}
39
+
40
+
41
+ @sensor("the greeting is {string}")
42
+ def _(state, expected):
43
+ return state["greeting"]
44
+ '''
45
+
46
+ _FILES: tuple[tuple[str, str], ...] = (
47
+ ("varar.config.json", _CONFIG),
48
+ ("varar-examples/01-hello.md", _EXAMPLE_MD),
49
+ ("varar-examples/steps/01-hello.steps.py", _EXAMPLE_STEPS),
50
+ )
51
+
52
+ _USAGE = """varar — scaffold and run Markdown specs
53
+
54
+ Usage:
55
+ varar init scaffold a new project
56
+ """
57
+
58
+
59
+ def run_init(cwd: Path, write: Callable[[str], None]) -> int:
60
+ """Write the scaffold into *cwd*, skipping any file that already exists."""
61
+ for rel, content in _FILES:
62
+ target = cwd / rel
63
+ if target.exists():
64
+ write(f"skipped {rel} (already exists)\n")
65
+ continue
66
+ target.parent.mkdir(parents=True, exist_ok=True)
67
+ target.write_text(content, encoding="utf-8")
68
+ write(f"created {rel}\n")
69
+ return 0
70
+
71
+
72
+ def main(argv: list[str] | None = None) -> int:
73
+ args = list(sys.argv[1:] if argv is None else argv)
74
+ command = args[0] if args else ""
75
+ if command == "init":
76
+ return run_init(Path.cwd(), sys.stdout.write)
77
+ sys.stdout.write(_USAGE)
78
+ return 0 if command in ("", "help", "-h", "--help") else 1
79
+
80
+
81
+ if __name__ == "__main__":
82
+ raise SystemExit(main())
@@ -0,0 +1,99 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import re
5
+ from collections.abc import Sequence
6
+ from pathlib import Path
7
+
8
+
9
+ def _abs_no_deref(path: Path) -> Path:
10
+ # os.path.abspath normalizes (cwd-joins, collapses ..) WITHOUT dereferencing
11
+ # symlinks — a symlinked spec must match the docs globs by its apparent path,
12
+ # not its target's (mirrors Java's toAbsolutePath().normalize()).
13
+ return Path(os.path.abspath(path))
14
+
15
+
16
+ def _rel_posix(path: Path, root: Path) -> str:
17
+ # walk_up=True (Python 3.12+) yields a ``../`` prefix when *path* is outside
18
+ # *root*, so specs can live outside the config root (e.g. a shared corpus in a
19
+ # sibling directory) and still match a ``../sibling/**`` glob.
20
+ return _abs_no_deref(path).relative_to(_abs_no_deref(root), walk_up=True).as_posix()
21
+
22
+
23
+ def _glob_to_regex(pattern: str) -> re.Pattern[str]:
24
+ """Translate a glob pattern with **, *, ? to a compiled regex.
25
+
26
+ Semantics (same as ``pathlib.Path.full_match`` / PEP 428):
27
+ - ``/**/`` (slash–doublestar–slash) → ``/(?:.+/)?`` zero or more intermediate
28
+ directory segments (the surrounding slashes are absorbed into the token).
29
+ - ``/**`` at end of pattern → ``(?:/.*)?`` optional trailing path.
30
+ - ``**/`` not preceded by ``/`` (leading or after a literal) → ``(?:.*/)?``
31
+ zero or more path segments including the trailing slash, so a leading ``**/``
32
+ matches both root-level paths and nested ones.
33
+ - bare ``**`` elsewhere → ``.*``.
34
+ - ``*`` → ``[^/]*`` (any chars except ``/``).
35
+ - ``?`` → ``[^/]`` (single char except ``/``).
36
+
37
+ ``pathlib.Path.full_match`` (Python 3.13+) would express this natively,
38
+ but Python 3.12 does not have it, so we compile a regex instead.
39
+ """
40
+ result = ""
41
+ i = 0
42
+ n = len(pattern)
43
+ while i < n:
44
+ c = pattern[i]
45
+ if c == "/" and pattern[i : i + 4] == "/**/":
46
+ # /**/ → /(?:.+/)? — absorb both slashes; zero or more intermediate dirs
47
+ result += "/(?:.+/)?"
48
+ i += 4
49
+ elif c == "/" and pattern[i : i + 3] == "/**" and i + 3 == n:
50
+ # /** at end → optional trailing /anything
51
+ result += "(?:/.*)?"
52
+ i += 3
53
+ elif c == "*" and pattern[i : i + 3] == "**/":
54
+ # **/ not preceded by / (leading **/ or after a literal char)
55
+ # → zero or more path segments with their trailing slash (optional)
56
+ result += "(?:.*/)?"
57
+ i += 3
58
+ elif c == "*" and pattern[i : i + 2] == "**":
59
+ # bare ** (e.g. at end of pattern with no following /)
60
+ result += ".*"
61
+ i += 2
62
+ elif c == "*":
63
+ result += "[^/]*"
64
+ i += 1
65
+ elif c == "?":
66
+ result += "[^/]"
67
+ i += 1
68
+ else:
69
+ result += re.escape(c)
70
+ i += 1
71
+ return re.compile(result)
72
+
73
+
74
+ def _matches_any(rel: str, globs: Sequence[str]) -> bool:
75
+ return any(_glob_to_regex(g).fullmatch(rel) is not None for g in globs)
76
+
77
+
78
+ def match_spec(
79
+ path: Path,
80
+ include: Sequence[str],
81
+ exclude: Sequence[str],
82
+ root: Path,
83
+ ) -> bool:
84
+ """Return True iff *path* matches an include glob and no exclude glob."""
85
+ rel = _rel_posix(path, root)
86
+ return _matches_any(rel, include) and not _matches_any(rel, exclude)
87
+
88
+
89
+ def find_specs(
90
+ include: Sequence[str],
91
+ exclude: Sequence[str],
92
+ root: Path,
93
+ ) -> tuple[Path, ...]:
94
+ """Return existing files under *root* matching any include glob, minus any exclude; sorted."""
95
+ out: set[Path] = set()
96
+ for g in include:
97
+ out.update(p for p in root.glob(g) if p.is_file())
98
+ keep = [p for p in out if not _matches_any(_rel_posix(p, root), exclude)]
99
+ return tuple(sorted(keep))
@@ -0,0 +1,46 @@
1
+ """render.py — pure human-readable rendering of var diff errors.
2
+
3
+ Pure function: no I/O, no side effects.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ from varar_core.cell_diff import ReturnShapeError, is_cell_mismatch_error
8
+ from varar_core.doc_string_diff import is_doc_string_mismatch_error
9
+
10
+
11
+ def render_failure(error: BaseException, source: str, path: str) -> str: # noqa: ARG001
12
+ """Render a step failure as a human-readable, markdown-anchored string.
13
+
14
+ Dispatches on the concrete error type:
15
+ - CellMismatchError → list each failing cell with column/expected/actual/line.
16
+ - DocStringMismatchError → expected vs actual + line.
17
+ - ReturnShapeError → its message.
18
+ - Any other exception → ``TypeName: message``.
19
+
20
+ ``source`` is available for additional context but line numbers from spans
21
+ are the primary anchor.
22
+ """
23
+ if is_cell_mismatch_error(error):
24
+ lines: list[str] = [f"Cell mismatch in {path}:"]
25
+ failing = [c for c in error.cells if not c.ok] # type: ignore[union-attr]
26
+ if not failing:
27
+ lines.append(" (no failing cells)")
28
+ for cell in failing:
29
+ lines.append(
30
+ f" line {cell.span.start_line} | column '{cell.column}'"
31
+ f" — expected: {cell.expected!r}, actual: {cell.actual!r}"
32
+ )
33
+ return "\n".join(lines)
34
+
35
+ if is_doc_string_mismatch_error(error):
36
+ diff = error.diff # type: ignore[union-attr]
37
+ return (
38
+ f"Doc string mismatch at line {diff.span.start_line}:\n"
39
+ f" expected: {diff.expected!r}\n"
40
+ f" actual: {diff.actual!r}"
41
+ )
42
+
43
+ if isinstance(error, ReturnShapeError):
44
+ return str(error)
45
+
46
+ return f"{type(error).__name__}: {error}"
@@ -0,0 +1,25 @@
1
+ from __future__ import annotations
2
+ from collections.abc import Callable
3
+ from typing import Any
4
+ from varar_core.execute import CollectPorts, collect_examples
5
+ from varar_core.parse import parse
6
+ from varar_core.plan import ExecutionPlan, PlannedExample, plan
7
+ from varar_core.registry import Registry
8
+
9
+ class RecordingReporter:
10
+ def __init__(self) -> None:
11
+ self.diagnostics: list[Any] = []
12
+ def diagnostic(self, d: Any) -> None:
13
+ self.diagnostics.append(d)
14
+
15
+ def plan_spec(path: str, source: str, registry: Registry) -> ExecutionPlan:
16
+ return plan(parse(path, source), registry)
17
+
18
+ def examples_with_runs(
19
+ execution_plan: ExecutionPlan,
20
+ create_context: Callable[[str], Any],
21
+ reporter: Any,
22
+ ) -> tuple[tuple[PlannedExample, Callable[[], None]], ...]:
23
+ queue = collect_examples(execution_plan, CollectPorts(reporter=reporter, create_context=create_context))
24
+ # collect_examples preserves plan.examples order
25
+ return tuple((ex, q.run) for ex, q in zip(execution_plan.examples, queue, strict=True))
@@ -0,0 +1,31 @@
1
+ from __future__ import annotations
2
+ import importlib.util
3
+ from collections.abc import Callable, Sequence
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import Any
7
+ from varar.registry import _reset_builder, build_registry, context_factory
8
+ from varar_core.registry import Registry
9
+
10
+
11
+ @dataclass(frozen=True, slots=True)
12
+ class LoadedSteps:
13
+ registry: Registry
14
+ create_context: Callable[[str], Any]
15
+
16
+
17
+ def _import_file(path: Path, module_name: str) -> None:
18
+ spec = importlib.util.spec_from_file_location(module_name, path)
19
+ assert spec and spec.loader
20
+ mod = importlib.util.module_from_spec(spec)
21
+ spec.loader.exec_module(mod)
22
+
23
+
24
+ def load_steps(step_globs: Sequence[str], root: Path) -> LoadedSteps:
25
+ _reset_builder()
26
+ files: set[Path] = set()
27
+ for g in step_globs:
28
+ files.update(p for p in root.glob(g) if p.is_file())
29
+ for i, path in enumerate(sorted(files)):
30
+ _import_file(path, f"_var_steps_{i}_{path.stem}")
31
+ return LoadedSteps(registry=build_registry(), create_context=context_factory())
@@ -0,0 +1,31 @@
1
+ from pathlib import Path
2
+
3
+ from varar_runner.cli import run_init
4
+
5
+
6
+ def _capture() -> tuple[list[str], object]:
7
+ lines: list[str] = []
8
+ return lines, lines.append
9
+
10
+
11
+ def test_init_scaffolds_the_three_files(tmp_path: Path) -> None:
12
+ lines, write = _capture()
13
+ exit_code = run_init(tmp_path, write)
14
+
15
+ assert exit_code == 0
16
+ assert (tmp_path / "varar.config.json").exists()
17
+ assert (tmp_path / "varar-examples/01-hello.md").exists()
18
+ steps = (tmp_path / "varar-examples/steps/01-hello.steps.py").read_text(encoding="utf-8")
19
+ assert "from varar import steps" in steps
20
+ assert "@stimulus" in steps and "@sensor" in steps
21
+ assert all(line.startswith("created ") for line in lines)
22
+
23
+
24
+ def test_init_skips_existing_files(tmp_path: Path) -> None:
25
+ (tmp_path / "varar.config.json").write_text("{}\n", encoding="utf-8")
26
+ lines, write = _capture()
27
+
28
+ run_init(tmp_path, write)
29
+
30
+ assert (tmp_path / "varar.config.json").read_text(encoding="utf-8") == "{}\n"
31
+ assert any("skipped varar.config.json" in line for line in lines)
@@ -0,0 +1,93 @@
1
+ from pathlib import Path
2
+
3
+ from varar_runner.discovery import find_specs, match_spec
4
+
5
+
6
+ def _touch(root: Path, rel: str) -> Path:
7
+ p = root / rel
8
+ p.parent.mkdir(parents=True, exist_ok=True)
9
+ p.write_text("", encoding="utf-8")
10
+ return p
11
+
12
+
13
+ def test_find_specs_include_minus_exclude(tmp_path: Path) -> None:
14
+ _touch(tmp_path, "features/a.md")
15
+ _touch(tmp_path, "features/wip/b.md")
16
+ _touch(tmp_path, "README.md")
17
+ found = find_specs(["features/**/*.md"], ["**/wip/**"], tmp_path)
18
+ assert found == (tmp_path / "features/a.md",)
19
+
20
+
21
+ def test_match_spec(tmp_path: Path) -> None:
22
+ inc, exc = ["features/**/*.md"], ["**/wip/**"]
23
+ assert match_spec(tmp_path / "features/a.md", inc, exc, tmp_path) is True
24
+ assert match_spec(tmp_path / "features/wip/b.md", inc, exc, tmp_path) is False
25
+ assert match_spec(tmp_path / "README.md", inc, exc, tmp_path) is False
26
+
27
+
28
+ def test_symlinked_spec_matches_by_apparent_path(tmp_path: Path) -> None:
29
+ """A symlinked spec matches by where the link sits, not where it points.
30
+
31
+ Mirrors Java's toAbsolutePath().normalize() (no dereference): a project may
32
+ link its specs from a shared corpus outside the include globs.
33
+ """
34
+ _touch(tmp_path, "corpus/a.md")
35
+ (tmp_path / "project").mkdir()
36
+ (tmp_path / "project/a.md").symlink_to(tmp_path / "corpus/a.md")
37
+ root = tmp_path / "project"
38
+ assert match_spec(root / "a.md", ["*.md"], [], root) is True
39
+
40
+
41
+ def test_deeply_nested_spec_matches(tmp_path: Path) -> None:
42
+ """features/**/*.md must match specs nested more than one level deep."""
43
+ inc, exc = ["features/**/*.md"], []
44
+ assert match_spec(tmp_path / "features/sub/deep/c.md", inc, exc, tmp_path) is True
45
+ assert match_spec(tmp_path / "features/sub/c.md", inc, exc, tmp_path) is True
46
+ assert match_spec(tmp_path / "features/c.md", inc, exc, tmp_path) is True
47
+
48
+
49
+ def test_leading_doublestar_matches_root_level_file(tmp_path: Path) -> None:
50
+ """**/*.md must match a file directly under root (zero preceding dirs)."""
51
+ assert match_spec(tmp_path / "README.md", ["**/*.md"], [], tmp_path) is True
52
+
53
+
54
+ def test_leading_doublestar_exclude_root_level_dir(tmp_path: Path) -> None:
55
+ """find_specs with **/wip/** must exclude wip/ directly under root."""
56
+ _touch(tmp_path, "b.md")
57
+ _touch(tmp_path, "wip/a.md")
58
+ found = find_specs(["**/*.md"], ["**/wip/**"], tmp_path)
59
+ assert found == (tmp_path / "b.md",)
60
+
61
+
62
+ def test_find_specs_dedup(tmp_path: Path) -> None:
63
+ """A file matching multiple include globs appears only once in the result."""
64
+ _touch(tmp_path, "b.md")
65
+ found = find_specs(["**/*.md", "**/b.md"], [], tmp_path)
66
+ assert found == (tmp_path / "b.md",)
67
+
68
+
69
+ def test_single_star_does_not_cross_slash(tmp_path: Path) -> None:
70
+ """* must not match a path separator."""
71
+ assert match_spec(tmp_path / "dir/file.md", ["*.md"], [], tmp_path) is False
72
+
73
+
74
+ def test_specs_outside_root_via_parent_glob(tmp_path: Path) -> None:
75
+ """A spec in a SIBLING of the config root is reachable via a ``../`` glob.
76
+
77
+ This backs pointing ``varar.config.json`` at a shared corpus that lives outside the
78
+ package (e.g. ``../conformance/bundles``): ``relative_to(..., walk_up=True)``
79
+ yields a ``../corpus/...`` path that matches a ``../corpus/**`` glob.
80
+ """
81
+ root = tmp_path / "proj"
82
+ root.mkdir()
83
+ spec = _touch(tmp_path, "corpus/features/a.md")
84
+ inc = ["../corpus/**/*.md"]
85
+ found = find_specs(inc, [], root)
86
+ # find_specs returns the glob path (which carries the ``..``); compare by
87
+ # resolved file identity, not exact Path form.
88
+ assert len(found) == 1
89
+ assert found[0].resolve() == spec.resolve()
90
+ assert match_spec(spec, inc, [], root) is True
91
+ # a sibling file NOT under the glob is not matched
92
+ other = _touch(tmp_path, "other/b.md")
93
+ assert match_spec(other, inc, [], root) is False
@@ -0,0 +1,22 @@
1
+ """Smoke-test: every public symbol is importable from the top-level package."""
2
+ from varar_runner import (
3
+ find_specs,
4
+ match_spec,
5
+ load_steps,
6
+ LoadedSteps,
7
+ plan_spec,
8
+ examples_with_runs,
9
+ RecordingReporter,
10
+ render_failure,
11
+ )
12
+
13
+
14
+ def test_public_api_all_importable():
15
+ assert callable(find_specs)
16
+ assert callable(match_spec)
17
+ assert callable(load_steps)
18
+ assert LoadedSteps
19
+ assert callable(plan_spec)
20
+ assert callable(examples_with_runs)
21
+ assert RecordingReporter
22
+ assert callable(render_failure)
@@ -0,0 +1,101 @@
1
+ """Tests for render_failure — pure human-readable rendering of diff errors."""
2
+ from varar_core.cell_diff import CellDiff, CellMismatchError, ReturnShapeError
3
+ from varar_core.doc_string_diff import DocStringDiff, DocStringMismatchError
4
+ from varar_core.span import Span
5
+
6
+ from varar_runner.render import render_failure
7
+
8
+
9
+ def _span(line: int) -> Span:
10
+ """Minimal Span anchored to a known line (offsets are arbitrary for rendering)."""
11
+ return Span(
12
+ start_offset=0,
13
+ end_offset=1,
14
+ start_line=line,
15
+ start_col=1,
16
+ end_line=line,
17
+ end_col=2,
18
+ )
19
+
20
+
21
+ # ---------------------------------------------------------------------------
22
+ # CellMismatchError
23
+ # ---------------------------------------------------------------------------
24
+
25
+
26
+ def test_cell_mismatch_lists_failing_cells():
27
+ cells = (
28
+ CellDiff(column="total", span=_span(7), expected="9", actual="8", ok=False),
29
+ CellDiff(column="label", span=_span(7), expected="foo", actual="foo", ok=True),
30
+ )
31
+ error = CellMismatchError(cells)
32
+ result = render_failure(error, "", "spec.md")
33
+
34
+ assert "total" in result
35
+ assert "9" in result # expected
36
+ assert "8" in result # actual
37
+ assert "7" in result # line number
38
+ assert "spec.md" in result
39
+
40
+
41
+ def test_cell_mismatch_omits_passing_cells():
42
+ cells = (
43
+ CellDiff(column="ok_col", span=_span(3), expected="x", actual="x", ok=True),
44
+ )
45
+ error = CellMismatchError(cells)
46
+ result = render_failure(error, "", "spec.md")
47
+ # No failing cells — should still mention the file but not "ok_col"
48
+ assert "ok_col" not in result
49
+
50
+
51
+ def test_cell_mismatch_multiple_failing():
52
+ cells = (
53
+ CellDiff(column="a", span=_span(10), expected="1", actual="2", ok=False),
54
+ CellDiff(column="b", span=_span(11), expected="3", actual="4", ok=False),
55
+ )
56
+ error = CellMismatchError(cells)
57
+ result = render_failure(error, "", "my.md")
58
+
59
+ assert "a" in result
60
+ assert "b" in result
61
+ assert "10" in result
62
+ assert "11" in result
63
+
64
+
65
+ # ---------------------------------------------------------------------------
66
+ # DocStringMismatchError
67
+ # ---------------------------------------------------------------------------
68
+
69
+
70
+ def test_doc_string_mismatch_shows_expected_actual_and_line():
71
+ diff = DocStringDiff(span=_span(15), expected="hello\n", actual="world\n")
72
+ error = DocStringMismatchError(diff)
73
+ result = render_failure(error, "", "doc.md")
74
+
75
+ assert "hello" in result
76
+ assert "world" in result
77
+ assert "15" in result
78
+
79
+
80
+ # ---------------------------------------------------------------------------
81
+ # ReturnShapeError
82
+ # ---------------------------------------------------------------------------
83
+
84
+
85
+ def test_return_shape_error_renders_message():
86
+ error = ReturnShapeError("expected a table, got str")
87
+ result = render_failure(error, "", "spec.md")
88
+
89
+ assert "expected a table, got str" in result
90
+
91
+
92
+ # ---------------------------------------------------------------------------
93
+ # Generic exception
94
+ # ---------------------------------------------------------------------------
95
+
96
+
97
+ def test_generic_exception_renders_type_and_message():
98
+ error = ValueError("boom")
99
+ result = render_failure(error, "", "spec.md")
100
+
101
+ assert result == "ValueError: boom"
@@ -0,0 +1,34 @@
1
+ from varar_runner.steps import load_steps
2
+ from varar_runner.run import plan_spec, examples_with_runs, RecordingReporter
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
+ @sensor("the total is {int}")
11
+ def _(state, total):
12
+ if state["n"] != total:
13
+ raise AssertionError(f"expected {total} got {state['n']}")
14
+ '''
15
+ SRC_PASS = "# Calc\n\n## adds\n\nI add 2\nthe total is 2\n"
16
+ SRC_FAIL = "# Calc\n\n## adds wrong\n\nI add 2\nthe total is 99\n"
17
+
18
+ def _runs(tmp_path, src):
19
+ (tmp_path / "c.steps.py").write_text(STEPS, encoding="utf-8")
20
+ loaded = load_steps(["**/*.steps.py"], tmp_path)
21
+ plan = plan_spec("c.md", src, loaded.registry)
22
+ return examples_with_runs(plan, loaded.create_context, RecordingReporter())
23
+
24
+ def test_passing_example_runs_clean(tmp_path):
25
+ pairs = _runs(tmp_path, SRC_PASS)
26
+ assert len(pairs) == 1
27
+ example, run = pairs[0]
28
+ assert example.name and run() is None # no raise
29
+
30
+ def test_failing_example_raises(tmp_path):
31
+ import pytest
32
+ _example, run = _runs(tmp_path, SRC_FAIL)[0]
33
+ with pytest.raises(Exception):
34
+ run()
@@ -0,0 +1,27 @@
1
+ from varar_runner.steps import load_steps
2
+
3
+ STEPS = '''
4
+ from varar import steps
5
+ param, stimulus, sensor = steps(lambda: {"n": 0})
6
+ @stimulus("I add {int}")
7
+ def _(state, n):
8
+ return {"n": state["n"] + n}
9
+ @sensor("the total is {int}")
10
+ def _(state, total):
11
+ return state["n"]
12
+ '''
13
+
14
+ def test_load_steps_builds_registry_and_context(tmp_path):
15
+ (tmp_path / "calc.steps.py").write_text(STEPS, encoding="utf-8")
16
+ loaded = load_steps(["**/*.steps.py"], tmp_path)
17
+ exprs = [s.expression for s in loaded.registry.steps]
18
+ assert "I add {int}" in exprs and "the total is {int}" in exprs
19
+ # context factory yields the stepfile's fresh state
20
+ ctx = loaded.create_context(str(tmp_path / "calc.steps.py"))
21
+ assert ctx == {"n": 0}
22
+
23
+ def test_load_steps_resets_between_calls(tmp_path):
24
+ (tmp_path / "a.steps.py").write_text(STEPS, encoding="utf-8")
25
+ load_steps(["**/*.steps.py"], tmp_path)
26
+ loaded2 = load_steps(["**/*.steps.py"], tmp_path)
27
+ assert len(loaded2.registry.steps) == 2 # not 4 — reset cleared the first load