diff --git a/docs/coverage.md b/docs/coverage.md index ad85a32..405d63f 100644 --- a/docs/coverage.md +++ b/docs/coverage.md @@ -79,6 +79,8 @@ topics are emitted, so every clause is green. ## OVOS-STOP-1 — `test_stop1_conformance.py` +`test_stop1_dual_emit_off_conformance.py` runs a subset of these clauses with the legacy bridge off. + *Stop Pipeline Plugin Specification.* Asserts the §9 conformance clauses and the §8 bus surface against ovos-core's in-process stop pipeline. Deterministic on a `FakeBus`. @@ -161,6 +163,8 @@ pipeline. ## OVOS-FALLBACK-1 — `test_fallback1_conformance.py` +`test_solvers_conformance.py` asserts the contract against the shipped reference fallback skill, and against the reference question solver for OVOS-PERSONA-1. + *Fallback Pipeline Plugin Specification.* Driven by the real `ovos-skill-fallback-unknown` priority-100 catch-all, pinned after the matcher so it only runs on a no-match. @@ -467,6 +471,8 @@ are xfail — see [known-gaps.md](known-gaps.md). ## OVOS-OCP-1 — `test_ocp1_conformance.py` +`test_ocp1_plugins_conformance.py` asserts the §4.1 and §4.2 discovery contract against the shipped OCP extractor. + *OVOS Common Playback (the Virtual Media Player).* Asserts the OCP-1 clauses end-to-end against the real `ovos_media.player.OCPMediaPlayer`, driven on a `FakeBus` through `ovoscope.OCPPlayerHarness` with a @@ -484,6 +490,8 @@ driven on a `FakeBus` through `ovoscope.OCPPlayerHarness` with a ## OVOS-PERSONA-1 — `test_persona1_conformance.py` +`test_solvers_conformance.py` asserts the contract against the shipped reference question solver, and against the reference fallback skill for OVOS-FALLBACK-1. + *Persona Pipeline Plugin.* Asserts the §12 conformance clauses and the message-shape rules as ovoscope end-to-end assertions against ovos-core's orchestrator driving the `ovos-persona-pipeline-plugin`, with a throwaway @@ -502,6 +510,8 @@ orchestrator driving the `ovos-persona-pipeline-plugin`, with a throwaway ## OVOS-TRANSFORM-1 — `test_transform1_conformance.py` +`test_transform1_plugins_conformance.py` asserts the §3 and §8.1 contract against the shipped transformer plugins. + *Transformer Plugins (the transformer-chain pattern).* Asserts the TRANSFORM-1 clauses against the real ovos-core transformer services (`UtteranceTransformersService`, `MetadataTransformersService`, @@ -563,6 +573,50 @@ red cell green. --- +## Strict xfail count + +The number is the count of collected test items under `test/conformance/` that +carry a strict xfail mark that applies on the installed stack. Each one is a +known gap that has a test: a clause that a spec requires and the stack does not +meet. A clause with no test is not counted. A test that calls `skipTest` +because a clause is not observable on the bus is not counted. + +`tools/xfail_count.py` prints it as one JSON line. It collects the suites with +pytest and runs no test, so parametrized cases and module-level marks count +once per test item. It needs the stack from `requirements.txt` to be installed. +It ignores `OVOS_CHANNEL`, so the channel gap marks that the root `conftest.py` +adds are not counted. + +``` +python tools/xfail_count.py # one JSON line +python tools/xfail_count.py --pretty # table for people +``` + +The fields are: + +- `value`: the test items whose applicable xfail mark is strict. Pytest decides + which mark applies, and whether it is strict, including the `condition` + argument and the `xfail_strict` and `strict` ini options. +- `by_spec`: `value` split by spec, using the suite-to-spec rows of this file. + A suite that more than one spec shares is listed under the ids joined by + `+`. The session suite is reported under `OVOS-SESSION-1+OVOS-SESSION-2`. +- `unmapped_files`: the suite files that no row of this file maps to a spec. + The tool exits with a non-zero code when this list, or `unmapped` in + `by_spec`, is not empty, so a new suite needs a row here. The helper tests + in `test__conformance_helpers.py` are exempt. +- `non_strict`, `non_strict_items`: the items whose applicable xfail mark is + not strict. `TestE2ETemplateGeneralizes::test_unseen_phrasing_still_matches` + in the INTENT-3 suite is one. +- `runtime_xfail_calls`: the call sites of `pytest.xfail()`, `add_marker` and + `applymarker` in the suites. They are not visible at collection and are not + part of `value`. +- `commit` and `dirty`: the checkout that the tool ran in. `commit` is null + outside the repository checkout. +- `stack`: the installed versions of the OVOS packages that the count depends + on, null for a package that is absent. + +--- + ## See also - [known-gaps.md](known-gaps.md) — the live `xfail` clauses, with the diff --git a/test/meta/test_xfail_count.py b/test/meta/test_xfail_count.py new file mode 100644 index 0000000..54d16b1 --- /dev/null +++ b/test/meta/test_xfail_count.py @@ -0,0 +1,252 @@ +"""Meta-test: tools/xfail_count.py counts the strict xfails right.""" +import json +import os +import pathlib +import subprocess +import sys + +import pytest +from _pytest.skipping import evaluate_xfail_marks + +ROOT = pathlib.Path(__file__).resolve().parent.parent.parent +TOOL = ROOT / "tools" / "xfail_count.py" + +PLAIN = '''\ +import pytest + +@pytest.mark.xfail(strict=True, reason="plain") +def test_plain(): + assert False + +@pytest.mark.parametrize("n", [ + 1, + pytest.param(2, marks=pytest.mark.xfail(strict=True, reason="param")), +]) +def test_param(n): + assert n == 1 + +@pytest.mark.xfail(False, strict=True, reason="condition is false") +def test_false_condition(): + pass + +@pytest.mark.xfail("sys.version_info < (3,)", strict=True, reason="string") +def test_false_string_condition(): + pass + +@pytest.mark.xfail(strict=False, reason="lax") +def test_non_strict(): + pass + +def test_runtime(): + pytest.xfail("runtime") +''' + +MODULE_LEVEL = '''\ +import pytest + +pytestmark = pytest.mark.xfail(strict=True, reason="whole module") + +def test_one(): + assert False + +def test_two(): + assert False +''' + +NO_XFAIL = '''\ +def test_green(): + pass +''' + +# pytest takes `condition=` over a positional condition +KEYWORD_CONDITION = '''\ +import pytest + +@pytest.mark.xfail(True, condition=False, strict=True, reason="keyword wins") +def test_keyword_false(): + pass + +@pytest.mark.xfail(False, condition=True, strict=True, reason="keyword wins") +def test_keyword_true(): + pass +''' + +# the mark nearest the test decides, and only if it applies +CLASS_AND_METHOD = '''\ +import pytest + +@pytest.mark.xfail(strict=True, reason="class") +class TestMarks: + @pytest.mark.xfail(strict=False, reason="method, lax") + def test_method_lax_wins(self): + pass + + @pytest.mark.xfail(False, strict=False, reason="method, does not apply") + def test_class_mark_applies(self): + pass +''' + +INI_DEFAULT = '''\ +import pytest + +@pytest.mark.xfail(strict=None, reason="strict None") +def test_strict_none(): + pass + +@pytest.mark.xfail(reason="no strict argument") +def test_no_strict_argument(): + pass +''' + +RUNTIME_FORMS = '''\ +import pytest +import pytest as pt +from pytest import xfail as bail + +def _gap(msg): + pytest.xfail(msg) + +def test_wrapper(): + _gap("wrapper") + +def test_alias(): + bail("alias") + +def test_module_alias(): + pt.xfail("module alias") + +def test_add_marker(request): + request.node.add_marker(pytest.mark.xfail(strict=True, reason="rt")) + +def test_applymarker(request): + request.applymarker(pytest.mark.xfail(strict=True, reason="rt")) +''' + +COVERAGE = '''\ +| Architecture spec | Spec ID | Suite | Status | +|---|---|---|---| +| A | OVOS-A-1 | `test_a_conformance.py` | implemented | +| B | OVOS-B-1 | `test_b_conformance.py` | implemented | +''' + + +def _run(tmp_path, files, ini=None, coverage=COVERAGE): + suites = tmp_path / "suites" + suites.mkdir() + for name, text in files.items(): + (suites / name).write_text(text) + if ini: + (suites / "pytest.ini").write_text(ini) + cov = tmp_path / "coverage.md" + cov.write_text(coverage) + done = subprocess.run( + [sys.executable, str(TOOL), "--suite-dir", str(suites), + "--coverage", str(cov)], capture_output=True, text=True) + return done, json.loads(done.stdout) + + +def test_synthetic_suites(tmp_path): + done, out = _run(tmp_path, {"test_a_conformance.py": PLAIN, + "test_b_conformance.py": MODULE_LEVEL}) + assert done.returncode == 0, done.stderr + # plain + parametrized + two module-level; the false conditions are not + # counted and the lax mark is reported apart + assert out["value"] == 4 + assert out["by_spec"] == {"OVOS-A-1": 2, "OVOS-B-1": 2} + assert out["non_strict"] == 1 + assert out["runtime_xfail_calls"] == 1 + assert out["metric"] == "conformance_strict_xfails" + assert len(out["commit"]) == 40 + assert out["dirty"] in (True, False) + assert set(out["stack"]) >= {"ovos-core", "ovos-bus-client"} + + +def test_keyword_condition_beats_positional(tmp_path): + done, out = _run(tmp_path, {"test_a_conformance.py": KEYWORD_CONDITION}) + assert out["value"] == 1 + + +def test_nearest_applicable_mark_decides_strictness(tmp_path): + done, out = _run(tmp_path, {"test_a_conformance.py": CLASS_AND_METHOD}) + assert (out["value"], out["non_strict"]) == (1, 1) + + +def test_strict_none_follows_ini_xfail_strict(tmp_path): + done, out = _run(tmp_path, {"test_a_conformance.py": INI_DEFAULT}, + ini="[pytest]\nxfail_strict = true\n") + assert (out["value"], out["non_strict"]) == (2, 0) + + +def test_strict_none_without_ini_is_non_strict(tmp_path): + done, out = _run(tmp_path, {"test_a_conformance.py": INI_DEFAULT}) + assert (out["value"], out["non_strict"]) == (0, 2) + + +@pytest.mark.skipif(pytest.version_tuple < (9,), + reason="the `strict` ini option exists from pytest 9") +def test_strict_ini_makes_xfail_strict(tmp_path): + done, out = _run(tmp_path, {"test_a_conformance.py": INI_DEFAULT}, + ini="[pytest]\nstrict = true\n") + assert (out["value"], out["non_strict"]) == (2, 0) + + +def test_runtime_forms(tmp_path): + done, out = _run(tmp_path, {"test_a_conformance.py": RUNTIME_FORMS}) + assert out["runtime_xfail_calls"] == 5 + + +def test_suite_without_xfail_needs_a_mapping(tmp_path): + done, out = _run(tmp_path, {"test_a_conformance.py": PLAIN, + "test_c_conformance.py": NO_XFAIL}) + assert done.returncode == 1 + assert out["unmapped_files"] == ["test_c_conformance.py"] + + +def test_helper_tests_need_no_mapping(tmp_path): + done, out = _run(tmp_path, {"test_a_conformance.py": PLAIN, + "test__conformance_helpers.py": NO_XFAIL}) + assert done.returncode == 0, done.stderr + assert out["unmapped_files"] == [] + + +def test_unmapped_xfails_are_counted_under_unmapped(tmp_path): + done, out = _run(tmp_path, {"test_c_conformance.py": MODULE_LEVEL}) + assert done.returncode == 1 + assert out["by_spec"] == {"unmapped": 2} + + +class _SecondWalk: + """Counts strict applicable xfails over the collected items.""" + + def __init__(self): + self.value = 0 + + def pytest_collection_modifyitems(self, session, items): + for item in session.items: + if not list(item.iter_markers("xfail")): + continue + xfailed = evaluate_xfail_marks(item) + if xfailed is not None and xfailed.strict: + self.value += 1 + + +@pytest.mark.skipif("OVOS_CHANNEL" in os.environ, + reason="a channel stack cannot collect the suites") +def test_real_repo_count(): + walk = _SecondWalk() + pytest.main([str(ROOT / "test" / "conformance"), "--collect-only", "-q", + "-p", "no:cacheprovider"], plugins=[walk]) + done = subprocess.run([sys.executable, str(TOOL)], capture_output=True, + text=True, cwd=ROOT) + assert done.returncode == 0, done.stderr + out = json.loads(done.stdout) + assert out["value"] == walk.value + assert sum(out["by_spec"].values()) == out["value"] + assert "unmapped" not in out["by_spec"] + assert out["unmapped_files"] == [] + assert out["runtime_xfail_calls"] == 0 + # channel gap marks of the root conftest do not count + channel = subprocess.run( + [sys.executable, str(TOOL)], capture_output=True, text=True, cwd=ROOT, + env={**os.environ, "OVOS_CHANNEL": "stable"}) + assert json.loads(channel.stdout)["value"] == out["value"] diff --git a/tools/xfail_count.py b/tools/xfail_count.py new file mode 100644 index 0000000..f73cdb2 --- /dev/null +++ b/tools/xfail_count.py @@ -0,0 +1,204 @@ +#!/usr/bin/env python3 +"""Count the strict xfails of the conformance suites. + +Prints one JSON line: the collected conformance test items that carry an +applicable strict xfail mark, split by spec. No test runs; the items come from +pytest's own collection and its own xfail evaluation. Exit code 1 when a suite +file maps to no spec in docs/coverage.md. + + python tools/xfail_count.py [--pretty] [--suite-dir DIR] [--coverage FILE] +""" +import argparse +import ast +import collections +import importlib.metadata +import json +import os +import pathlib +import re +import subprocess +import sys + +import pytest +from _pytest.skipping import evaluate_xfail_marks + +TOOL_VERSION = "2.0.0" +REPO_SLUG = "OpenVoiceOS/ovos-test-harness" +ROOT = pathlib.Path(__file__).resolve().parent.parent + +# Files in the suite directory that test the suites' helpers, not a spec. +NON_SUITE_FILES = {"test__conformance_helpers.py"} + +STACK = ("ovos-core", "ovos-workshop", "ovos-utils", "ovos-bus-client", + "ovos-messagebus", "ovos-plugin-manager", "ovos-spec-tools") + +_SUITE = re.compile(r"`(test_\w+\.py)`") +_SPEC = re.compile(r"OVOS-[A-Z0-9-]+") +_RUNTIME_MARKING = {"add_marker", "applymarker"} + + +def suite_specs(coverage): + """`{suite file name: [spec id]}` read off docs/coverage.md. + + A top-level matrix row (`| name | OVOS-X | `suite` | status |`) names the + spec of its suites. A suite the matrix omits takes the spec of every + `## OVOS-X` section that names it. + """ + matrix = collections.defaultdict(set) + sections = collections.defaultdict(set) + heading_ids = [] + for line in coverage.read_text().split("\n"): + cells = [c.strip() for c in line.split("|")] + if len(cells) >= 5 and cells[2].startswith("OVOS-"): + for name in _SUITE.findall(cells[3]): + matrix[name].add(cells[2]) + if line.startswith("## "): + heading_ids = _SPEC.findall(line) + for name in _SUITE.findall(line): + sections[name].update(heading_ids) + out = {name: ids for name, ids in sections.items() if ids} + out.update(matrix) + return {name: sorted(ids) for name, ids in out.items()} + + +class Collector: + """Counts, per suite file, the items whose applicable xfail is strict.""" + + def __init__(self): + self.strict = collections.Counter() + self.non_strict = [] + + def pytest_collection_modifyitems(self, items): + for item in items: + xfailed = evaluate_xfail_marks(item) + if xfailed is None: + continue + if xfailed.strict: + self.strict[pathlib.Path(str(item.path)).name] += 1 + else: + self.non_strict.append(item.nodeid) + + +def runtime_xfail_calls(suite_dir): + """Call sites that xfail or mark a test while it runs. + + These are `pytest.xfail(...)` (also through an import alias) and + `add_marker` / `applymarker`. Collection cannot see them, so they are + not part of `value`. + """ + count = 0 + for path in sorted(suite_dir.glob("*.py")): + tree = ast.parse(path.read_text()) + pytest_names = {"pytest"} + xfail_names = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + pytest_names.update(a.asname or a.name for a in node.names + if a.name == "pytest") + elif isinstance(node, ast.ImportFrom) and node.module == "pytest": + xfail_names.update(a.asname or a.name for a in node.names + if a.name == "xfail") + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + func = node.func + if isinstance(func, ast.Attribute): + if func.attr in _RUNTIME_MARKING: + count += 1 + elif (func.attr == "xfail" and isinstance(func.value, ast.Name) + and func.value.id in pytest_names): + count += 1 + elif isinstance(func, ast.Name) and func.id in xfail_names: + count += 1 + return count + + +def repo_state(): + """`(commit, dirty)` of the checkout, or `(None, None)` outside it.""" + def git(*args): + return subprocess.run(["git", *args], cwd=ROOT, capture_output=True, + text=True) + top = git("rev-parse", "--show-toplevel") + if top.returncode or pathlib.Path(top.stdout.strip()).resolve() != ROOT: + return None, None + commit = git("rev-parse", "HEAD").stdout.strip() + return commit, bool(git("status", "--porcelain").stdout.strip()) + + +def stack_versions(): + out = {} + for name in STACK: + try: + out[name] = importlib.metadata.version(name) + except importlib.metadata.PackageNotFoundError: + out[name] = None + return out + + +def count(suite_dir, coverage): + # The root conftest reads OVOS_CHANNEL at import and adds a strict xfail + # per known channel gap. Those are not suite marks. + os.environ.pop("OVOS_CHANNEL", None) + collector = Collector() + code = pytest.main([str(suite_dir), "--collect-only", "-q", "-p", + "no:cacheprovider"], plugins=[collector]) + if code not in (0, pytest.ExitCode.NO_TESTS_COLLECTED): + raise SystemExit(f"collection failed with exit code {int(code)}") + mapping = suite_specs(coverage) + by_spec = collections.Counter() + for name, n in collector.strict.items(): + by_spec["+".join(mapping[name]) if name in mapping else "unmapped"] += n + suites = {p.name for p in suite_dir.glob("test_*.py")} - NON_SUITE_FILES + commit, dirty = repo_state() + return { + "metric": "conformance_strict_xfails", + "value": sum(collector.strict.values()), + "repo": REPO_SLUG, + "commit": commit, + "dirty": dirty, + "tool_version": TOOL_VERSION, + "stack": stack_versions(), + "by_spec": dict(sorted(by_spec.items())), + "unmapped_files": sorted(suites - mapping.keys()), + "non_strict": len(collector.non_strict), + "non_strict_items": collector.non_strict, + "runtime_xfail_calls": runtime_xfail_calls(suite_dir), + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("--pretty", action="store_true", + help="print an indented table") + parser.add_argument("--suite-dir", type=pathlib.Path, + default=ROOT / "test" / "conformance") + parser.add_argument("--coverage", type=pathlib.Path, + default=ROOT / "docs" / "coverage.md") + args = parser.parse_args() + # pytest writes its own report to stdout; keep stdout for the result + real_stdout, sys.stdout = sys.stdout, sys.stderr + try: + result = count(args.suite_dir.resolve(), args.coverage) + finally: + sys.stdout = real_stdout + if args.pretty: + commit = (result["commit"] or "no commit")[:12] + print(f"{result['metric']}: {result['value']} " + f"({result['repo']} @ {commit}, dirty={result['dirty']}, " + f"tool {result['tool_version']})") + for spec, n in result["by_spec"].items(): + print(f" {spec:<45} {n:>4}") + print(f"non_strict: {result['non_strict']} " + f"runtime_xfail_calls: {result['runtime_xfail_calls']}") + for name, version in result["stack"].items(): + print(f" {name:<20} {version}") + if result["unmapped_files"]: + print("unmapped suites:", ", ".join(result["unmapped_files"])) + else: + print(json.dumps(result)) + unmapped = "unmapped" in result["by_spec"] or result["unmapped_files"] + return 1 if unmapped else 0 + + +if __name__ == "__main__": + sys.exit(main())