varar-runner 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,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)
varar_runner/cli.py ADDED
@@ -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))
varar_runner/render.py ADDED
@@ -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}"
varar_runner/run.py ADDED
@@ -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))
varar_runner/steps.py ADDED
@@ -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,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,11 @@
1
+ varar_runner/__init__.py,sha256=tgCLLY_LGbwTulAxhXk4A7_LMUXFTgLxL89od6cdq_I,506
2
+ varar_runner/baseline_store.py,sha256=a_7mV-BLNUPMvhGRTA7Yzn9vYViwFw61twbK1LZZj_0,753
3
+ varar_runner/cli.py,sha256=Y5CDuOjmdb_H45WhM0_aN3jKh04vdHlX9_8xnpCx6uM,2327
4
+ varar_runner/discovery.py,sha256=kvSlkSsENGA9hhqeBJkp3pv4HVkYx3d9kQTvk_9vtcI,3755
5
+ varar_runner/render.py,sha256=2bZEA18FJQcJ9tuwClW_y4ZHcxZmvypbhqGMQ26LSt4,1766
6
+ varar_runner/run.py,sha256=JN5Q8md0KUzAdSge0sbUvxfG0tk3Z1VmQ7jnO-0ptRc,1032
7
+ varar_runner/steps.py,sha256=PSuxQIJk4xcPbCxbf7j4Wrp2lahY6hNsLJihaN6DccM,1058
8
+ varar_runner-0.5.0.dist-info/METADATA,sha256=xiomto-QqQ8mhDWa5CG8l4Qv5gDWf8ZMebEDxJ0QlRk,236
9
+ varar_runner-0.5.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
10
+ varar_runner-0.5.0.dist-info/entry_points.txt,sha256=b6wXve0pWZoiz7PsHNuY0FJ8aViHEHbjNHamQ1BbC2w,48
11
+ varar_runner-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
+ [console_scripts]
2
+ varar = varar_runner.cli:main