From cc6e58eec59610c3826188a6d910b49467471c5f Mon Sep 17 00:00:00 2001 From: Ashish Sharma Date: Tue, 22 Sep 2026 08:42:32 +0000 Subject: [PATCH] (improv): add optional log parser health checks - Add opt-in --doctor --health checks for DT and SR while preserving the existing readiness-only preflight. - Check registry requirements, standalone packaging, raw logs, compliance decisions, waivers, incomplete inputs and stale results using independent expectations. - Verify JSON and HTML consistency and provide optional browser and PDF checks without modifying supplied reports. - Compare the overall HTML verdict with merged JSON and preserve malformed-input findings while checking independent packages. - Keep Doctor code and fixtures in doctor_checks while retaining the existing entry point and normal parser behavior. - Record supplied test-category metadata so Doctor applies suite-information requirements only when appropriate. - Generate readable HTML, JSON and text findings with expected and actual results, reproduction evidence and coverage gaps. - Add regression tests and document manual usage, check groups and limitations. Keep production parser fixes separate. - Align BSA test expectations with whole-test waiver precedence and use result_status in Capsule test definitions. Signed-off-by: Ashish Sharma Change-Id: I202f7c0d90ddd9373ae9b1daaf405612824372b9 --- .../apply_waivers.yaml | 25 +- .../capsule-ondisk-reporting-vars-check.yaml | 8 +- .../acs_test_framework_runner/test_doctor.py | 2361 +++++++++++++++++ .../test_doctor_report.py | 2280 ++++++++++++++++ common/log_parser/doctor.py | 33 + common/log_parser/doctor_checks/__init__.py | 20 + common/log_parser/doctor_checks/artifacts.py | 1275 +++++++++ common/log_parser/doctor_checks/core.py | 636 +++++ .../doctor_checks/data/native_cases.json | 1881 +++++++++++++ common/log_parser/doctor_checks/merge.py | 638 +++++ common/log_parser/doctor_checks/probes.py | 1426 ++++++++++ common/log_parser/doctor_checks/report.py | 1478 +++++++++++ common/log_parser/standalone_runner.py | 61 +- docs/log_parser_guide.md | 181 ++ 14 files changed, 12290 insertions(+), 13 deletions(-) create mode 100644 common/acs_test_framework_runner/test_doctor.py create mode 100644 common/acs_test_framework_runner/test_doctor_report.py create mode 100644 common/log_parser/doctor.py create mode 100644 common/log_parser/doctor_checks/__init__.py create mode 100644 common/log_parser/doctor_checks/artifacts.py create mode 100644 common/log_parser/doctor_checks/core.py create mode 100644 common/log_parser/doctor_checks/data/native_cases.json create mode 100644 common/log_parser/doctor_checks/merge.py create mode 100644 common/log_parser/doctor_checks/probes.py create mode 100644 common/log_parser/doctor_checks/report.py diff --git a/common/acs_test_framework_manifests/apply_waivers.yaml b/common/acs_test_framework_manifests/apply_waivers.yaml index 5396335c..ce371949 100644 --- a/common/acs_test_framework_manifests/apply_waivers.yaml +++ b/common/acs_test_framework_manifests/apply_waivers.yaml @@ -591,8 +591,9 @@ suites: - - name: bsa_subtest_waiver_applies_by_sub_rule_id + - name: bsa_testcase_waiver_reason_applies_to_failed_subtests type: cli + description: "A whole-test waiver supplies the reason for failed subtests; a child waiver must not replace it." text_files: bsa.json: | { @@ -631,7 +632,7 @@ suites: "TestCases": [ { "Test_case": "RULE_001", - "Reason": "Case waiver placeholder", + "Reason": "BSA whole-test waiver", "SubTests": [ { "sub_Rule_ID": "SUB_01", @@ -651,15 +652,25 @@ suites: - "{dir}/waiver.json" expect_exit_code: 0 post_checks: - - type: file_contains + - type: file_not_contains path: "{dir}/bsa.json" text: "BSA subtest waiver" - - type: file_contains + # Check the parent and failed child separately, including both reasons. + - type: ordered_contains path: "{dir}/bsa.json" - text: "WITH WAIVER" - - type: file_contains + texts: + - '"Test_case": "RULE_001"' + - '"Test_result": "FAILED (WITH WAIVER)"' + - '"sub_Rule_ID": "SUB_01"' + - '"sub_test_result": "FAILED (WITH WAIVER)"' + - '"waiver_reason": "BSA whole-test waiver"' + - '"sub_Rule_ID": "SUB_02"' + - '"sub_test_result": "PASSED"' + - '"waiver_reason": "BSA whole-test waiver"' + # A passing child must stay passed without gaining a waiver reason. + - type: regex path: "{dir}/bsa.json" - text: "\"sub_Rule_ID\": \"SUB_02\"" + pattern: '"sub_Rule_ID": "SUB_02",\s*"sub_Test_Description": "second subtest",\s*"sub_test_result": "PASSED"\s*\}' - name: passed_result_is_not_modified_by_waiver type: cli diff --git a/common/acs_test_framework_manifests/capsule-ondisk-reporting-vars-check.yaml b/common/acs_test_framework_manifests/capsule-ondisk-reporting-vars-check.yaml index d2561974..e9fe9913 100644 --- a/common/acs_test_framework_manifests/capsule-ondisk-reporting-vars-check.yaml +++ b/common/acs_test_framework_manifests/capsule-ondisk-reporting-vars-check.yaml @@ -16,15 +16,15 @@ suites: type: main_guard description: "Check that the script contains a standard __main__ guard." - - name: status_true_returns_passed + - name: result_status_true_returns_passed type: py_function - function: status + function: result_status args: [true] expect_return: "PASSED" - - name: status_false_returns_warning + - name: result_status_false_returns_warning type: py_function - function: status + function: result_status args: [false] expect_return: "WARNING" diff --git a/common/acs_test_framework_runner/test_doctor.py b/common/acs_test_framework_runner/test_doctor.py new file mode 100644 index 00000000..0e85f515 --- /dev/null +++ b/common/acs_test_framework_runner/test_doctor.py @@ -0,0 +1,2361 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026, Arm Limited or its affiliates. All rights reserved. +# SPDX-License-Identifier : Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Test Doctor's decisions, safe execution, packaging and coverage checks. + +These tests check the checker, not the separate production parser fixes. Small +made-up inputs cover both correct and deliberately broken results. Fake command +responses keep most checks quick; temporary folders keep the real logs safe. +The tests run only when requested and are not part of normal log parsing. +""" + +from copy import deepcopy +from pathlib import Path +from types import SimpleNamespace +from unittest import mock +from unittest.mock import patch +import argparse +import contextlib +import copy +import hashlib +import io +import json +import subprocess +import sys +import tarfile +import tempfile +import unittest + +# Import Doctor from this checkout, not an installed or neighbouring copy. +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "log_parser")) +from doctor_checks.core import ( + Context, Finding, extract_package, package_differences, verify_checksum, +) +from doctor_checks.merge import ( + ComplianceHTML, EXPECTED_REQUIREMENTS, aggregate, differences, expected_leaves, + oracle, payload, policy_differences, scenarios, status, +) +from standalone_runner import record_category_provenance +from doctor_checks import ( + core as doctor, artifacts as policy, merge as doctor_merge, probes as native, probes, +) + + +# Overall verdicts, optional check groups and safe output locations. + +class DoctorTests(unittest.TestCase): + """Check that Doctor reports success, failure and blocked work honestly.""" + + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.parser = self.root / "parser" + self.parser.mkdir() + self.out = self.root / "results" + + def args(self, **changes): + """Build minimal command-line options, changing only what a test needs.""" + values = dict(mode=None, doctor_timeout=60, doctor_report=[], + doctor_output=str(self.out)) + values.update(changes) + return argparse.Namespace(**values) + + def finding(self, status): + """Create one simple check result for overall-verdict tests.""" + return Finding("CONTROL", status, "Example", "Expected", "Actual") + + def test_verdict_never_passes_zero_or_blocked(self): + """Check verdict never passes zero or blocked.""" + for findings in ([], [self.finding("WARN")], [self.finding("BLOCKED")], + [self.finding("PASS"), self.finding("BLOCKED")]): + self.assertEqual(doctor.verdict(findings), ("INCOMPLETE", 2)) + + def test_fail_and_pass_exit_codes(self): + """Check fail and pass exit codes.""" + self.assertEqual(doctor.verdict([self.finding("PASS")])[1], 0) + self.assertEqual(doctor.verdict([self.finding("PASS"), self.finding("FAIL")])[1], 1) + self.assertEqual(doctor.verdict([self.finding("FAIL"), self.finding("BLOCKED")])[1], 1) + + def test_status_is_closed_set(self): + """Check status is closed set.""" + with self.assertRaises(ValueError): + self.finding("SKIPPED_AS_PASS") + + def test_registry_empty_and_duplicate_alias(self): + """Check registry empty and duplicate alias.""" + self.assertTrue(doctor.registry_issues({"suites": []}, self.parser)) + suites = [{"canonical": "A", "aliases": ["shared_alias"]}, + {"canonical": "B", "aliases": ["SHARED-ALIAS"]}] + self.assertIn("resolves to both", + " ".join(doctor.registry_issues({"suites": suites}, self.parser))) + + def test_registry_missing_parser_and_fragment(self): + """Check registry missing parser and fragment.""" + suites = [{"canonical": "BSA", "logs_to_json": "absent.py", + "schema": "missing.json#/definitions/suite"}] + issues = doctor.registry_issues({"suites": suites}, self.parser) + self.assertEqual(len(issues), 3) + + def test_registry_valid_positive_control(self): + """Check registry valid positive control.""" + data = {"suites": [{"canonical": "A", "modes": ["DT"], + "requirement_key": "A", "requirements": {"DT": "M"}}]} + self.assertEqual(doctor.registry_issues(data, self.parser), []) + + def test_output_cannot_overwrite_or_be_inside_input(self): + """Check output cannot overwrite or be inside input.""" + self.out.mkdir() + with self.assertRaises(FileExistsError): + doctor.run_health(self.args(), self.parser) + for output in (self.parser / "new", self.out / "new"): + with self.assertRaises(ValueError): + doctor.run_health(self.args(doctor_output=str(output), + doctor_report=["DT=" + str(self.out)]), self.parser) + self.assertFalse(output.exists()) + + def test_bad_report_and_timeout_arguments(self): + """Check bad report and timeout arguments.""" + for change in ({"doctor_report": ["/missing/mode"]}, + {"doctor_report": ["DT="]}, + {"doctor_report": ["SR=/tmp/example"], "mode": "DT"}, + {"doctor_timeout": 0}, {"doctor_timeout": 301}): + with self.assertRaises(ValueError): + doctor.run_health(self.args(**change), self.parser) + self.assertFalse(self.out.exists()) + + def test_default_temp_directory_must_not_be_inside_protected_input(self): + """Check default temp directory must not be inside protected input.""" + for protected in (self.parser, self.out): + with mock.patch.object(doctor.tempfile, "gettempdir", return_value=str(protected)), \ + mock.patch.object(doctor.tempfile, "mkdtemp") as create: + with self.assertRaisesRegex(ValueError, "Temporary directory"): + doctor.run_health(self.args(doctor_output=None, + doctor_report=["DT=" + str(self.out)]), self.parser) + create.assert_not_called() + + def test_source_checkout_root_is_protected_not_only_parser_subdirectory(self): + """Check source checkout root is protected not only parser subdirectory.""" + (self.root / ".git").write_text("gitdir: /unused/test") + with self.assertRaises(ValueError): + doctor.run_health(self.args(doctor_output=str(self.root / "new-results")), self.parser) + self.assertFalse((self.root / "new-results").exists()) + self.assertEqual(doctor.protected_source_root(self.parser), self.root) + + def test_repository_json_rejects_ambiguous_keys_and_nonfinite_values(self): + """Check repository JSON rejects ambiguous keys and nonfinite values.""" + path = self.parser / "metadata.json" + for value in ('{"scope":"R","scope":"M"}', '{"count":NaN}', '{"count":1e999}'): + path.write_text(value) + with self.assertRaises(ValueError): + doctor.load_json(path) + + def test_report_escapes_untrusted_text(self): + """Check report escapes untrusted text.""" + self.out.mkdir() + ctx = Context(self.parser, self.out) + ctx.add("TEST", "FAIL", "", "A & B", 'actual "value"') + doctor.render_reports(ctx, {"revision": "control"}) + page = (self.out / "index.html").read_text() + self.assertNotIn("", page) + self.assertIn("<script>", page) + payload = json.loads((self.out / "doctor.json").read_text()) + self.assertEqual(payload["exit_code"], 1) + self.assertEqual(payload["findings"][0]["expected"], "A & B") + + def test_group_headings_do_not_describe_only_the_first_finding(self): + """Check group headings do not describe only the first finding.""" + self.out.mkdir() + ctx = Context(self.parser, self.out) + for rule, issues, title in ( + ("NATIVE_RAW_SCHEMA", ("bsa.json", "sct.json"), + "Generated raw JSON does not match its registered schema"), + ("ARTIFACT.SCHEMA", ("bsa.json violates the JSON schema", + "sct.json violates the JSON schema"), + "Report JSON files do not match their registered schemas"), + ("ARTIFACT.PARITY", ("Different records: sct_detailed.html", + "Different records: sbsa_detailed.html"), + "Raw and displayed result identities do not agree"), + ("MERGE_OVERALL_POLICY", ("Recommended result incorrectly blocks overall SRS", + "Mandatory input is empty"), + "Overall SRS compliance does not match the requirement policy"), + ("FUTURE_CHECK", ("First scenario", "Second scenario"), "Future check")): + for issue in issues: + ctx.add(rule, "FAIL", issue, "Expected", "Actual") + doctor.render_reports(ctx, {"revision": "control"}) + page = (self.out / "index.html").read_text() + # Plain-language topic titles may change, but the original grouped + # title must remain searchable alongside every recorded finding. + self.assertIn(title.lower(), page.lower()) + self.assertIn('data-check-id="%s"' % rule, page) + for issue in issues: + self.assertIn(issue, page) + + def test_command_records_success_and_nonzero(self): + """Check command records success and nonzero.""" + ctx = Context(self.parser, self.out) + directory = ctx.case_dir("control") + result = ctx.run([sys.executable, "-c", "print('actual output'); raise SystemExit(7)"], + directory) + self.assertEqual(result.returncode, 7) + self.assertIn("actual output", result.stdout) + self.assertTrue((directory / "command.command.json").is_file()) + + def test_command_timeout_is_not_success(self): + """Check command timeout is not success.""" + ctx = Context(self.parser, self.out, timeout=0.05) + directory = ctx.case_dir("timeout") + with self.assertRaisesRegex(RuntimeError, "timed out"): + ctx.run([sys.executable, "-c", "import time; time.sleep(5)"], directory) + self.assertIn("incomplete", (directory / "command.log").read_text()) + + def test_case_directory_cannot_escape(self): + """Check case directory cannot escape.""" + ctx = Context(self.parser, self.out) + for name in ("../escape", "/tmp/escape"): + with self.assertRaises(ValueError): + ctx.case_dir(name) + + def run_mocked(self, prerequisite, module): + """Run Doctor with fake checks so each test controls what they report.""" + for group, _ in doctor.GROUPS: + setattr(module, "run_" + group, module.run) + with mock.patch.object(doctor, "check_repository", side_effect=prerequisite), \ + mock.patch.object(doctor.importlib, "import_module", return_value=module), \ + mock.patch.object(doctor.shutil, "which", return_value=None), \ + contextlib.redirect_stdout(io.StringIO()): + code = doctor.run_health(self.args(), self.parser) + payload = json.loads((self.out / "doctor.json").read_text()) + return code, payload + + def test_missing_dependencies_block_all_probes(self): + """Check missing dependencies block all probes.""" + module = mock.Mock() + code, payload = self.run_mocked(lambda ctx: False, module) + self.assertEqual(code, 2) + self.assertEqual(payload["counts"]["BLOCKED"], len(doctor.GROUPS)) + module.run.assert_not_called() + + def test_group_selection_is_explicit_and_native_requires_package(self): + """Check group selection is explicit and native requires package.""" + self.assertEqual( + [name for name, _ in doctor.selected_groups(self.args(doctor_checks="native"))], + ["package", "native"]) + self.assertEqual( + [name for name, _ in doctor.selected_groups(self.args(doctor_checks="reports"))], + ["reports"]) + for change in ({"doctor_checks": ""}, {"doctor_checks": "typo"}, + {"doctor_checks": "raw,"}, {"doctor_browser": "/not-requested"}): + with self.assertRaises(ValueError): + doctor.selected_groups(self.args(**change)) + + def test_unavailable_group_does_not_block_independent_groups(self): + """Check unavailable group does not block independent groups.""" + module = mock.Mock() + module.run.side_effect = lambda ctx: ctx.add("CONTROL", "PASS", "Independent group ran", + "yes", "yes") + readiness = {name: name in {"policy", "package", "merge"} for name, _ in doctor.GROUPS} + code, payload = self.run_mocked(lambda ctx: readiness, module) + self.assertEqual(code, 2) + self.assertEqual(module.run.call_count, 3) + self.assertEqual(payload["counts"]["BLOCKED"], 3) + + def test_package_intent_survives_package_module_import_failure(self): + """Check package intent survives package module import failure.""" + seen = [] + # Simulate a broken package check without disabling independent checks. + def imported(name): + """Return a broken package check and a working native check.""" + if name == "doctor_checks.core": + return mock.Mock(run_package=mock.Mock( + side_effect=ImportError("broken package group"))) + def run(ctx): + """Record the package state seen by the independent check.""" + seen.append((ctx.package_checked, ctx.portable_parser)) + ctx.add("CONTROL", "BLOCKED", "No package", "verified package", "None") + return mock.Mock(run_native=run) + with mock.patch.object(doctor, "check_repository", return_value=True), \ + mock.patch.object(doctor.importlib, "import_module", side_effect=imported), \ + mock.patch.object(doctor.shutil, "which", return_value=None), \ + contextlib.redirect_stdout(io.StringIO()): + code = doctor.run_health(self.args(doctor_checks="native"), self.parser) + self.assertEqual(code, 2) + self.assertEqual(seen, [(True, None)]) + + def test_legacy_launcher_uses_one_canonical_doctor_module(self): + # A fresh process catches duplicate imports that this test process could hide. + """Check legacy launcher uses one canonical doctor module.""" + script = r''' +import contextlib +import importlib +import io +import json +import runpy +import sys +sys.argv = [sys.argv[1], "--help"] +try: + with contextlib.redirect_stdout(io.StringIO()): + runpy.run_path(sys.argv[0], run_name="__main__") +except SystemExit as error: + assert error.code == 0 +launcher = importlib.import_module("doctor") +canonical = importlib.import_module("doctor_checks.core") +assert launcher.Context is canonical.Context +assert launcher.Finding is canonical.Finding +assert launcher.run_health is canonical.run_health +assert launcher.add_arguments is canonical.add_arguments +assert canonical.Context.__module__ == "doctor_checks.core" +print(json.dumps({"canonical": True, "file": launcher.__file__})) +''' + launcher = doctor.BASE_DIR / "doctor.py" + completed = subprocess.run([sys.executable, "-B", "-c", script, str(launcher)], + cwd=doctor.BASE_DIR, capture_output=True, text=True, timeout=20) + self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr) + self.assertEqual(json.loads(completed.stdout), {"canonical": True, "file": str(launcher)}) + + def test_normal_argument_registration_does_not_load_health_checks(self): + # Ordinary parsing can expose the optional flags without loading checks. + """Check normal argument registration does not load health checks.""" + script = r''' +import sys +import standalone_runner +parser = standalone_runner.build_parser() +assert "--doctor" in parser.format_help() +for name in ("report", "merge", "probes", "artifacts"): + assert "doctor_checks." + name not in sys.modules, name +''' + completed = subprocess.run([sys.executable, "-B", "-c", script], + cwd=doctor.BASE_DIR, capture_output=True, text=True, timeout=20) + self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr) + + def test_zero_assertions_from_a_group_is_incomplete(self): + """Check zero assertions from a group is incomplete.""" + code, payload = self.run_mocked(lambda ctx: True, mock.Mock()) + self.assertEqual(code, 2) + self.assertTrue(any(item["check_id"] == "ZERO_CHECKS" for item in payload["findings"])) + + def test_probe_exception_is_reported_not_silently_skipped(self): + """Check probe exception is reported not silently skipped.""" + module = mock.Mock() + module.run.side_effect = RuntimeError("fixture cannot execute") + code, payload = self.run_mocked(lambda ctx: True, module) + self.assertEqual(code, 2) + self.assertTrue( + any("fixture cannot execute" in item["actual"] for item in payload["findings"])) + + +# Expected compliance rules and comparison of merged JSON with displayed results. + +def suite(name, requirement="M", mode="DT"): + """Build a small suite entry for one requirement and execution mode.""" + return {"canonical": name, "modes": [mode], "requirements": {mode: requirement}, + "requirement_key": name} + + +class DoctorMergeControls(unittest.TestCase): + """Check the expected rules independently of the production merger.""" + + def test_pcie_policy_is_explicit_sr_only_and_recommended(self): + """Check PCIE policy is explicit SR only and recommended.""" + name = "PCIE-OPTION-ROM-ARCH-AUDIT" + self.assertEqual(EXPECTED_REQUIREMENTS[name], {"SR": "R"}) + # Deliberately supply the wrong registry policy: it must not change + # Doctor's independently reviewed answer. + leaves = expected_leaves([suite(name, "M", "DT")]) + self.assertEqual(leaves[0]["requirements"], {"SR": "R"}) + self.assertEqual(leaves[0]["modes"], ["SR"]) + self.assertEqual(oracle(leaves, "DT", {name: "pass"}), ({}, "compliant")) + for state, expected in (("pass", "compliant"), ("fail", "not_compliant"), + ("missing", "not_run")): + for selected in (None, [name]): + with self.subTest(state=state, selected=selected): + rows, overall = oracle(leaves, "SR", {name: state}, selected) + self.assertEqual(rows[name], {"requirement": "Recommended", "status": expected}) + self.assertEqual(overall, "compliant") + + def test_pcie_registry_policy_drift_is_not_accepted_as_its_own_oracle(self): + """Check PCIE registry policy drift is not accepted as its own oracle.""" + registry = native.load_json(doctor.BASE_DIR / "suite_registry.json") + name = "PCIE-OPTION-ROM-ARCH-AUDIT" + self.assertFalse([issue for issue in policy_differences(registry) if issue[0] == name]) + for fields in ({"requirements": {"SR": "M"}}, + {"modes": ["DT", "SR"], "requirements": {"DT": "R", "SR": "R"}}): + with self.subTest(fields=fields): + mutated = deepcopy(registry) + next(item for item in mutated["suites"] if item["canonical"] == name).update(fields) + self.assertTrue( + [issue for issue in policy_differences(mutated) if issue[0] == name]) + registry["suites"] = [item for item in registry["suites"] if item["canonical"] != name] + self.assertTrue([issue for issue in policy_differences(registry) if issue[0] == name]) + + def test_pcie_payload_retains_standalone_identity_and_one_result(self): + """Check PCIE payload retains standalone identity and one result.""" + for state, wanted in (("pass", "PASSED"), ("fail", "FAILED")): + with self.subTest(state=state): + data = payload("PCIE-OPTION-ROM-ARCH-AUDIT", state) + self.assertEqual(len(data["test_results"]), 1) + row = data["test_results"][0] + self.assertEqual(row["Test_case"], "pcie_option_rom_arch_audit") + self.assertEqual(row["test_result"], wanted) + self.assertEqual(len(row["subtests"]), 1) + + def test_memory_map_suites_are_explicit_mandatory_dt_contracts(self): + """Check memory map suites are explicit mandatory DT contracts.""" + registry = json.loads((Path(__file__).resolve().parents[1] / "log_parser" / + "suite_registry.json").read_text(encoding="utf-8")) + names = {"RESERVED-MEMORY-MAP": "RESERVED_MEMORY_MAP", "DTB-ALIGNMENT": "DTB_ALIGNMENT"} + leaves = expected_leaves( + [item for item in registry["suites"] if item["canonical"] in names]) + self.assertEqual(len(leaves), 2) + standalone = next(item for item in registry["suites"] if item["canonical"] == "STANDALONE") + for leaf in leaves: + name = leaf["canonical"] + self.assertEqual(EXPECTED_REQUIREMENTS[name], {"DT": "M"}) + self.assertEqual(leaf["requirement_key"], names[name]) + self.assertIn(name, standalone["included_suites"]) + self.assertEqual(registry["standalone"]["suite_execution"][name]["handler"], + "standalone_single") + for name in names: + for state in ("pass", "fail", "missing", "waived"): + with self.subTest(suite=name, state=state): + states = {**dict.fromkeys(names, "pass"), name: state} + rows, overall = oracle(leaves, "DT", states) + self.assertEqual(rows[name]["requirement"], "Mandatory") + self.assertEqual( + overall, { + "pass": "compliant", + "fail": "not_compliant", + "missing": "not_compliant", + "waived": "waived" + }[state]) + full = [case for case in scenarios(leaves, "DT") if case[0].startswith("full_")] + self.assertTrue(full) + self.assertTrue(all(set(case[1]) == set(names) for case in full)) + + def test_recommended_failure_is_visible_but_nonblocking(self): + """Check recommended failure is visible but nonblocking.""" + rows, overall = oracle([suite("BSA", "R")], "DT", {"BSA": "fail"}) + self.assertEqual(rows["BSA"]["status"], "not_compliant") + self.assertEqual(overall, "compliant") + + def test_recommended_missing_nonblocking_full_and_selected(self): + """Check recommended missing nonblocking full and selected.""" + leaves = [suite("BSA", "R"), suite("FWTS")] + for selection in (None, ["BSA"]): + self.assertEqual( + oracle(leaves, "DT", { + "BSA": "missing", + "FWTS": "pass" + }, selection)[1], "compliant") + + def test_mandatory_missing_and_unwaived_failure_block(self): + """Check mandatory missing and unwaived failure block.""" + for state in ("missing", "empty", "header", "fail", "mixed"): + self.assertEqual(oracle([suite("FWTS")], "DT", {"FWTS": state})[1], "not_compliant") + + def test_only_sr_os_recommended_entries_are_exempt(self): + """Check only SR OS recommended entries are exempt.""" + for name, mode, wanted in (("OS-TESTS", "SR", "compliant"), + ("OS-TESTS", "DT", "not_compliant"), + ("BSA", "SR", "not_compliant")): + self.assertEqual( + oracle([suite(name, mode=mode)], mode, + {name: "recommended_fail"})[0][name]["status"], wanted) + + def test_sbmr_missing_interface_promoted_mandatory(self): + """Check SBMR missing interface promoted mandatory.""" + leaves = [suite("SBMR-IB", "R", "SR"), suite("SBMR-OOB", "R", "SR")] + rows, overall = oracle(leaves, "SR", {"SBMR-IB": "pass", "SBMR-OOB": "missing"}) + self.assertEqual(rows["SBMR-OOB"], {"requirement": "Mandatory", "status": "not_run"}) + self.assertEqual(overall, "not_compliant") + self.assertEqual(aggregate(list(rows.values())), "Mandatory (Not Compliant)") + + def test_extensions_do_not_block_srs(self): + """Check extensions do not block SRS.""" + self.assertEqual( + oracle([suite("BBSR-TPM", "EM")], "DT", {"BBSR-TPM": "fail"})[1], "compliant") + + def test_conditional_missing_not_blocking_but_failure_blocks(self): + """Check conditional missing not blocking but failure blocks.""" + leaves = [suite("PFDI", "CM")] + self.assertEqual(oracle(leaves, "DT", {"PFDI": "missing"})[1], "compliant") + self.assertEqual(oracle(leaves, "DT", {"PFDI": "fail"})[1], "not_compliant") + + def test_execution_proof_preserves_sbsa_requirement_without_result_json(self): + """Check execution proof preserves SBSA requirement without result JSON.""" + leaves = [suite("SBSA", "R", "SR")] + for state in ("missing", "empty", "header"): + with self.subTest(state=state): + rows, overall = oracle(leaves, "SR", {"SBSA": state}, executed={"SBSA"}) + self.assertEqual(rows["SBSA"], {"requirement": "Mandatory", "status": "not_run"}) + self.assertEqual(overall, "not_compliant") + + def test_explicit_no_execution_does_not_promote_from_json_presence(self): + """Check explicit no execution does not promote from JSON presence.""" + names = ("SBSA", "SBMR-IB", "SBMR-OOB") + leaves = [suite(name, "R", "SR") for name in names] + for state in ("missing", "empty", "header", "pass", "fail"): + with self.subTest(state=state): + rows, overall = oracle(leaves, "SR", dict.fromkeys(names, state), executed=set()) + self.assertEqual({row["requirement"] for row in rows.values()}, {"Recommended"}) + self.assertEqual(overall, "compliant") + + def test_either_sbmr_execution_promotes_both_without_result_json(self): + """Check either SBMR execution promotes both without result JSON.""" + names = ("SBMR-IB", "SBMR-OOB") + leaves = [suite(name, "R", "SR") for name in names] + for executed_name in names: + for state in ("missing", "empty", "header"): + with self.subTest(executed=executed_name, state=state): + rows, overall = oracle(leaves, "SR", dict.fromkeys(names, state), + executed={executed_name}) + self.assertEqual(rows, dict.fromkeys(names, + {"requirement": "Mandatory", "status": "not_run"})) + self.assertEqual(overall, "not_compliant") + + def test_selected_sbmr_requirement_keeps_its_executed_peer(self): + """Check selected SBMR requirement keeps its executed peer.""" + leaves = [suite(name, "R", "SR") for name in ("SBMR-IB", "SBMR-OOB")] + rows, overall = oracle(leaves, "SR", {"SBMR-IB": "missing"}, + selected=["SBMR-IB"], executed={"SBMR-OOB"}) + self.assertEqual(rows, {"SBMR-IB": {"requirement": "Mandatory", "status": "not_run"}}) + self.assertEqual(overall, "not_compliant") + + def test_missing_pfdi_blocks_only_with_execution_proof(self): + """Check missing pfdi blocks only with execution proof.""" + leaves = [suite("PFDI", "CM")] + for state in ("missing", "empty", "header"): + for executed in (None, set(), {"PFDI"}): + with self.subTest(state=state, executed=executed): + rows, overall = oracle(leaves, "DT", {"PFDI": state}, executed=executed) + self.assertEqual(rows["PFDI"], + {"requirement": "Conditional-Mandatory", "status": "not_run"}) + self.assertEqual(overall, "not_compliant" if executed else "compliant") + + def test_execution_proof_wrong_mode_and_unknown_names_are_inert(self): + """Check execution proof wrong mode and unknown names are inert.""" + leaves = [suite("PFDI", "CM"), suite("BSA", "R"), + suite("SBSA", "R", "SR"), suite("SBMR-IB", "R", "SR")] + wrong_mode = {"SBSA", "SBMR-IB", "UNKNOWN"} + rows, overall = oracle(leaves, "DT", {"BSA": "pass", "PFDI": "missing"}, + executed=wrong_mode) + self.assertEqual(rows["PFDI"]["requirement"], "Conditional-Mandatory") + self.assertEqual(overall, "compliant") + # An unregistered peer must not promote a registered SBMR interface. + rows, overall = oracle(leaves, "SR", {"SBSA": "missing", "SBMR-IB": "missing"}, + executed={"PFDI", "SBMR-OOB", "UNKNOWN"}) + self.assertEqual({row["requirement"] for row in rows.values()}, {"Recommended"}) + self.assertEqual(overall, "compliant") + + def test_default_oracle_retains_existing_present_result_rules(self): + """Check default oracle retains existing present result rules.""" + leaves = [suite(name, "R", "SR") for name in ("SBSA", "SBMR-IB", "SBMR-OOB")] + states = {"SBSA": "pass", "SBMR-IB": "fail", "SBMR-OOB": "missing"} + default = oracle(leaves, "SR", states) + self.assertEqual(default, oracle(leaves, "SR", states, executed=None)) + self.assertEqual(default, oracle(leaves, "SR", states, executed={"SBSA", "SBMR-IB"})) + self.assertEqual({row["requirement"] for row in default[0].values()}, {"Mandatory"}) + self.assertEqual(default[1], "not_compliant") + + def test_waived_and_mixed_failures_distinct(self): + """Check waived and mixed failures distinct.""" + leaves = [suite("BSA")] + self.assertEqual(oracle(leaves, "DT", {"BSA": "waived"})[1], "waived") + self.assertEqual(oracle(leaves, "DT", {"BSA": "mixed"})[1], "not_compliant") + + def test_detector_catches_mutated_status_requirement_absence_extra(self): + """Check detector catches mutated status requirement absence extra.""" + wanted = {"BSA": {"requirement": "Mandatory", "status": "not_compliant"}} + self.assertEqual(differences(wanted, wanted), {}) + for actual in ({}, {"BSA": {"requirement": "Mandatory", "status": "compliant"}}, + {"BSA": {"requirement": "Recommended", "status": "not_compliant"}}, + {**wanted, "SBSA": wanted["BSA"]}): + self.assertTrue(differences(wanted, actual)) + + def test_html_detector_parses_nested_escaped_labels(self): + """Check HTML detector parses nested escaped labels.""" + parser = ComplianceHTML() + parser.feed( + 'BSAMandatory' + 'Not Compliant (Not Run)' + 'Mandatory (Not Compliant)') + self.assertEqual(parser.rows, [("BSA", "Mandatory", "Not Compliant (Not Run)")]) + self.assertEqual(parser.badges, ["Mandatory (Not Compliant)"]) + + def test_no_guessed_policy_for_unknown_status(self): + """Check no guessed policy for unknown status.""" + with self.assertRaises(ValueError): + oracle([suite("BSA")], "DT", {"BSA": "aborted"}) + self.assertEqual(status("garbage"), "unknown") + + def test_bsa_payload_does_not_invent_extra_top_level_outcomes(self): + """Check BSA payload does not invent extra top level outcomes.""" + data = payload("BSA", "mixed") + self.assertEqual(len(data["test_results"][0]["testcases"]), 2) + self.assertEqual(data["suite_summary"]["total_failed"], 1) + self.assertEqual(data["suite_summary"]["total_failed_with_waiver"], 1) + + def test_matrix_names_are_unique(self): + """Check matrix names are unique.""" + names = [case[0] for case in scenarios([suite("FWTS"), suite("BSA", "R")], "DT")] + self.assertEqual(len(names), len(set(names))) + + def exercise_case(self, ctx, ui, registry_requirement="M"): + """Feed a fixed passing merge result to Doctor's JSON and HTML checks.""" + leaf = { + **suite("FWTS", registry_requirement), "json_output": "fwts.json", + "detailed_html": "fwts_detailed.html" + } + # The fake merger isolates Doctor's verdict from real parser behaviour. + def merge_json_files(_paths, output): + """Write a fixed passing report without invoking the real merger.""" + Path(output).write_text(json.dumps({"Suite_Name: acs_info": {"ACS Results Summary": { + "Overall Compliance Result": "Compliant", + "Suite_Name: Mandatory : EBBR-FWTS_compliance": "Compliant"}}}), encoding="utf-8") + merger = SimpleNamespace(set_run_mode=lambda mode: None, + build_selected_suite_filter=lambda selected: selected, + merge_json_files=merge_json_files) + registry = SimpleNamespace(requirement_table=lambda mode: [("FWTS", "M")]) + doctor_merge.run_case(ctx, registry, merger, ui, [leaf], set(), "DT", + ("complete_FWTS", {"FWTS": "pass"}, ["FWTS"], None)) + + def test_missing_html_capability_keeps_json_findings(self): + """Check missing HTML capability keeps JSON findings.""" + with tempfile.TemporaryDirectory() as directory: + ctx = Context(Path(directory) / "parser", directory) + with patch.object(doctor_merge, "check_html") as html_check: + self.exercise_case(ctx, None) + html_check.assert_not_called() + self.assertEqual([item.status for item in ctx.findings], ["PASS"] * 3) + self.assertEqual( + [item.check_id for item in ctx.findings], + ["MERGE_SUITE_STATUS", "MERGE_OVERALL_POLICY", "MERGE_INPUT_PRESERVED"]) + observation = json.loads( + (ctx.case_dir("merge/DT_complete_FWTS") / "observed.json").read_text()) + self.assertEqual(observation["html_check"], "not available") + + def test_available_but_broken_html_fails_without_erasing_json(self): + """Check available but broken HTML fails without erasing JSON.""" + with tempfile.TemporaryDirectory() as directory: + ctx = Context(Path(directory) / "parser", directory) + with patch.object(doctor_merge, + "check_html", + side_effect=RuntimeError("template defect")): + self.exercise_case(ctx, object()) + self.assertEqual([item.status for item in ctx.findings], ["PASS"] * 3 + ["FAIL"]) + self.assertEqual(ctx.findings[-1].check_id, "HTML_COMPLIANCE_EXECUTION") + self.assertIn("template defect", ctx.findings[-1].actual) + + def test_supported_html_checked_and_bad_labels_fail(self): + """Check supported HTML checked and bad labels fail.""" + for difference in ({ + "badges": {}, + "tables": {} + }, { + "badges": { + "FWTS": "wrong" + }, + "tables": {} + }): + with self.subTest(difference=difference), tempfile.TemporaryDirectory() as directory: + ctx = Context(Path(directory) / "parser", directory) + with patch.object(doctor_merge, "check_html", + return_value=difference) as html_check: + self.exercise_case(ctx, object()) + html_check.assert_called_once() + self.assertEqual(ctx.findings[-1].check_id, "HTML_COMPLIANCE_MATCH") + self.assertEqual(ctx.findings[-1].status, + "FAIL" if any(difference.values()) else "PASS") + + def test_html_capability_reports_missing_helpers_and_checks_checkout(self): + """Check HTML capability reports missing helpers and checks checkout.""" + with tempfile.TemporaryDirectory() as directory: + ctx = Context(directory, directory) + module = SimpleNamespace(__file__=str(Path(directory) / "generate_acs_summary.py")) + with patch.object(doctor_merge.importlib, "import_module", return_value=module): + self.assertIsNone(doctor_merge.usable_html_module(ctx)) + self.assertEqual(len(ctx.findings), 1) + self.assertEqual(ctx.findings[0].status, "BLOCKED") + self.assertIn("_summary_cards", ctx.findings[0].actual) + module._summary_cards = lambda: None + module.inject_detail_compliance = lambda: None + with patch.object(doctor_merge.importlib, "import_module", return_value=module): + self.assertIs(doctor_merge.usable_html_module(ctx), module) + self.assertEqual(len(ctx.findings), 1) + + def test_live_case_uses_independent_requirement_not_registry_value(self): + """Check live case uses independent requirement not registry value.""" + with tempfile.TemporaryDirectory() as directory: + ctx = Context(Path(directory) / "parser", directory) + real_oracle = doctor_merge.oracle + with patch.object(doctor_merge, "oracle", wraps=real_oracle) as oracle_call: + self.exercise_case(ctx, None, registry_requirement="R") + self.assertEqual(oracle_call.call_args.args[0][0]["requirements"], { + "DT": "M", + "SR": "M" + }) + + +# Raw parser output: expected test identities, counts and suite/mode coverage. + +def golden(): + """Return known results and separately written expectations for comparison.""" + data = { + "suite_summary": { + "Passed": 1, + "Failed": 1 + }, + "test_results": [{ + "testcases": [ + { + "Test_case": "QA_01", + "Test_case_description": "Known passing rule", + "Test_result": "PASSED" + }, + { + "Test_case": + "QA_02", + "Test_case_description": + "Known failing rule", + "Test_result": + "FAILED", + "subtests": [{ + "sub_Test_Number": "QA_CHILD", + "sub_Test_Description": "Known failing child", + "sub_test_result": "FAILED" + }] + }, + ] + }] + } + expected = { + "assertions": [{ + "path": ["suite_summary", "Passed"], + "value": 1 + }, { + "path": ["suite_summary", "Failed"], + "value": 1 + }], + "records": [{ + "path": ["test_results", 0, "testcases", 0], + "fields": { + "Test_case": "QA_01", + "Test_case_description": "Known passing rule", + "Test_result": "PASSED" + } + }, { + "path": ["test_results", 0, "testcases", 1], + "fields": { + "Test_case": "QA_02", + "Test_case_description": "Known failing rule", + "Test_result": "FAILED" + } + }, { + "path": ["test_results", 0, "testcases", 1, "subtests", 0], + "fields": { + "sub_Test_Number": "QA_CHILD", + "sub_Test_Description": "Known failing child", + "sub_test_result": "FAILED" + } + }] + } + return data, expected + + +def completed_schema_failure(path, issue="MISSING_KEY"): + """Mimic a validator that finished and reported an error for the given file.""" + return ("*suite=Suite_Name: BSA issue=" + issue + ": Test_suite_info required count=1\n" + "--- Files Checked ---\nBSA: " + str(path) + "\n" + "Schema validation result: \x1b[0;31mFAIL\x1b[0m (1 failed, 0 passed, 0 skipped)\n") + + +class NativeIdentityTests(unittest.TestCase): + """Check individual test details as well as totals, so swaps cannot hide.""" + + def test_golden_positive_control(self): + """Check golden positive control.""" + data, expected = golden() + before = copy.deepcopy((data, expected)) + self.assertEqual(native.raw_issues(data, expected), []) + self.assertEqual((data, expected), before) + + def test_balanced_status_swap_does_not_pass_on_totals(self): + """Check balanced status swap does not pass on totals.""" + data, expected = golden() + rows = data["test_results"][0]["testcases"] + rows[0]["Test_result"], rows[1]["Test_result"] = "FAILED", "PASSED" + self.assertEqual(data["suite_summary"], {"Passed": 1, "Failed": 1}) + self.assertIn("Test_result", "\n".join(native.raw_issues(data, expected))) + + def test_balanced_identity_swap_is_detected(self): + """Check balanced identity swap is detected.""" + data, expected = golden() + rows = data["test_results"][0]["testcases"] + rows[0]["Test_case"], rows[1]["Test_case"] = "QA_02", "QA_01" + self.assertIn("Test_case", "\n".join(native.raw_issues(data, expected))) + + def test_descriptions_and_unknown_statuses_are_checked(self): + """Check descriptions and unknown statuses are checked.""" + for field, replacement in (("Test_case_description", "Unrelated test"), + ("Test_result", "UNKNOWN")): + with self.subTest(field=field): + data, expected = golden() + data["test_results"][0]["testcases"][0][field] = replacement + self.assertIn(field, "\n".join(native.raw_issues(data, expected))) + + def test_missing_extra_moved_or_resultless_records_are_detected(self): + """Check missing extra moved or resultless records are detected.""" + for mutation in ("missing_parent", "missing_child", "extra_child", "moved_child", + "missing_result"): + with self.subTest(mutation=mutation): + data, expected = golden() + rows = data["test_results"][0]["testcases"] + if mutation == "missing_parent": + rows.pop() + elif mutation == "missing_child": + rows[1]["subtests"].clear() + elif mutation == "extra_child": + rows[1]["subtests"].append(copy.deepcopy(rows[1]["subtests"][0])) + elif mutation == "moved_child": + rows[0]["subtests"] = rows[1].pop("subtests") + else: + del rows[0]["Test_result"] + self.assertIn("Result inventory differs", + "\n".join(native.raw_issues(data, expected))) + + def test_counts_are_checked_even_when_records_match(self): + """Check counts are checked even when records match.""" + data, expected = golden() + data["suite_summary"]["Failed"] = 0 + self.assertIn("suite_summary", "\n".join(native.raw_issues(data, expected))) + + def test_boolean_is_not_an_integer_count(self): + """Check boolean is not an integer count.""" + data, expected = golden() + data["suite_summary"]["Passed"] = True + self.assertTrue(native.raw_issues(data, expected)) + + def test_nonzero_unexpected_status_counter_is_detected(self): + """Check nonzero unexpected status counter is detected.""" + data = {"test_results": [{"subtests": [{"sub_test_result": { + "PASSED": 1, "FAILED": 0, "FAILED_WITH_WAIVER": 0, "pass_reasons": ["Known pass"]}}]}]} + expected = {"assertions": [], "records": [{ + "path": ["test_results", 0, "subtests", 0], "fields": { + "sub_test_result": {"PASSED": 1, "FAILED": 0}}}]} + self.assertEqual(native.raw_issues(data, expected), []) + data["test_results"][0]["subtests"][0]["sub_test_result"]["FAILED_WITH_WAIVER"] = 1 + self.assertIn("unexpected nonzero", "\n".join(native.raw_issues(data, expected))) + + def test_multiple_mismatches_are_not_hidden_by_first_error(self): + """Check multiple mismatches are not hidden by first error.""" + data, expected = golden() + rows = data["test_results"][0]["testcases"] + rows[0]["Test_result"] = "UNKNOWN" + rows[1]["Test_case"] = "wrong" + issues = "\n".join(native.raw_issues(data, expected)) + self.assertIn("UNKNOWN", issues) + self.assertIn("wrong", issues) + + +class NativeContractTests(unittest.TestCase): + """Check that saved sample logs cover the registered suites and modes.""" + + def setUp(self): + self.data = native.load_json(native.DATA_FILE) + self.registry = native.load_json(doctor.BASE_DIR / "suite_registry.json") + + def test_bundled_fixture_is_valid_and_independently_attributed(self): + """Check bundled fixture is valid and independently attributed.""" + self.assertEqual(native.contract_issues(self.data), []) + self.assertEqual(self.data["provenance"]["commit"], + "b6a8a78d1fef3d6e41d2d2aec94006e0a9263c8c") + self.assertNotIn("compliance", self.data["scenarios"][1]) + + def test_bundled_fixture_covers_all_32_routes(self): + """Check bundled fixture covers all 32 routes.""" + self.assertEqual(native.coverage_issues(self.registry, self.data["scenarios"]), []) + routes = {(name, case["mode"]) + for case in self.data["scenarios"] + for name in case["suites"]} + self.assertEqual(len(routes), 32) + self.assertIn(("PCIE-OPTION-ROM-ARCH-AUDIT", "SR"), routes) + self.assertNotIn(("PCIE-OPTION-ROM-ARCH-AUDIT", "DT"), routes) + + def test_pcie_native_fixtures_keep_independent_pass_fail_skip_answers(self): + """Check PCIE native fixtures keep independent pass fail skip answers.""" + cases = {case["name"]: case for case in self.data["scenarios"]} + for suffix, wanted, counter in (("pass", "PASSED", "total_passed"), + ("fail", "FAILED", "total_failed"), + ("skip", "SKIPPED", "total_skipped")): + with self.subTest(outcome=suffix): + case = cases["sr_pcie_" + suffix] + self.assertEqual(case["mode"], "SR") + self.assertEqual(case["suites"], ["PCIE-OPTION-ROM-ARCH-AUDIT"]) + self.assertIn("results/uefi_dump/PcieOptionRomArchAudit.log", case["files"]) + expected = case["raw"]["pcie_option_rom_arch_audit.json"] + self.assertEqual(expected["destination"], "Suite_Name: Standalone") + assertions = {tuple(item["path"]): item["value"] for item in expected["assertions"]} + self.assertEqual(assertions[("test_results", 0, "test_result")], wanted) + self.assertEqual(assertions[("suite_summary", counter)], 1) + for other in {"total_passed", "total_failed", "total_skipped"} - {counter}: + self.assertEqual(assertions[("suite_summary", other)], 0) + self.assertEqual(len(expected["records"]), 1) + self.assertEqual(expected["records"][0]["fields"]["sub_test_result"][wanted], 1) + + def test_removing_pcie_fixtures_reports_only_the_sr_pcie_gap(self): + """Check removing PCIE fixtures reports only the SR PCIE gap.""" + cases = [case for case in self.data["scenarios"] + if "PCIE-OPTION-ROM-ARCH-AUDIT" not in case["suites"]] + self.assertEqual(native.coverage_issues(self.registry, cases), [ + "Missing independent native fixture: SR/PCIE-OPTION-ROM-ARCH-AUDIT"]) + + def test_pcie_drift_in_counts_parent_status_or_child_identity_is_detected(self): + """Check PCIE drift in counts parent status or child identity is detected.""" + case = next(case for case in self.data["scenarios"] if case["name"] == "sr_pcie_fail") + expected = case["raw"]["pcie_option_rom_arch_audit.json"] + # This is a small explicit observed result, not output copied from the + # production parser. Each mutation changes one externally visible fact. + actual = { + "suite_summary": { + "total_passed": 0, + "total_failed": 1, + "total_skipped": 0 + }, + "test_results": [{ + "Test_suite": + "PCIeOptionRomArchAudit", + "Test_case": + "pcie_option_rom_arch_audit", + "test_result": + "FAILED", + "subtests": [{ + "sub_Test_Number": "1", + "sub_Test_Description": "PCIe Option ROM UEFI driver architecture compliance", + "sub_test_result": { + "PASSED": 0, + "FAILED": 1, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0, + "FAILED_WITH_WAIVER": 0 + } + }] + }] + } + self.assertEqual(native.raw_issues(actual, expected), [], + "Control must match before mutation") + for mutation in ("count", "parent", "identity", "missing-child"): + with self.subTest(mutation=mutation): + changed = deepcopy(actual) + if mutation == "count": + changed["suite_summary"]["total_failed"] = 0 + elif mutation == "parent": + changed["test_results"][0]["test_result"] = "PASSED" + elif mutation == "identity": + changed["test_results"][0]["subtests"][0]["sub_Test_Number"] = "2" + else: + changed["test_results"][0]["subtests"] = [] + self.assertTrue(native.raw_issues(changed, expected)) + + def test_memory_map_fixtures_keep_independent_identity_and_counts(self): + """Check memory map fixtures keep independent identity and counts.""" + case = next(case for case in self.data["scenarios"] + if case["name"] == "dt_memory_map_routes") + self.assertEqual(case["mode"], "DT") + self.assertEqual(case["suites"], ["RESERVED-MEMORY-MAP", "DTB-ALIGNMENT"]) + reserved = case["raw"]["reserved_memory_map.json"] + self.assertEqual( + [record["fields"]["sub_Test_Description"] for record in reserved["records"]], + ["Reserved Memory Map Compliance Test", "Memory Reservation Block Compliance Test"]) + self.assertEqual( + [record["fields"]["sub_test_result"]["FAILED"] for record in reserved["records"]], + [0, 1]) + aligned = case["raw"]["dtb_alignment.json"] + self.assertEqual(aligned["records"][0]["fields"]["sub_test_result"]["PASSED"], 1) + self.assertIn("RESULTS: FAILED", + case["files"]["results/linux_tools/reserved_memory_map_test.log"]) + self.assertIn("RESULT: PASS", case["files"]["results/linux_tools/dtb_alignment_test.log"]) + + def test_removing_memory_map_fixture_reports_both_new_coverage_gaps(self): + """Check removing memory map fixture reports both new coverage gaps.""" + cases = [case for case in self.data["scenarios"] if case["name"] != "dt_memory_map_routes"] + self.assertEqual(native.coverage_issues(self.registry, cases), [ + "Missing independent native fixture: DT/DTB-ALIGNMENT", + "Missing independent native fixture: DT/RESERVED-MEMORY-MAP", + ]) + + def test_new_suite_requires_fixture_onboarding(self): + """Check new suite requires fixture onboarding.""" + self.registry["suites"].append({ + "canonical": "NEW-SUITE", + "modes": ["DT"], + "logs_to_json": "new/logs_to_json.py", + "schema": "new.json" + }) + self.registry["standalone"]["suite_execution"]["NEW-SUITE"] = {} + self.assertIn("Missing independent native fixture: DT/NEW-SUITE", + native.coverage_issues(self.registry, self.data["scenarios"])) + + def test_new_mode_requires_fixture_onboarding(self): + """Check new mode requires fixture onboarding.""" + next(suite for suite in self.registry["suites"] + if suite["canonical"] == "PFDI")["modes"].append("SR") + self.assertIn("Missing independent native fixture: SR/PFDI", + native.coverage_issues(self.registry, self.data["scenarios"])) + + def test_unknown_fixture_route_is_not_silently_ignored(self): + """Check unknown fixture route is not silently ignored.""" + self.data["scenarios"][0]["suites"].append("TYPO") + self.assertIn("Fixture targets an unknown/unsupported route: SR/TYPO", + native.coverage_issues(self.registry, self.data["scenarios"])) + + def test_missing_raw_expectation_is_a_coverage_gap(self): + """Check missing raw expectation is a coverage gap.""" + del self.data["scenarios"][0]["raw"]["bsa.json"] + issues = native.coverage_issues(self.registry, self.data["scenarios"]) + self.assertTrue( + any("BSA: no independently expected raw output" in issue for issue in issues)) + + def test_fixture_cannot_hide_orphan_raw_output(self): + """Check fixture cannot hide orphan raw output.""" + self.data["scenarios"][0]["raw"]["unexpected.json"] = golden()[1] + self.assertTrue(any("no selected suite: unexpected.json" in issue for issue in + native.coverage_issues(self.registry, self.data["scenarios"]))) + + def test_result_inventory_must_be_nonempty(self): + """Check result inventory must be nonempty.""" + self.data["scenarios"][0]["raw"]["bsa.json"]["records"] = [] + self.assertTrue(any("non-empty exact record inventory" in issue + for issue in native.contract_issues(self.data))) + + def test_count_expectations_must_be_nonempty(self): + """Check count expectations must be nonempty.""" + self.data["scenarios"][0]["raw"]["bsa.json"]["assertions"] = [] + self.assertTrue(any("independent count assertions" in issue + for issue in native.contract_issues(self.data))) + + def test_every_record_needs_identity_description_and_status(self): + """Check every record needs identity description and status.""" + record = self.data["scenarios"][0]["raw"]["bsa.json"]["records"][0] + del record["fields"]["Test_case"] + self.assertTrue(any("identity, description and result" in issue + for issue in native.contract_issues(self.data))) + + def test_duplicate_expected_path_cannot_mask_missing_record(self): + """Check duplicate expected path cannot mask missing record.""" + records = self.data["scenarios"][0]["raw"]["bsa.json"]["records"] + records.append(copy.deepcopy(records[0])) + self.assertTrue(any("duplicate expected record path" in issue + for issue in native.contract_issues(self.data))) + + def test_unknown_expected_status_cannot_be_a_positive_control(self): + """Check unknown expected status cannot be a positive control.""" + self.data["scenarios"][0]["raw"]["bsa.json"]["records"][0]["fields"][ + "Test_result"] = "UNKNOWN" + self.assertTrue(any("invalid expected result" in issue + for issue in native.contract_issues(self.data))) + + def test_fixture_paths_cannot_escape_evidence(self): + """Check fixture paths cannot escape evidence.""" + for path in ("../source.py", "/tmp/absolute", "results/../../source.py", "..\\source.py", + "."): + with self.subTest(path=path): + data = copy.deepcopy(self.data) + data["scenarios"][0]["files"][path] = "unsafe" + self.assertTrue( + any("unsafe input path" in issue for issue in native.contract_issues(data))) + + def test_malformed_fixture_reports_errors_without_crashing(self): + """Check malformed fixture reports errors without crashing.""" + for data in (None, [], {}, {"format_version": 1, "scenarios": []}, + {"format_version": 1, "scenarios": [None, {}, {"name": [], "mode": []}]}): + with self.subTest(data=data): + self.assertTrue(native.contract_issues(data)) + + def test_boolean_or_negative_path_indices_are_rejected(self): + """Check boolean or negative path indices are rejected.""" + for index in (True, -1): + with self.subTest(index=index): + data = copy.deepcopy(self.data) + data["scenarios"][0]["raw"]["bsa.json"]["records"][0]["path"][1] = index + self.assertTrue( + any("invalid record path" in issue for issue in native.contract_issues(data))) + + def test_strict_json_rejects_duplicates_and_nonfinite_numbers(self): + """Check strict JSON rejects duplicates and nonfinite numbers.""" + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "input.json" + for text in ('{"x": 1, "x": 2}', '{"x": NaN}', '{"x": Infinity}', '{"x": -Infinity}', + '{"x": 1e999}'): + with self.subTest(text=text): + path.write_text(text) + with self.assertRaises(ValueError): + native.load_json(path) + + +class NativeExecutionTests(unittest.TestCase): + """Check command routing and error reporting using controlled responses.""" + + def test_native_contract_and_routes_do_not_require_merge_module_import(self): + # Block one import in a fresh process to test check-group independence. + """Check native contract and routes do not require merge module import.""" + script = r''' +import importlib.abc +import json +import sys +import tempfile +from unittest import mock +class NoMerge(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path=None, target=None): + if fullname == "doctor_checks.merge": + raise ImportError("merge-only helpers deliberately unavailable") +sys.meta_path.insert(0, NoMerge()) +from doctor_checks import core as doctor +from doctor_checks import probes as doctor_probes +assert doctor_probes.contract_issues(doctor_probes.load_json(doctor_probes.DATA_FILE)) == [] +with tempfile.TemporaryDirectory() as folder: + ctx = doctor.Context(doctor.BASE_DIR, folder) + ctx.package_checked = True + ctx.portable_parser = doctor.BASE_DIR + with mock.patch.object(doctor_probes, "_run_route") as route: + doctor_probes.run_native(ctx) + assert route.call_count > 0 + assert all(item.status == "PASS" for item in ctx.findings) +assert "doctor_checks.merge" not in sys.modules +print(json.dumps({"routes": route.call_count, "merge_loaded": False})) +''' + completed = subprocess.run([sys.executable, "-B", "-c", script], + cwd=doctor.BASE_DIR, capture_output=True, text=True, timeout=20) + self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr) + result = json.loads(completed.stdout) + self.assertGreater(result["routes"], 0) + self.assertFalse(result["merge_loaded"]) + + def test_schema_diagnostic_includes_issue_and_path_without_ansi(self): + """Check schema diagnostic includes issue and path without ansi.""" + completed = subprocess.CompletedProcess([], 1, + "\x1b[0;31m*suite=BSA issue=MISSING_KEY: Test_suite_info\x1b[0m\n" + " *at=BSA.test_results[0]\n") + text = native.command_diagnostic(completed) + self.assertIn("MISSING_KEY: Test_suite_info", text) + self.assertIn("BSA.test_results[0]", text) + self.assertNotIn("\x1b", text) + + def test_verified_portable_parser_is_used_without_mutating_original_context(self): + """Check verified portable parser is used without mutating original context.""" + with tempfile.TemporaryDirectory() as folder: + source = doctor.BASE_DIR + portable = Path(folder) / "package" / "log_parser" + portable.mkdir(parents=True) + (portable / "suite_registry.json").write_text( + (source / "suite_registry.json").read_text()) + ctx = Context(source, Path(folder) / "evidence", modes=("SR",)) + ctx.package_checked = True + ctx.portable_parser = portable + with mock.patch.object(native, "_run_route") as invoke: + native.run_native(ctx) + # Three independent PCIe outcomes add three calls, but only one + # newly covered SR route, to the ten existing SR fixture calls. + self.assertEqual(invoke.call_count, 13) + self.assertTrue( + all(call.args[0].parser_dir == portable for call in invoke.call_args_list)) + self.assertEqual(ctx.parser_dir, source) + self.assertTrue(ctx.findings) + + def test_failed_package_never_falls_back_to_source(self): + """Check failed package never falls back to source.""" + with tempfile.TemporaryDirectory() as folder: + ctx = Context(doctor.BASE_DIR, folder) + ctx.package_checked = True + native.run_native(ctx) + self.assertEqual(len(ctx.findings), 1) + self.assertEqual(ctx.findings[0].status, "BLOCKED") + self.assertEqual(ctx.findings[0].check_id, "NATIVE_PACKAGE_PREREQUISITE") + + def test_route_uses_public_cli_and_separate_schema(self): + """Check route uses public CLI and separate schema.""" + with tempfile.TemporaryDirectory() as folder: + ctx = Context(doctor.BASE_DIR, folder, modes=("SR",)) + ctx.native_outputs = [] + case = native.load_json(native.DATA_FILE)["scenarios"][0] + data, expectation = golden() + case = copy.deepcopy(case) + case["raw"] = {"bsa.json": expectation} + calls = [] + + def invoke(command, directory, name, **kwargs): + """Record commands and provide known output without running a parser.""" + calls.append([str(arg) for arg in command]) + if name == "parser": + output = Path(directory) / "output" / "acs_jsons" + output.mkdir(parents=True) + (output / "bsa.json").write_text(json.dumps(data)) + if name.startswith("schema-policy-"): + return subprocess.CompletedProcess(command, 0, json.dumps({ + "category_provenance": {"source": "bundled", "invalid": False}, + "errors": [], "omitted_missing_info_paths": [], "strict_error_count": 0})) + return subprocess.CompletedProcess(command, 0, "ok") + + ctx.run = invoke + native._run_route(ctx, case, "BSA", {"json_output": "bsa.json"}) + self.assertEqual(len(calls), 3) + self.assertEqual(calls[0][0], "bash") + self.assertIn("--standalone", calls[0]) + self.assertIn("raw", calls[1]) + self.assertIn("-m", calls[2]) + self.assertIn("doctor_checks.artifacts", calls[2]) + self.assertIn("--schema-policy", calls[2]) + self.assertTrue(all(finding.status == "PASS" for finding in ctx.findings)) + self.assertEqual(len(ctx.native_outputs), 1) + + def test_policy_result_retains_strict_exit_and_legacy_warning(self): + """Check policy result retains strict exit and legacy warning.""" + for source in ("explicit", "bundled", "unknown"): + with self.subTest(source=source), tempfile.TemporaryDirectory() as folder: + ctx = Context(doctor.BASE_DIR, folder) + omitted = [] if source == "explicit" else ["/test_results/0"] + errors = [{ + "path": "/test_results/0", + "message": "Test_suite_info required" + }] if source == "explicit" else [] + result = { + "category_provenance": { + "source": source, + "invalid": False, + "message": "Legacy run" + }, + "errors": errors, + "omitted_missing_info_paths": omitted, + "strict_error_count": 3 + } + ctx.run = mock.Mock(side_effect=[ + subprocess.CompletedProcess( + [], 1, completed_schema_failure(Path(folder) / "bsa.json")), + subprocess.CompletedProcess([], 0, json.dumps(result)) + ]) + base = Path(folder) + native._check_raw_schema(ctx, base, base / "output", base / "bsa.json", "SR", "BSA") + schema = next(finding for finding in ctx.findings + if finding.check_id == "NATIVE_RAW_SCHEMA") + self.assertEqual("FAIL" if source == "explicit" else "PASS", schema.status) + self.assertIn("Strict validator exit 1", schema.actual) + warnings = [finding for finding in ctx.findings if finding.status == "WARN"] + self.assertEqual(source == "unknown", bool(warnings)) + + def test_policy_evaluator_failure_does_not_turn_strict_failure_green(self): + """Check policy evaluator failure does not turn strict failure green.""" + with tempfile.TemporaryDirectory() as folder: + ctx = Context(doctor.BASE_DIR, folder) + ctx.run = mock.Mock(side_effect=[ + subprocess.CompletedProcess([], 1, + completed_schema_failure(Path(folder) / "bsa.json")), + subprocess.CompletedProcess([], 2, "policy unavailable") + ]) + base = Path(folder) + native._check_raw_schema(ctx, base, base / "output", base / "bsa.json", "SR", "BSA") + self.assertEqual("BLOCKED", ctx.findings[-1].status) + + def test_strict_validator_crash_or_fatal_file_error_cannot_receive_policy_exemption(self): + """Check strict validator crash or fatal file error cannot receive policy exemption.""" + with tempfile.TemporaryDirectory() as folder: + base = Path(folder) + raw = base / "bsa.json" + completed = completed_schema_failure(raw) + broken_outputs = [ + "Traceback (most recent call last):\nRuntimeError: independent validator crash", + "*suite=BSA issue=JSON_FILE: failed to read JSON: permission denied count=1", + completed_schema_failure(raw, "JSON_FILE"), + completed_schema_failure(raw, "SCHEMA_FILE"), + "Traceback (most recent call last):\nRuntimeError: independent validator crash\n" + + completed, + completed.replace(str(raw), str(base / "wrong.json")), + completed.replace("(1 failed, 0 passed, 0 skipped)", "(0 validated)"), + "ERROR: validation could not execute\n" + completed, + ] + for output in broken_outputs: + with self.subTest(output=output): + ctx = Context(doctor.BASE_DIR, folder) + passing_policy = { + "category_provenance": { + "source": "bundled", + "invalid": False + }, + "strict_error_count": 3, + "errors": [], + "omitted_missing_info_paths": ["/test_results/0"] + } + ctx.run = mock.Mock(side_effect=[ + subprocess.CompletedProcess([], 1, output), + subprocess.CompletedProcess([], 0, json.dumps(passing_policy)) + ]) + native._check_raw_schema(ctx, base, base / "output", raw, "SR", "BSA") + self.assertEqual("FAIL", ctx.findings[-1].status) + self.assertEqual(1, ctx.run.call_count, + "A failed strict execution must not reach applicability") + + def test_failed_parser_and_missing_outputs_do_not_report_identity_pass(self): + """Check failed parser and missing outputs do not report identity pass.""" + with tempfile.TemporaryDirectory() as folder: + ctx = Context(doctor.BASE_DIR, folder) + ctx.native_outputs = [] + ctx.run = mock.Mock(return_value=subprocess.CompletedProcess([], 5, "parse failed")) + case = native.load_json(native.DATA_FILE)["scenarios"][0] + native._run_route(ctx, case, "BSA", {"json_output": "bsa.json"}) + statuses = {finding.check_id: finding.status for finding in ctx.findings} + self.assertEqual(statuses["NATIVE_EXECUTION"], "FAIL") + self.assertEqual(statuses["NATIVE_OUTPUT_INVENTORY"], "FAIL") + self.assertEqual(statuses["NATIVE_RAW_IDENTITY"], "BLOCKED") + + +# Independent requirement rules and safe extraction of portable parser packages. + +class IndependentPolicyTests(unittest.TestCase): + """Ensure a registry change cannot silently change Doctor's expected rules.""" + + def registry(self): + """Build a registry copy from Doctor's separate requirement reference.""" + return {"suites": [{"canonical": name, "requirements": dict(requirements), + "modes": list(requirements), "json_output": name + ".json"} + for name, requirements in EXPECTED_REQUIREMENTS.items()]} + + def test_exact_contract_is_accepted(self): + """Check exact contract is accepted.""" + self.assertEqual(policy_differences(self.registry()), []) + + def test_registry_cannot_rewrite_expected_requirement(self): + """Check registry cannot rewrite expected requirement.""" + registry = self.registry() + bsa = registry["suites"][0] + bsa["requirements"]["DT"] = "M" + expected = expected_leaves(registry["suites"]) + self.assertEqual(expected[0]["requirements"]["DT"], "R") + self.assertTrue(policy_differences(registry)) + self.assertEqual(bsa["requirements"]["DT"], "M") # No production mutation. + + def test_new_missing_suite_and_unsupported_mode_are_not_silent(self): + """Check new missing suite and unsupported mode are not silent.""" + baseline = self.registry() + for mutation in ("new", "missing", "mode", "requirement"): + with self.subTest(mutation=mutation): + registry = copy.deepcopy(baseline) + if mutation == "new": + registry["suites"].append({"canonical": "NEW-SUITE", "json_output": "new.json"}) + elif mutation == "missing": + registry["suites"].pop() + elif mutation == "mode": + registry["suites"][0]["modes"].remove("DT") + else: + registry["suites"][0]["requirements"].clear() + self.assertTrue(policy_differences(registry)) + + +class PackageTests(unittest.TestCase): + """Check archive paths, checksums and whether packaged files match source.""" + + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.root = Path(temp.name) + self.archive = self.root / "parser.tar.gz" + + def bundle(self, name="systemready-log-parser/common/log_parser/doctor.py", link=False): + """Build a tiny archive, optionally with a deliberately unsafe member.""" + with tarfile.open(self.archive, "w:gz") as archive: + member = tarfile.TarInfo(name) + if link: + member.type = tarfile.SYMTYPE + member.linkname = "/tmp/outside" + archive.addfile(member) + else: + member.size = 4 + archive.addfile(member, io.BytesIO(b"test")) + + def test_matching_package_is_extractable(self): + """Check matching package is extractable.""" + self.bundle() + parser = extract_package(self.archive, self.root / "extract") + self.assertEqual((parser / "doctor.py").read_text(), "test") + + def test_archive_traversal_and_links_are_rejected_before_extract(self): + """Check archive traversal and links are rejected before extract.""" + for name, link in (("../outside", False), ("/absolute", False), + ("systemready-log-parser/../../outside", False), + ("systemready-log-parser/linked", True)): + self.bundle(name, link) + destination = self.root / "extract" + with self.assertRaises(ValueError): + extract_package(self.archive, destination) + self.assertFalse(destination.exists()) + + def test_checksum_and_filename_must_both_match(self): + """Check checksum and filename must both match.""" + self.bundle() + digest = hashlib.sha256(self.archive.read_bytes()).hexdigest() + checksum = self.archive.with_name(self.archive.name + ".sha256") + checksum.write_text(digest + " " + self.archive.name + "\n") + self.assertEqual(verify_checksum(self.archive), digest) + for value in ("0" * 64 + " " + self.archive.name, digest + " other.tar.gz"): + checksum.write_text(value) + with self.assertRaises(ValueError): + verify_checksum(self.archive) + + def test_missing_fixture_or_changed_runtime_is_detected(self): + """Check missing fixture or changed runtime is detected.""" + source, packaged = self.root / "source", self.root / "package" + source.mkdir() + packaged.mkdir() + for directory in (source, packaged): + (directory / "doctor.py").write_text("original") + (directory / "doctor_checks/data").mkdir(parents=True) + (directory / "doctor_checks/data/native_cases.json").write_text("{}") + self.assertEqual(package_differences(source, packaged), {}) + (packaged / "doctor.py").write_text("different") + (packaged / "doctor_checks/data/native_cases.json").unlink() + self.assertEqual(package_differences(source, packaged), { + "missing": ["doctor_checks/data/native_cases.json"], + "changed": ["doctor.py"] + }) + + +# Doctor's interpretation of passing, malformed, waived and missing results. + +class ConditionalExecutionTests(unittest.TestCase): + """Keep proof that a conditional suite ran separate from its JSON delivery.""" + + def test_conditional_fixtures_cover_exactly_four_mode_filtered_routes(self): + """Check conditional fixtures cover exactly four mode filtered routes.""" + cases = probes.conditional_execution_cases(("DT", "SR")) + self.assertEqual({tuple(case[:2]) for case in cases}, { + ("DT", "PFDI"), ("SR", "SBSA"), ("SR", "SBMR-IB"), ("SR", "SBMR-OOB")}) + self.assertEqual(len(cases), 4) + self.assertEqual(len(probes.conditional_execution_cases(("DT",))), 1) + self.assertEqual(len(probes.conditional_execution_cases(("SR",))), 3) + self.assertEqual(probes.conditional_execution_cases(()), []) + for mode, name, relative, content, provenance in cases: + with self.subTest(suite=name): + self.assertTrue(relative) + self.assertTrue(provenance) + self.assertEqual(len(probes.conditional_execution_records(name, content)), + 2 if name in ("SBSA", "PFDI") else 1) + + def test_rule_execution_needs_known_rule_and_terminal_result_pair(self): + """Check rule execution needs known rule and terminal result pair.""" + for name, heading, rule in (("SBSA", "PE", "S_L3PE_01"), ("PFDI", "PFDI", "R0040")): + header = "*** Running " + heading + " tests ***\n" + record = rule + " : 23 : Example rule\n" + for text in ("", header, header + "Tests complete: 0 executed\n", header + record, + header + "Result: PASSED\n", header + record + "Result: UNKNOWN\n", + header + record + "Result: SKIPPED\n", record + "Result: PASSED\n"): + with self.subTest(suite=name, text=text): + self.assertEqual(probes.conditional_execution_records(name, text), []) + for result in ("PASSED", "FAILED"): + self.assertEqual(probes.conditional_execution_records( + name, header + record + " Result: " + result + "\n"), + [(rule + " : 23", "Example rule", result)]) + + def test_robot_execution_uses_only_named_test_direct_terminal_status(self): + """Check robot execution uses only named test direct terminal status.""" + for name in ("SBMR-IB", "SBMR-OOB"): + for text in ( + "", "", '', + '' + '', + '', + '', + ''): + with self.subTest(suite=name, text=text): + self.assertEqual(probes.conditional_execution_records(name, text), []) + for direct, nested, expected in (("PASS", "FAIL", "PASSED"), ("FAIL", "PASS", + "FAILED")): + text = ('' + '') + self.assertEqual(probes.conditional_execution_records(name, text), + [("Host", expected)]) + self.assertEqual(probes.conditional_execution_records("UNKNOWN", "Result: PASSED\n"), []) + + def control(self, directory): + """Return literal native SBSA records, not values derived from the oracle.""" + raw = { + "suite_summary": { + "Total Rules Run": 2, + "Passed": 2, + "Failed": 0, + "Total_failed_with_waiver": 0, + "Skipped": 0, + "Warnings": 0, + "Passed (Partial)": 0, + "PAL Not Supported": 0, + "Not Implemented": 0 + }, + "test_results": [{ + "testcases": [{ + "Test_case": "S_L3PE_01 : 23", + "Test_case_description": "Check PE Granule Support", + "Test_result": "PASSED" + }, { + "Test_case": "S_L3PE_02 : 24", + "Test_case_description": "Check for 16-bit ASID support", + "Test_result": "PASSED" + }] + }] + } + folder = Path(directory) / "native-control" + source = folder / "input/acs_results/uefi/SbsaResults.log" + output = folder / "output/acs_jsons/sbsa.json" + source.parent.mkdir(parents=True) + output.parent.mkdir(parents=True) + case = probes.conditional_execution_cases(("SR",))[0] + source.write_text(case[3]) + output.write_text(json.dumps(raw)) + return {"exit": 0, "raw": raw, "traceback": False, "folder": str(folder), + "counts": probes.counts(raw), "status": "Not Compliant", "html_status": None, + "html_failed": None, "error": "", "evidence": [source, output]}, case + + def registry(self): + """Limit these plumbing tests to the one selected conditional suite.""" + return {"SBSA": {**suite("SBSA", "R", "SR"), "json_output": "sbsa.json"}} + + def test_conditional_control_failure_or_changed_identity_blocks_probe(self): + """Check conditional control failure or changed identity blocks probe.""" + for mutation in ("empty", "exit", "traceback", "identity"): + with self.subTest(mutation=mutation), tempfile.TemporaryDirectory() as directory: + control, case = self.control(directory) + if mutation == "empty": + control["raw"] = {"suite_summary": {}, "test_results": []} + elif mutation == "identity": + # Counts remain exactly correct; identity must still be checked. + control["raw"]["test_results"][0]["testcases"][0][ + "Test_case"] = "S_WRONG_01 : 23" + elif mutation == "exit": + control["exit"] = 5 + else: + control["traceback"] = True + ctx = Context(doctor.BASE_DIR, Path(directory) / "doctor", modes=("SR",)) + ctx.run = mock.Mock() + with patch.object(probes, "conditional_execution_cases", return_value=[case]), \ + patch.object(probes, "invoke", return_value=control): + probes.run_conditional_execution(ctx, self.registry()) + ctx.run.assert_not_called() + self.assertEqual([(item.check_id, item.status) for item in ctx.findings], + [("raw.conditional-control", "BLOCKED"), + ("raw.conditional-execution", "BLOCKED")]) + + def test_conditional_proof_does_not_require_a_green_merged_control(self): + """Check conditional proof does not require a green merged control.""" + with tempfile.TemporaryDirectory() as directory: + control, case = self.control(directory) + self.assertEqual(control["status"], "Not Compliant") + ctx = Context(doctor.BASE_DIR, Path(directory) / "doctor", modes=("SR",)) + ctx.run = mock.Mock( + return_value=subprocess.CompletedProcess([], 5, "controlled merge rejection")) + with patch.object(probes, "conditional_execution_cases", return_value=[case]), \ + patch.object(probes, "invoke", return_value=control): + probes.run_conditional_execution(ctx, self.registry()) + ctx.run.assert_called_once() + self.assertEqual([(item.check_id, item.status) for item in ctx.findings], [ + ("raw.conditional-control", "PASS"), ("raw.conditional-execution", "BLOCKED")]) + + def test_conditional_probe_omits_json_but_preserves_native_proof(self): + # Direct merger input omission bypasses standalone's delivery guard: + # its mismatch is a boundary warning, not a proven public-flow failure. + """Check conditional probe omits JSON but preserves native proof.""" + for retained, verdict in ((True, "PASS"), (False, "WARN")): + with self.subTest(retained=retained), tempfile.TemporaryDirectory() as directory: + control, case = self.control(directory) + originals = {path: path.read_bytes() for path in control["evidence"]} + ctx = Context(doctor.BASE_DIR, Path(directory) / "doctor", modes=("SR",)) + + def merge(command, folder, name): + """Model whether a missing JSON keeps its mandatory requirement.""" + destination = Path(command[5]) + baseline = name == "merge-baseline" + self.assertIn(name, ("merge-baseline", "merge-withheld-json")) + self.assertEqual(any(Path(arg).name == "sbsa.json" for arg in command), + baseline) + requirement = "Mandatory" if baseline or retained else "Recommended" + destination.write_text( + json.dumps({ + "Suite_Name: acs_info": { + "ACS Results Summary": { + "Suite_Name: " + requirement + " : SBSA_compliance": + "Compliant" if baseline else + "Not Compliant: not run" if retained else "Not Run", + "Overall Compliance Result": + "Not Compliant" if retained and not baseline else "Compliant" + } + } + })) + return subprocess.CompletedProcess(command, 0, "merged") + + ctx.run = mock.Mock(side_effect=merge) + with patch.object(probes, "conditional_execution_cases", return_value=[case]), \ + patch.object(probes, "invoke", return_value=control): + probes.run_conditional_execution(ctx, self.registry()) + self.assertEqual(ctx.run.call_count, 2) + self.assertEqual([(item.check_id, item.status) for item in ctx.findings], [ + ("raw.conditional-control", "PASS"), ("raw.conditional-execution", verdict)]) + self.assertEqual({path: path.read_bytes() for path in originals}, originals) + manifest = json.loads( + (ctx.case_dir("conditional/SR/SBSA") / "scenario.json").read_text()) + self.assertEqual(manifest["withheld_json"], "sbsa.json") + self.assertEqual(manifest["executed_suite"], "SBSA") + self.assertEqual(manifest["expected_overall"], "not_compliant") + self.assertIn("direct-merger", manifest["scope"]) + self.assertIn("bypasses that safeguard", manifest["scope"]) + self.assertIn("normal-flow conversion failure not tested", ctx.findings[-1].actual) + + def test_conditional_probe_blocks_unrelated_baseline_or_omission_failures(self): + """Check conditional probe blocks unrelated baseline or omission failures.""" + for break_at, calls in (("merge-baseline", 1), ("merge-withheld-json", 2)): + with self.subTest(break_at=break_at), tempfile.TemporaryDirectory() as directory: + control, case = self.control(directory) + ctx = Context(doctor.BASE_DIR, Path(directory) / "doctor", modes=("SR",)) + registry = {**self.registry(), "FWTS": { + **suite("FWTS", "M", "SR"), "json_output": "fwts.json"}} + + def merge(command, folder, name): + """Model an unrelated failure in either comparison report.""" + broken = name == break_at + baseline = name == "merge-baseline" + Path(command[5]).write_text( + json.dumps({ + "Suite_Name: acs_info": { + "ACS Results Summary": { + "Suite_Name: Mandatory : SBSA_compliance": + "Compliant" if baseline else "Not Compliant: not run", + "Suite_Name: Mandatory : SBBR-FWTS_compliance": + "Not Compliant" if broken else "Compliant", + "Overall Compliance Result": + "Not Compliant" if broken or not baseline else "Compliant" + } + } + })) + return subprocess.CompletedProcess(command, 0, "merged") + + ctx.run = mock.Mock(side_effect=merge) + with patch.object(probes, "conditional_execution_cases", return_value=[case]), \ + patch.object(probes, "invoke", return_value=control): + probes.run_conditional_execution(ctx, registry) + self.assertEqual(ctx.run.call_count, calls) + self.assertEqual([(item.check_id, item.status) for item in ctx.findings], [ + ("raw.conditional-control", "PASS"), ("raw.conditional-execution", "BLOCKED")]) + + +class ProbeTests(unittest.TestCase): + """Verify that bad input, crashes and missing evidence never look like success.""" + + def test_new_bad_input_jobs_cover_each_requested_route_and_all_four_cases(self): + """Check new bad input jobs cover each requested route and all four cases.""" + wanted = {("DT", name) for name in ( + "DTB-ALIGNMENT", "NETWORK-BOOT", "OS-TESTS", "PFDI", "POST-SCRIPT", + "PSCI", "RESERVED-MEMORY-MAP", "SCMI", "SMBIOS", "DT-KSELFTEST", "RUNTIME-DEV-MAP")} + wanted.update({("SR", "OS-TESTS"), ("SR", "PCIE-OPTION-ROM-ARCH-AUDIT")}) + jobs = probes.additional_raw_jobs(("DT", "SR")) + self.assertEqual({tuple(job[:2]) for job in jobs}, wanted) + self.assertEqual(len(jobs), len(wanted), "A duplicate route must not inflate coverage") + for mode, name, relative, complete, broken, _counts in jobs: + with self.subTest(mode=mode, suite=name): + self.assertEqual({case[0] for case in broken}, { + "empty-log", "header-only", "truncated-log", "malformed-log"}) + self.assertEqual(len(broken), 4) + self.assertTrue(complete) + empty = next(content for kind, content, _ in broken if kind == "empty-log") + self.assertTrue(all(not text for text in empty.values()) if isinstance(empty, dict) + else not empty) + for kind, content, caveat in broken: + self.assertNotEqual(content, complete, + kind + " must actually alter the native input") + self.assertFalse(caveat, "Known missing checks must not be silently downgraded") + if isinstance(complete, dict): + self.assertIsNone(relative) + self.assertTrue(all(isinstance(value, str) for value in complete.values())) + else: + self.assertIsInstance(relative, str) + + def test_new_bad_input_jobs_respect_selected_modes(self): + """Check new bad input jobs respect selected modes.""" + dt = probes.additional_raw_jobs(("DT",)) + sr = probes.additional_raw_jobs(("SR",)) + self.assertEqual(len(dt), 11) + self.assertEqual(len(sr), 2) + self.assertTrue(all(job[0] == "DT" for job in dt)) + self.assertTrue(all(job[0] == "SR" for job in sr)) + self.assertNotIn("PCIE-OPTION-ROM-ARCH-AUDIT", {job[1] for job in dt}) + self.assertEqual(probes.additional_raw_jobs(()), []) + + def test_psci_header_only_is_a_capture_compatible_kernel_introduction(self): + """Check psci header only is a capture compatible kernel introduction.""" + job = next(job for job in probes.additional_raw_jobs(("DT",)) if job[1] == "PSCI") + self.assertEqual(job[2], "linux_tools/psci/psci_kernel.log") + header = next(content for name, content, _ in job[4] if name == "header-only") + self.assertEqual(header, "psci: probing for conduit method from DT.\n") + producer = (Path(__file__).resolve().parents[2] / "SystemReady-devicetree-band" / + "Yocto/meta-woden/recipes-acs/install-files/files/init.sh").read_text() + self.assertIn("dmesg | grep psci >", producer) + self.assertTrue(all("psci" in line for line in header.splitlines())) + self.assertNotIn("PSCIv", header) + self.assertNotIn("Booting Linux kernel", header) + + def test_raw_group_reports_scheduled_but_unevaluated_cases_as_missing_coverage(self): + """Check raw group reports scheduled but unevaluated cases as missing coverage.""" + with tempfile.TemporaryDirectory() as directory: + ctx = Context(doctor.BASE_DIR, directory) + with patch.object(probes, "html_capability", return_value=False), \ + patch.object(probes, "run_conditional_execution"), \ + patch.object(probes, "family", return_value=set()) as family, \ + patch.object(probes, "waiver_probe"), \ + patch.object(probes, "waiver_idempotence"), \ + patch.object(probes, "stale_rerun"): + probes.run_raw(ctx) + self.assertTrue(family.called) + coverage = {item.mode: item for item in ctx.findings if item.check_id == "raw.coverage"} + self.assertEqual(set(coverage), {"DT", "SR"}) + for mode, suite, *_ in probes.additional_raw_jobs(("DT", "SR")): + self.assertEqual(coverage[mode].status, "WARN") + self.assertIn(suite + ": empty-log, header-only, malformed-log, truncated-log", + coverage[mode].actual) + self.assertFalse(any(item.status == "PASS" for item in ctx.findings)) + + def test_bad_input_control_failure_cannot_claim_negative_coverage(self): + """Check bad input control failure cannot claim negative coverage.""" + broken = [("empty-log", "", ""), ("header-only", "Introduction\n", "")] + for change in ({"exit": 5}, {"counts": {"passed": 0, "failed": 0, "failed_with_waiver": 0}}, + {"status": None}, {"status": "Not Run"}): + with self.subTest(change=change), tempfile.TemporaryDirectory() as directory: + ctx = Context(directory, directory) + actual = {**self.observation(), "html_failed": 0, "evidence": [], **change} + with patch.object(probes, "invoke", return_value=actual) as invoke: + executed = probes.family(ctx, {}, "DT", "PFDI", "uefi/pfdiresults.log", + "complete", broken, html_available=False) + self.assertEqual(executed, set()) + self.assertEqual(invoke.call_count, 1) + self.assertEqual([(item.check_id, item.status) for item in ctx.findings], [ + ("raw.positive", "BLOCKED"), ("raw.incomplete.coverage", "BLOCKED")]) + + def test_bad_input_coverage_counts_only_evaluated_not_blocked_cases(self): + """Check bad input coverage counts only evaluated not blocked cases.""" + positive = {**self.observation(), "html_failed": 0, "evidence": []} + rejected = {**positive, "exit": 5, "status": None, "html_status": None} + observations = [ + positive, { + **positive, "exit": 3 + }, { + **positive, "exit": 4 + }, rejected, positive + ] + broken = [(name, name, "") for name in ( + "empty-log", "header-only", "truncated-log", "malformed-log")] + with tempfile.TemporaryDirectory() as directory: + ctx = Context(directory, directory) + with patch.object(probes, "invoke", side_effect=observations): + executed = probes.family(ctx, {}, "DT", "PFDI", "uefi/pfdiresults.log", + "complete", broken, html_available=False) + self.assertEqual(executed, {"truncated-log", "malformed-log"}) + results = {item.check_id: item.status for item in ctx.findings} + self.assertEqual(results["raw.empty-log"], "BLOCKED") + self.assertEqual(results["raw.header-only"], "BLOCKED") + self.assertEqual(results["raw.truncated-log"], "PASS") + self.assertEqual(results["raw.malformed-log"], "FAIL") + + def test_zero_negative_cases_cannot_claim_bad_input_coverage(self): + """Check zero negative cases cannot claim bad input coverage.""" + with tempfile.TemporaryDirectory() as directory: + ctx = Context(directory, directory) + actual = {**self.observation(), "html_failed": 0, "evidence": []} + with patch.object(probes, "invoke", return_value=actual) as invoke: + executed = probes.family(ctx, {}, "DT", "PFDI", "uefi/pfdiresults.log", + "complete", [], html_available=False) + self.assertEqual(executed, set()) + self.assertEqual(invoke.call_count, 1) + self.assertFalse(any(item.check_id != "raw.positive" for item in ctx.findings)) + + def test_completed_failure_control_requires_exact_counts_and_non_green_status(self): + """Check completed failure control requires exact counts and non green status.""" + expected_counts = {**probes.counts({}), "failed": 1} + complete = {**self.observation(), "status": "Not Compliant", "html_status": "Not Compliant", + "counts": dict(expected_counts), "html_failed": 1, "evidence": []} + for changed, expected_coverage in ( + ({}, {"empty-log"}), ({"status": "Compliant"}, set()), + ({"status": "UNKNOWN"}, set()), ({"status": "Not Run"}, set()), + ({"status": "Not Compliant (Not Run)"}, set()), + ({"counts": {**expected_counts, "failed": 0}}, set()), + ({"counts": {**expected_counts, "failed": 2}}, set()), + ({"counts": {**expected_counts, "skipped": 1}}, set()), + ({"counts": {**expected_counts, "failed_with_waiver": 1}}, set()), + ({"counts": {**expected_counts, "aborted": 1}}, set()), + ({"exit": 5}, set())): + with self.subTest(changed=changed), tempfile.TemporaryDirectory() as directory: + ctx = Context(directory, directory) + observations = [{**complete, **changed}, + {**complete, "exit": 5, "status": None, "html_status": None}] + with patch.object(probes, "invoke", side_effect=observations): + executed = probes.family(ctx, {}, "DT", "POST-SCRIPT", "post-script/log.txt", + "A complete recorded failure", [("empty-log", "", "")], + control_counts=expected_counts, html_available=False) + self.assertEqual(executed, expected_coverage) + self.assertEqual(ctx.findings[0].status, "PASS" if expected_coverage else "BLOCKED") + + def test_multiple_input_files_are_forwarded_without_changing_controls(self): + """Check multiple input files are forwarded without changing controls.""" + complete = {"../os-logs/install.log": "Installation: PASSED\n", + "../os-logs/runtime/check.log": "Runtime check: PASSED\n"} + incomplete = {"../os-logs/install.log": "Installation: PASSED\n", + "../os-logs/runtime/check.log": "Runtime check started\n"} + before = deepcopy((complete, incomplete)) + actual = {**self.observation(), "html_failed": 0, "evidence": []} + with tempfile.TemporaryDirectory() as directory: + ctx = Context(directory, directory) + rejected = {**actual, "exit": 5, "status": None, "html_status": None} + with patch.object(probes, "invoke", side_effect=[actual, rejected]) as invoke: + executed = probes.family(ctx, {}, "SR", "OS-TESTS", None, complete, + [("truncated-log", incomplete, "")], html_available=False) + self.assertEqual(executed, {"truncated-log"}) + self.assertEqual(invoke.call_args_list[0].args[5], complete) + self.assertEqual(invoke.call_args_list[1].args[5], incomplete) + self.assertEqual((complete, incomplete), before) + + def test_generated_probe_inputs_stay_inside_own_case_directory(self): + """Check generated probe inputs stay inside own case directory.""" + with tempfile.TemporaryDirectory() as directory: + ctx = Context(directory, Path(directory) / "output") + files = {"linux_tools/nested/check.log": "result\n", + "../os-logs/setup.log": "setup\n"} + before = deepcopy(files) + ctx.run = mock.Mock(return_value=subprocess.CompletedProcess([], 0, "done")) + with patch.object(probes, "observe", return_value={}) as observe: + probes.invoke(ctx, {}, "SR", "OS-TESTS", "safe-multifile", files) + base = ctx.case_dir("raw/SR/OS-TESTS/safe-multifile") + self.assertEqual((base / "input/acs_results/linux_tools/nested/check.log").read_text(), + "result\n") + self.assertEqual((base / "input/os-logs/setup.log").read_text(), "setup\n") + self.assertEqual(files, before) + observe.assert_called_once() + # A log path may name a sibling OS folder, but never escape the + # disposable case into another job, the repository or real logs. + with self.assertRaisesRegex(ValueError, "escaped"): + probes.invoke(ctx, {}, "SR", "OS-TESTS", "unsafe-multifile", + {"../../../outside.log": "must not be written"}) + self.assertFalse((Path(directory) / "outside.log").exists()) + + def observation(self): + """Start with one passing result that each test can change deliberately.""" + return {"exit": 0, "status": "Compliant", "html_status": "Compliant", + "counts": {"passed": 1, "failed": 0, "failed_with_waiver": 0}, + "traceback": False} + + def test_compliant_is_not_substring_match(self): + """Check compliant is not substring match.""" + self.assertTrue(probes.green("Compliant (with waivers)")) + for status in (None, "Not Compliant", "Not Compliant (Not Run)", "Not Run"): + self.assertFalse(probes.green(status)) + + def test_positive_control_requires_real_passed_outcome(self): + """Check positive control requires real passed outcome.""" + actual = self.observation() + self.assertTrue(probes.control_ok(actual)) + actual["counts"]["passed"] = 0 + self.assertFalse(probes.control_ok(actual)) + + def test_positive_control_requires_both_json_and_html(self): + """Check positive control requires both JSON and HTML.""" + actual = self.observation() + actual["html_status"] = None + self.assertFalse(probes.control_ok(actual)) + actual["html_status"] = "Not Compliant" + self.assertFalse(probes.control_ok(actual)) + + def test_positive_control_rejects_invented_waiver(self): + """Check positive control rejects invented waiver.""" + actual = self.observation() + actual["counts"]["failed_with_waiver"] = 1 + self.assertFalse(probes.control_ok(actual)) + + def test_incomplete_green_is_failure(self): + """Check incomplete green is failure.""" + self.assertEqual(probes.invalid_verdict(self.observation()), "FAIL") + + def test_incomplete_non_green_is_safe(self): + """Check incomplete non green is safe.""" + actual = self.observation() + actual.update(status="Not Compliant (Not Run)", html_status="Not Compliant (Not Run)") + self.assertEqual(probes.invalid_verdict(actual), "PASS") + + def test_json_html_disagreement_is_failure(self): + """Check JSON HTML disagreement is failure.""" + actual = self.observation() + actual["status"] = "Not Compliant" + self.assertEqual(probes.invalid_verdict(actual), "FAIL") + + def test_rejected_input_is_not_confused_with_crash(self): + """Check rejected input is not confused with crash.""" + actual = self.observation() + actual.update(exit=5, status=None, html_status=None) + self.assertEqual(probes.invalid_verdict(actual), "PASS") + actual["traceback"] = True + self.assertEqual(probes.invalid_verdict(actual), "FAIL") + + def test_rejected_input_cannot_hide_published_green_artifacts(self): + """Check rejected input cannot hide published green artifacts.""" + for changed in ({"status": "Compliant", "html_status": None}, + {"status": None, "html_status": "Compliant"}, + {"status": "Compliant", "html_status": "Compliant"}): + with self.subTest(changed=changed): + actual = {**self.observation(), "exit": 5, **changed} + self.assertEqual(probes.invalid_verdict(actual), "FAIL") + + def test_empty_log_needs_not_run_without_invented_results(self): + """Check empty log needs not run without invented results.""" + positive = {**self.observation(), "html_failed": 0, "evidence": []} + zero_counts = probes.counts({}) + empty = {**positive, "status": "Not Run", "html_status": None, + "counts": zero_counts} + cases = [({}, "PASS"), ({"status": "Not Compliant (Not Run)"}, "PASS"), + ({"status": "Not Compliant: not run"}, "PASS"), + ({"status": "Not Compliant"}, "FAIL"), ({"status": None}, "FAIL"), + ({"exit": 5, "status": None}, "FAIL"), + ({"exit": 5, "status": "Not Compliant", + "counts": {**zero_counts, "failed": 1}}, "FAIL")] + cases.extend(({"counts": {**zero_counts, counter: 1}}, "FAIL") for counter in zero_counts) + for changed, wanted in cases: + for name in ("empty-log", "header-only"): + with self.subTest(case=name, + changed=changed), tempfile.TemporaryDirectory() as directory: + ctx = Context(directory, directory) + with patch.object(probes, + "invoke", + side_effect=[positive, { + **empty, + **changed + }]): + executed = probes.family(ctx, {}, "DT", "PFDI", "uefi/pfdiresults.log", + "complete", [(name, "", "")], html_available=False) + self.assertEqual(executed, {name}) + self.assertEqual(ctx.findings[-1].status, wanted) + self.assertEqual(ctx.findings[-1].expected, + "Publish Not Run with zero executed outcomes") + + def test_empty_verdict_cannot_accept_nonzero_exit_or_crash(self): + """Check empty verdict cannot accept nonzero exit or crash.""" + empty = {**self.observation(), "status": "Not Run", "html_status": None, + "counts": probes.counts({})} + for changed in ({"exit": 1}, {"exit": 5}, {"exit": -11}, {"traceback": True}, + {"exit": 5, "traceback": True}, {"html_status": "Compliant"}): + with self.subTest(changed=changed): + self.assertEqual(probes.empty_verdict({**empty, **changed}), "FAIL") + + def test_empty_verdict_keeps_missing_prerequisites_blocked(self): + """Check empty verdict keeps missing prerequisites blocked.""" + for code in (3, 4): + for counter in (None, *probes.counts({})): + with self.subTest(exit=code, counter=counter): + actual = {**self.observation(), "exit": code, "status": None, + "html_status": None, "counts": probes.counts({})} + if counter: + actual["counts"][counter] = 1 + self.assertEqual(probes.empty_verdict(actual), "BLOCKED") + + def test_empty_verdict_rejects_every_invented_outcome_even_on_rejection(self): + """Check empty verdict rejects every invented outcome even on rejection.""" + for code in (0, 5): + for counter in probes.counts({}): + with self.subTest(exit=code, counter=counter): + actual = {**self.observation(), "exit": code, "status": "Not Run", + "html_status": None, "counts": {**probes.counts({}), counter: 1}} + self.assertEqual(probes.empty_verdict(actual), "FAIL") + + def test_missing_dependencies_or_invalid_fixture_are_blocked(self): + """Check missing dependencies or invalid fixture are blocked.""" + for code in (3, 4): + actual = self.observation() + actual["exit"] = code + self.assertEqual(probes.invalid_verdict(actual), "BLOCKED") + + def test_missing_artifacts_cannot_pass(self): + """Check missing artifacts cannot pass.""" + for field in ("status", "html_status"): + actual = self.observation() + actual.update(status="Not Run", html_status="Not Run") + actual[field] = None + self.assertEqual(probes.invalid_verdict(actual), "BLOCKED") + # When the other artifact is actually green, that is already evidence + # of the defect, even if its partner artifact is missing. + for field in ("status", "html_status"): + actual = self.observation() + actual[field] = None + self.assertEqual(probes.invalid_verdict(actual), "FAIL") + + def test_parent_only_fixture_keeps_failures_not_subtests(self): + """Check parent only fixture keeps failures not subtests.""" + complete = probes.sct_log(failed=True) + parent_only = probes.sct_log(failed=True, parent_only=True) + self.assertEqual(parent_only.count(": [FAIL]"), 2) + self.assertNotIn(" -- FAIL", parent_only) + self.assertEqual(complete.count(" -- FAIL"), 2) + + def test_fwts_fixture_preserves_assertion_multiplicity(self): + """Check FWTS fixture preserves assertion multiplicity.""" + text = probes.fwts_log(failed=2) + self.assertEqual(text.count("FAILED: Test 1"), 2) + self.assertIn("0 passed, 2 failed", text) + + def test_robot_unknown_and_missing_are_distinct(self): + """Check robot unknown and missing are distinct.""" + self.assertNotIn("BSA' + 'RecommendedNot Compliant' + '
Failed2
') + self.assertEqual(html.tables[0]["rows"], [["BSA", "Recommended", "Not Compliant"]]) + self.assertEqual(html.tables[1]["rows"], [["Failed", "2"]]) + + def test_mode_aware_suite_status(self): + """Check mode aware suite status.""" + registry = {"SCT": {"requirement_key": "SCT"}} + merged = {"Suite_Name: acs_info": {"ACS Results Summary": { + "Suite_Name: Mandatory : EBBR-SCT_compliance": "Not Compliant", + "Suite_Name: Mandatory : SBBR-SCT_compliance": "Compliant"}}} + self.assertEqual(probes.suite_status(merged, "SCT", "DT", registry), "Not Compliant") + self.assertEqual(probes.suite_status(merged, "SCT", "SR", registry), "Compliant") + + def test_json_positive_control_does_not_depend_on_new_html_layout(self): + """Check JSON positive control does not depend on new HTML layout.""" + actual = self.observation() + actual["html_status"] = None + self.assertTrue(probes.control_ok(actual, require_html=False)) + self.assertEqual(probes.invalid_verdict(actual, require_html=False), "FAIL") + actual["status"] = "Not Compliant (Not Run)" + self.assertEqual(probes.invalid_verdict(actual, require_html=False), "PASS") + actual["status"] = None + self.assertEqual(probes.invalid_verdict(actual, require_html=False), "BLOCKED") + + def test_missing_html_does_not_suppress_malformed_log_case(self): + """Check missing HTML does not suppress malformed log case.""" + actual = {**self.observation(), "html_status": None, "html_failed": 0, "evidence": []} + with tempfile.TemporaryDirectory() as directory: + ctx = Context(directory, directory) + with patch.object(probes, "invoke", return_value=actual) as invoke: + probes.family(ctx, {}, "DT", "BSA", "bsa.log", "good", + [("empty-log", "", "")], html_available=False) + self.assertEqual(invoke.call_count, 2) + self.assertEqual([(item.check_id, item.status) for item in ctx.findings], + [("raw.positive", "PASS"), ("raw.empty-log", "FAIL")]) + + def test_supported_but_missing_html_is_failure_and_raw_checks_continue(self): + """Check supported but missing HTML is failure and raw checks continue.""" + actual = {**self.observation(), "html_status": None, "html_failed": 0, "evidence": []} + with tempfile.TemporaryDirectory() as directory: + ctx = Context(directory, directory) + with patch.object(probes, "invoke", return_value=actual) as invoke: + probes.family(ctx, {}, "DT", "BSA", "bsa.log", "good", [("empty-log", "", "")]) + self.assertEqual(invoke.call_count, 2) + self.assertEqual([(item.check_id, item.status) for item in ctx.findings], + [("raw.positive", "PASS"), ("raw.html-compliance", "FAIL"), + ("raw.empty-log", "FAIL"), ("raw.html-compliance", "FAIL")]) + + def test_waiver_json_checks_do_not_require_new_html_layout(self): + """Check waiver JSON checks do not require new HTML layout.""" + actual = {**self.observation(), "html_status": None, "html_failed": 0, "evidence": []} + expected = ({ + "passed": 1, + "failed": 0 + }, { + "passed": 1, + "failed": 0 + }, "Unmatched waiver is inert") + with tempfile.TemporaryDirectory() as directory: + ctx = Context(directory, directory) + with patch.object(probes, "invoke", return_value=actual): + probes.waiver_probe(ctx, {}, "DT-KSELFTEST", "test.log", "pass", {}, + "unmatched", expected, html_available=False) + self.assertEqual([(item.check_id, item.status) for item in ctx.findings], + [("waiver.unmatched", "PASS")]) + + def test_raw_html_capability_absent_is_one_blocked_check(self): + """Check raw HTML capability absent is one blocked check.""" + with tempfile.TemporaryDirectory() as directory: + ctx = Context(directory, directory) + source = Path(directory) / "generate_acs_summary.py" + source.write_text("def legacy_report():\n pass\n", encoding="utf-8") + self.assertFalse(probes.html_capability(ctx)) + self.assertEqual(len(ctx.findings), 1) + self.assertEqual(ctx.findings[0].check_id, "raw.html-capability") + self.assertEqual(ctx.findings[0].status, "BLOCKED") + source.write_text("def _summary_cards():\n raise RuntimeError('broken')\n" + "def inject_detail_compliance():\n pass\n", encoding="utf-8") + self.assertTrue(probes.html_capability(ctx)) + # Present functions are not certified correct by source detection: + # render failures/missing tables must still fail the per-report check. + self.assertEqual(len(ctx.findings), 1) + + +# When category metadata is required, and how its supplied file is recorded. + +class SchemaPolicyTests(unittest.TestCase): + """Check category-specific schema rules without changing the saved schema.""" + + def setUp(self): + temporary = tempfile.TemporaryDirectory(prefix="doctor_category_policy_") + self.addCleanup(temporary.cleanup) + self.base = Path(temporary.name) + self.schema = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "definitions": { + "metadata": { + "type": "object", + "required": ["Main Readiness Grouping", "SRS scope", "Waivable"], + "properties": { + "Main Readiness Grouping": { + "type": "string" + }, + "SRS scope": { + "type": "string" + }, + "Waivable": { + "type": "string" + }, + "Test_suite_info": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "entry": { + "allOf": [{ + "$ref": "#/definitions/metadata" + }, { + "required": ["Test_suite", "Test_suite_info"], + "properties": { + "Test_suite": { + "type": "string", + "not": { + "const": "Unknown" + } + } + } + }], + "unevaluatedProperties": + False + }, + "raw": { + "type": "object", + "required": ["test_results"], + "properties": { + "test_results": { + "type": "array", + "items": { + "$ref": "#/definitions/entry" + } + } + }, + "unevaluatedProperties": False + } + }, + "properties": { + "Suite_Name: BSA": { + "$ref": "#/definitions/raw" + } + } + } + self.path = self.base / "schema.json" + self.path.write_text(json.dumps(self.schema)) + self.entry = {"Test_suite": "PE", "Main Readiness Grouping": "physical", + "SRS scope": "Mandatory", "Waivable": "no"} + + def evaluate(self, source="bundled", entry=None, merged=False): + """Check a raw or merged sample and verify both inputs stay unchanged.""" + raw = {"test_results": [self.entry if entry is None else entry]} + data = {"Suite_Name: BSA": raw} if merged else raw + before = deepcopy(data) + digest = hashlib.sha256(self.path.read_bytes()).hexdigest() + result = policy.evaluate_schema(self.path, "" if merged else "#/definitions/raw", data, + {"source": source}) + self.assertEqual(before, data) + self.assertEqual(digest, hashlib.sha256(self.path.read_bytes()).hexdigest()) + return result + + def test_bundled_and_legacy_omit_only_missing_info_and_its_cascades(self): + """Check bundled and legacy omit only missing info and its cascades.""" + for source in ("bundled", "unknown"): + for merged in (False, True): + with self.subTest(source=source, merged=merged): + result = self.evaluate(source, merged=merged) + self.assertEqual([], result["errors"]) + self.assertGreater(result["strict_error_count"], 1) + self.assertEqual(1, len(result["omitted_missing_info_paths"])) + + def test_explicit_missing_info_stays_required_even_without_description(self): + """Check explicit missing info stays required even without description.""" + result = self.evaluate("explicit") + self.assertTrue( + any(error["validator"] == "required" and "Test_suite_info" in error["message"] + for error in result["errors"])) + self.assertEqual([], result["omitted_missing_info_paths"]) + + def test_info_present_is_always_validated(self): + """Check info present is always validated.""" + for value in (None, "not a list", 1, {}, [True]): + for source in ("explicit", "bundled", "unknown"): + with self.subTest(value=value, source=source): + result = self.evaluate(source, dict(self.entry, Test_suite_info=value)) + self.assertTrue(any(error["validator"] == "type" for error in result["errors"])) + self.assertEqual([], + self.evaluate("explicit", + dict(self.entry, + Test_suite_info=["PE information"]))["errors"]) + + def test_other_required_fields_unknown_suite_and_unknown_properties_still_fail(self): + """Check other required fields unknown suite and unknown properties still fail.""" + for field in ("Main Readiness Grouping", "SRS scope", "Waivable"): + row = deepcopy(self.entry) + del row[field] + result = self.evaluate(entry=row) + self.assertTrue( + any(error["validator"] == "required" and field in error["message"] + for error in result["errors"])) + result = self.evaluate(entry=dict(self.entry, Test_suite="Unknown")) + self.assertTrue(any(error["validator"] == "not" for error in result["errors"])) + result = self.evaluate(entry=dict(self.entry, unexpected="real extra field")) + self.assertTrue( + any(error["validator"] == "unevaluatedProperties" and "unexpected" in error["message"] + for error in result["errors"])) + + def test_only_schema_required_lists_are_changed(self): + """Check only schema required lists are changed.""" + schema = {"required": ["Test_suite_info", "other"], + "const": {"required": ["Test_suite_info"]}, + "default": {"required": ["Test_suite_info"]}, + "examples": [{"required": ["Test_suite_info"]}]} + original = deepcopy(schema) + effective = policy.applicable_schema(schema) + self.assertEqual(["other"], effective["required"]) + for key in ("const", "default", "examples"): + self.assertEqual(schema[key], effective[key]) + self.assertEqual(original, schema) + + +class CategoryProvenanceTests(unittest.TestCase): + """Check the record of which category file a report actually used.""" + + def setUp(self): + temporary = tempfile.TemporaryDirectory(prefix="doctor_category_provenance_") + self.addCleanup(temporary.cleanup) + self.base = Path(temporary.name) + self.report = self.base / "report" + self.report.mkdir() + self.source = self.base / "supplied.json" + self.source.write_text('{"category":[{"Suite":"BSA","Test Suite":"PE"}]}') + + def record(self, explicit=True): + """Record a supplied category file or the use of bundled defaults.""" + return record_category_provenance( + self.report, + SimpleNamespace(mode="SR", test_category=str(self.source) if explicit else None), + self.source) + + def test_explicit_snapshot_is_consumed_and_bound_to_mode_and_digest(self): + """Check explicit snapshot is consumed and bound to mode and digest.""" + original = self.source.read_bytes() + effective = self.record() + self.assertNotEqual(self.source, effective) + self.assertEqual(original, effective.read_bytes()) + self.assertEqual(original, self.source.read_bytes()) + self.source.write_text('{"changed_after_snapshot":true}') + self.assertEqual(original, effective.read_bytes()) + provenance = policy.category_provenance(self.report, "SR") + self.assertEqual("explicit", provenance["source"]) + self.assertFalse(provenance["invalid"]) + self.assertEqual(hashlib.sha256(original).hexdigest(), provenance["sha256"]) + + def test_bundled_is_explicitly_recorded_without_guessing(self): + """Check bundled is explicitly recorded without guessing.""" + self.assertEqual(self.source, self.record(explicit=False)) + self.assertEqual("bundled", policy.category_provenance(self.report, "SR")["source"]) + self.assertFalse((self.report / "config/test_category.json").exists()) + + def test_legacy_category_filename_does_not_prove_it_was_used(self): + """Check legacy category filename does not prove it was used.""" + (self.report / "test_category.json").write_text(self.source.read_text()) + provenance = policy.category_provenance(self.report, "SR") + self.assertEqual("unknown", provenance["source"]) + self.assertFalse(provenance["invalid"]) + + def test_tampered_hash_mode_missing_snapshot_and_bad_manifest_are_invalid(self): + """Check tampered hash mode missing snapshot and bad manifest are invalid.""" + effective = self.record() + self.assertTrue(policy.category_provenance(self.report, "DT")["invalid"]) + effective.write_text('{"tampered":true}') + self.assertIn("SHA-256 does not match", + policy.category_provenance(self.report, "SR")["message"]) + effective.unlink() + self.assertTrue(policy.category_provenance(self.report, "SR")["invalid"]) + (self.report / policy.MANIFEST).write_text('{"mode":"SR","mode":"DT"}') + self.assertTrue(policy.category_provenance(self.report, "SR")["invalid"]) + + def test_escaping_manifest_and_snapshot_paths_are_not_read(self): + """Check escaping manifest and snapshot paths are not read.""" + self.record() + manifest_path = self.report / policy.MANIFEST + manifest = json.loads(manifest_path.read_text()) + for path in ("../supplied.json", str(self.source)): + manifest["test_category"]["path"] = path + manifest_path.write_text(json.dumps(manifest)) + self.assertTrue(policy.category_provenance(self.report, "SR")["invalid"]) + snapshot = self.report / "config/external.json" + snapshot.symlink_to(self.source) + manifest["test_category"]["path"] = "config/external.json" + manifest_path.write_text(json.dumps(manifest)) + self.assertIn("escapes", policy.category_provenance(self.report, "SR")["message"]) + manifest_path.unlink() + manifest_path.symlink_to(self.source) + self.assertIn("escapes", policy.category_provenance(self.report, "SR")["message"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/common/acs_test_framework_runner/test_doctor_report.py b/common/acs_test_framework_runner/test_doctor_report.py new file mode 100644 index 00000000..7e2d11fa --- /dev/null +++ b/common/acs_test_framework_runner/test_doctor_report.py @@ -0,0 +1,2280 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026, Arm Limited or its affiliates. All rights reserved. +# SPDX-License-Identifier : Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Test Doctor's explanations, HTML report and checks of saved JSON, HTML and PDF. + +These tests check Doctor, not the separate production parser fixes. Small +temporary reports include correct examples and deliberate errors. Fake browser +and PDF responses test Doctor's decisions without requiring those tools here; +real browser and PDF checks belong to Doctor's optional visual check group. +""" + +from collections import Counter +from copy import deepcopy +from html.parser import HTMLParser +from pathlib import Path +from unittest import mock +from unittest.mock import patch +import hashlib +import json +import shutil +import subprocess +import sys +import tempfile +import unittest + +# Import Doctor from this checkout, not an installed or neighbouring copy. +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "log_parser")) +from doctor_checks.core import Context, Finding +from doctor_checks.report import describe_finding, describe_group, render_html +from doctor_checks import artifacts as doctor_artifacts, artifacts as visual + + +# Report structure, readable explanations and safe display of untrusted text. + +class Page(HTMLParser): + """Read report text and marked elements without a browser or JavaScript.""" + + def __init__(self, source): + """Parse one report and collect its visible text and elements.""" + super().__init__(convert_charrefs=True) + self.elements = [] + self.nodes = [] + self.stack = [] + self.text = [] + self.hidden_text_depth = 0 + self.feed(source) + self.close() + + def handle_starttag(self, tag, attrs): + """Record the element and its position in the parent stack.""" + attributes = dict(attrs) + self.elements.append((tag, attributes)) + node = {"tag": tag, "attrs": attributes, + "ancestors": tuple(self.stack), "text": []} + self.nodes.append(node) + # Remember parent elements so tests can tell visible text from folded details. + if tag not in {"area", "base", "br", "col", "embed", "hr", "img", "input", + "link", "meta", "param", "source", "track", "wbr"}: + self.stack.append(node) + if tag in {"script", "style"}: + self.hidden_text_depth += 1 + + def handle_endtag(self, tag): + """Close the matching element and restore its parent context.""" + if tag in {"script", "style"}: + self.hidden_text_depth -= 1 + for index in range(len(self.stack) - 1, -1, -1): + if self.stack[index]["tag"] == tag: + del self.stack[index:] + break + + def handle_data(self, text): + """Keep visible text without treating script or style text as results.""" + if not self.hidden_text_depth: + self.text.append(text) + for node in self.stack: + node["text"].append(text) + + def with_class(self, name): + """Find elements by a CSS class used as a stable report marker.""" + return [(tag, attrs) for tag, attrs in self.elements + if name in attrs.get("class", "").split()] + + def with_id(self, identifier): + """Find elements by their unique report identifier.""" + return [(tag, attrs) for tag, attrs in self.elements if attrs.get("id") == identifier] + + def nodes_with_class(self, name): + """Find marked elements with their text and parent elements attached.""" + return [node for node in self.nodes if name in node["attrs"].get("class", "").split()] + + +class DoctorReportTests(unittest.TestCase): + """Check that the HTML report stays clear, complete and safe to open.""" + + def setUp(self): + self.temporary = tempfile.TemporaryDirectory(prefix="doctor_report_test_") + self.addCleanup(self.temporary.cleanup) + self.output = Path(self.temporary.name) + + @staticmethod + def finding(status="FAIL", check_id="MERGE_OVERALL_POLICY", **changes): + """Create one sample finding, with optional changes for each scenario.""" + values = dict(check_id=check_id, + status=status, + issue="Recommended failure blocks overall SRS", + expected="Suite Not Compliant; overall Compliant", + actual="Overall Not Compliant", + mode="DT", + suite="BSA", + evidence=[]) + values.update(changes) + return Finding(**values) + + def render(self, findings, **changes): + """Render a report in memory and return a helper for checking its HTML.""" + values = dict(metadata={"revision": "ff0cd1d1", "branch": "user/ashsha06/PJ03164-4164"}, + output_dir=self.output, status="FAIL", + counts=Counter(item.status for item in findings), + group_titles={(severity, "MERGE_OVERALL_POLICY"): + "Overall SRS compliance does not match the requirement policy" + for severity in ("FAIL", "WARN", "BLOCKED")}) + values.update(changes) + source = render_html(findings, **values) + return source, Page(source) + + def test_escapes_finding_metadata_and_attribute_values(self): + """Check escapes finding metadata and attribute values.""" + attack = '' + item = self.finding(issue=attack, expected="Expected & details", actual=attack, + mode='DT" onclick="alert(1)', suite=attack, + check_id='CHECK" autofocus="x') + source, page = self.render([item], metadata={"revision": attack, "branch": attack}) + self.assertIn("<img", source) + self.assertNotIn(attack, source) + self.assertTrue(all(tag != "img" for tag, _ in page.elements)) + self.assertTrue(all("onclick" not in attrs and "onerror" not in attrs + for _, attrs in page.elements)) + record = page.with_class("finding")[0][1] + self.assertEqual(item.mode, record["data-mode"]) + self.assertEqual(item.suite, record["data-suite"]) + self.assertEqual(item.check_id, record["data-check-id"]) + + def test_legacy_title_stays_searchable_and_severities_stay_separate(self): + """Check legacy title stays searchable and severities stay separate.""" + findings = [ + self.finding(issue="BSA failure"), + self.finding(issue="SCT incomplete input", suite="SCT"), + self.finding(status="BLOCKED", issue="Cannot inspect input", mode="SR") + ] + _, page = self.render(findings) + for _, attrs in page.with_class("finding"): + self.assertIn("overall srs compliance does not match the requirement policy", + attrs["data-search"]) + groups = page.with_class("finding-group") + self.assertEqual(2, len(groups)) + self.assertEqual({"FAIL", "BLOCKED"}, {attrs["data-severity"] for _, attrs in groups}) + self.assertEqual({"MERGE_OVERALL_POLICY"}, {attrs["data-check-id"] for _, attrs in groups}) + self.assertEqual(3, len(page.with_class("finding"))) + + def test_topic_explanations_are_visible_outside_collapsed_technical_details(self): + """Check topic explanations are visible outside collapsed technical details.""" + _, page = self.render([self.finding()]) + self.assertTrue(all(tag == "article" for tag, _ in page.with_class("finding-group"))) + explanations = page.nodes_with_class("group-explanation") + self.assertEqual(1, len(explanations)) + for explanation in explanations: + self.assertEqual("dl", explanation["tag"]) + self.assertFalse(any(parent["tag"] == "details" for parent in explanation["ancestors"])) + text = " ".join(explanation["text"]) + for heading in ("What happened", "Why it matters", "Next step"): + self.assertIn(heading, text) + technical = page.with_class("group-checks") + self.assertEqual(1, len(technical)) + self.assertEqual("details", technical[0][0]) + self.assertNotIn("open", technical[0][1]) + for node in page.nodes_with_class("finding"): + self.assertEqual("details", node["tag"]) + self.assertTrue(any("group-checks" in parent["attrs"].get("class", "").split() + for parent in node["ancestors"])) + + def test_expected_and_actual_are_retained_in_separate_technical_panels(self): + """Check expected and actual are retained in separate technical panels.""" + item = self.finding(expected="Expected current-run failures: 2", + actual="Observed merged failures: 0") + _, page = self.render([item]) + self.assertEqual(2, len(page.with_class("comparison-panel"))) + text = " ".join(page.text) + self.assertIn(item.expected, text) + self.assertIn(item.actual, text) + self.assertTrue(any(tag == "h4" for tag, _ in page.elements)) + for node in page.nodes_with_class("comparison-panel"): + self.assertTrue(any(parent["tag"] == "details" for parent in node["ancestors"])) + + def test_schema_checks_share_a_topic_without_merging_assertions_or_severities(self): + """Check schema checks share a topic without merging assertions or severities.""" + findings = [self.finding(check_id="NATIVE_RAW_SCHEMA", suite="SCT"), + self.finding(check_id="ARTIFACT.SCHEMA", suite="FWTS"), + self.finding(check_id="ARTIFACT.SCHEMA", status="WARN", suite="SCT")] + _, page = self.render(findings) + groups = page.with_class("finding-group") + self.assertEqual(2, len(groups)) + failed = [attrs for _, attrs in groups if attrs["data-severity"] == "FAIL"] + self.assertEqual(1, len(failed)) + self.assertEqual({"NATIVE_RAW_SCHEMA", "ARTIFACT.SCHEMA"}, + set(failed[0]["data-check-id"].split())) + self.assertEqual("2", failed[0]["data-total"]) + self.assertEqual(Counter((item.status, item.check_id) for item in findings), + Counter((attrs["data-severity"], attrs["data-check-id"]) + for _, attrs in page.with_class("finding"))) + + def test_sbmr_missing_and_unknown_status_share_one_topic_with_four_original_checks(self): + """Check SBMR missing and unknown status share one topic with four original checks.""" + findings = [self.finding(check_id=check_id, suite=suite, mode="SR", + actual="exit=7; merged=None; HTML=None") + for check_id in ("raw.missing-status", "raw.unknown-status") + for suite in ("SBMR-IB", "SBMR-OOB")] + _, page = self.render(findings) + groups = page.with_class("finding-group") + self.assertEqual(1, len(groups)) + self.assertEqual("4", groups[0][1]["data-total"]) + self.assertEqual({"raw.missing-status", "raw.unknown-status"}, + set(groups[0][1]["data-check-id"].split())) + self.assertEqual(Counter((item.check_id, item.suite) for item in findings), + Counter((attrs["data-check-id"], attrs["data-suite"]) + for _, attrs in page.with_class("finding"))) + + def test_warnings_blocked_checks_and_package_rollups_have_separate_sections(self): + """Check warnings blocked checks and package rollups have separate sections.""" + findings = [self.finding(), self.finding(status="WARN", check_id="raw.coverage"), + self.finding(status="BLOCKED", check_id="VISUAL_BROWSER"), + self.finding(check_id="ARTIFACT.CONSISTENCY")] + _, page = self.render(findings) + locations = {} + for node in page.nodes_with_class("finding"): + sections = [ancestor["attrs"].get("id") for ancestor in node["ancestors"] + if "findings-section" in ancestor["attrs"].get("class", "").split()] + self.assertEqual(1, len(sections)) + locations[node["attrs"]["data-check-id"]] = sections[0] + self.assertEqual( + { + "MERGE_OVERALL_POLICY": "issues-section", + "raw.coverage": "warnings-section", + "VISUAL_BROWSER": "blocked-section", + "ARTIFACT.CONSISTENCY": "summaries-section" + }, locations) + + def test_original_fields_and_evidence_survive_topic_grouping(self): + """Check original fields and evidence survive topic grouping.""" + findings = [ + self.finding(check_id=check_id, + issue="Exact issue " + check_id, + expected="Expected \n" + check_id, + actual="Actual & mismatch\n" + check_id, + evidence=[str(self.output / "evidence" / (check_id + ".log"))]) + for check_id in ("NATIVE_RAW_SCHEMA", "ARTIFACT.SCHEMA", "ARTIFACT.CONSISTENCY", + "raw.missing-status", "raw.unknown-status", "UNREGISTERED.CHECK") + ] + _, page = self.render(findings) + records = { + node["attrs"]["data-check-id"]: node + for node in page.nodes_with_class("finding") + } + self.assertEqual(len(findings), len(records)) + for item in findings: + node = records[item.check_id] + text = "".join(node["text"]) + for value in (item.check_id, item.issue, item.expected, item.actual, + item.mode, item.suite, Path(item.evidence[0]).name): + with self.subTest(check=item.check_id, value=value): + self.assertIn(value, text) + self.assertEqual(item.status, node["attrs"]["data-severity"]) + self.assertEqual(item.mode, node["attrs"]["data-mode"]) + self.assertEqual(item.suite, node["attrs"]["data-suite"]) + + def test_affected_suites_are_unique_without_rewriting_original_suite_fields(self): + """Check affected suites are unique without rewriting original suite fields.""" + findings = [self.finding(check_id="HTML_COMPLIANCE_MATCH", suite=suite, mode="SR") + for suite in ("SBMR-IB, SBMR-OOB", "SBMR-IB", "SBMR-OOB")] + _, page = self.render(findings) + metadata = page.nodes_with_class("group-meta") + self.assertEqual(1, len(metadata)) + affected = "".join(metadata[0]["text"]) + self.assertEqual(1, affected.count("SBMR-IB")) + self.assertEqual(1, affected.count("SBMR-OOB")) + self.assertEqual(Counter(item.suite for item in findings), + Counter(attrs["data-suite"] for _, attrs in page.with_class("finding"))) + + def test_compliance_example_is_plain_while_technical_comparison_stays_exact(self): + """Check compliance example is plain while technical comparison stays exact.""" + actual = ("{'badges': {'BSA': {'expected': 'Recommended (Not Run)', " + "'actual': 'Recommended (Compliant)'}}, 'tables': {}}") + item = self.finding( + check_id="HTML_COMPLIANCE_MATCH", + suite="BSA", + issue= + "full_BSA_empty: summary badges and detail tables must agree with the independent compliance expectation", + expected="Exactly one correct badge/row for each applicable card/test", + actual=actual) + snapshot = deepcopy(item) + _, page = self.render([item]) + preview = " ".join("".join(node["text"]) + for node in page.nodes_with_class("topic-examples")) + for word in ("BSA", "Recommended", "Not Run", "Compliant"): + self.assertIn(word, preview) + self.assertNotIn("{'badges'", preview) + self.assertNotIn("'actual':", preview) + self.assertNotIn("full_BSA_empty", preview) + technical = page.nodes_with_class("finding") + self.assertEqual(1, len(technical)) + text = "".join(technical[0]["text"]) + for value in (item.check_id, item.issue, item.expected, item.actual): + self.assertIn(value, text) + self.assertEqual(snapshot, item) + + def test_summary_counters_include_pass_fail_warn_and_blocked(self): + """Check summary counters include pass fail warn and blocked.""" + findings = [self.finding(status=status, check_id=status + "_CHECK") + for status in ("PASS", "PASS", "FAIL", "WARN", "BLOCKED")] + _, page = self.render(findings) + metrics = {attrs["data-count-status"]: int(attrs["data-count"]) + for _, attrs in page.elements if "data-count-status" in attrs} + self.assertEqual({"PASS": 2, "FAIL": 1, "WARN": 1, "BLOCKED": 1}, metrics) + self.assertEqual(3, len(page.with_class("finding"))) + self.assertNotIn("PASS", + {attrs["data-severity"] + for _, attrs in page.with_class("finding-group")}) + + def test_all_pass_has_no_issue_groups_but_keeps_verdict_and_counts(self): + """Check all pass has no issue groups but keeps verdict and counts.""" + source, page = self.render([self.finding(status="PASS")], status="PASS") + self.assertEqual([], page.with_class("finding-group")) + self.assertEqual([], page.with_class("finding")) + self.assertIn("PASS", " ".join(page.text)) + self.assertIn("1", " ".join(page.text)) + self.assertIn("doctor.json", source) + self.assertIn("doctor.md", source) + self.assertNotIn("SBMR", " ".join(page.text)) + + def test_green_sbmr_observation_never_gets_blanket_non_green_reassurance(self): + """Check green SBMR observation never gets blanket non green reassurance.""" + item = self.finding( + check_id="raw.unknown-status", + suite="SBMR-IB", + mode="SR", + actual="exit=0; raw counts={'passed': 1}; merged='Compliant'; HTML='Compliant'") + _, page = self.render([item]) + explanation = " ".join(text for node in page.nodes_with_class("group-explanation") + for text in node["text"]).lower() + for unsafe in ("sbmr is safe", "not a false green", "not a false pass", + "did not publish a green", "no false-green", "no green result", + "stopped without publishing"): + self.assertNotIn(unsafe, explanation) + self.assertIn("recorded compliant", explanation) + self.assertNotIn("not evidence of a completed report incorrectly marked compliant", + explanation) + + def test_sbmr_stopped_run_explanation_depends_on_every_recorded_observation(self): + """Check SBMR stopped run explanation depends on every recorded observation.""" + stopped = self.finding(check_id="raw.missing-status", suite="SBMR-IB", mode="SR", + actual="exit=7; merged=None; HTML=None") + green = self.finding(check_id="raw.unknown-status", suite="SBMR-OOB", mode="SR", + actual="exit=0; merged='Compliant'; HTML='Compliant'") + _, stopped_page = self.render([stopped]) + stopped_explanation = " ".join( + text for node in stopped_page.nodes_with_class("group-explanation") + for text in node["text"]) + self.assertIn("No completed merged result or HTML status was recorded", stopped_explanation) + _, mixed_page = self.render([stopped, green]) + mixed_explanation = " ".join(text + for node in mixed_page.nodes_with_class("group-explanation") + for text in node["text"]) + self.assertIn("At least one", mixed_explanation) + self.assertNotIn("No completed merged result or HTML status was recorded", + mixed_explanation) + self.assertNotIn("not evidence of a completed report incorrectly marked Compliant", + mixed_explanation) + + def test_empty_results_do_not_claim_a_pass(self): + """Check empty results do not claim a pass.""" + _, page = self.render([], status="INCOMPLETE", metadata={}) + self.assertEqual([], page.with_class("finding-group")) + text = " ".join(page.text) + self.assertIn("INCOMPLETE", text) + self.assertIn("Not recorded", text) + metrics = {attrs["data-count-status"]: int(attrs["data-count"]) + for _, attrs in page.elements if "data-count-status" in attrs} + self.assertEqual({"PASS": 0, "FAIL": 0, "WARN": 0, "BLOCKED": 0}, metrics) + + def test_missing_metadata_values_have_a_readable_fallback(self): + """Check missing metadata values have a readable fallback.""" + _, page = self.render([self.finding()], metadata={}) + text = " ".join(page.text) + self.assertIn("Not recorded", text) + self.assertNotIn("undefined", text) + self.assertNotIn("None", text) + + def test_relative_evidence_links_are_url_encoded_without_changing_labels(self): + """Check relative evidence links are url encoded without changing labels.""" + evidence = self.output / "evidence" / "DT report #1" / "case & result?.json" + item = self.finding(evidence=[str(evidence)]) + source, page = self.render([item]) + links = [attrs["href"] for tag, attrs in page.elements if tag == "a" and "href" in attrs] + self.assertIn("evidence/DT%20report%20%231/case%20%26%20result%3F.json", links) + self.assertNotIn(evidence.as_uri(), links) + self.assertIn("case & result?.json", " ".join(page.text)) + self.assertNotIn('href="evidence/DT report #1/', source) + + def test_all_filter_and_action_controls_have_stable_unique_ids(self): + """Check all filter and action controls have stable unique IDS.""" + _, page = self.render( + [self.finding(), + self.finding(status="WARN", mode="SR", suite="SBMR-IB")]) + for identifier in ("doctor-search", "severity-filter", "mode-filter", "suite-filter", + "expand-all", "collapse-all", "reset-filters", "print-report"): + with self.subTest(identifier=identifier): + self.assertEqual(1, len(page.with_id(identifier))) + findings = [attrs for _, attrs in page.with_class("finding")] + self.assertEqual({"DT", "SR"}, {attrs["data-mode"] for attrs in findings}) + self.assertEqual({"BSA", "SBMR-IB"}, {attrs["data-suite"] for attrs in findings}) + self.assertTrue(all(attrs["data-search"] for attrs in findings)) + self.assertTrue(all(attrs["data-check-id"] for attrs in findings)) + + def test_no_javascript_still_has_all_explanations_and_native_details(self): + """Check no javascript still has all explanations and native details.""" + _, page = self.render([self.finding(), self.finding(status="BLOCKED")]) + self.assertEqual(2, len(page.nodes_with_class("group-explanation"))) + for node in page.nodes_with_class("group-explanation") + page.nodes_with_class( + "group-checks"): + for ancestor in (*node["ancestors"], node): + self.assertNotIn("hidden", ancestor["attrs"]) + self.assertNotIn("js-only", ancestor["attrs"].get("class", "").split()) + self.assertTrue(any(tag == "noscript" for tag, _ in page.elements)) + + def test_evidence_filename_cannot_become_an_executable_url(self): + """Check evidence filename cannot become an executable url.""" + _, page = self.render([self.finding(evidence=["javascript:alert(1)"])]) + links = [attrs["href"] for tag, attrs in page.elements if tag == "a" and "href" in attrs] + self.assertFalse(any(link.lower().startswith("javascript:") for link in links)) + + def test_report_has_no_external_script_style_or_font_dependencies(self): + """Check report has no external script style or font dependencies.""" + source, page = self.render([self.finding()]) + for tag, attrs in page.elements: + if tag == "script": + self.assertNotIn("src", attrs) + if tag == "link": + self.assertNotIn("stylesheet", attrs.get("rel", "").lower()) + self.assertNotIn("@import", source) + self.assertNotIn("fonts.googleapis.com", source) + self.assertNotIn("cdn.jsdelivr.net", source) + + def test_rendering_does_not_mutate_findings_metadata_or_write_artifacts(self): + """Check rendering does not mutate findings metadata or write artifacts.""" + findings = [self.finding(evidence=[str(self.output / "evidence.json")])] + metadata = {"revision": "12345", "modes": ["DT", "SR"]} + snapshot = deepcopy((findings, metadata)) + self.render(findings, metadata=metadata) + self.assertEqual(snapshot, (findings, metadata)) + self.assertEqual([], list(self.output.iterdir())) + + +# Plain-language summaries must match the evidence, not assume an outcome. + +class DoctorExplanationTests(unittest.TestCase): + """Check that explanations name the problem without making unsupported claims.""" + + @staticmethod + def finding(identifier="raw.missing-status", status="FAIL", **changes): + """Start with a recorded rejection and vary the evidence under test.""" + values = dict( + check_id=identifier, + status=status, + issue="Input handling must be safe", + expected="Reject clearly or keep non-green", + actual=("exit=7; raw counts={'passed': 0}; merged=None; HTML=None; HTML Failed=None"), + mode="SR", + suite="SBMR-IB", + evidence=["evidence/parser.log"]) + values.update(changes) + return Finding(**values) + + def test_schema_ids_share_explanation_without_claiming_wrong_results(self): + """Check schema IDS share explanation without claiming wrong results.""" + items = [ + self.finding(identifier) for identifier in ("NATIVE_RAW_SCHEMA", "ARTIFACT.SCHEMA") + ] + description = describe_group([item.check_id for item in items], items) + self.assertEqual("issues", description["category"]) + self.assertIn("JSON", description["title"]) + self.assertIn("does not prove", description["impact"]) + self.assertIn("not necessarily separate defects", description["next_step"]) + + def test_schema_and_parity_headings_use_plain_language(self): + """Check schema and parity headings use plain language.""" + for identifier, title in ( + ("NATIVE_RAW_SCHEMA", "Some JSON files do not match the expected format"), + ("ARTIFACT.PARITY", "Report details do not match the source results")): + with self.subTest(identifier=identifier): + self.assertEqual(title, + describe_group(identifier, [self.finding(identifier)])["title"]) + + def test_html_compliance_topic_names_wrong_labels_not_first_scenario(self): + """Check HTML compliance topic names wrong labels not first scenario.""" + item = self.finding( + "HTML_COMPLIANCE_MATCH", + suite="BSA", + mode="DT", + issue= + "full_BSA_empty: summary badges and detail tables must agree with the independent compliance expectation", + expected="Exactly one correct badge/row for each applicable card/test", + actual= + "{'badges': {'BSA': {'expected': 'Recommended (Not Run)', 'actual': 'Recommended (Compliant)'}}, 'tables': {}}" + ) + description = describe_group(item.check_id, [item]) + self.assertIn("compliance", description["title"].lower()) + self.assertTrue(any(word in description["title"].lower() + for word in ("wrong", "incorrect", "match", "differ", "disagree"))) + self.assertNotIn("full_BSA_empty", description["title"]) + self.assertNotIn("BSA", description["title"]) + observed = describe_finding(item)["observed"] + for word in ("BSA", "Recommended", "Not Run", "Compliant"): + self.assertIn(word, observed) + self.assertTrue(any(word in observed.lower() for word in ("expected", "should"))) + self.assertTrue( + any(word in observed.lower() for word in ("actual", "shows", "showed", "displayed"))) + self.assertNotIn("{", observed) + self.assertNotIn("}", observed) + self.assertNotIn("'actual':", observed) + + def test_html_comparison_omits_matching_detail_rows(self): + """Check HTML comparison omits matching detail rows.""" + matching = ("SBMR-IB", "Mandatory", "Compliant") + missing = ("SBMR-OOB", "Mandatory", "Not Compliant (Not Run)") + item = self.finding("HTML_COMPLIANCE_MATCH", actual=repr({ + "badges": {}, "tables": {"sbmr_detailed.html": { + "expected": [matching, missing], "actual": [matching]}}})) + snapshot = deepcopy(item) + description = describe_finding(item) + rows = description.get("comparisons", []) + self.assertEqual(1, len(rows)) + self.assertIn("SBMR-OOB", rows[0][0]) + self.assertIn("Mandatory", rows[0][1]) + self.assertIn("Not Run", rows[0][1]) + self.assertIn("missing", rows[0][2].lower()) + self.assertNotIn("SBMR-IB", description["observed"]) + self.assertEqual(snapshot, item) + + def test_html_comparison_preserves_repeated_missing_detail_rows(self): + """Check HTML comparison preserves repeated missing detail rows.""" + row = ("SBMR-OOB", "Mandatory", "Not Compliant (Not Run)") + item = self.finding("HTML_COMPLIANCE_MATCH", actual=repr({ + "badges": {}, "tables": {"sbmr_detailed.html": { + "expected": [row, row, row], "actual": [row]}}})) + rows = describe_finding(item).get("comparisons", []) + self.assertEqual(2, len(rows)) + self.assertEqual(rows[0], rows[1]) + self.assertIn("SBMR-OOB", rows[0][0]) + self.assertIn("missing", rows[0][2].lower()) + + def test_html_comparison_preserves_requirement_changes_missing_and_extra_rows(self): + """Check HTML comparison preserves requirement changes missing and extra rows.""" + item = self.finding("HTML_COMPLIANCE_MATCH", actual=repr({ + "badges": {}, "tables": {"sbmr_detailed.html": { + "expected": [("SBMR-IB", "Mandatory", "Compliant"), + ("SBMR-OOB", "Mandatory", "Not Compliant (Not Run)")], + "actual": [("SBMR-IB", "Recommended", "Compliant"), + ("SBSA", "Recommended", "Compliant")]}}})) + rows = describe_finding(item).get("comparisons", []) + self.assertEqual(3, len(rows)) + by_name = {name.rsplit(" · ", 1)[-1]: (wanted, actual) for name, wanted, actual in rows} + self.assertIn("Mandatory", by_name["SBMR-IB"][0]) + self.assertIn("Recommended", by_name["SBMR-IB"][1]) + self.assertIn("Mandatory", by_name["SBMR-OOB"][0]) + self.assertIn("missing", by_name["SBMR-OOB"][1].lower()) + self.assertIn("no row", by_name["SBSA"][0].lower()) + self.assertIn("Recommended", by_name["SBSA"][1]) + + def test_malformed_comparison_data_is_not_executed_and_does_not_crash(self): + """Check malformed comparison data is not executed and does not crash.""" + cases = ( + '__import__("os").system("DOCTOR_MUST_NOT_EXECUTE")', + "{'badges': {'BSA':", + "{'badges': None, 'tables': None}", + "{'badges': [], 'tables': []}", + "{'badges': 7, 'tables': 'not a table'}", + "{'badges': {'BSA': 'invalid'}, 'tables': {'detail.html': None}}", + "{'badges': {}, 'tables': {'detail.html': {'expected': ['bad', None, 7], 'actual': {}}}}", + ) + with mock.patch("os.system") as execute: + for actual in cases: + with self.subTest(actual=actual): + item = self.finding("HTML_COMPLIANCE_MATCH", actual=actual) + snapshot = deepcopy(item) + result = describe_finding(item) + self.assertIsInstance(result["observed"], str) + self.assertEqual([], result.get("comparisons", [])) + self.assertEqual(snapshot, item) + execute.assert_not_called() + + def test_empty_log_examples_distinguish_no_report_green_and_invented_outcomes(self): + """Check empty log examples distinguish no report green and invented outcomes.""" + observations = {} + cases = { + "rejected": + "exit=5; raw counts={'passed': 0, 'failed': 0}; merged=None; HTML=None", + "green": + "exit=0; raw counts={'passed': 0, 'failed': 0}; merged='Compliant'; HTML='Compliant'", + "invented": + "exit=0; raw counts={'passed': 1, 'failed': 0}; merged='Not Compliant'; HTML='Not Compliant'", + } + for case, actual in cases.items(): + item = self.finding("raw.empty-log", actual=actual) + observations[case] = describe_finding(item)["observed"] + self.assertIn("Not Run", observations[case]) + self.assertNotIn("{'passed'", observations[case]) + self.assertIn("exit code 5", observations["rejected"]) + self.assertIn("no compliance report", observations["rejected"]) + self.assertNotIn("says Compliant", observations["rejected"]) + self.assertIn("says Compliant", observations["green"]) + self.assertNotIn("no compliance report", observations["green"]) + self.assertIn("1 passed", observations["invented"]) + self.assertIn("Not Compliant", observations["invented"]) + self.assertEqual(3, len(set(observations.values()))) + + def test_overall_policy_heading_covers_incorrect_pass_and_incorrect_failure(self): + """Check overall policy heading covers incorrect pass and incorrect failure.""" + headings = [] + for expected, actual in (("compliant", "Not Compliant"), ("not_compliant", "Compliant")): + item = self.finding("MERGE_OVERALL_POLICY", expected=expected, actual=actual) + description = describe_group(item.check_id, [item]) + headings.append(description["title"]) + for keyword in ("Mandatory", "Recommended"): + self.assertIn(keyword, description["impact"]) + rows = describe_finding(item).get("comparisons", []) + self.assertEqual(1, len(rows)) + self.assertEqual("Compliant" if expected == "compliant" else "Not Compliant", + rows[0][1]) + self.assertEqual(actual, rows[0][2]) + self.assertEqual(headings[0], headings[1]) + self.assertNotIn("Recommended", headings[0]) + self.assertNotIn("incorrect pass", headings[0].lower()) + self.assertNotIn("incorrect fail", headings[0].lower()) + + def test_stale_rerun_explanations_use_the_recorded_suite_not_bsa(self): + """Check stale rerun explanations use the recorded suite not BSA.""" + for suite in ("FWTS", "SCT"): + with self.subTest(suite=suite): + item = self.finding( + "normal.stale-rerun", + suite=suite, + issue= + f"Removing the {suite} raw log must not reuse the previous run's Compliant JSON.", + actual="first='Compliant'; rerun='Compliant'; fresh='Not Compliant: not run'") + finding = describe_finding(item) + group = describe_group(item.check_id, [item]) + self.assertIn(suite, finding["title"]) + self.assertNotIn("BSA", " ".join(group.values())) + self.assertNotIn("BSA", finding["observed"]) + self.assertIn("Compliant", finding["observed"]) + self.assertIn("Not Compliant: not run", finding["observed"]) + self.assertTrue(any(word in finding["observed"].lower() + for word in ("previous", "old", "retained"))) + + def test_saved_failure_topics_have_specific_explanations(self): + # Representative failures from a completed DT/SR run are kept here; + # tests never depend on a user's saved report or an external file path. + """Check saved failure topics have specific explanations.""" + cases = ( + ("ARTIFACT.CONSISTENCY", "Supplied report package has correctness problems", + "11 JSON files, 11 HTML pages; JSON schema validation failed: 2", ("report", + "package")), + ("ARTIFACT.SCHEMA", "merged_results.json violates applicable Doctor schema checks", + "'SRS scope' is a required property", ("json", "format")), + ("HTML_COMPLIANCE_MATCH", "full_BSA_empty: summary badges and detail tables must agree", + "{'badges': {'BSA': {'expected': 'Recommended (Not Run)', 'actual': 'Recommended (Compliant)'}}, 'tables': {}}", + ("compliance", "label")), + ("MERGE_EXTENSION_AGGREGATION", + "full_BBSR-FWTS_empty: BBSR aggregates its three members separately from SRS", + "Compliant", ("bbsr", "extension")), + ("MERGE_FAILURE_COUNT", "SCT parent-only failures", "Failed/waived=(0, 0)", ("failure", + "failed")), + ("MERGE_INCOMPLETE_NOT_GREEN", + "full_BSA_empty: Empty/header-only input was marked as completed", + "{'BSA': {'requirement': 'Recommended', 'status': 'compliant'}}", + ("empty", "incomplete", "not run")), + ("MERGE_INVALID_INPUT_SAFETY", + "BSA: invalid result shape must not produce a green result", "Compliant", + ("invalid", "malformed")), + ("MERGE_OVERALL_POLICY", + "full_BSA_missing: Recommended result incorrectly blocks overall SRS", + "Not Compliant : Recommended - (not run: BSA)", ("recommended", "overall")), + ("NATIVE_EXECUTION", "Public CLI must parse the known native fixture", + "dt_memory_map_routes; Exit 5\nIndexError: list index out of range", + ("parser", "command", "sample", "fixture")), + ("NATIVE_OUTPUT_INVENTORY", + "Native route must produce exactly its expected suite JSON files", + "missing=['reserved_memory_map.json']; unexpected=[]", ("file", "output", "json")), + ("NATIVE_RAW_SCHEMA", + "Generated raw file must satisfy applicable Doctor schema checks: os_test.json", + "'Main Readiness Grouping' is a required property", ("json", "format")), + ("normal.stale-rerun", + "Removing the BSA raw log must not reuse the previous run's Compliant JSON.", + "first='Compliant'; rerun='Compliant'; fresh='Not Compliant: not run'", + ("previous", "old", "stale", "rerun")), + ("raw.empty-log", + "Empty or introductory-only input must be Not Run, not invented test outcomes.", + "exit=5; raw counts={'passed': 0}; merged=None; HTML=None", ("empty", "not run")), + ("raw.header-only", + "Empty or introductory-only input must be Not Run, not invented test outcomes.", + "exit=5; raw counts={'passed': 0}; merged=None; HTML=None", ("introductory", "header", + "not run")), + ("raw.malformed-log", + "Incomplete or unrecognized raw evidence must not become a green result.", + "exit=0; raw counts={'passed': 0}; merged='Compliant'; HTML='Compliant'", ("malformed", + "invalid")), + ("raw.missing-status", + "Incomplete or unrecognized raw evidence must not become a green result.", + "exit=0; raw counts={'passed': 0}; merged='Compliant'; HTML='Compliant'", + ("status", "compliant")), + ("raw.missing-terminal-result", + "Incomplete or unrecognized raw evidence must not become a green result.", + "exit=0; raw counts={'passed': 1}; merged='Compliant'; HTML='Compliant'", + ("incomplete", "final", "finish", "end")), + ("raw.sct-parent-failure", + "Two explicit failed SCT entries must remain non-compliant when subtest detail is absent.", + "exit=0; raw counts={'failed': 2}; merged='Compliant'; HTML='Compliant'; HTML Failed=2", + ("sct", "parent")), + ("raw.truncated-final-subtest", + "Incomplete or unrecognized raw evidence must not become a green result.", + "exit=0; raw counts={'passed': 1, 'warnings': 1}; merged='Compliant'; HTML='Compliant'", + ("truncated", "incomplete", "finish", "end")), + ("raw.truncated-log", + "Incomplete or unrecognized raw evidence must not become a green result.", + "exit=0; raw counts={'passed': 1}; merged='Compliant'; HTML='Compliant'", + ("truncated", "incomplete", "finish", "end")), + ("raw.unknown-status", + "Incomplete or unrecognized raw evidence must not become a green result.", + "exit=0; raw counts={'passed': 0}; merged='Compliant'; HTML='Compliant'", + ("status", "compliant")), + ("waiver.runtime-map-whole-suite", + "A valid Runtime Device Map whole-suite waiver must not crash on nested failure reasons.", + 'exit=5; merged=None; HTML=None; TypeError: can only concatenate list (not "str") to list', + ("waiver", "crash")), + ("waiver.whole-suite-multiple-assertions", + "A whole-suite waiver must cover both failed FWTS assertions, not just one.", + "exit=0; raw counts={'failed': 1, 'failed_with_waiver': 1}; merged='Not Compliant: Failed 1'; HTML='Not Compliant'", + ("waiver", "fwts")), + ) + for identifier, issue, actual, topic_words in cases: + with self.subTest(identifier=identifier): + item = self.finding(identifier, issue=issue, actual=actual) + snapshot = deepcopy(item) + description = describe_group(identifier, [item]) + self.assertNotIn("The recorded check did not establish its expected outcome", + description["happened"]) + words = " ".join(description.values()).lower() + self.assertTrue(any(word in words for word in topic_words), words) + self.assertTrue( + all(isinstance(value, str) and value for value in description.values())) + self.assertEqual(snapshot, item) + + def test_missing_json_replay_explains_requirement_without_claiming_public_flow_failure(self): + """Check missing JSON replay explains requirement without claiming public flow failure.""" + items = [self.finding("raw.conditional-execution", status="WARN", suite=suite, mode=mode, + actual="Raw control passed; omitted JSON; merged=Compliant") + for mode, suite in (("SR", "SBSA"), ("SR", "SBMR-IB"), + ("SR", "SBMR-OOB"), ("DT", "PFDI"))] + snapshot = deepcopy(items) + description = describe_group("raw.conditional-execution", items) + self.assertEqual("Conditional requirements need execution evidence beyond JSON", + description["title"]) + self.assertEqual("coverage", description["category"]) + self.assertIn("raw-log control proves", description["happened"]) + self.assertIn("deliberately", description["happened"]) + self.assertIn("disposable", description["happened"]) + for rule in ("SR SBSA is Mandatory", "both interfaces Mandatory", + "DT PFDI", "Conditional-Mandatory", "not allow overall Compliant"): + self.assertIn(rule, description["impact"]) + self.assertIn("directly to the merger", description["happened"]) + self.assertIn("controlled fault injection does not establish a public-flow failure", + description["impact"]) + self.assertIn("standalone already rejects parser errors and missing generated output", + description["impact"]) + self.assertIn("did not test whether normal runs can reach this state", + description["impact"]) + self.assertIn("Verify the public-flow guards", description["next_step"]) + self.assertIn("fact that a required test ran", description["next_step"]) + for item in items: + finding = describe_finding(item) + self.assertIn(item.suite, finding["title"]) + self.assertIn("JSON-only merge replay", finding["title"]) + self.assertIn("public-flow failure not established", finding["observed"]) + self.assertLess(len(finding["observed"]), 600) + self.assertNotIn("{", finding["observed"]) + self.assertEqual(snapshot, items) + + def test_missing_json_control_pass_and_blocked_do_not_claim_lost_requirements(self): + """Check missing JSON control pass and blocked do not claim lost requirements.""" + for identifier in ("raw.conditional-execution", "raw.conditional-control"): + for status, title in (("PASS", "Checks completed successfully"), + ("BLOCKED", "Checks could not finish")): + with self.subTest(identifier=identifier, status=status): + item = self.finding(identifier, status=status) + description = describe_group(identifier, [item]) + self.assertEqual(title, description["title"]) + self.assertNotIn("raw-log control proves", description["happened"]) + self.assertNotIn("JSON-only merge replay", describe_finding(item)["title"]) + + def test_unrelated_warning_and_unexpected_failures_keep_safe_fallbacks(self): + """Check unrelated warning and unexpected failures keep safe fallbacks.""" + item = self.finding("raw.conditional-execution", status="FAIL") + failure = describe_group(item.check_id, [item]) + self.assertNotIn("raw-log control proves", failure["happened"]) + self.assertNotIn("JSON-only merge replay", describe_finding(item)["title"]) + item.status = "WARN" + other = self.finding("FUTURE_CHECK", status="WARN") + unrelated = describe_group(other.check_id, [other]) + self.assertEqual("coverage", unrelated["category"]) + self.assertNotIn("raw-log control proves", unrelated["happened"]) + mixed = describe_group([item.check_id, other.check_id], [item, other]) + self.assertNotIn("raw-log control proves", mixed["happened"]) + + def test_missing_schema_fields_are_named_but_unknown_category_is_not_test_status(self): + """Check missing schema fields are named but unknown category is not test status.""" + item = self.finding("NATIVE_RAW_SCHEMA", issue="Generated raw file: bsa.json", + actual="'Test_suite_info' is a required property") + description = describe_finding(item) + self.assertEqual("bsa.json: format check failed", description["title"]) + self.assertIn("Test_suite_info", description["observed"]) + item.actual = "'UNKNOWN' is not one of the allowed category values" + observed = describe_finding(item)["observed"] + self.assertIn("category", observed) + self.assertNotIn("test status", observed) + + def test_all_sbmr_missing_unknown_cases_can_have_specific_heading(self): + """Check all SBMR missing unknown cases can have specific heading.""" + items = [self.finding(identifier, suite=suite) + for identifier in ("raw.missing-status", "raw.unknown-status") + for suite in ("SBMR-IB", "SBMR-OOB")] + description = describe_group([item.check_id for item in items], items) + self.assertIn("SBMR", description["title"]) + self.assertIn("did not produce a completed report", description["title"]) + self.assertIn("not evidence", description["impact"]) + self.assertNotIn("incorrectly marked Compliant", description["happened"]) + self.assertEqual("Exit code 7; no completed merged result or HTML status was recorded.", + describe_finding(items[0])["observed"]) + + def test_non_sbmr_and_missing_suite_never_get_sbmr_heading(self): + """Check non SBMR and missing suite never get SBMR heading.""" + for suite in ("BSA", "SCT", "", "SBMR-INVENTED", ""): + for items in ([self.finding(suite=suite)], [self.finding(), self.finding(suite=suite)]): + with self.subTest(suite=suite, count=len(items)): + self.assertNotIn("SBMR", describe_group("raw.missing-status", items)["title"]) + + def test_mixed_observations_do_not_claim_all_reports_stopped(self): + """Check mixed observations do not claim all reports stopped.""" + completed = self.finding( + actual="exit=0; merged='Compliant'; HTML='Compliant'; HTML Failed=0") + description = describe_group("raw.missing-status", [self.finding(), completed]) + self.assertIn("Compliant result", description["title"]) + self.assertIn("At least one", description["happened"]) + self.assertNotIn("No completed", description["happened"]) + self.assertNotIn("not evidence", description["impact"]) + self.assertIn("merged JSON says Compliant", describe_finding(completed)["observed"]) + + def test_non_green_and_unknown_observations_do_not_claim_protected_rejection(self): + """Check non green and unknown observations do not claim protected rejection.""" + for actual in ("exit=0; merged='Not Compliant'; HTML='Not Compliant'", + "exit=0; merged=None; HTML=None", "exit=7; merged=None", "No output"): + with self.subTest(actual=actual): + description = describe_group("raw.missing-status", [self.finding(actual=actual)]) + self.assertNotIn("did not produce", description["title"]) + self.assertNotIn("Compliant result", description["title"]) + self.assertNotIn("No completed", description["happened"]) + + def test_status_spelling_and_html_only_compliant_are_handled_conservatively(self): + """Check status spelling and HTML only compliant are handled conservatively.""" + for actual in ('exit=0; merged="Compliant"; HTML=None', + "exit=1; merged=None; HTML='Compliant'", + "exit=0; merged='COMPLIANT'; HTML=None"): + with self.subTest(actual=actual): + description = describe_group("raw.unknown-status", [self.finding(actual=actual)]) + self.assertIn("Compliant result", description["title"]) + for actual in ("exit=0; merged='Not Compliant'; HTML=None", + "exit=0; merged='Compliant with caveats'; HTML=None", + "exit=0; raw counts={'status': 'Compliant'}; merged=None; HTML=None"): + with self.subTest(actual=actual): + self.assertNotIn("Compliant result", describe_group("raw.missing-status", + [self.finding(actual=actual)])["title"]) + + def test_repeated_fields_and_invalid_exit_are_not_treated_as_known_outcomes(self): + """Check repeated fields and invalid exit are not treated as known outcomes.""" + for actual in ("exit=7; exit=7; merged=None; HTML=None", + "exit=7; merged=None; merged=None; HTML=None", + "exit=error; merged=None; HTML=None", + "prefix exit=7; merged=None; HTML=None"): + with self.subTest(actual=actual): + self.assertNotIn("did not produce", describe_group("raw.missing-status", + [self.finding(actual=actual)])["title"]) + + def test_literal_none_status_is_not_confused_with_missing_observation(self): + """Check literal none status is not confused with missing observation.""" + item = self.finding(actual="exit=7; merged='None'; HTML=None") + self.assertNotIn("did not produce", describe_group(item.check_id, [item])["title"]) + self.assertEqual("Exit code 7; merged JSON says None; HTML status was not recorded.", + describe_finding(item)["observed"]) + + def test_rollup_is_summary_without_unverified_deduplication_claim(self): + """Check rollup is summary without unverified deduplication claim.""" + item = self.finding("ARTIFACT.CONSISTENCY") + description = describe_group(item.check_id, [item]) + self.assertEqual("summaries", description["category"]) + self.assertIn("before treating it as an additional defect", description["impact"]) + self.assertNotIn("repeats", " ".join(description.values())) + + def test_all_eight_saved_warning_instances_have_explanations(self): + """Check all eight saved warning instances have explanations.""" + samples = [ + ("PACKAGE_ENVIRONMENT", "Recorded Python"), + ("MERGE_UNAGREED_STATUS_POLICY", "Not covered"), + ("raw.completion-evidence", "exit=0; merged='Compliant'; HTML='Compliant'"), + ("raw.coverage", "DTB-ALIGNMENT, NETWORK-BOOT"), + ("raw.coverage", "OS-TESTS"), + ("ARTIFACT.COVERAGE", + "acs_summary.html: aggregate/unmapped chart standalone_summary.html"), + ("ARTIFACT.COVERAGE", + "sbmr.html: link outside supplied package not inspected: ../../report.html"), + ("VISUAL_SCOPE", "Synthetic DT/SR reports"), + ] + for identifier, actual in samples: + with self.subTest(identifier=identifier, actual=actual): + item = self.finding(identifier, status="WARN", actual=actual) + description = describe_group(identifier, [item]) + self.assertEqual("coverage", description["category"]) + self.assertNotEqual(item.issue, description["title"]) + self.assertTrue( + all(isinstance(value, str) and value for value in description.values())) + + def test_chart_and_external_link_warnings_explain_different_limits(self): + """Check chart and external link warnings explain different limits.""" + chart = self.finding("ARTIFACT.COVERAGE", + status="WARN", + actual="aggregate/unmapped chart chart.html") + link = self.finding("ARTIFACT.COVERAGE", status="WARN", + actual="link outside supplied package not inspected: ../outside.html") + self.assertIn("chart totals", describe_group(chart.check_id, [chart])["title"]) + self.assertIn("outside", describe_group(link.check_id, [link])["title"]) + self.assertIn("does not establish", describe_group(link.check_id, [link])["impact"]) + mixed = describe_group(chart.check_id, [chart, link]) + self.assertIn("comparisons remain unverified", mixed["title"]) + + def test_unknown_category_choice_warns_without_claiming_explicit_or_bundled_use(self): + """Check unknown category choice warns without claiming explicit or bundled use.""" + for identifier in ("NATIVE_CATEGORY_PROVENANCE", "ARTIFACT.CATEGORY_PROVENANCE"): + with self.subTest(identifier=identifier): + item = self.finding( + identifier, + status="WARN", + actual="Run category provenance is unavailable; missing-info requirement " + "not applied in bsa.json; all other schema checks remain active") + snapshot = deepcopy(item) + description = describe_group(identifier, [item]) + self.assertEqual("coverage", description["category"]) + self.assertEqual("The run's category-file choice is not recorded", + description["title"]) + self.assertIn("could not verify whether", description["happened"]) + self.assertIn("All other format checks remain active", description["impact"]) + self.assertIn("Known bundled defaults alone", description["next_step"]) + self.assertIn("do not make", description["next_step"]) + self.assertIn("or cause this warning", description["next_step"]) + self.assertIn("not treated as a failure", describe_finding(item)["observed"]) + self.assertEqual(snapshot, item) + + def test_known_bundled_defaults_are_not_described_as_unknown_category_choice(self): + """Check known bundled defaults are not described as unknown category choice.""" + item = self.finding( + "NATIVE_RAW_SCHEMA", + status="PASS", + actual="Strict validator exit 1; category source: bundled; missing Test_suite_info " + "not required at 1 record(s); all applicable Doctor schema checks passed") + description = describe_group(item.check_id, [item]) + self.assertEqual("Checks completed successfully", description["title"]) + self.assertNotIn("could not verify", description["happened"]) + self.assertNotIn("failure", description["impact"]) + + def test_invalid_category_record_remains_failure_not_coverage_warning(self): + """Check invalid category record remains failure not coverage warning.""" + for identifier in ("NATIVE_CATEGORY_PROVENANCE", "ARTIFACT.CATEGORY_PROVENANCE"): + with self.subTest(identifier=identifier): + item = self.finding(identifier, actual="Invalid run category provenance: " + "Explicit category snapshot SHA-256 does not match") + description = describe_group(identifier, [item]) + self.assertEqual("issues", description["category"]) + self.assertEqual("The run's category-file record cannot be verified", + description["title"]) + self.assertIn("invalid record", description["happened"]) + self.assertNotIn("not treated", description["impact"]) + self.assertEqual(item.actual, describe_finding(item)["observed"]) + + def test_explicit_category_missing_info_stays_schema_failure_without_description_requirement( + self): + """Check explicit category missing info stays schema failure without description + requirement. + """ + item = self.finding("NATIVE_RAW_SCHEMA", issue="Generated raw file: bsa.json", + actual="Strict validator exit 1; category source: explicit\n" + "/test_results/0: 'Test_suite_info' is a required property") + description = describe_group(item.check_id, [item]) + self.assertEqual("issues", description["category"]) + self.assertEqual("Validator reports missing required fields: Test_suite_info.", + describe_finding(item)["observed"]) + self.assertNotIn("Description", " ".join(description.values())) + + def test_both_category_record_ids_can_share_an_explanation(self): + """Check both category record IDS can share an explanation.""" + items = [self.finding(identifier, status="WARN") + for identifier in ("NATIVE_CATEGORY_PROVENANCE", "ARTIFACT.CATEGORY_PROVENANCE")] + description = describe_group([item.check_id for item in items], items) + self.assertEqual("The run's category-file choice is not recorded", description["title"]) + blocked = self.finding("ARTIFACT.CATEGORY_PROVENANCE", status="BLOCKED") + self.assertEqual("Checks could not finish", + describe_group(blocked.check_id, [blocked])["title"]) + + def test_empty_input_warning_uses_actual_not_presumed_green(self): + """Check empty input warning uses actual not presumed green.""" + item = self.finding("raw.completion-evidence", status="WARN", + actual="exit=0; merged='Compliant'; HTML='Compliant'") + description = describe_group(item.check_id, [item]) + self.assertIn("recorded Compliant", description["happened"]) + self.assertIn("quiet but completed", description["impact"]) + item.actual = "exit=7; merged=None; HTML=None" + self.assertNotIn("recorded Compliant", describe_group(item.check_id, [item])["happened"]) + + def test_blocked_known_ids_do_not_claim_confirmed_defects(self): + """Check blocked known IDS do not claim confirmed defects.""" + for identifier in ("NATIVE_RAW_SCHEMA", "ARTIFACT.SCHEMA", "raw.missing-status", + "ARTIFACT.CONSISTENCY", "ARTIFACT.PARITY", "ARTIFACT.INPUT"): + with self.subTest(identifier=identifier): + item = self.finding(identifier, status="BLOCKED", actual="Missing dependency") + description = describe_group(identifier, [item]) + self.assertEqual("coverage", description["category"]) + self.assertIn("could not finish", description["title"]) + self.assertIn("not a confirmed parser defect", description["impact"]) + self.assertIn("did not complete", describe_finding(item)["observed"]) + + def test_unknown_ids_and_empty_groups_keep_safe_fallbacks(self): + """Check unknown IDS and empty groups keep safe fallbacks.""" + for status, category in (("FAIL", "issues"), ("WARN", "coverage"), + ("BLOCKED", "coverage"), ("PASS", "summaries")): + with self.subTest(status=status): + item = self.finding("FUTURE_CHECK", status=status, issue="New check mismatch") + description = describe_group(item.check_id, [item]) + self.assertEqual(category, description["category"]) + self.assertTrue(description["next_step"]) + self.assertIn("does not establish", describe_group([], [])["impact"]) + + def test_unknown_ids_mixed_with_schema_or_status_do_not_inherit_specific_claims(self): + """Check unknown IDS mixed with schema or status do not inherit specific claims.""" + for identifier in ("NATIVE_RAW_SCHEMA", "raw.missing-status"): + items = [self.finding(identifier), self.finding("FUTURE_CHECK")] + description = describe_group([identifier, "FUTURE_CHECK"], items) + self.assertEqual(items[0].issue, description["title"]) + + def test_literal_angle_bracket_name_difference_is_described_as_text(self): + """Check literal angle bracket name difference is described as text.""" + item = self.finding( + "ARTIFACT.PARITY", + issue="Raw and detailed HTML result identities differ", + expected= + "{'missing': [('RAS_07 : 1206', 'RAS ERRADDR.AI bit status check', 'WARNINGS')]}", + actual= + "{'extra_or_changed': [('RAS_07 : 1206', 'RAS ERRADDR.AI bit status check', 'WARNINGS')]}" + ) + observed = describe_finding(item)["observed"] + self.assertIn("Raw test name: RAS ERRADDR.AI bit status check", observed) + self.assertIn("Displayed test name: RAS ERRADDR.AI bit status check", observed) + self.assertNotIn("test status", observed) + + def test_malicious_strings_remain_plain_text_and_are_never_evaluated(self): + """Check malicious strings remain plain text and are never evaluated.""" + attack = '' + item = self.finding("FUTURE_CHECK", issue=attack, actual=attack) + with patch("builtins.eval", side_effect=AssertionError("must not evaluate")), \ + patch("builtins.exec", side_effect=AssertionError("must not execute")), \ + patch("builtins.open", side_effect=AssertionError("must not read evidence")): + self.assertEqual(attack, describe_group(item.check_id, [item])["title"]) + self.assertEqual(attack, describe_finding(item)["observed"]) + item.check_id = "raw.missing-status" + item.actual = "exit=__import__('os').system('false'); merged=None; HTML=None" + self.assertNotIn("did not produce", describe_group(item.check_id, [item])["title"]) + + def test_inputs_are_not_mutated_and_mapping_and_object_apis_agree(self): + """Check inputs are not mutated and mapping and object apis agree.""" + item = self.finding() + mapping = item.to_dict() + snapshot = deepcopy((item, mapping)) + self.assertEqual(describe_group([item.check_id], [item]), + describe_group(item.check_id, [mapping])) + self.assertEqual(describe_finding(item), describe_finding(mapping)) + self.assertEqual(snapshot, (item, mapping)) + + +# Saved report checks compare JSON, compliance labels, chart counts and test text. + +class ArtifactChecks(unittest.TestCase): + """Change disposable report copies to test detection without editing real logs.""" + + def setUp(self): + """Build a tiny, consistent report before each test introduces its change.""" + self.temporary = tempfile.TemporaryDirectory(prefix="doctor_artifact_test_") + self.addCleanup(self.temporary.cleanup) + self.base = Path(self.temporary.name) + self.parser = self.base / "parser" + self.report = self.base / "input" + self.json_dir = self.report / "acs_jsons" + self.html_dir = self.report / "html_detailed_summaries" + for directory in (self.parser, self.json_dir, self.html_dir): + directory.mkdir(parents=True) + suite = {"canonical": "BSA", "requirement_key": "BSA", "modes": ["SR", "DT"], + "schema": "acs-results-schema.json#/definitions/raw", "json_output": "bsa.json", + "json_to_html": "bsa/json_to_html.py", + "detailed_html": "bsa_detailed.html", "summary_html": "bsa_summary.html"} + self.write(self.parser / "suite_registry.json", {"suites": [suite]}) + raw_schema = { + "type": "object", + "required": ["test_results", "suite_summary"], + "properties": { + "test_results": { + "type": "array" + }, + "suite_summary": { + "type": "object", + "properties": { + "Passed": { + "type": "integer", + "minimum": 0 + } + } + } + } + } + schema = {"$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", + "required": ["Suite_Name: acs_info"], "definitions": {"raw": raw_schema}} + self.write(self.parser / "acs-results-schema.json", schema) + self.raw = {"test_results": [{"Test_suite": "PE", "Test_case": "PE-01", + "Test_case_description": "Check PE", "test_result": "PASSED"}], + "suite_summary": {"Total Rules Run": 1, "Passed": 1, "Failed": 0}} + self.merged = {"Suite_Name: acs_info": {"ACS Results Summary": { + "Overall Compliance Result": "Compliant", + "Suite_Name: Mandatory : BSA_compliance": "Compliant"}}, "Suite_Name: BSA": self.raw} + self.write(self.json_dir / "bsa.json", self.raw) + self.write(self.json_dir / "merged_results.json", self.merged) + self.table = ( + '' + '
Total Tests1
Passed1
Failed0
') + self.detail = ('' + '
BSAMandatoryCompliant
' + self.table + + '' + '
Test CaseDescriptionResult
PE-01Check PEPASSED
') + self.summary = ('
' + '' + '
SRS requirements compliance resultsCompliant
' + '
Mandatory (Compliant)' + + self.table + '
') + (self.html_dir / "acs_summary.html").write_text(self.summary, encoding="utf-8") + (self.html_dir / "bsa_detailed.html").write_text(self.detail, encoding="utf-8") + + @staticmethod + def write(path, data): + """Write a JSON sample inside the test's temporary folder.""" + path.write_text(json.dumps(data), encoding="utf-8") + + def check(self): + """Inspect the sample report and prove Doctor did not rewrite any inputs.""" + before = {str(path): hashlib.sha256(path.read_bytes()).hexdigest() + for path in self.report.rglob("*") if path.is_file()} + ctx = Context(self.parser, self.base / "output", report_inputs=[("SR", self.report)]) + doctor_artifacts.run_reports(ctx) + after = {str(path): hashlib.sha256(path.read_bytes()).hexdigest() + for path in self.report.rglob("*") if path.is_file()} + self.assertEqual(before, after, "Doctor must never rewrite source reports") + evidence = json.loads( + (self.base / "output/evidence/artifacts/0_SR/issues.json").read_text()) + return ctx.findings, evidence["issues"] + + def test_clean_consistent_package_passes_read_only(self): + """Check clean consistent package passes read only.""" + findings, issues = self.check() + self.assertEqual([], issues) + self.assertEqual("PASS", findings[0].status) + + def test_malformed_raw_json_is_not_green(self): + """Check malformed raw JSON is not green.""" + (self.json_dir / "bsa.json").write_text("{broken", encoding="utf-8") + findings, issues = self.check() + self.assertIn("Malformed report JSON", [i["issue"] for i in issues]) + self.assertIn("FAIL", [f.status for f in findings]) + + def test_schema_error_has_exact_path_and_message(self): + """Check schema error has exact path and message.""" + self.raw["suite_summary"]["Passed"] = -1 + self.write(self.json_dir / "bsa.json", self.raw) + _, issues = self.check() + errors = next(i["errors"] for i in issues if i["issue"] == "JSON schema validation failed") + self.assertEqual("/suite_summary/Passed", errors[0]["path"]) + self.assertIn("minimum", errors[0]["message"]) + self.assertIn("Invalid suite counter", [i["issue"] for i in issues]) + + def require_suite_info(self): + """Make the temporary schema require category descriptions for this test.""" + schema_path = self.parser / "acs-results-schema.json" + schema = json.loads(schema_path.read_text()) + schema["definitions"]["raw"]["properties"]["test_results"]["items"] = { + "type": "object", "required": ["Test_suite_info"], + "properties": {"Test_suite_info": {"type": "array", "items": {"type": "string"}}}} + schema["properties"] = {"Suite_Name: BSA": {"$ref": "#/definitions/raw"}} + self.write(schema_path, schema) + + def category_manifest(self, source): + """Record whether the temporary report used a supplied category file.""" + config = self.report / "config" + config.mkdir(exist_ok=True) + category = {"source": source} + if source == "explicit": + # A supplied file without Description must NOT exempt the required result field. + snapshot = config / "test_category.json" + self.write(snapshot, {}) + category.update(path="config/test_category.json", + sha256=hashlib.sha256(snapshot.read_bytes()).hexdigest()) + self.write(config / "parser_run.json", { + "format_version": 1, + "mode": "SR", + "test_category": category + }) + + def test_bundled_info_omission_is_applicable_pass_without_provenance_warning(self): + """Check bundled info omission is applicable pass without provenance warning.""" + self.require_suite_info() + self.category_manifest("bundled") + findings, issues = self.check() + self.assertEqual([], issues) + self.assertTrue(all(f.status == "PASS" for f in findings)) + + def test_legacy_info_omission_warns_without_guessing_bundled_defaults(self): + """Check legacy info omission warns without guessing bundled defaults.""" + self.require_suite_info() + findings, issues = self.check() + self.assertEqual([], issues) + warning = next(f for f in findings if f.check_id == "ARTIFACT.CATEGORY_PROVENANCE") + self.assertEqual("WARN", warning.status) + self.assertIn("bsa.json", warning.actual) + self.assertIn("merged_results.json", warning.actual) + + def test_explicit_info_omission_fails_even_if_supplied_category_has_no_description(self): + """Check explicit info omission fails even if supplied category has no description.""" + self.require_suite_info() + self.category_manifest("explicit") + findings, issues = self.check() + self.assertEqual(2, sum(i["issue"] == "JSON schema validation failed" for i in issues)) + self.assertTrue( + any(f.check_id == "ARTIFACT.SCHEMA" and f.status == "FAIL" for f in findings)) + + def test_present_invalid_info_is_not_exempted_for_bundled_or_legacy(self): + """Check present invalid info is not exempted for bundled or legacy.""" + self.require_suite_info() + self.raw["test_results"][0]["Test_suite_info"] = 42 + self.write(self.json_dir / "bsa.json", self.raw) + self.write(self.json_dir / "merged_results.json", self.merged) + findings, issues = self.check() + self.assertTrue(any(i["issue"] == "JSON schema validation failed" for i in issues)) + self.assertFalse(any(f.check_id == "ARTIFACT.CATEGORY_PROVENANCE" for f in findings)) + self.category_manifest("bundled") + findings, _ = self.check() + self.assertTrue( + any(f.check_id == "ARTIFACT.SCHEMA" and f.status == "FAIL" for f in findings)) + + def test_tampered_category_provenance_fails_without_hiding_other_schema_faults(self): + """Check tampered category provenance fails without hiding other schema faults.""" + self.require_suite_info() + self.category_manifest("explicit") + self.write(self.report / "config/test_category.json", {"tampered": True}) + self.raw["suite_summary"]["Passed"] = -1 + self.write(self.json_dir / "bsa.json", self.raw) + findings, issues = self.check() + self.assertTrue( + any(f.check_id == "ARTIFACT.CATEGORY_PROVENANCE" and f.status == "FAIL" + for f in findings)) + errors = [ + error for issue in issues if issue["issue"] == "JSON schema validation failed" + for error in issue["errors"] + ] + self.assertTrue(any(error["validator"] == "minimum" for error in errors)) + + def test_detail_status_discrepancy_is_detected(self): + """Check detail status discrepancy is detected.""" + (self.html_dir / "bsa_detailed.html").write_text(self.detail.replace( + "Compliant", "Not Compliant"), encoding="utf-8") + _, issues = self.check() + self.assertIn("Detail compliance differs from merged JSON", [i["issue"] for i in issues]) + + def test_overall_verdict_mutation_is_detected_without_changing_suite_results(self): + """Check overall verdict mutation is detected without changing suite results.""" + for expected, actual in (("Not Compliant: BSA failed", "Compliant"), + ("Compliant", "Not Compliant"), + ("Compliant with Waivers: BSA", "Compliant")): + with self.subTest(expected=expected, actual=actual): + self.merged["Suite_Name: acs_info"]["ACS Results Summary"][ + "Overall Compliance Result"] = expected + self.write(self.json_dir / "merged_results.json", self.merged) + (self.html_dir / "acs_summary.html").write_text(self.summary.replace( + 'Compliant', + '' + actual + ''), encoding="utf-8") + findings, issues = self.check() + mismatch = next(issue for issue in issues if issue["issue"] == + "Overall HTML compliance differs from merged JSON") + self.assertEqual(doctor_artifacts.decision(expected), mismatch["expected"]) + self.assertEqual(actual, mismatch["actual"]) + self.assertTrue(any(f.status == "FAIL" for f in findings)) + + def test_overall_verdict_must_be_present_and_unambiguous(self): + """Check overall verdict must be present and unambiguous.""" + marker = ('SRS requirements compliance results' + 'Compliant') + for replacement in ("", marker + '' + marker): + with self.subTest(replacement=replacement): + (self.html_dir / "acs_summary.html").write_text( + self.summary.replace(marker, replacement), encoding="utf-8") + _, issues = self.check() + self.assertIn("Main HTML overall compliance verdict is missing or ambiguous", + [issue["issue"] for issue in issues]) + + def test_matching_overall_verdict_supports_waivers_and_nested_text(self): + """Check matching overall verdict supports waivers and nested text.""" + self.merged["Suite_Name: acs_info"]["ACS Results Summary"][ + "Overall Compliance Result"] = "Compliant with Waivers: BSA" + self.write(self.json_dir / "merged_results.json", self.merged) + (self.html_dir / "acs_summary.html").write_text(self.summary.replace( + 'Compliant', + 'Compliant with waivers'), + encoding="utf-8") + _, issues = self.check() + self.assertEqual([], issues) + + def test_invalid_standalone_results_keep_schema_findings_and_check_later_packages(self): + """Check invalid standalone results keep schema findings and check later packages.""" + valid_report = self.base / "valid_input" + shutil.copytree(self.report, valid_report) + registry = json.loads((self.parser / "suite_registry.json").read_text()) + registry["suites"].append({"canonical": "ONE", "requirement_key": "ONE", + "modes": ["SR"], "waiver_suite": "Standalone", "json_output": "one.json", + "schema": "acs-results-schema.json#/definitions/raw"}) + self.write(self.parser / "suite_registry.json", registry) + for index, value in enumerate((None, 1, "bad", {}, False)): + with self.subTest(value=value): + self.write(self.json_dir / "one.json", {"test_results": value, "suite_summary": {}}) + self.merged["Suite_Name: Standalone"] = [] + self.write(self.json_dir / "merged_results.json", self.merged) + ctx = Context(self.parser, self.base / ("invalid_output_" + str(index)), + report_inputs=[("SR", self.report), ("SR", valid_report)]) + doctor_artifacts.run_reports(ctx) + self.assertTrue(any(f.check_id == "ARTIFACT.SCHEMA" and f.status == "FAIL" + for f in ctx.findings)) + summaries = [f for f in ctx.findings if f.check_id == "ARTIFACT.CONSISTENCY"] + self.assertEqual(["FAIL", "PASS"], [f.status for f in summaries]) + evidence = json.loads( + (ctx.output_dir / "evidence/artifacts/0_SR/issues.json").read_text()) + self.assertTrue(any(error["path"] == "/test_results" + for issue in evidence["issues"] if "errors" in issue + for error in issue["errors"])) + + def test_invalid_results_in_multi_file_aggregate_do_not_crash(self): + """Check invalid results in multi file aggregate do not crash.""" + registry = json.loads((self.parser / "suite_registry.json").read_text()) + registry["suites"][0]["json_output_patterns"] = ["bsa_extra*.json"] + self.write(self.parser / "suite_registry.json", registry) + self.write(self.json_dir / "bsa_extra.json", {"test_results": None, "suite_summary": {}}) + findings, issues = self.check() + self.assertTrue( + any(f.check_id == "ARTIFACT.SCHEMA" and f.status == "FAIL" for f in findings)) + self.assertTrue(any(issue["issue"] == "Invalid result collection" for issue in issues)) + + def test_detail_missing_not_run_reason_is_detected(self): + """Check detail missing not run reason is detected.""" + self.merged["Suite_Name: acs_info"]["ACS Results Summary"][ + "Suite_Name: Mandatory : BSA_compliance"] = "Not Compliant: not run" + self.write(self.json_dir / "merged_results.json", self.merged) + (self.html_dir / "bsa_detailed.html").write_text(self.detail.replace( + "Compliant", "Not Compliant"), encoding="utf-8") + _, issues = self.check() + self.assertIn("Detail compliance differs from merged JSON", [i["issue"] for i in issues]) + + def test_missing_sbmr_peer_row_is_detected(self): + """Check missing SBMR peer row is detected.""" + records = { + "SBMRIB": { + "suite": "SBMR-IB", + "requirement": "Mandatory", + "value": "Compliant" + }, + "SBMROOB": { + "suite": "SBMR-OOB", + "requirement": "Mandatory", + "value": "Not Compliant: not run" + } + } + page = doctor_artifacts.ReportHTML(self.detail.replace("BSA", "SBMR-IB")) + issues = [] + doctor_artifacts._inspect_html(Path("sbmr_detailed.html"), page, records, {}, [], issues, + []) + missing = next(i for i in issues if i["issue"] == "Applicable compliance row is missing") + self.assertEqual("SBMR-OOB", missing["expected"]["suite"]) + + def test_missing_mandatory_standalone_row_is_detected(self): + """Check missing mandatory standalone row is detected.""" + records = {"CAPSULEUPDATE": {"suite": "Capsule Update", "requirement": "Mandatory", + "value": "Not Compliant: not run"}} + registry = [{"canonical": "CAPSULE-UPDATE", "requirement_key": "Capsule Update", + "waiver_suite": "Standalone"}] + issues = [] + doctor_artifacts._inspect_html(Path("standalone_tests_detailed.html"), + doctor_artifacts.ReportHTML(""), records, {}, registry, + issues, []) + self.assertIn("Applicable compliance row is missing", [i["issue"] for i in issues]) + + def test_summary_badge_and_chart_mutations_are_detected(self): + """Check summary badge and chart mutations are detected.""" + text = self.summary.replace(">Mandatory (Compliant)<", ">Recommended (Not Compliant)<") + text = text.replace("Passed1", "Passed2") + (self.html_dir / "acs_summary.html").write_text(text, encoding="utf-8") + _, issues = self.check() + self.assertIn("Summary badge differs from merged JSON", [i["issue"] for i in issues]) + self.assertIn("Chart differs from raw suite summary", [i["issue"] for i in issues]) + + def test_broken_local_link_is_detected(self): + """Check broken local link is detected.""" + (self.html_dir / "acs_summary.html").write_text( + self.summary + 'Details', encoding="utf-8") + _, issues = self.check() + self.assertIn("Broken local HTML link", [i["issue"] for i in issues]) + + def test_unreadable_merged_is_not_green(self): + """Check unreadable merged is not green.""" + (self.json_dir / "merged_results.json").write_text("null", encoding="utf-8") + _, issues = self.check() + self.assertIn("Merged JSON is missing or unreadable", [i["issue"] for i in issues]) + + def test_unknown_green_and_false_green_failure_are_detected(self): + """Check unknown green and false green failure are detected.""" + self.raw["test_results"][0]["test_result"] = "UNKNOWN" + self.raw["suite_summary"] = {"Total Rules Run": 1, "Passed": 0, "Failed": 1} + self.write(self.json_dir / "bsa.json", self.raw) + _, issues = self.check() + self.assertIn("UNKNOWN result is reported as compliant", [i["issue"] for i in issues]) + self.assertIn("Unwaived suite failures are reported as compliant", + [i["issue"] for i in issues]) + + def test_sr_os_tool_exception_is_not_a_false_alarm(self): + """Check SR OS tool exception is not a false alarm.""" + issues = [] + raw = {"test_results": [{"SRS scope": "Recommended", "test_result": "FAILED"}], + "suite_summary": {"total_failed": 1}} + doctor_artifacts._raw_integrity(Path("os_test.json"), raw, + {"value": "Compliant"}, issues, sr_os=True) + self.assertEqual([], issues) + + def test_invalid_counter_types_cannot_crash_or_pass(self): + """Check invalid counter types cannot crash or pass.""" + for value in (float("nan"), float("inf"), True, "1", -1, 1.5): + with self.subTest(value=value): + issues = [] + doctor_artifacts._raw_integrity(Path("bsa.json"), + {"suite_summary": {"Passed": value}}, None, issues) + self.assertIn("Invalid suite counter", [i["issue"] for i in issues]) + + def test_broken_schema_evaluator_is_blocked_not_parser_failure(self): + """Check broken schema evaluator is blocked not parser failure.""" + (self.parser / "acs-results-schema.json").write_text("{broken", encoding="utf-8") + findings, issues = self.check() + self.assertIn("Schema validation could not execute", [i["issue"] for i in issues]) + self.assertTrue(all(f.status == "BLOCKED" for f in findings)) + + def test_empty_input_and_missing_report_are_explicit(self): + """Check empty input and missing report are explicit.""" + ctx = Context(self.parser, self.base / "out") + doctor_artifacts.run_reports(ctx) + self.assertEqual("WARN", ctx.findings[0].status) + ctx = Context(self.parser, self.base / "out2", report_inputs=[("DT", self.base / "absent")]) + doctor_artifacts.run_reports(ctx) + self.assertEqual("BLOCKED", ctx.findings[0].status) + + def test_strict_json_rejects_duplicate_keys_and_nonfinite_values(self): + """Check strict JSON rejects duplicate keys and nonfinite values.""" + for text in ('{"nested":{"result":"PASS","result":"FAIL"}}', + '{"value":NaN}', '{"value":Infinity}', '{"value":-Infinity}', + '{"value":1e999}'): + with self.subTest(text=text): + path = self.base / "ambiguous.json" + path.write_text(text, encoding="utf-8") + with self.assertRaises(ValueError): + doctor_artifacts._strict_json(path) + path.write_text('{"value":[1,0.5,null,true]}', encoding="utf-8") + self.assertEqual({"value": [1, 0.5, None, True]}, doctor_artifacts._strict_json(path)) + + def test_duplicate_raw_json_keys_fail_without_suppressing_html_errors(self): + """Check duplicate raw JSON keys fail without suppressing HTML errors.""" + (self.json_dir / "bsa.json").write_text('{"x":1,"x":2}', encoding="utf-8") + (self.html_dir / "acs_summary.html").write_text(self.summary + + 'X') + findings, issues = self.check() + self.assertIn("Malformed report JSON", [i["issue"] for i in issues]) + self.assertIn("Broken local HTML link", [i["issue"] for i in issues]) + self.assertTrue(any(f.check_id == "ARTIFACT.JSON" and f.status == "FAIL" for f in findings)) + self.assertTrue(any(f.check_id == "ARTIFACT.HTML" and f.status == "FAIL" for f in findings)) + + def test_raw_merged_balanced_status_swap_is_detected(self): + """Check raw merged balanced status swap is detected.""" + failed = { + "Test_case": "PE-02", + "Test_case_description": "Second PE", + "test_result": "FAILED" + } + self.raw["test_results"].append(failed) + self.raw["suite_summary"] = {"Total Rules Run": 2, "Passed": 1, "Failed": 1} + self.merged = deepcopy(self.merged) + self.merged["Suite_Name: BSA"]["test_results"][0]["test_result"] = "FAILED" + self.merged["Suite_Name: BSA"]["test_results"][1]["test_result"] = "PASSED" + self.write(self.json_dir / "bsa.json", self.raw) + self.write(self.json_dir / "merged_results.json", self.merged) + _, issues = self.check() + self.assertIn("Raw and merged result records differ", [i["issue"] for i in issues]) + self.assertNotIn("Raw and merged suite counters differ", [i["issue"] for i in issues]) + difference = next(i["actual"] for i in issues + if i["issue"] == "Raw and merged result records differ") + self.assertEqual("/test_results/0/test_result", difference["path"]) + self.assertEqual("PASSED", difference["expected"]) + self.assertEqual("FAILED", difference["actual"]) + + def test_merge_enrichment_is_allowed_but_identity_change_is_not(self): + """Check merge enrichment is allowed but identity change is not.""" + enriched = deepcopy(self.raw) + enriched["test_results"][0].update({ + "Waivable": "yes", + "SRS scope": "Mandatory", + "Test_suite_info": "metadata", + "Main Readiness Grouping": "PE" + }) + suite = {"canonical": "BSA"} + for change, expected in ((False, []), (True, ["Raw and merged result records differ"])): + with self.subTest(change=change): + if change: + enriched["test_results"][0]["Test_case"] = "other" + issues = [] + doctor_artifacts._merged_parity(self.report, + {"BSA": [(Path("bsa.json"), self.raw)]}, + {"Suite_Name: BSA": enriched}, [suite], issues) + self.assertEqual(expected, [i["issue"] for i in issues]) + + def test_multi_distribution_os_records_do_not_overwrite_each_other(self): + """Check multi distribution OS records do not overwrite each other.""" + suites = [{ + "canonical": "OS-TESTS", + "requirement_key": "OS_TEST", + "json_output": "os_test.json" + }] + second = deepcopy(self.raw) + second["test_results"][0]["Test_case"] = "ubuntu-02" + inputs = {"OS-TESTS": [(Path("ethtool_test_linux1.json"), self.raw), + (Path("ethtool_test_linux2.json"), second)]} + merged = {"Suite_Name: OS Tests - ethtool_test_linux1": self.raw, + "Suite_Name: OS Tests - ethtool_test_linux2": second} + issues = [] + doctor_artifacts._merged_parity(self.report, inputs, merged, suites, issues) + self.assertEqual([], issues) + merged["Suite_Name: OS Tests - ethtool_test_linux1"] = second + doctor_artifacts._merged_parity(self.report, inputs, merged, suites, issues) + self.assertIn("Raw and merged result records differ", [i["issue"] for i in issues]) + + def test_standalone_aggregate_preserves_all_records_and_waiver_reasons(self): + """Check standalone aggregate preserves all records and waiver reasons.""" + a = { + "test_results": [{ + "Test_case": "one", + "test_result": "FAILED (WITH WAIVER)", + "waiver_reason": "accepted" + }] + } + b = {"test_results": [{"Test_case": "two", "test_result": "PASSED"}]} + suites = [{"canonical": name, "waiver_suite": "Standalone"} for name in ("ONE", "TWO")] + raw = {"ONE": [(Path("one.json"), a)], "TWO": [(Path("two.json"), b)]} + merged = {"Suite_Name: Standalone": deepcopy(b["test_results"] + a["test_results"])} + issues = [] + doctor_artifacts._merged_parity(self.report, raw, merged, suites, issues) + self.assertEqual([], issues) + merged["Suite_Name: Standalone"][1]["waiver_reason"] = "lost reason" + doctor_artifacts._merged_parity(self.report, raw, merged, suites, issues) + self.assertIn("Raw and merged result records differ", [i["issue"] for i in issues]) + + def test_stale_merged_section_with_no_raw_input_is_detected(self): + """Check stale merged section with no raw input is detected.""" + self.merged["Suite_Name: SCT"] = deepcopy(self.raw) + self.write(self.json_dir / "merged_results.json", self.merged) + _, issues = self.check() + self.assertIn("Merged result section has no matching raw input", + [i["issue"] for i in issues]) + + def test_anchor_checks_include_percent_encoded_and_same_page_fragments(self): + """Check anchor checks include percent encoded and same page fragments.""" + detail = self.detail + '
' + (self.html_dir / "bsa_detailed.html").write_text(detail) + (self.html_dir / "acs_summary.html").write_text(self.summary + + 'OKOK' + 'BadBad') + _, issues = self.check() + broken = [i for i in issues if i["issue"] == "Broken local HTML fragment"] + self.assertEqual(2, len(broken)) + + def test_duplicate_html_ids_and_empty_link_target_are_detected(self): + """Check duplicate HTML IDS and empty link target are detected.""" + (self.html_dir / "empty.html").write_text("") + (self.html_dir / "acs_summary.html").write_text(self.summary + + '
Bad') + _, issues = self.check() + self.assertIn("Duplicate HTML element ID", [i["issue"] for i in issues]) + self.assertIn("Broken local HTML link", [i["issue"] for i in issues]) + + def test_external_symlink_is_not_read(self): + """Check external symlink is not read.""" + outside = self.base / "external.json" + outside.write_text('{"secret":"NEVER_READ_THIS"}') + (self.json_dir / "bsa.json").unlink() + (self.json_dir / "bsa.json").symlink_to(outside) + findings, issues = self.check() + self.assertIn("Report input escapes supplied package", [i["issue"] for i in issues]) + self.assertNotIn("NEVER_READ_THIS", repr(issues) + repr(findings)) + + def test_detail_identity_balanced_swap_and_nested_parent_rows(self): + """Check detail identity balanced swap and nested parent rows.""" + data = { + "test_results": [{ + "testcases": [{ + "Test_case": + "parent", + "Test_case_description": + "root", + "Test_result": + "FAILED", + "subtests": [{ + "sub_Test_Number": "child", + "sub_Test_Description": "leaf", + "sub_test_result": "PASSED" + }] + }] + }] + } + expected = doctor_artifacts._raw_detail_records(data, "bsa/json_to_html.py") + markup = ( + '' + '' + '
Test CaseDescriptionResult
parentrootFAILED
' + '
Subtest #DescriptionResult
childleafPASSED
') + actual, tables = doctor_artifacts._html_detail_records(doctor_artifacts.ReportHTML(markup)) + self.assertEqual(expected, actual) + self.assertEqual(2, tables) + swapped = markup.replace('>FAILED<', + '>TMP<').replace('>PASSED<', + '>FAILED<').replace('>TMP<', '>PASSED<') + actual, _ = doctor_artifacts._html_detail_records(doctor_artifacts.ReportHTML(swapped)) + self.assertNotEqual(expected, actual) + self.assertEqual(Counter(record[2] for record in expected), + Counter(record[2] for record in actual)) + + @staticmethod + def reason_button_detail_fixture(): + """Build parent and child rows with expandable diagnostic text.""" + data = {"test_results": [{"testcases": [ + {"Test_case": "B_GIC_02 : 202", "Test_case_description": "Parent check", + "Test_result": "FAILED", "subtests": [ + {"sub_Test_Number": "B_GIC_02 : 202.1", "sub_Test_Description": "Child check", + "sub_test_result": "PASSED"}]}]}]} + # Match the BSA/SBSA report shape: visible IDs are reason disclosure + # buttons, while folded reason content occupies its own non-result cell. + markup = ( + '' + '' + '' + '' + '
Test CaseDescriptionResultWaiver ReasonReason
' + 'Parent checkFAILEDN/A' + '
' + 'View full reason' + 'OTHER_ID : 999 PASSED is diagnostic text, not another result.' + '
' + '' + '
' + '' + '' + '' + '
Sub Test NumberDescriptionResultWaiver ReasonReason
' + 'Child checkPASSEDN/A
' + 'View full reasonFAILED is quoted diagnostic text.' + '
') + return data, markup + + def test_reason_rule_button_labels_keep_bsa_and_sbsa_parent_child_identities(self): + """Check reason rule button labels keep BSA and SBSA parent child identities.""" + data, markup = self.reason_button_detail_fixture() + expected = doctor_artifacts._raw_detail_records(data, "bsa/json_to_html.py") + parsed = doctor_artifacts.ReportHTML(markup) + actual, tables = doctor_artifacts._html_detail_records(parsed) + self.assertEqual(expected, actual) + self.assertEqual(sum(actual.values()), 2) + self.assertEqual(tables, 2) + for suite in ("BSA", "SBSA"): + with self.subTest(suite=suite): + name = suite.lower() + "_detailed.html" + registry = [{"canonical": suite, "detailed_html": name, + "json_to_html": "bsa/json_to_html.py"}] + issues = [] + doctor_artifacts._detail_parity(Path(name), parsed, + {suite: [(Path(suite.lower() + ".json"), data)]}, registry, issues, []) + self.assertEqual(issues, []) + + def test_reason_rule_buttons_do_not_hide_missing_or_changed_result_identity(self): + """Check reason rule buttons do not hide missing or changed result identity.""" + data, markup = self.reason_button_detail_fixture() + expected = doctor_artifacts._raw_detail_records(data, "bsa/json_to_html.py") + mutations = ( + markup.replace('B_GIC_02 : 202', ''), + markup.replace('B_GIC_02 : 202.1', 'WRONG_ID'), + markup.replace('Child check', 'Different check'), + markup.replace('FAILED', 'TMP') + .replace('PASSED', 'FAILED') + .replace('TMP', 'PASSED')) + for index, changed in enumerate(mutations): + with self.subTest(mutation=index): + actual, _ = doctor_artifacts._html_detail_records( + doctor_artifacts.ReportHTML(changed)) + self.assertNotEqual(expected, actual) + self.assertTrue(expected - actual) + self.assertTrue(actual - expected) + + def test_generic_and_hidden_reason_controls_still_do_not_enter_result_cells(self): + """Check generic and hidden reason controls still do not enter result cells.""" + markup = ('' + '' + '
Test CaseDescriptionResult
plain-idPlain checkPASSED
') + actual, _ = doctor_artifacts._html_detail_records(doctor_artifacts.ReportHTML(markup)) + self.assertEqual(actual, Counter({("plain-id", "Plain check", "PASSED"): 1})) + + def test_unknown_detail_identity_contract_is_blocked_not_green(self): + """Check unknown detail identity contract is blocked not green.""" + del self.raw["test_results"][0]["Test_case"] + self.write(self.json_dir / "bsa.json", self.raw) + self.write(self.json_dir / "merged_results.json", self.merged) + findings, issues = self.check() + self.assertIn("Detailed identity comparison could not execute", + [i["issue"] for i in issues]) + self.assertTrue(all(f.status == "BLOCKED" for f in findings)) + + def test_missing_and_extra_chart_categories_are_detected(self): + """Check missing and extra chart categories are detected.""" + text = self.summary.replace('Failed0', + 'Ignored3') + (self.html_dir / "acs_summary.html").write_text(text) + _, issues = self.check() + differences = [i for i in issues if i["issue"] == "Chart differs from raw suite summary"] + self.assertEqual({"failed", "ignored"}, {i["count"] for i in differences}) + + def test_combined_sbmr_detail_keeps_both_interface_records(self): + """Check combined SBMR detail keeps both interface records.""" + ib = { + "test_results": [{ + "Test_case": "ib-host", + "Test_case_description": "Host", + "Test_result": "PASSED" + }] + } + oob = { + "test_results": [{ + "Test_case": "oob-host", + "Test_case_description": "Host", + "Test_result": "FAILED" + }] + } + inputs = {"SBMR-IB": [(Path("ib.json"), ib)], "SBMR-OOB": [(Path("oob.json"), oob)]} + suites = [{ + "canonical": name, + "json_to_html": "sbmr/json_to_html.py", + "detailed_html": filename + } for name, filename in (("SBMR-IB", "sbmr_ib_detailed.html"), ("SBMR-OOB", + "sbmr_oob_detailed.html"))] + text = ('' + '' + '
Test CaseDescriptionResult
ib-hostHostPASSED
oob-hostHostFAILED
') + issues, coverage = [], [] + doctor_artifacts._detail_parity(Path("sbmr_detailed.html"), + doctor_artifacts.ReportHTML(text), inputs, suites, issues, + coverage) + self.assertEqual([], issues) + text = text.replace('oob-host', 'ib-host') + doctor_artifacts._detail_parity(Path("sbmr_detailed.html"), + doctor_artifacts.ReportHTML(text), inputs, suites, issues, + coverage) + self.assertIn("Raw and detailed HTML result identities differ", + [i["issue"] for i in issues]) + + def test_unescaped_description_text_is_not_treated_as_equal(self): + """Check unescaped description text is not treated as equal.""" + text = self.detail.replace('Check PE', 'Check register <n>') + data = deepcopy(self.raw) + data["test_results"][0]["Test_case_description"] = "Check register " + expected = doctor_artifacts._raw_detail_records(data, "bsa/json_to_html.py") + actual, _ = doctor_artifacts._html_detail_records(doctor_artifacts.ReportHTML(text)) + self.assertEqual(expected, actual) + actual, _ = doctor_artifacts._html_detail_records(doctor_artifacts.ReportHTML( + text.replace('<n>', ''))) + self.assertNotEqual(expected, actual) + + def test_sct_parent_without_subtests_still_requires_a_visible_result(self): + """Check SCT parent without subtests still requires a visible result.""" + data = { + "test_results": [{ + "Test_case": "SCT-01", + "Test_case_description": "Parent failure", + "Test_result": "FAILED", + "subtests": [] + }] + } + suites = [{ + "canonical": "SCT", + "json_to_html": "bbr/sct/json_to_html.py", + "detailed_html": "sct_detailed.html" + }] + issues, coverage = [], [] + doctor_artifacts._detail_parity(Path("sct_detailed.html"), doctor_artifacts.ReportHTML(""), + {"SCT": [(Path("sct.json"), data)]}, suites, issues, + coverage) + self.assertIn("Detailed result rows are missing", [i["issue"] for i in issues]) + + @staticmethod + def sct_heading_page(status="IGNORED", children=""): + """Build SCT's heading-based parent result with optional subtest rows.""" + return ('
Test Suite Name: Misc
' + '
Test Case: SCT-01
' + '
Test Case Description: Parent check
' + '
Test Entry Point GUID: parent-guid
' + '
Test Result: ' + status + '
' + '' + '' + children + '
Sub Test GUIDSub Test DescriptionSub Test Result
') + + def sct_parity_issues(self, data, text): + """Compare an SCT JSON sample with the corresponding visible HTML text.""" + issues = [] + suites = [{"canonical": "SCT", "json_to_html": "bbr/sct/json_to_html.py", + "detailed_html": "sct_detailed.html"}] + doctor_artifacts._detail_parity(Path("sct_detailed.html"), + doctor_artifacts.ReportHTML(text), + {"SCT": [(Path("sct.json"), data)]}, suites, issues, []) + return issues + + def test_sct_childless_heading_results_match_raw_statuses(self): + """Check SCT childless heading results match raw statuses.""" + for status in ("IGNORED", "SKIPPED", "NOT SUPPORTED", "FAILED"): + with self.subTest(status=status): + data = { + "test_results": [{ + "Test_case": "SCT-01", + "Test_case_description": "Parent check", + "test_result": status, + "subtests": [] + }] + } + self.assertEqual([], self.sct_parity_issues(data, self.sct_heading_page(status))) + + def test_sct_heading_does_not_double_count_child_results(self): + """Check SCT heading does not double count child results.""" + data = { + "test_results": [{ + "Test_case": + "SCT-01", + "Test_case_description": + "Parent check", + "test_result": + "FAILED", + "subtests": [{ + "sub_Test_GUID": "child-guid", + "sub_Test_Description": "Child check", + "sub_test_result": "FAILED" + }] + }] + } + child = 'child-guidChild checkFAILED' + self.assertEqual([], self.sct_parity_issues(data, self.sct_heading_page("FAILED", child))) + self.assertTrue(self.sct_parity_issues(data, self.sct_heading_page("FAILED"))) + + def test_sct_childless_heading_mutations_and_missing_fields_are_detected(self): + """Check SCT childless heading mutations and missing fields are detected.""" + data = {"test_results": [{"Test_case": "SCT-01", "Test_case_description": "Parent check", + "test_result": "IGNORED", "subtests": []}]} + text = self.sct_heading_page() + mutations = (text.replace("SCT-01", + "SCT-02"), text.replace("Parent check", "Different check"), + text.replace("IGNORED", "PASSED"), + text.replace('
Test Result: IGNORED
', + ""), + text.replace('
Test Case: SCT-01
', "")) + for changed in mutations: + with self.subTest(markup=changed): + issues = self.sct_parity_issues(data, changed) + self.assertIn("Raw and detailed HTML result identities differ", + [i["issue"] for i in issues]) + + def test_sct_childless_heading_duplicate_multiplicity_is_preserved(self): + """Check SCT childless heading duplicate multiplicity is preserved.""" + entry = {"Test_case": "SCT-01", "Test_case_description": "Parent check", + "test_result": "IGNORED", "subtests": []} + text = self.sct_heading_page() + self.assertEqual([], self.sct_parity_issues({"test_results": [entry, entry]}, text + text)) + self.assertTrue(self.sct_parity_issues({"test_results": [entry, entry]}, text)) + self.assertTrue(self.sct_parity_issues({"test_results": [entry]}, text + text)) + + def test_sct_heading_contract_is_not_applied_to_other_renderers(self): + """Check SCT heading contract is not applied to other renderers.""" + actual, _ = doctor_artifacts._html_detail_records( + doctor_artifacts.ReportHTML(self.sct_heading_page())) + self.assertEqual(Counter(), actual) + + def test_chart_total_is_derived_when_raw_has_only_status_counts(self): + """Check chart total is derived when raw has only status counts.""" + data = { + "suite_summary": { + "total_passed": 8, + "total_failed": 1, + "total_failed_with_waiver": 2 + } + } + registry = [{"canonical": "FWTS", "summary_html": "fwts_summary.html"}] + text = ('' + '' + '
Total Tests11
Passed8
Failed1
Failed with Waiver2
') + issues, coverage = [], [] + doctor_artifacts._inspect_html(Path("fwts_summary.html"), doctor_artifacts.ReportHTML(text), + {}, {"FWTS": data}, registry, issues, coverage) + self.assertEqual([], issues) + doctor_artifacts._inspect_html(Path("fwts_summary.html"), + doctor_artifacts.ReportHTML(text.replace('>11<', '>9<')), {}, + {"FWTS": data}, registry, issues, coverage) + difference = next(i for i in issues if i["issue"] == "Chart differs from raw suite summary") + self.assertEqual("total", difference["count"]) + self.assertEqual(11, difference["expected"]) + self.assertEqual(9, difference["actual"]) + + def test_sbmr_zero_ignored_counter_has_no_required_chart_row(self): + """Check SBMR zero ignored counter has no required chart row.""" + registry = [{"canonical": "SBMR-IB", "summary_html": "sbmr_ib_summary.html"}] + data = {"suite_summary": {"total_passed": 1, "total_ignored": 0}} + text = ('' + '
Total Tests1
Passed1
') + issues, coverage = [], [] + doctor_artifacts._inspect_html(Path("sbmr_ib_summary.html"), + doctor_artifacts.ReportHTML(text), {}, {"SBMR-IB": data}, + registry, issues, coverage) + self.assertEqual([], issues) + data["suite_summary"]["total_ignored"] = 2 + doctor_artifacts._inspect_html(Path("sbmr_ib_summary.html"), + doctor_artifacts.ReportHTML(text), {}, {"SBMR-IB": data}, + registry, issues, coverage) + differences = [i for i in issues if i["issue"] == "Chart differs from raw suite summary"] + self.assertEqual({"total", "ignored"}, {i["count"] for i in differences}) + + +# Browser and PDF evidence: successful commands alone are not proof of success. + +def marker(checks=8, failures=None): + """Build the result marker that Doctor expects from its browser checks.""" + return '
' + json.dumps({
+        "checks": checks, "failures": failures if failures is not None else []}) + '
' + + +def pdf_text(prefix="SBBR", outcome="fail"): + """Build sample extracted PDF text with known counts and compliance.""" + passed, failed, waived, compliance = visual.OUTCOMES[outcome] + return (prefix + "-FWTS Test Summary\nSRS requirements compliance results\n" + + compliance + "\nTotal Tests 2\nPassed " + str(passed) + "\nFailed " + + str(failed) + "\nFailed with Waiver " + str(waived)) + + +class BrowserResultTests(unittest.TestCase): + """Reject browser output unless the requested checks actually reported results.""" + + def test_executed_positive_control(self): + """Check executed positive control.""" + self.assertEqual(visual.browser_result(marker()), {"checks": 8, "failures": []}) + + def test_reported_assertion_failures_are_preserved(self): + """Check reported assertion failures are preserved.""" + self.assertEqual(visual.browser_result(marker(failures=["Wrong chart count"]))["failures"], + ["Wrong chart count"]) + + def test_no_marker_cannot_be_a_successful_browser_run(self): + """Check no marker cannot be a successful browser run.""" + for text in ("", "Nice report", "Chrome exited normally"): + with self.subTest(text=text): + with self.assertRaisesRegex(ValueError, "without running"): + visual.browser_result(text) + + def test_zero_few_boolean_and_noninteger_checks_are_incomplete(self): + """Check zero few boolean and noninteger checks are incomplete.""" + for checks in (0, 1, 3, -1, True, 4.0, "8", None): + with self.subTest(checks=checks): + with self.assertRaises(ValueError): + visual.browser_result(marker(checks=checks)) + + def test_failures_must_be_a_list(self): + """Check failures must be a list.""" + for failures in ("", "no failure", {}, False): + with self.subTest(failures=failures): + with self.assertRaises(ValueError): + visual.browser_result(marker(failures=failures)) + + def test_bad_json_and_non_object_payloads_are_controlled_errors(self): + """Check bad JSON and non object payloads are controlled errors.""" + for payload in ("broken", "[]", "null", "1", '"text"', '{}'): + with self.subTest(payload=payload): + with self.assertRaises(ValueError): + visual.browser_result('
' + payload + '
') + + def test_dom_encoded_json_is_decoded(self): + """Check dom encoded JSON is decoded.""" + text = marker(failures=["Expected A & B"]).replace("&", "&") + self.assertEqual(visual.browser_result(text)["failures"], ["Expected A & B"]) + + +class PdfContractTests(unittest.TestCase): + """Check that PDF text retains suite names, exact counts and compliance.""" + + def test_positive_controls_for_both_modes_and_all_outcomes(self): + """Check positive controls for both modes and all outcomes.""" + for prefix in ("EBBR", "SBBR"): + for outcome in visual.OUTCOMES: + with self.subTest(prefix=prefix, outcome=outcome): + self.assertEqual( + visual.pdf_problems(pdf_text(prefix, outcome), prefix, outcome), []) + + def test_print_wrapping_and_extra_whitespace_do_not_change_semantics(self): + """Check print wrapping and extra whitespace do not change semantics.""" + text = pdf_text().replace(" ", " \n ") + self.assertEqual(visual.pdf_problems(text, "SBBR", "fail"), []) + + def test_wrong_or_missing_suite_identity_is_detected(self): + """Check wrong or missing suite identity is detected.""" + for replacement in ("EBBR-FWTS", "SBBR-SCT", "", "NOT-SBBR-FWTS"): + with self.subTest(replacement=replacement): + text = pdf_text().replace("SBBR-FWTS", replacement) + self.assertTrue(any("suite identity" in issue + for issue in visual.pdf_problems(text, "SBBR", "fail"))) + + def test_noncompliant_is_not_accepted_as_compliant_substring(self): + """Check noncompliant is not accepted as compliant substring.""" + self.assertTrue( + any("Expected overall Compliant" in issue + for issue in visual.pdf_problems(pdf_text(outcome="fail"), "SBBR", "pass"))) + + def test_waiver_status_must_not_be_reduced_to_plain_compliant(self): + """Check waiver status must not be reduced to plain compliant.""" + text = pdf_text(outcome="waived").replace("Compliant with waivers", "Compliant") + self.assertTrue(any("Expected overall Compliant with waivers" in issue + for issue in visual.pdf_problems(text, "SBBR", "waived"))) + + def test_missing_compliance_heading_cannot_match_unrelated_status(self): + """Check missing compliance heading cannot match unrelated status.""" + text = pdf_text().replace("SRS requirements compliance results", "Unrelated test output") + self.assertTrue( + any("actual missing" in issue for issue in visual.pdf_problems(text, "SBBR", "fail"))) + + def test_each_exact_counter_is_independently_checked(self): + """Check each exact counter is independently checked.""" + for label in ("Total Tests 2", "Passed 1", "Failed 1", "Failed with Waiver 0"): + with self.subTest(label=label): + text = pdf_text().replace(label, label.rsplit(" ", 1)[0] + " 9") + self.assertTrue(any("Expected PDF count" in issue + for issue in visual.pdf_problems(text, "SBBR", "fail"))) + + def test_count_prefix_does_not_accept_ten_as_one(self): + """Check count prefix does not accept ten as one.""" + text = pdf_text().replace("Passed 1", "Passed 10") + self.assertTrue( + any("Passed=1" in issue for issue in visual.pdf_problems(text, "SBBR", "fail"))) + + def test_contradictory_duplicate_count_cannot_hide_behind_matching_count(self): + """Check contradictory duplicate count cannot hide behind matching count.""" + self.assertTrue(visual.pdf_problems(pdf_text() + "\nPassed 9", "SBBR", "fail")) + + def test_empty_pdf_text_never_passes(self): + """Check empty PDF text never passes.""" + self.assertGreaterEqual(len(visual.pdf_problems("", "SBBR", "fail")), 6) + + +class BrowserExecutionTests(unittest.TestCase): + """Check browser setup and outcomes using fake server and command responses.""" + + def invoke(self, stdout, returncode=0): + """Simulate both browser sizes without launching a browser or HTTP server.""" + folder = tempfile.TemporaryDirectory() + self.addCleanup(folder.cleanup) + root = Path(folder.name) + source, destination = root / "source", root / "browser" + source.mkdir() + destination.mkdir() + page = source / "fwts_detailed.html" + content = 'Results

FWTS

' + page.write_text(content) + ctx = Context(root, root) + ctx.run = mock.Mock(return_value=subprocess.CompletedProcess([], returncode, stdout)) + server = mock.Mock(server_port=41111) + with mock.patch.object(visual, "ThreadingHTTPServer", return_value=server), \ + mock.patch.object(visual, "Thread") as thread: + visual.check_browser(ctx, "/browser", page, destination, "SR", "fail") + self.assertEqual(page.read_text(), content, + "Original generated report must not be instrumented in place") + self.assertIn("doctor-browser-result", (destination / page.name).read_text()) + self.assertIn("window.doctorErrors", (destination / page.name).read_text()) + server.shutdown.assert_called_once() + server.server_close.assert_called_once() + thread.return_value.join.assert_called_once() + return ctx + + def test_both_viewports_must_execute_and_pass(self): + """Check both viewports must execute and pass.""" + ctx = self.invoke(marker()) + self.assertEqual(len(ctx.findings), 2) + self.assertTrue(all(finding.status == "PASS" for finding in ctx.findings)) + sizes = {next(str(arg) for arg in call.args[0] if str(arg).startswith("--window-size=")) + for call in ctx.run.call_args_list} + self.assertEqual(sizes, {"--window-size=1600,900", "--window-size=430,900"}) + + def test_javascript_assertion_failure_is_failure(self): + """Check javascript assertion failure is failure.""" + ctx = self.invoke(marker(failures=["Report overflows viewport"])) + self.assertTrue(all(finding.status == "FAIL" for finding in ctx.findings)) + self.assertTrue(all("overflows" in finding.actual for finding in ctx.findings)) + + def test_successful_process_without_assertions_is_failure(self): + """Check successful process without assertions is failure.""" + ctx = self.invoke("Uninitialized report") + self.assertTrue(all(finding.status == "FAIL" for finding in ctx.findings)) + + def test_nonzero_browser_exit_cannot_pass_matching_marker(self): + """Check nonzero browser exit cannot pass matching marker.""" + ctx = self.invoke(marker(), returncode=1) + self.assertTrue(all(finding.status == "FAIL" for finding in ctx.findings)) + + +class VisualDependencyTests(unittest.TestCase): + """Keep browser and PDF checks independent when one tool is unavailable.""" + + def setUp(self): + self.folder = tempfile.TemporaryDirectory() + self.addCleanup(self.folder.cleanup) + self.root = Path(self.folder.name) + self.ctx = Context(self.root / "source", self.root / "output", modes=("DT",)) + self.ctx.portable_parser = self.root / "package" / "log_parser" + + def completed(self, code=0, text="ok"): + """Return a fake command result for a dependency or generation step.""" + return subprocess.CompletedProcess([], code, text) + + def test_no_verified_package_is_blocked_and_does_not_invoke_tools(self): + """Check no verified package is blocked and does not invoke tools.""" + self.ctx.portable_parser = None + self.ctx.run = mock.Mock() + visual.run_visual(self.ctx) + self.assertEqual(self.ctx.findings[0].check_id, "VISUAL_PACKAGE") + self.assertEqual(self.ctx.findings[0].status, "BLOCKED") + self.ctx.run.assert_not_called() + + def test_absent_browser_and_pdf_dependencies_are_both_blocked(self): + """Check absent browser and PDF dependencies are both blocked.""" + self.ctx.run = mock.Mock(return_value=self.completed(1, "missing package")) + with mock.patch.object(visual.shutil, "which", return_value=None): + visual.run_visual(self.ctx) + self.assertEqual({finding.check_id: finding.status for finding in self.ctx.findings}, { + "VISUAL_BROWSER_DEPENDENCY": "BLOCKED", "VISUAL_PDF_DEPENDENCY": "BLOCKED"}) + self.ctx.run.assert_called_once() + + def test_missing_browser_does_not_suppress_available_pdf_checks(self): + """Check missing browser does not suppress available PDF checks.""" + calls = [] + + def invoke(command, directory, name, **kwargs): + """Simulate PDF text extraction while leaving browser checks unavailable.""" + calls.append(name) + if name == "pdf-read": + outcome = Path(directory).name.split("_", 1)[1] + (Path(directory) / "pdf-text.txt").write_text(pdf_text("EBBR", outcome)) + return self.completed() + + self.ctx.run = invoke + with mock.patch.object(visual.shutil, "which", return_value=None): + visual.run_visual(self.ctx) + self.assertEqual(calls.count("pdf-read"), 3) + self.assertEqual([finding.status for finding in self.ctx.findings + if finding.check_id == "VISUAL_BROWSER_DEPENDENCY"], ["BLOCKED"]) + self.assertEqual([finding.status for finding in self.ctx.findings + if finding.check_id == "VISUAL_PDF"], ["PASS", "PASS", "PASS"]) + + def test_missing_pdf_dependencies_do_not_suppress_available_browser_checks(self): + """Check missing PDF dependencies do not suppress available browser checks.""" + browser = self.root / "chromium" + browser.write_text("synthetic executable path; never invoked") + self.ctx.browser = browser + + def invoke(command, directory, name, **kwargs): + """Provide generated HTML while simulating a missing PDF dependency.""" + if name == "pdf-dependencies": + return self.completed(1, "pypdf missing") + if name == "generate": + reports = Path(directory) / "output" / "html_detailed_summaries" + reports.mkdir(parents=True) + for page in ("acs_summary.html", "fwts_detailed.html"): + (reports / page).write_text("Generated report") + return self.completed() + + self.ctx.run = invoke + with mock.patch.object(visual, "check_browser") as check: + visual.run_visual(self.ctx) + self.assertEqual(check.call_count, 6) + self.assertEqual([finding.status for finding in self.ctx.findings + if finding.check_id == "VISUAL_PDF_DEPENDENCY"], ["BLOCKED"]) + self.assertFalse(any(finding.check_id == "VISUAL_PDF" for finding in self.ctx.findings)) + + def test_failed_generation_does_not_create_green_browser_results(self): + """Check failed generation does not create green browser results.""" + browser = self.root / "chromium" + browser.write_text("synthetic") + self.ctx.browser = browser + self.ctx.run = mock.Mock(side_effect=[self.completed(1)] + [self.completed(5)] * 3) + with mock.patch.object(visual, "check_browser") as check: + visual.run_visual(self.ctx) + check.assert_not_called() + blocked = [ + finding for finding in self.ctx.findings + if finding.check_id == "VISUAL_DEPENDENT_CHECKS" + ] + self.assertEqual(len(blocked), 3) + self.assertTrue(all(finding.status == "BLOCKED" for finding in blocked)) + + def test_generated_category_has_description_required_by_raw_schema(self): + """Check generated category has description required by raw schema.""" + self.ctx.run = mock.Mock(return_value=self.completed()) + with mock.patch.object(visual.shutil, "which", return_value=None): + visual.run_visual(self.ctx) + category = json.loads( + (self.ctx.output_dir / "evidence/visual/DT_pass/category.json").read_text()) + self.assertEqual(category["doctor"][0]["Description"], + ["Doctor synthetic FWTS interface checks"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/common/log_parser/doctor.py b/common/log_parser/doctor.py new file mode 100644 index 00000000..de0231c5 --- /dev/null +++ b/common/log_parser/doctor.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026, Arm Limited or its affiliates. All rights reserved. +# SPDX-License-Identifier : Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Keep the existing optional Doctor entry point while its code lives in one folder. + +Normal parser commands only register Doctor's flags. Health checks run only +when explicitly requested; importing this launcher never starts them. +""" + +import sys + +from doctor_checks.core import Context, Finding, add_arguments, main, run_health + +# These imports are the existing public entry points, not unused local helpers. +__all__ = ("Context", "Finding", "add_arguments", "main", "run_health", "sys") + + +if __name__ == "__main__": + sys.dont_write_bytecode = True + sys.exit(main()) diff --git a/common/log_parser/doctor_checks/__init__.py b/common/log_parser/doctor_checks/__init__.py new file mode 100644 index 00000000..66bc153f --- /dev/null +++ b/common/log_parser/doctor_checks/__init__.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026, Arm Limited or its affiliates. All rights reserved. +# SPDX-License-Identifier : Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Optional Doctor checks; importing this package does not start any checks.""" + +# License metadata only; importing this package never starts health checks. +__license__ = "Apache-2.0" diff --git a/common/log_parser/doctor_checks/artifacts.py b/common/log_parser/doctor_checks/artifacts.py new file mode 100644 index 00000000..14f5b8c0 --- /dev/null +++ b/common/log_parser/doctor_checks/artifacts.py @@ -0,0 +1,1275 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026, Arm Limited or its affiliates. All rights reserved. +# SPDX-License-Identifier : Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Check that saved JSON, HTML and optional PDF reports agree with their inputs. + +Doctor calls these checks only when the user selects them. Saved report packages +are read without changing them or running their scripts. Findings and supporting +files are written to Doctor's output folder. Browser and PDF checks use separate +sample reports created by Doctor, never the supplied reports. +""" + +import argparse +from collections import Counter, defaultdict +from concurrent.futures import ThreadPoolExecutor +from copy import deepcopy +from functools import partial +import hashlib +import html +from html.parser import HTMLParser +from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer +import json +import math +from pathlib import Path +import re +import shutil +from threading import Thread +from urllib.parse import unquote, urlsplit + +from .core import load_json + +_strict_json = load_json + + +# --------------------------------------------------------------------------- +# Check which category file the run used before applying its schema requirements. +# --------------------------------------------------------------------------- + +MANIFEST = "config/parser_run.json" +INFO_FIELD = "Test_suite_info" + + +def _contained_file(root, relative): + """Allow evidence files inside the supplied package, not outside symlink targets.""" + if (not isinstance(relative, str) or not relative or "\\" in relative + or Path(relative).is_absolute() or ".." in Path(relative).parts): + raise ValueError("Category evidence path must be relative to the report package") + path = root / relative + if root not in path.resolve().parents: + raise ValueError("Category evidence path escapes the report package") + if not path.is_file(): + raise ValueError("Category evidence file is missing: " + relative) + return path + + +def category_provenance(report_root, mode): + """Read the run's saved category choice and verify any supplied-file copy. + + Current repository defaults cannot tell us which file an older run used. + """ + root = Path(report_root).resolve() + result = {"source": "unknown", "manifest": str(root / MANIFEST), + "invalid": False, "message": "Run category provenance is unavailable"} + manifest = root / MANIFEST + if not manifest.exists() and not manifest.is_symlink(): + return result + try: + data = load_json(_contained_file(root, MANIFEST)) + if not isinstance(data, dict) or type(data.get("format_version")) is not int or data["format_version"] != 1: + raise ValueError("Unsupported parser-run provenance format") + if data.get("mode") != mode: + raise ValueError("Parser-run provenance mode does not match " + mode) + category = data.get("test_category") + if not isinstance(category, dict) or category.get("source") not in {"explicit", "bundled"}: + raise ValueError("Parser-run category source must be explicit or bundled") + if category["source"] == "explicit": + # A supplied category only counts as evidence if its saved copy matches + # the checksum recorded when that run was generated. + snapshot = _contained_file(root, category.get("path")) + digest = category.get("sha256") + if not isinstance(digest, str) or not re.fullmatch(r"[0-9a-f]{64}", digest): + raise ValueError("Explicit category snapshot has no valid SHA-256") + if hashlib.sha256(snapshot.read_bytes()).hexdigest() != digest: + raise ValueError("Explicit category snapshot SHA-256 does not match") + if not isinstance(load_json(snapshot), dict): + raise ValueError("Explicit category snapshot must be a JSON object") + result.update(snapshot=str(snapshot), sha256=digest) + result.update(source=category["source"], message=( + "Category explicitly supplied to the generating run" if category["source"] == "explicit" + else "Generating run used its bundled category")) + except (OSError, ValueError, TypeError) as error: + result.update(invalid=True, message="Invalid run category provenance: " + str(error)) + return result + + +def applicable_schema(schema): + """Return a copy that does not require missing Test_suite_info fields. + + Only schema rules are visited. Example data and the original schema stay intact. + """ + result = deepcopy(schema) + + def visit(node): + if not isinstance(node, dict): + return + if isinstance(node.get("required"), list): + node["required"] = [key for key in node["required"] if key != INFO_FIELD] + for keyword in ("$defs", "definitions", "properties", "patternProperties", + "dependentSchemas", "dependencies"): + children = node.get(keyword) + if isinstance(children, dict): + for child in children.values(): + visit(child) + for keyword in ("allOf", "anyOf", "oneOf", "prefixItems"): + children = node.get(keyword) + if isinstance(children, list): + for child in children: + visit(child) + for keyword in ("items", "additionalItems", "contains", "additionalProperties", + "unevaluatedProperties", "unevaluatedItems", "propertyNames", + "if", "then", "else", "not", "contentSchema"): + child = node.get(keyword) + if isinstance(child, list): + for item in child: + visit(item) + else: + visit(child) + + visit(result) + return result + + +def _pointer(path): + return "/" + "/".join(str(part).replace("~", "~0").replace("/", "~1") for part in path) + + +def _all_errors(errors): + for error in errors: + yield error + yield from _all_errors(error.context) + + +def flatten_errors(errors): + """Keep parent and nested schema errors with their exact JSON field paths.""" + return [{"path": _pointer(error.absolute_path), "message": error.message, + "validator": error.validator} for error in _all_errors(errors)] + + +def evaluate_schema(schema_path, fragment, data, provenance): + """Check the schema using the generating run's category-file information. + + Keep the strict error count as evidence. Relax only the requirement for a + missing Test_suite_info when no explicitly supplied category is confirmed. + """ + from jsonschema import Draft202012Validator + from validate import _load_schema + + _, strict = _load_schema(Path(schema_path), fragment) + strict_errors = list(strict.iter_errors(data)) + omitted = [] + errors = strict_errors + if provenance["source"] != "explicit": + omitted = sorted({_pointer(error.absolute_path) for error in _all_errors(strict_errors) + if error.validator == "required" and INFO_FIELD in error.validator_value + and isinstance(error.instance, dict) and INFO_FIELD not in error.instance}) + if omitted: + # The copy includes all locally referenced schema definitions. A new + # validator prevents references from returning to the unchanged schema. + effective = applicable_schema(strict.schema) + Draft202012Validator.check_schema(effective) + errors = list(Draft202012Validator(effective).iter_errors(data)) + return {"errors": flatten_errors(errors), "strict_error_count": len(flatten_errors(strict_errors)), + "omitted_missing_info_paths": omitted, "category_provenance": provenance} + + +def schema_policy_main(): + """Expose the same schema check to Doctor's packaged-parser subprocess.""" + parser = argparse.ArgumentParser(description="Doctor-only applicability of Test_suite_info, without changing " + "result/schema files.") + parser.add_argument("--schema-policy", action="store_true", + required=True, help=argparse.SUPPRESS) + parser.add_argument("--registry", required=True) + parser.add_argument("--report", required=True) + parser.add_argument("--mode", choices=("DT", "SR"), required=True) + parser.add_argument("json_file") + args = parser.parse_args() + try: + from suite_registry import load_registry + from validate import _build_file_schema_index, _find_schema_for_file + + registry = load_registry(args.registry) + exact, patterns = _build_file_schema_index(registry, args.registry) + info = _find_schema_for_file(args.json_file, exact, patterns) + if not info: + raise ValueError("No registered raw schema for " + Path(args.json_file).name) + result = evaluate_schema(info["schema"], info["schema_fragment"], load_json(args.json_file), + category_provenance(args.report, args.mode)) + print(json.dumps(result, indent=2)) + return 0 + except (OSError, ValueError, TypeError, KeyError, ImportError) as error: + print(json.dumps({"error": str(error)})) + return 2 + + +# --------------------------------------------------------------------------- +# Compare saved report content without executing HTML or changing input files. +# --------------------------------------------------------------------------- + +def identity(value): + """Match display spelling without changing a compliance decision.""" + return re.sub(r"[^A-Z0-9]", "", str(value).upper()) + + +def decision(value): + text = str(value).lower() + if text.startswith("not compliant"): + return "Not Compliant" + if text.startswith("compliant with waiver"): + return "Compliant with waivers" + if text.startswith("compliant"): + return "Compliant" + if "not run" in text: + return "Not Run" + return "Unknown" + + +class ReportHTML(HTMLParser): + """Collect table text, badges and local links without running page scripts.""" + + def __init__(self, text): + super().__init__(convert_charrefs=True) + self.stack, self.tables, self.badges, self.links = [], [], [], [] + self.ids, self.anchors = Counter(), set() + self.active_tables = [] + self.badge = None + self.detail_headings, self.heading, self.detail_heading = [], None, None + self.feed(text) + self.close() + + def handle_starttag(self, tag, attrs): + attrs = dict(attrs) + classes = attrs.get("class", "").split() + if attrs.get("id"): + self.ids[attrs["id"]] += 1 + if tag == "a" and attrs.get("name"): + self.anchors.add(attrs["name"]) + card = next((item[2] for item in reversed(self.stack) if item[2]), "") + if "summary" in classes and attrs.get("id"): + card = attrs["id"] + for key in ("href", "src"): + if attrs.get(key): + self.links.append(attrs[key]) + if tag == "table": + # Nested tables have separate rows. Mark the outer cell so its wrapper + # is not mistaken for an extra test result later. + if self.active_tables and self.active_tables[-1]["cell"] is not None: + self.active_tables[-1]["cell"]["nested"] = True + table = {"kind": "compliance" if "acs-compliance-table" in classes + else "counts" if "summary-table" in classes else "detail", + "card": card, "rows": [], "cells": [], "row": None, "cell": None} + self.tables.append(table) + self.active_tables.append(table) + if table["kind"] == "detail" and self.detail_heading is not None: + self.detail_heading["tables"].append(table) + if self.active_tables: + table = self.active_tables[-1] + if tag == "tr": + table["row"] = [] + elif tag in ("td", "th") and table["row"] is not None: + table["cell"] = {"tag": tag, "text": [], "nested": False} + if "acs-suite-compliance" in classes: + self.badge = {"card": card, "context": attrs.get("title", ""), + "text": []} + if "heading" in classes: + self.heading = {"tag": tag, "depth": len(self.stack), "text": []} + if tag not in {"area", "base", "br", "col", "embed", "hr", "img", + "input", "link", "meta", "param", "source", "wbr"}: + self.stack.append((tag, classes, card)) + + def handle_data(self, data): + # BSA/SBSA reason buttons display the actual rule ID. Other buttons + # contain hierarchy/action controls, not result-cell content. + if self.active_tables and not any(item[0] == "button" and "reason-rule-toggle" not in item[1] + for item in self.stack): + cell = self.active_tables[-1]["cell"] + if cell is not None: + cell["text"].append(data) + if self.badge is not None: + self.badge["text"].append(data) + if self.heading is not None: + self.heading["text"].append(data) + + def handle_endtag(self, tag): + if (self.heading is not None and tag == self.heading["tag"] + and len(self.stack) == self.heading["depth"] + 1): + label, separator, value = " ".join("".join(self.heading["text"]).split()).partition(":") + if separator: + field = identity(label) + if field == "TESTCASE": + self.detail_heading = {"id": value.strip(), "description": "", + "status": "", "tables": []} + self.detail_headings.append(self.detail_heading) + elif self.detail_heading is not None: + if field == "TESTCASEDESCRIPTION": + self.detail_heading["description"] = value.strip() + elif field == "TESTRESULT": + self.detail_heading["status"] = value.strip() + self.heading = None + if self.active_tables: + table = self.active_tables[-1] + if tag in ("td", "th") and table["cell"] is not None: + cell = table["cell"] + cell["text"] = " ".join("".join(cell["text"]).split()) + table["row"].append(cell) + table["cell"] = None + elif tag == "tr" and table["row"] is not None: + table["cells"].append(table["row"]) + table["rows"].append([cell["text"] for cell in table["row"]]) + table["row"] = None + elif tag == "table": + self.active_tables.pop() + if tag == "span" and self.badge is not None: + self.badge["text"] = " ".join("".join(self.badge["text"]).split()) + self.badges.append(self.badge) + self.badge = None + for index in range(len(self.stack) - 1, -1, -1): + if self.stack[index][0] == tag: + del self.stack[index:] + break + + +def _records(merged): + """Read suite requirements and decisions recorded in the merged summary.""" + info = merged.get("Suite_Name: acs_info", {}) + summary = info.get("ACS Results Summary", {}) if isinstance(info, dict) else {} + if not isinstance(summary, dict): + return {} + records = {} + for key, value in summary.items(): + match = re.fullmatch(r"Suite_Name:\s*(.*?)\s*:\s*(.*?)_compliance", key) + if match: + requirement, suite = match.groups() + records[identity(suite)] = {"suite": suite, "requirement": requirement, + "value": str(value)} + return records + + +def _record_names(suite): + names = [suite["canonical"], suite.get("requirement_key", "")] + if suite["canonical"] in ("FWTS", "SCT"): + names.extend(prefix + "-" + suite["canonical"] for prefix in ("EBBR", "SBBR")) + if suite["canonical"] == "OS-TESTS": + names.extend(("OS_TEST", "OS Tests")) + return [identity(name) for name in names] + + +def _counts(raw): + """Normalize counter names so JSON and chart labels can be compared.""" + aliases = {"totalrulesrun": "total", "totaltests": "total", "total": "total", + "failedwithwaiver": "failedwithwaiver"} + result = {} + summary = raw.get("suite_summary", {}) + if not isinstance(summary, dict): + return result + for key, value in summary.items(): + name = identity(key).lower() + name = aliases.get(name, name[5:] if name.startswith("total") else name) + if isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value): + result[name] = value + return result + + +def _chart_counts(table): + result = {} + for row in table["rows"]: + if len(row) == 2 and re.fullmatch(r"\d[\d,]*", row[1]): + name = identity(row[0]).lower() + result["total" if name in ("totaltests", "totalrulesrun") else name] = int( + row[1].replace(",", "")) + return result + + +def _result_payload(value): + """Keep result and waiver data, excluding metadata added during merging.""" + enriched = {"Waivable", "SRS scope", "Test_suite_info", "Main Readiness Grouping"} + if isinstance(value, dict): + return {key: _result_payload(child) for key, child in value.items() if key not in enriched} + if isinstance(value, list): + return [_result_payload(child) for child in value] + return value + + +def _json_inventory(values): + return Counter(json.dumps(_result_payload(value), sort_keys=True, ensure_ascii=True) + for value in values) + + +def _result_entries(data): + """Do not iterate malformed result collections as if they were test records.""" + value = data.get("test_results", []) + return value if isinstance(value, list) else None + + +def _first_difference(expected, actual, path=""): + """Point to the first changed JSON field without changing either input.""" + if type(expected) is not type(actual): + return {"path": path or "/", "expected": type(expected).__name__, "actual": type(actual).__name__} + if isinstance(expected, dict): + for key in sorted(set(expected) | set(actual)): + pointer = path + "/" + key.replace("~", "~0").replace("/", "~1") + if key not in expected or key not in actual: + return {"path": pointer, "expected": "Present" if key in expected else "Absent", + "actual": "Present" if key in actual else "Absent"} + different = _first_difference(expected[key], actual[key], pointer) + if different: + return different + elif isinstance(expected, list): + if len(expected) != len(actual): + return {"path": path, "expected": f"{len(expected)} entries", "actual": f"{len(actual)} entries"} + for index, (left, right) in enumerate(zip(expected, actual)): + different = _first_difference(left, right, path + "/" + str(index)) + if different: + return different + elif expected != actual: + return {"path": path, "expected": expected, "actual": actual} + return None + + +def _merged_parity(root, raw_files, merged, registry, issues): + """Check that merging preserves each raw result, not just the total counts.""" + by_suite = {suite["canonical"]: suite for suite in registry} + expected = defaultdict(list) + merged_path = root / "acs_jsons" / "merged_results.json" + for canonical, items in raw_files.items(): + suite = by_suite[canonical] + for path, data in items: + if suite.get("waiver_suite") == "Standalone": + destination = "Suite_Name: Standalone" + elif canonical == "OS-TESTS" and path.name != suite.get("json_output"): + destination = "Suite_Name: OS Tests - " + path.stem + else: + matches = [key for key in merged if key.startswith("Suite_Name: ") + and identity(key[len("Suite_Name: "):]) in _record_names(suite)] + if len(matches) != 1: + issues.append({"file": str(merged_path), "issue": "Raw suite has no unique merged section", + "suite": canonical, "expected": str(path), "actual": matches}) + continue + destination = matches[0] + expected[destination].append((path, data)) + for destination, items in expected.items(): + actual = merged.get(destination) + if destination == "Suite_Name: Standalone": + # Standalone combines several input files into one list. Compare the + # records without assuming that their order stays the same. + collections = [_result_entries(data) for _, data in items] + if any(entries is None for entries in collections): + # The input-shape finding is kept by run_reports. This comparison + # cannot run, but other suites and supplied packages still can. + continue + entries = [entry for collection in collections for entry in collection] + equivalent = isinstance(actual, list) and _json_inventory( + entries) == _json_inventory(actual) + else: + # OS distributions have separate sections; duplicate non-aggregate producers + # are ambiguous, never silently overwritten by the last filename. + equivalent = len(items) == 1 and _result_payload(items[0][1]) == _result_payload(actual) + if not equivalent: + difference = (_first_difference(_result_payload(items[0][1]), _result_payload(actual)) + if len(items) == 1 and destination != "Suite_Name: Standalone" else None) + issues.append({"file": str(merged_path), "issue": "Raw and merged result records differ", + "suite": destination, "expected": "Identical identities, nested results, statuses and waiver evidence", + "actual": difference or "Missing, extra or changed records; compare raw files " + + ", ".join(path.name for path, _ in items)}) + expected_names = set(expected) + for destination in sorted(set(merged) - {"Suite_Name: acs_info"} - expected_names): + # Report stale/unregistered result sections even if the suite counters happen to match. + issues.append({"file": str(merged_path), "issue": "Merged result section has no matching raw input", + "suite": destination, "expected": "Every result section is traceable to current raw JSON", + "actual": destination}) + + +def _local_links(path, parsed, root, documents, issues, coverage): + """Check local files and anchors; report links outside the package as unchecked.""" + for anchor, count in sorted(parsed.ids.items()): + if count > 1: + issues.append({"file": str(path), "issue": "Duplicate HTML element ID", + "expected": "One unique element", "actual": {"id": anchor, "count": count}}) + for link in sorted(set(parsed.links)): + try: + target = urlsplit(link) + if target.scheme or target.netloc: + continue # Never fetch remote content or execute a URL. + destination = (path.parent / unquote(target.path) + ).resolve() if target.path else path.resolve() + if root != destination and root not in destination.parents: + coverage.append( + path.name + ": link outside supplied package not inspected: " + link) + continue + if not destination.is_file() or not destination.stat().st_size: + issues.append({"file": str(path), "issue": "Broken local HTML link", + "expected": "A non-empty local file", "actual": link}) + continue + if target.fragment: + if destination.suffix.lower() not in (".html", ".htm"): + coverage.append(path.name + ": non-HTML fragment not inspected: " + link) + continue + if destination not in documents: + documents[destination] = ReportHTML(destination.read_text(encoding="utf-8")) + document = documents[destination] + anchor = unquote(target.fragment) + if document.ids[anchor] != 1 and anchor not in document.anchors: + issues.append({"file": str(path), "issue": "Broken local HTML fragment", + "expected": "Exactly one local anchor", "actual": link}) + except (OSError, ValueError, UnicodeError) as error: + issues.append({"file": str(path), "issue": "Local HTML link could not be inspected", + "actual": link + ": " + str(error)}) + + +def _status(value): + token = identity(value) + aliases = {"PASS": "PASSED", "FAIL": "FAILED", "WARNING": "WARNINGS", + "SKIP": "SKIPPED", "ABORT": "ABORTED", "WAIVED": "FAILEDWITHWAIVER", + "FAILWITHWAIVER": "FAILEDWITHWAIVER", "TESTNOTIMPLEMENTED": "NOTIMPLEMENTED", + "NOTTESTEDTESTNOTIMPLEMENTED": "NOTIMPLEMENTED", + "NOTTESTEDPALNOTSUPPORTED": "PALNOTSUPPORTED"} + if token.startswith("KNOWN") and token.endswith("LIMITATION"): + return "IGNORED" + return aliases.get(token, token) + + +def _display_status(value, renderer): + if not isinstance(value, dict): + return _status(value) + positive = {_status(key) for key, count in value.items() + if isinstance(count, (int, float)) and not isinstance(count, bool) and count > 0} + if not positive: + return "INFO" if renderer.endswith("os_tests/json_to_html.py") else "UNKNOWN" + order = ["PASSED", "FAILEDWITHWAIVER", "FAILED", "ABORTED", "SKIPPED", "WARNINGS", + "IGNORED", "PASSEDPARTIAL", "NOTIMPLEMENTED", "PALNOTSUPPORTED", "NOTTESTED"] + if renderer.endswith("bbr/fwts/json_to_html.py"): + order[:3] = ["FAILED", "PASSED", "FAILEDWITHWAIVER"] + elif renderer.endswith(("post_script/json_to_html.py", "os_tests/json_to_html.py")): + order[:3] = ["PASSED", "FAILED", "FAILEDWITHWAIVER"] + return next((status for status in order if status in positive), "UNKNOWN") + + +def _raw_detail_records(value, renderer): + """Build expected visible rows from raw results without calling the renderer. + + BSA displays parent and child results. Other supported pages display the + deepest result rows, with a parent used only when it has no result children. + """ + records = [] + def visit(node, position=None): + if isinstance(node, list): + for index, child in enumerate(node, 1): + visit(child, index) + elif isinstance(node, dict): + fields = {identity(key): child for key, child in node.items()} + result_keys = [key for key in fields if key in ("TESTRESULT", "SUBTESTRESULT")] + before = len(records) + for key, child in node.items(): + if identity(key) not in result_keys: + visit(child) + if not result_keys or (len(records) != before and not renderer.endswith("bsa/json_to_html.py")): + return + def field(names): + return next((" ".join(str(fields[name]).split()) for name in names + if fields.get(name) not in (None, "")), "") + identifier = field(("SUBTESTGUID", "SUBTESTNUMBER", "TESTCASENUMBER", + "TESTNUMBER", "TESTID", "TESTCASE", "GUID", "ID")) + if renderer.endswith("bbr/tpm/json_to_html.py"): + identifier = str(position) + if not identifier: + raise ValueError("Result record lacks a stable visible ID: " + ", ".join(node)) + description = field(("SUBTESTDESCRIPTION", "TESTCASEDESCRIPTION", + "TESTDESCRIPTION", "DESCRIPTION", "NAME")) + records.append((identifier, description, _display_status( + fields[result_keys[0]], renderer))) + visit(value) + return Counter(records) + + +def _html_detail_records(parsed, sct_headings=False): + """Read displayed IDs, descriptions and statuses, including SCT parent headings.""" + records, tables = [], 0 + populated_tables = set() + for table in (table for table in parsed.tables if table["kind"] == "detail"): + columns = None + for row in table["cells"]: + if any(cell["tag"] == "th" for cell in row): + headers = [identity(cell["text"]) for cell in row] + results = [i for i, name in enumerate(headers) if name in ( + "TESTRESULT", "SUBTESTRESULT", "RESULT", "STATUS", "OUTCOME")] + if not results: + continue + ids = [i for i, name in enumerate(headers) if name in ("TESTCASE", "SUBTEST", "TEST", "ID", "GUID", "SUBTESTGUID") + or name.endswith("NUMBER") or "#" in row[i]["text"]] + descriptions = [i for i, name in enumerate( + headers) if "DESCRIPTION" in name or name == "NAME"] + if len(ids) > 1: + ids = [i for i in ids if "GUID" in headers[i]] + if len(results) != 1 or len(ids) != 1 or len(descriptions) != 1: + raise ValueError("Ambiguous result table columns: " + ", ".join(headers)) + columns = ids[0], descriptions[0], results[0] + tables += 1 + elif columns and row: + if len(row) == 1 and row[0]["nested"]: + continue + if max(columns) >= len(row): + raise ValueError("Result row is missing ID, description or status cells") + records.append((row[columns[0]]["text"], row[columns[1]] + ["text"], _status(row[columns[2]]["text"]))) + populated_tables.add(id(table)) + if sct_headings: + for heading in parsed.detail_headings: + # SCT renders a parent result in headings, and child outcomes in the + # following table. Count the parent only when that table has no rows. + if not any(id(table) in populated_tables for table in heading["tables"]): + records.append((heading["id"], heading["description"], _status(heading["status"]))) + tables += 1 + return Counter(records), tables + + +def _detail_parity(path, parsed, raw_files, registry, issues, coverage): + """Report missing or changed result rows between raw JSON and detailed HTML.""" + suites = [suite for suite in registry if suite.get("detailed_html") == path.name + and suite["canonical"] in raw_files] + if path.name == "sbmr_detailed.html": + suites = [suite for suite in registry if suite["canonical"] in ("SBMR-IB", "SBMR-OOB") + and suite["canonical"] in raw_files] + if not suites: + return + try: + expected = Counter() + for suite in suites: + for _, data in raw_files[suite["canonical"]]: + expected.update(_raw_detail_records(data, suite.get("json_to_html", ""))) + actual, tables = _html_detail_records(parsed, sct_headings=all( + suite.get("json_to_html", "").endswith("bbr/sct/json_to_html.py") for suite in suites)) + if expected and not tables: + issues.append({"file": str(path), "issue": "Detailed result rows are missing", + "expected": sum(expected.values()), "actual": 0}) + elif expected != actual: + issues.append({"file": str(path), "issue": "Raw and detailed HTML result identities differ", + "expected": {"missing": list((expected - actual).elements())[:10]}, + "actual": {"extra_or_changed": list((actual - expected).elements())[:10]}}) + except ValueError as error: + issues.append({"file": str(path), "issue": "Detailed identity comparison could not execute", + "blocked": True, "expected": "A supported unambiguous result-row identity contract", + "actual": str(error)}) + + +def _raw_integrity(path, data, record, issues, sr_os=False): + """Check counter totals and flag clear contradictions with suite compliance.""" + counts = _counts(data) + categories = {"passed", "failed", "failedwithwaiver", "aborted", "skipped", + "warnings", "passedpartial", "notimplemented", "palnotsupported", "ignored"} + summary = data.get("suite_summary", {}) + for name, value in summary.items() if isinstance(summary, dict) else []: + if (not isinstance(value, (int, float)) or isinstance(value, bool) or + not math.isfinite(value) or value < 0 or int(value) != value): + issues.append({"file": str(path), "issue": "Invalid suite counter", "count": name, + "expected": "A non-negative whole number", "actual": value}) + if "total" in counts and set(counts) <= categories | {"total"}: + summed = sum(value for key, value in counts.items() if key != "total") + if summed != counts["total"]: + issues.append({"file": str(path), "issue": "Suite categories do not sum to declared total", + "expected": counts["total"], "actual": summed}) + def unknown(node): + if isinstance(node, dict): + for key, value in node.items(): + if key.lower() in ("test_result", "sub_test_result") and value == "UNKNOWN": + return True + if unknown(value): + return True + elif isinstance(node, list): + return any(unknown(value) for value in node) + return False + if record and decision(record["value"]).startswith("Compliant") and unknown(data): + issues.append({"file": str(path), "issue": "UNKNOWN result is reported as compliant", + "expected": "Unknown execution evidence must not silently become success", + "actual": record["value"]}) + if record and decision(record["value"]).startswith("Compliant"): + if data.get("test_results") == []: + issues.append({"file": str(path), "issue": "Empty execution evidence is reported as compliant", + "actual": record["value"]}) + if counts.get("failed", 0) > 0 and not sr_os: + issues.append({"file": str(path), "issue": "Unwaived suite failures are reported as compliant", + "expected": "Not Compliant at suite level; Recommended may remain non-blocking " + "overall", + "actual": {"failed": counts["failed"], "compliance": record["value"]}}) + + +def _aggregate(records): + """Calculate the expected combined display badge, not overall SRS compliance.""" + mandatory = [r for r in records if r["requirement"] in ( + "Mandatory", "Conditional-Mandatory")] + relevant = mandatory or records + requirements = sorted({r["requirement"] for r in relevant}) + requirement = "Mandatory" if "Mandatory" in requirements else " / ".join(requirements) + if all("not run" in r["value"].lower() for r in records): + status = "Not Run" + elif any(decision(r["value"]) == "Not Compliant" for r in relevant): + status = "Not Compliant" + elif any(decision(r["value"]) == "Unknown" for r in relevant): + status = "Unknown" + elif any(decision(r["value"]) == "Compliant with waivers" for r in relevant): + status = "Compliant with waivers" + else: + status = "Compliant" + return requirement + " (" + status + ")" + + +def _inspect_html(path, parsed, records, raw_by_suite, registry, issues, coverage, + overall=None): + """Compare HTML compliance with merged JSON and chart totals with raw JSON.""" + if path.name == "acs_summary.html" and overall is not None: + # Compare the displayed SRS decision, not a suite badge or extension's + # verdict. The report may omit the explanatory suffix after the decision. + displayed = [row[1] for table in parsed.tables for row in table["rows"] + if len(row) >= 2 and identity(row[0]) == "SRSREQUIREMENTSCOMPLIANCERESULTS"] + if len(displayed) != 1: + issues.append({"file": str(path), "issue": "Main HTML overall compliance verdict is missing or ambiguous", + "expected": decision(overall), "actual": displayed}) + elif decision(displayed[0]) != decision(overall): + issues.append({"file": str(path), "issue": "Overall HTML compliance differs from merged JSON", + "expected": decision(overall), "actual": displayed[0]}) + aliases = {name: record for suite in registry for name in _record_names(suite) + for key, record in records.items() if key in _record_names(suite)} + aliases.update(records) + detail_rows = [row for table in parsed.tables if table["kind"] == "compliance" + for row in table["rows"] if len(row) == 3 and row[1] != "Requirement"] + for name, requirement, status in detail_rows: + record = aliases.get(identity(name)) + if record is None: + coverage.append(str(path.name) + ": unmapped compliance row " + name) + elif (identity(requirement), decision(status), "not run" in status.lower()) != ( + identity(record["requirement"]), decision(record["value"]), + "not run" in record["value"].lower()): + issues.append({"file": str(path), "issue": "Detail compliance differs from merged JSON", + "suite": name, "expected": record, "actual": [requirement, status]}) + if path.name == "sbmr_detailed.html": + expected_rows = {key for key in ("SBMRIB", "SBMROOB") if key in records} + elif path.name == "standalone_tests_detailed.html": + expected_rows = {name for suite in registry if suite.get("waiver_suite") == "Standalone" + for name in _record_names(suite) if name in records and ( + suite["canonical"] in raw_by_suite or ( + records[name]["requirement"] == "Mandatory" and + "not run" in records[name]["value"].lower()))} + else: + expected_rows = set() + present_rows = {identity(row[0]) for row in detail_rows} + present_rows.update(identity(aliases[name]["suite"]) + for name in list(present_rows) if name in aliases) + for missing in sorted(expected_rows - present_rows): + issues.append({"file": str(path), "issue": "Applicable compliance row is missing", + "expected": records[missing], "actual": "No row for " + records[missing]["suite"]}) + if path.name.endswith("_detailed.html") and not detail_rows: + issues.append({"file": str(path), "issue": "Detailed report has no compliance rows"}) + if path.name == "acs_summary.html" and records and not parsed.badges: + issues.append({"file": str(path), "issue": "Main report has no suite compliance badges"}) + for badge in parsed.badges: + names = re.findall(r"(?:^|; )([^:;]+): (?:Mandatory|Recommended|Extension|Conditional-Mandatory)\s*\(", + badge["context"]) + rows = [aliases[identity(name)] for name in names if identity(name) in aliases] + if len(rows) != len(names) or not rows: + coverage.append(path.name + ": unmapped summary badge " + badge["card"]) + elif badge["text"] != _aggregate(rows): + issues.append({"file": str(path), "issue": "Summary badge differs from merged JSON", + "card": badge["card"], "expected": _aggregate(rows), "actual": badge["text"]}) + for table in (table for table in parsed.tables if table["kind"] == "counts"): + filename = table["card"] + ".html" if table["card"] else path.name + suites = [s for s in registry if filename in (s.get("summary_html"), s.get("detailed_html")) + and s["canonical"] in raw_by_suite] + if filename in ("sbmr_summary.html", "sbmr_detailed.html"): + suites = [s for s in registry if s["canonical"] in ("SBMR-IB", "SBMR-OOB") + and s["canonical"] in raw_by_suite] + if not suites or any(s.get("waiver_suite") == "Standalone" or + s["canonical"] == "OS-TESTS" for s in suites): + coverage.append(path.name + ": aggregate/unmapped chart " + filename) + continue + expected = Counter() + for suite in suites: + counts = _counts(raw_by_suite[suite["canonical"]]) + # Most producers store status counters only; HTML derives its Total + # Tests row from those counters rather than a missing JSON total=0. + categories = {"passed", "failed", "failedwithwaiver", "aborted", "skipped", + "warnings", "passedpartial", "notimplemented", "palnotsupported", "ignored"} + if counts and "total" not in counts and set(counts) <= categories: + counts["total"] = sum(counts.values()) + # The SBMR renderer has no Ignored row. Its schema includes the + # unused zero counter; a nonzero value must still be reported. + if suite["canonical"] in ("SBMR-IB", "SBMR-OOB") and counts.get("ignored") == 0: + counts.pop("ignored") + expected.update(counts) + actual = _chart_counts(table) + if not actual or not expected: + coverage.append(path.name + ": no comparable suite-summary counts " + filename) + continue + for key in sorted(set(expected) | set(actual)): + value = expected.get(key, 0) + if (key in expected and key not in actual) or actual.get(key, 0) != value: + issues.append({"file": str(path), "issue": "Chart differs from raw suite summary", + "chart": filename, "count": key, "expected": value, + "actual": actual.get(key, "Missing chart category")}) + + +def run_reports(ctx): + """Inspect user-supplied reports and save findings in Doctor's output folder.""" + if not ctx.report_inputs: + ctx.add("ARTIFACT.INPUT", "WARN", "Real-capture artifact checks were not run", + "Supply --doctor-report DT=/path or SR=/path to a report package", + "No report input supplied; synthetic probes are separate") + return + from validate import _build_file_schema_index, _find_schema_for_file + from suite_registry import load_registry + registry = load_registry(ctx.parser_dir / "suite_registry.json") + exact, patterns = _build_file_schema_index(registry, ctx.parser_dir / "suite_registry.json") + for index, (mode, supplied) in enumerate(ctx.report_inputs): + if mode not in ctx.modes: + continue + root = Path(supplied).resolve() + if not (root / "acs_jsons").is_dir() and (root / "acs_summary" / "acs_jsons").is_dir(): + root = root / "acs_summary" + evidence_dir = ctx.case_dir("artifacts/" + str(index) + "_" + mode) + issue_file = evidence_dir / "issues.json" + issues, coverage, raw, merged, json_count = [], [], {}, None, 0 + provenance = category_provenance(root, mode) + schema_checks = [] + if provenance["invalid"]: + issues.append({"file": provenance["manifest"], "issue": "Invalid category provenance", + "actual": provenance["message"]}) + raw_files = defaultdict(list) + json_dir = root / "acs_jsons" + if not json_dir.is_dir(): + ctx.add("ARTIFACT.INPUT", "BLOCKED", "Report JSON directory is missing", + "A report package containing acs_jsons/merged_results.json", str(root), mode) + continue + for path in sorted(json_dir.glob("*.json")): + # Even an in-package filename can point outside the package through a + # symlink. Do not follow those links into unrelated user data. + if root not in path.resolve().parents: + issues.append({"file": str(path), "issue": "Report input escapes supplied package", + "actual": "External symlink target was not read"}) + continue + info = _find_schema_for_file(path, exact, patterns) + is_merged = path.name == "merged_results.json" + if not info and not is_merged: + if path.name not in ("acs_info.json", "edk2_test_parser.json"): + coverage.append("No registered raw schema for " + path.name) + continue + json_count += 1 + schema_path = (ctx.parser_dir / "acs-results-schema.json" + if is_merged else info["schema"]) + fragment = "" if is_merged else info["schema_fragment"] + try: + data = _strict_json(path) + if not isinstance(data, dict): + raise ValueError("Expected a JSON object, got " + type(data).__name__) + except (OSError, ValueError) as error: + issues.append( + {"file": str(path), "issue": "Malformed report JSON", "actual": str(error)}) + continue + try: + evaluation = evaluate_schema(schema_path, fragment, data, provenance) + errors = evaluation["errors"] + schema_checks.append({"file": str(path), "strict_error_count": evaluation["strict_error_count"], + "applicable_error_count": len(errors), + "omitted_missing_info_paths": evaluation["omitted_missing_info_paths"]}) + if errors: + issues.append({"file": str(path), "issue": "JSON schema validation failed", + "schema": str(schema_path) + fragment, "errors": errors}) + except Exception as error: # A broken schema must not suppress the other supplied checks. + issues.append({"file": str(path), "issue": "Schema validation could not execute", + "actual": str(error)}) + if is_merged: + merged = data + else: + if _result_entries(data) is None: + issues.append({"file": str(path), "issue": "Invalid result collection", + "suite": info["canonical"], "expected": "test_results is an array of test records", + "actual": "test_results is " + type(data["test_results"]).__name__}) + raw_files[info["canonical"]].append((path, data)) + # Charts need combined counts, while exact parity retains every input file. + for canonical, items in raw_files.items(): + if len(items) == 1: + raw[canonical] = items[0][1] + else: + counters = Counter() + entries = [] + for _, data in items: + counters.update(_counts(data)) + values = _result_entries(data) + if values is not None: + entries.extend(values) + raw[canonical] = {"suite_summary": dict(counters), "test_results": entries} + if merged is None: + issues.append({"file": str(json_dir / "merged_results.json"), + "issue": "Merged JSON is missing or unreadable"}) + if not raw: + issues.append( + {"file": str(json_dir), "issue": "No readable registered raw suite JSON found"}) + if merged is not None: + _merged_parity(root, raw_files, merged, registry, issues) + records = _records(merged or {}) + info = (merged or {}).get("Suite_Name: acs_info", {}) + results = info.get("ACS Results Summary", {}) if isinstance(info, dict) else {} + band = str(results.get("Band", "")) if isinstance(results, dict) else "" + detected_mode = "DT" if "devicetree" in band.lower() else "SR" if band == "SystemReady band" else mode + if detected_mode != mode: + issues.append({"file": str(json_dir / "merged_results.json"), "issue": "Supplied mode does not match report band", + "expected": mode, "actual": band}) + if not records: + issues.append({"file": str(json_dir / "merged_results.json"), + "issue": "No run-specific compliance decisions found"}) + html_dir = root / "html_detailed_summaries" + for suite in registry: + canonical = suite["canonical"] + if canonical not in raw: + continue + record = next((records[name] for name in _record_names(suite) if name in records), None) + for source, data in raw_files[canonical]: + _raw_integrity(source, data, record, issues, + sr_os=detected_mode == "SR" and canonical == "OS-TESTS") + detail = suite.get("detailed_html", "") + if canonical.startswith("SBMR-") and (html_dir / "sbmr_detailed.html").is_file(): + detail = "sbmr_detailed.html" + if detail and raw[canonical].get("test_results") and not (html_dir / detail).is_file(): + issues.append({"file": str(html_dir / detail), "issue": "Detailed HTML for collected results is missing", + "suite": canonical}) + merged_suite = next((value for key, value in (merged or {}).items() + if key.startswith("Suite_Name: ") and + identity(key[len("Suite_Name: "):]) in _record_names(suite)), None) + if isinstance(merged_suite, dict) and _counts(raw[canonical]) != _counts(merged_suite): + issues.append({"file": str(source), "issue": "Raw and merged suite counters differ", + "suite": canonical, "expected": _counts(raw[canonical]), + "actual": _counts(merged_suite)}) + pages = list(sorted(html_dir.glob("*.html"))) + if not (html_dir / "acs_summary.html").is_file(): + issues.append({"file": str(html_dir / "acs_summary.html"), + "issue": "Main HTML report is missing"}) + documents = {} + for path in pages: + try: + if root not in path.resolve().parents: + issues.append({"file": str(path), "issue": "Report input escapes supplied package", + "actual": "External HTML symlink target was not read"}) + continue + parsed = ReportHTML(path.read_text(encoding="utf-8")) + documents[path.resolve()] = parsed + _inspect_html(path, parsed, records, raw, registry, issues, coverage, + overall=results.get("Overall Compliance Result") if isinstance(results, dict) else None) + _detail_parity(path, parsed, raw_files, registry, issues, coverage) + _local_links(path, parsed, root, documents, issues, coverage) + except (OSError, ValueError, TypeError, AttributeError) as error: + issues.append( + {"file": str(path), "issue": "HTML could not be inspected", "actual": str(error)}) + issue_file.write_text(json.dumps({"source": str(root), "mode": mode, + "not_checked": ["Browser rendering, PDF output, external URLs and JavaScript-created " + "anchors", + "Standalone component chart totals and multi-file OS aggregate chart " + "totals"], + "issues": issues, "coverage_gaps": sorted(set(coverage)), + "category_provenance": provenance, "schema_policy_checks": schema_checks}, indent=2) + "\n", encoding="utf-8") + for item in issues: + # Keep each concrete issue separate. The package-level result below is + # only a summary and must not be mistaken for another distinct bug. + if item["issue"] == "JSON schema validation failed": + first = item["errors"][0] + ctx.add("ARTIFACT.SCHEMA", "FAIL", Path(item["file"]).name + " violates applicable Doctor schema checks", + "Registered schema; missing Test_suite_info is required only for an " + "explicitly supplied category", + f'{first["path"]}: {first["message"][:220]}; {len(item["errors"])} error records in evidence', + mode, evidence=[issue_file]) + elif item["issue"] != "Schema validation could not execute": + category = ("CATEGORY_PROVENANCE" if item["issue"] == "Invalid category provenance" else + "JSON" if "JSON" in item["issue"] else "PARITY" if "record" in item["issue"].lower() + or "identit" in item["issue"].lower() else "HTML" if "HTML" in item["issue"] else "DATA") + ctx.add("ARTIFACT." + category, "BLOCKED" if item.get("blocked") else "FAIL", + item["issue"] + ": " + Path(item["file"]).name, + item.get("expected", "Consistent current-run report artifacts"), + item.get("actual", item.get("suite", "See evidence for the discrepancy")), + mode, suite=item.get("suite", ""), evidence=[issue_file]) + schema_blocked = [item for item in issues if item["issue"] + == "Schema validation could not execute"] + blocked = schema_blocked + [item for item in issues if item.get("blocked")] + for item in schema_blocked: + ctx.add("ARTIFACT.SCHEMA", "BLOCKED", "Schema evaluator could not check " + Path(item["file"]).name, + "The registered schema loads and validation completes", item["actual"], mode, evidence=[issue_file]) + counts = Counter(issue["issue"] for issue in issues) + omitted_files = [ + Path(check["file"]).name for check in schema_checks if check["omitted_missing_info_paths"]] + if provenance["source"] == "unknown" and omitted_files: + ctx.add("ARTIFACT.CATEGORY_PROVENANCE", "WARN", "Missing Test_suite_info could not be attributed to a supplied category", + "Verified generating-run category provenance for this conditional requirement", + provenance["message"] + "; missing-info requirement not applied in " + + ", ".join(omitted_files) + + "; all other schema checks remain active", mode, evidence=[issue_file]) + verdict = "FAIL" if len(issues) > len(blocked) else "BLOCKED" if blocked else "PASS" + ctx.add("ARTIFACT.CONSISTENCY", verdict, + "Supplied report package has correctness problems" if issues else "Supplied static report checks agree", + "Strict JSON, applicable Doctor schema checks, raw/merged identities, " + "HTML decisions/counts/rows, and local links/anchors", + f"{json_count} JSON files, {len(pages)} HTML pages; " + ( + "; ".join(f"{name}: {count}" for name, count in counts.items()) or "no discrepancies"), + mode, evidence=[issue_file]) + if coverage: + ctx.add("ARTIFACT.COVERAGE", "WARN", "Some artifact comparisons could not be safely evaluated", + "Explicit count units and a registered schema/display mapping", + "; ".join(sorted(set(coverage))[:5]) + + f"; {len(set(coverage))} coverage notes in evidence", + mode, evidence=[issue_file]) + + +# --------------------------------------------------------------------------- +# Optionally check browser controls and PDF content using Doctor's sample reports. +# --------------------------------------------------------------------------- + +FWTS_LOG = """Running tests: uefirtmisc +==================== +uefirtmisc: Doctor interface checks +Test 1 of 2: Doctor passing interface +PASSED: Test 1, Doctor passed +Test 2 of 2: Doctor failing interface +FAILED [HIGH] Doctor failed +""" +OUTCOMES = {"pass": (2, 0, 0, "Compliant"), + "fail": (1, 1, 0, "Not Compliant"), + "waived": (1, 0, 1, "Compliant with waivers")} + +# Check what a report reader sees and clicks; do not call private renderer helpers. +BROWSER_ASSERTIONS = r"""""" + + +def browser_result(output): + """Read the browser's check results; a missing result is not a passing check.""" + match = re.search(r'
(.*?)
', output, re.DOTALL) + if not match: + raise ValueError("Browser exited without running the report assertions") + data = json.loads(html.unescape(match.group(1))) + if (not isinstance(data, dict) or type(data.get("checks")) is not int or + data["checks"] < 4 or not isinstance(data.get("failures"), list)): + raise ValueError("Incomplete browser assertions: " + str(data)) + return data + + +def pdf_problems(text, prefix, outcome): + """Check expected suite names, compliance and counters in extracted PDF text.""" + passed, failed, waived, compliance = OUTCOMES[outcome] + text = " ".join(text.split()) + issues = [] + if not re.search(r"(?window.doctorErrors=[];window.addEventListener("error",function(e){' + 'window.doctorErrors.push(e.message);});window.addEventListener("unhandledrejection",' + 'function(e){window.doctorErrors.push(String(e.reason));});') + content = re.sub(r"]*>", lambda match: match.group(0) + + capture, content, count=1, flags=re.I) + content = re.sub(r"", lambda _: BROWSER_ASSERTIONS + + "", content, count=1, flags=re.I) + (directory / page.name).write_text(content, encoding="utf-8") + # Use a loopback-only web server so scripts behave as on a normal web page. + # The original sample page is left unchanged. + server = ThreadingHTTPServer(("127.0.0.1", 0), partial(QuietHandler, directory=str(directory))) + thread = Thread(target=server.serve_forever, daemon=True) + thread.start() + + def check_size(size): + name = page.stem + "-" + size.replace(",", "x") + try: + completed = ctx.run([browser, "--headless", "--no-sandbox", "--disable-gpu", + "--disable-dev-shm-usage", "--disable-background-networking", "--disable-component-update", + "--disable-extensions", "--disable-default-apps", "--disable-sync", "--no-proxy-server", + "--no-first-run", "--user-data-dir=" + str(directory / (name + "-profile")), + "--window-size=" + size, "--virtual-time-budget=2500", "--dump-dom", + "http://127.0.0.1:%d/%s" % (server.server_port, page.name)], directory, name) + try: + result = browser_result(completed.stdout) + ok = completed.returncode == 0 and not result["failures"] + actual = dict(result, exit_code=completed.returncode) + except (ValueError, TypeError) as error: + ok, actual = False, str(error) + return size, name, "PASS" if ok else "FAIL", actual + except (OSError, RuntimeError) as error: + return size, name, "BLOCKED", str(error) + + try: + with ThreadPoolExecutor(max_workers=2) as pool: + for size, name, status, actual in pool.map(check_size, ("1600,900", "430,900")): + ctx.add("VISUAL_BROWSER", status, + outcome + " " + page.name + " at " + size + ": UI, visible counts, filters and overflow", + "All browser assertions execute and pass", actual, mode, "FWTS", + (directory / (name + ".log"),)) + finally: + server.shutdown() + server.server_close() + thread.join(timeout=2) + + +def run_visual(ctx): + """Generate selected sample reports, then check browser and PDF output. + + Missing optional tools produce BLOCKED findings, not an implied pass. + """ + directory = ctx.case_dir("visual") + parser = getattr(ctx, "portable_parser", None) + if not parser: + ctx.add("VISUAL_PACKAGE", "BLOCKED", "Visual probes require the verified standalone package", + "Package checks completed", "No verified extracted parser") + return + browser = getattr(ctx, "browser", None) or shutil.which( + "chromium") or shutil.which("chromium-browser") + if not browser or not Path(browser).is_file(): + ctx.add("VISUAL_BROWSER_DEPENDENCY", "BLOCKED", "Requested browser checks cannot run", + "Chromium on PATH or --doctor-browser /absolute/path", "Chromium executable unavailable") + browser = None + probe = ctx.run([ctx.python, "-B", "-c", "import weasyprint; import pypdf"], + directory, "pdf-dependencies") + pdf_ready = probe.returncode == 0 + if not pdf_ready: + ctx.add("VISUAL_PDF_DEPENDENCY", "BLOCKED", "Requested PDF checks cannot run", + "weasyprint and pypdf import in the recorded Python environment", + "Install optional PDF dependencies separately; see pdf-dependencies.log", evidence=(directory,)) + if not browser and not pdf_ready: + return + for mode in ctx.modes: + for outcome in OUTCOMES: + case = ctx.case_dir("visual/" + mode + "_" + outcome) + source, category = case / "fwts.log", case / "category.json" + source.write_text(FWTS_LOG.replace("FAILED [HIGH] Doctor failed", "PASSED: Test 2, Doctor passed") + if outcome == "pass" else FWTS_LOG, encoding="utf-8") + category.write_text(json.dumps({"doctor": [{"Suite": "FWTS", "Test Suite": "uefirtmisc", + "Waivable": "yes", "SRS scope": "core", "Main Readiness Grouping": "Doctor", + "Description": ["Doctor synthetic FWTS interface checks"]}]}), encoding="utf-8") + output = case / "output" + command = ["bash", parser / "main_log_parser.sh", "--standalone", "--mode", mode, + "--suite", "FWTS", "--input-log", source, "--output", output, + "--outputs", "pdf" if pdf_ready else "summary", "--schema", "--test-category", category] + if outcome == "waived": + waiver = case / "waiver.json" + waiver.write_text(json.dumps( + {"Suites": [{"Suite": "FWTS", "Reason": "Doctor approved waiver"}]}), encoding="utf-8") + command.extend(["--waiver", waiver]) + try: + generated = ctx.run(command, case, "generate", cwd=case, env={"PYTHONPATH": ""}) + ctx.add("VISUAL_GENERATION", "PASS" if generated.returncode == 0 else "FAIL", + outcome + ": public standalone report export", "Exit 0", + "Exit " + str(generated.returncode), mode, "FWTS", (case / "generate.log",)) + if generated.returncode: + ctx.add("VISUAL_DEPENDENT_CHECKS", "BLOCKED", + outcome + ": browser/PDF assertions could not run because report generation " + "failed", + "Inspect successfully generated reports", "Fix the generation error, then rerun", + mode, "FWTS", (case / "generate.log",)) + continue + if pdf_ready: + pdf = output / "acs_summary.pdf" + text_file = case / "pdf-text.txt" + script = ("import sys; from pathlib import Path; from pypdf import PdfReader; " + "p=Path(sys.argv[1]); assert p.stat().st_size>1000 and " + "p.read_bytes().startswith(b'%PDF-'); " + "r=PdfReader(p,strict=True); assert not r.is_encrypted and " + "len(r.pages)>0; " + "Path(sys.argv[2]).write_text('\\n'.join(x.extract_text() or '' for x " + "in r.pages),encoding='utf-8')") + extracted = ctx.run([ctx.python, "-B", "-c", script, + pdf, text_file], case, "pdf-read") + problems = pdf_problems(text_file.read_text(encoding="utf-8"), + "EBBR" if mode == "DT" else "SBBR", outcome) if extracted.returncode == 0 else ["PDF missing or unreadable"] + ctx.add("VISUAL_PDF", "FAIL" if problems else "PASS", outcome + ": PDF preserves identity, compliance and counts", + OUTCOMES[outcome], problems or "Readable PDF; all expected fields retained", mode, "FWTS", + (pdf, text_file, case / "pdf-read.log")) + if browser: + reports = output / "html_detailed_summaries" + pages = [reports / "acs_summary.html", reports / "fwts_detailed.html"] + browser_dir = case / "browser" + # Add browser assertions only to this disposable copy. + if reports.is_dir(): + shutil.copytree(reports, browser_dir) + for page in pages: + if page.is_file(): + check_browser(ctx, browser, page, browser_dir, mode, outcome) + else: + ctx.add("VISUAL_BROWSER_INPUT", "FAIL", "Expected browser input report missing", + str(page), "Not generated", mode, "FWTS", (case / "generate.log",)) + except (OSError, ValueError, RuntimeError) as error: + ctx.add("VISUAL_EXECUTION", "BLOCKED", outcome + ": visual probe could not complete", + "Browser/PDF checks execute", str(error), mode, "FWTS", (case,)) + ctx.add("VISUAL_SCOPE", "WARN", "Rendering smoke checks are not full print or hardware certification", + "Separate pagination, other suites, paper sizes and supported-browser testing", + "Synthetic DT/SR FWTS pass/fail/waiver exports; Chromium desktop/mobile only") + + +if __name__ == "__main__": + raise SystemExit(schema_policy_main()) diff --git a/common/log_parser/doctor_checks/core.py b/common/log_parser/doctor_checks/core.py new file mode 100644 index 00000000..48821756 --- /dev/null +++ b/common/log_parser/doctor_checks/core.py @@ -0,0 +1,636 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026, Arm Limited or its affiliates. All rights reserved. +# SPDX-License-Identifier : Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Run the optional Doctor checks and save their findings for review. + +This file selects checks, checks prerequisites, runs commands with time limits, +and writes JSON, text and HTML reports in a new output folder. It also checks +that the portable parser package contains the same files as the checkout. +Doctor reports problems; it never repairs parser code or supplied results. +Importing this module only makes its helpers available; it does not run checks. +""" + +import argparse +import ast +from collections import Counter, defaultdict +from dataclasses import asdict, dataclass, field +from datetime import datetime, timezone +import hashlib +import importlib +import json +import math +import os +from pathlib import Path, PurePosixPath +import re +import shutil +import shlex +import signal +import subprocess +import sys +import tarfile +import tempfile +import traceback + +BASE_DIR = Path(__file__).resolve().parents[1] +# Each entry pairs a user-facing check group with the module that runs it. +GROUPS = (("policy", "doctor_checks.merge"), ("package", "doctor_checks.core"), + ("native", "doctor_checks.probes"), ("merge", "doctor_checks.merge"), + ("raw", "doctor_checks.probes"), ("reports", "doctor_checks.artifacts")) +FINDING_GROUP_TITLES = { + "NATIVE_RAW_SCHEMA": "Generated raw JSON does not match its registered schema", + "MERGE_OVERALL_POLICY": "Overall SRS compliance does not match the requirement policy", + "MERGE_INCOMPLETE_NOT_GREEN": "Empty or incomplete results must not become Compliant", + "MERGE_FAILURE_COUNT": "Merged failure counts do not match explicit test outcomes", + "MERGE_INVALID_INPUT_SAFETY": "Invalid result data must not become Compliant", + "ARTIFACT.SCHEMA": "Report JSON files do not match their registered schemas", + "ARTIFACT.PARITY": "Raw and displayed result identities do not agree", +} + + +# Read evidence and record each check separately from the ACS test results. + +def load_json(path): + """Read JSON without silently accepting duplicate keys or invalid numbers.""" + def pairs(items): + result = {} + for key, value in items: + if key in result: + raise ValueError("Duplicate JSON key: " + repr(key)) + result[key] = value + return result + + def constant(value): + raise ValueError("Non-finite JSON number: " + value) + + def number(value): + result = float(value) + if not math.isfinite(result): + return constant(value) + return result + + return json.loads(Path(path).read_text(encoding="utf-8"), object_pairs_hook=pairs, + parse_constant=constant, parse_float=number) + + +@dataclass +class Finding: + """Store one Doctor check: what was expected, what happened and the evidence.""" + + check_id: str + status: str + issue: str + expected: str + actual: str + mode: str = "" + suite: str = "" + evidence: list = field(default_factory=list) + + def __post_init__(self): + if self.status not in {"PASS", "FAIL", "BLOCKED", "WARN"}: + raise ValueError("Invalid doctor status: " + self.status) + + def to_dict(self): + return asdict(self) + + +class Context: + """Share run settings and keep generated evidence in one new output folder.""" + + def __init__(self, parser_dir, output_dir, modes=("DT", "SR"), timeout=60, + report_inputs=()): + self.parser_dir = Path(parser_dir).resolve() + self.output_dir = Path(output_dir).resolve() + self.modes = tuple(modes) + self.timeout = timeout + self.report_inputs = tuple(report_inputs) + self.findings = [] + self.python = sys.executable + + def add(self, check_id, status, issue, expected, actual, mode="", suite="", + evidence=()): + """Save a finding without changing the result being checked.""" + finding = Finding(check_id, status, str(issue), str(expected), str(actual), + mode, suite, [str(path) for path in evidence]) + self.findings.append(finding) + return finding + + def case_dir(self, name): + """Give a scenario its own evidence folder without allowing path escapes.""" + if Path(name).is_absolute() or ".." in Path(name).parts: + raise ValueError("Doctor case directory must be relative") + directory = self.output_dir / "evidence" / name + directory.mkdir(parents=True, exist_ok=True) + return directory + + def run(self, command, directory, name="command", timeout=None, cwd=None, + env=None): + """Save a command and its output so the check can be repeated later.""" + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + command = [str(item) for item in command] + environment = os.environ.copy() + # Put caches in the evidence folder and use the same Python environment + # for helper commands. Checks must not leave cache files in the source. + environment.update({"PYTHONDONTWRITEBYTECODE": "1", "MPLBACKEND": "Agg", + "MPLCONFIGDIR": str(directory / "mpl-cache"), + "PATH": str(Path(self.python).parent) + os.pathsep + + environment.get("PATH", "")}) + if env: + environment.update(env) + working = str(cwd or self.parser_dir) + (directory / (name + ".command.json")).write_text( + json.dumps({"argv": command, "cwd": working, + "command": shlex.join(command)}, indent=2) + "\n", + encoding="utf-8") + log = directory / (name + ".log") + try: + with log.open("w", encoding="utf-8") as handle: + process = subprocess.Popen(command, cwd=working, env=environment, + stdout=handle, stderr=subprocess.STDOUT, + start_new_session=(os.name == "posix")) + try: + process.wait(timeout=timeout or self.timeout) + except (subprocess.TimeoutExpired, KeyboardInterrupt): + # Stop child processes too, so a timed-out check cannot + # keep writing output while later checks are running. + if os.name == "posix": + os.killpg(process.pid, signal.SIGKILL) + else: + process.kill() + process.wait() + raise + return subprocess.CompletedProcess(command, process.returncode, + log.read_text(encoding="utf-8", errors="replace")) + except subprocess.TimeoutExpired as error: + with log.open("a", encoding="utf-8") as handle: + handle.write("\nDOCTOR: command timed out; check is incomplete.\n") + raise RuntimeError("Command timed out; see " + str(log)) from error + + +# Check the package a partner would extract, not just files in this checkout. + +def verify_checksum(archive): + """Check both the archive's recorded filename and its SHA-256 checksum.""" + fields = archive.with_name(archive.name + ".sha256").read_text(encoding="utf-8").split() + wanted = hashlib.sha256(archive.read_bytes()).hexdigest() + if len(fields) != 2 or fields[0] != wanted or fields[1] != archive.name: + raise ValueError("Archive checksum or recorded archive name does not match") + return wanted + + +def extract_package(archive, destination): + """Reject unsafe archive paths and links before writing any package files.""" + with tarfile.open(archive, "r:gz") as bundle: + members = bundle.getmembers() + names = set() + for member in members: + path = PurePosixPath(member.name) + if (path.is_absolute() or ".." in path.parts or not path.parts or + path.parts[0] != "systemready-log-parser" or + not (member.isfile() or member.isdir()) or str(path) in names): + raise ValueError("Unsafe or duplicate package member: " + member.name) + names.add(str(path)) + if not members: + raise ValueError("Archive contains no files") + destination.mkdir(exist_ok=False) + # Every entry was checked above. This also protects Python versions + # whose tarfile module does not filter unsafe entries by default. + bundle.extractall(destination, members=members) + return destination / "systemready-log-parser" / "common" / "log_parser" + + +def package_differences(source, packaged): + """List missing, extra or changed runtime files in the extracted package.""" + expected = {path.relative_to(source).as_posix(): path for path in source.rglob("*") + if path.is_file() and not any(part in {"tests", "__pycache__"} + for part in path.relative_to(source).parts) and path.suffix != ".pyc"} + actual = {path.relative_to(packaged).as_posix(): path for path in packaged.rglob("*") if path.is_file()} + missing, extra = sorted(expected.keys() - actual.keys()), sorted(actual.keys() - expected.keys()) + changed = sorted(name for name in expected.keys() & actual.keys() + if expected[name].read_bytes() != actual[name].read_bytes()) + return {key: value for key, value in (("missing", missing), ("extra", extra), ("changed", changed)) if value} + + +def run_package(ctx): + """Build and verify a package, then try its command-line entry points.""" + ctx.package_checked = True + ctx.portable_parser = None + directory = ctx.case_dir("package") + archive = directory / "systemready-log-parser-standalone.tar.gz" + build = ctx.run(["bash", ctx.parser_dir / "package_standalone.sh", archive], + directory, "build-package", cwd=directory) + if build.returncode: + ctx.add("PACKAGE_BUILD", "FAIL", "Standalone archive cannot be created from this distribution", + "Public package script creates an archive and checksum", + "Exit %d; see build-package.log" % build.returncode, + evidence=(directory / "build-package.log",)) + return + try: + digest = verify_checksum(archive) + packaged = extract_package(archive, directory / "extracted") + changes = package_differences(ctx.parser_dir, packaged) + except (OSError, ValueError, tarfile.TarError) as error: + ctx.add("PACKAGE_INTEGRITY", "FAIL", "Standalone archive integrity cannot be verified", + "Matching SHA-256, safe extraction, complete runtime", str(error), evidence=(archive,)) + return + ctx.add("PACKAGE_INTEGRITY", "FAIL" if changes else "PASS", + "Archive preserves the complete runtime and Doctor fixtures", + "Identical runtime files after extraction outside the repository", + changes or "SHA-256 " + digest + "; all files match", evidence=(archive, packaged)) + if changes: + return + # Do not let imports from the checkout hide missing files in the package. + ready = True + for name, command in ( + ("help", ["bash", packaged / "main_log_parser.sh", "--standalone", "--help"]), + ("suites", ["bash", packaged / "main_log_parser.sh", "--standalone", "--list-suites"]), + ("doctor", [ctx.python, "-B", packaged / "doctor.py", "--help"]), + ): + result = ctx.run(command, directory, "portable-" + name, cwd=directory, + env={"PYTHONPATH": "", "PYTHONNOUSERSITE": "1"}) + ok = result.returncode == 0 and bool(result.stdout.strip()) + ready &= ok + ctx.add("PACKAGE_CLI", "PASS" if ok else "FAIL", + "Extracted " + name + " entry point runs without checkout imports", + "Exit 0 and nonempty output", "Exit " + str(result.returncode), + evidence=(directory / ("portable-" + name + ".log"),)) + if ready: + ctx.portable_parser = packaged + ctx.add("PACKAGE_ENVIRONMENT", "WARN", "Package checks use the recorded Python environment", + "Separate clean-environment CI jobs verify dependency installation and supported Python versions", + "No packages are installed or upgraded by Doctor; native probes use " + ctx.python) + + +# Register optional flags, choose checks and turn their findings into reports. + +def add_arguments(parser): + """Add Doctor options to a CLI; registering them does not run Doctor.""" + parser.add_argument("--health", action="store_true", + help="With --doctor: run isolated DT/SR correctness probes") + parser.add_argument("--doctor-output", metavar="NEW_DIRECTORY", + help="New directory for doctor results and reproduction inputs") + parser.add_argument("--doctor-report", action="append", default=[], metavar="MODE=PATH", + help="Also check an existing DT or SR report package, read-only; repeatable") + parser.add_argument("--doctor-timeout", type=int, default=60, metavar="SECONDS", + help="Timeout per external check (default 60; range 1-300)") + parser.add_argument("--doctor-checks", metavar="GROUPS", + help="Comma-separated health groups: policy,package,native,merge,raw,reports (default all)") + parser.add_argument("--doctor-visual", action="store_true", + help="Also run optional Chromium and PDF export smoke checks") + parser.add_argument("--doctor-browser", metavar="EXECUTABLE", + help="Chromium executable for --doctor-visual (otherwise detected on PATH)") + + +def file_inventory(directory): + """Hash parser code and metadata so later checks can detect source changes.""" + return {str(path.relative_to(directory)): hashlib.sha256(path.read_bytes()).hexdigest() + for path in sorted(directory.rglob("*")) + if path.is_file() and path.suffix in {".py", ".sh", ".json", ".txt"} + and not any(part in {"__pycache__", ".git"} for part in path.parts)} + + +def registry_issues(data, parser_dir): + """Find duplicate suite names, conflicting aliases and missing suite files.""" + suites = data.get("suites") + if not isinstance(suites, list) or not suites: + return ["suite_registry.json must contain a non-empty suites list"] + issues, aliases, names, keys = [], {}, set(), set() + for suite in suites: + if not isinstance(suite, dict) or not isinstance(suite.get("canonical"), str): + issues.append("Every suite must have a string canonical name") + continue + name = suite["canonical"] + if name in names: + issues.append("Duplicate canonical suite: " + name) + names.add(name) + for alias in [name] + suite.get("aliases", []): + token = re.sub(r"[-_\s]+", "-", alias.strip().upper()) + if token in aliases and aliases[token] != name: + issues.append("Alias %s resolves to both %s and %s" % (alias, aliases[token], name)) + aliases[token] = name + if suite.get("requirements"): + key = suite.get("requirement_key") + if not key or key in keys: + issues.append("Missing or duplicate requirement key for " + name) + keys.add(key) + for mode, requirement in suite.get("requirements", {}).items(): + if mode not in suite.get("modes", []) or requirement not in {"M", "R", "CM", "EM"}: + issues.append("Invalid requirement/mode for " + name + ": " + mode) + for key in ("logs_to_json", "json_to_html", "schema"): + if suite.get(key): + relative = suite[key].split("#", 1)[0] + path = (parser_dir / relative).resolve() + if parser_dir not in path.parents or not path.is_file(): + issues.append(name + ": missing or out-of-package " + key + " " + relative) + if suite.get("schema"): + source, _, fragment = suite["schema"].partition("#") + try: + value = load_json(parser_dir / source) + for token in fragment.lstrip("/").split("/") if fragment else []: + value = value[token.replace("~1", "/").replace("~0", "~")] + except (OSError, ValueError, KeyError, TypeError): + issues.append(name + ": schema fragment cannot be resolved: " + suite["schema"]) + for suite in suites: + if isinstance(suite, dict): + for included in suite.get("included_suites", []): + if included not in names: + issues.append(suite["canonical"] + ": unknown included suite " + included) + return issues + + +def check_repository(ctx): + """Check syntax, suite settings and dependencies before starting scenarios.""" + directory = ctx.case_dir("repository") + syntax_errors = [] + sources = sorted(path for path in ctx.parser_dir.rglob("*.py") + if "__pycache__" not in path.parts) + for source in sources: + try: + ast.parse(source.read_bytes(), filename=str(source)) + except (SyntaxError, ValueError, OSError) as error: + syntax_errors.append(str(error)) + for index, source in enumerate(sorted(ctx.parser_dir.rglob("*.sh"))): + # Syntax checks read the shell scripts; they do not execute their tests. + result = ctx.run(["bash", "-n", source], directory, "shell-%d" % index) + if result.returncode: + syntax_errors.append(str(source) + ": " + result.stdout.strip()) + ctx.add("REPO_SYNTAX", "FAIL" if syntax_errors or not sources else "PASS", + "Parser Python and shell files must be syntactically valid", + "All files parse; no commands in shell files are executed", + "\n".join(syntax_errors) or "%d Python files checked, plus shell syntax" % len(sources), + evidence=[directory]) + try: + registry = load_json(ctx.parser_dir / "suite_registry.json") + problems = registry_issues(registry, ctx.parser_dir) + from standalone_runner import validate_registry + validate_registry(registry["suites"], registry["standalone"], + ctx.parser_dir / "suite_registry.json") + ctx.add("REPO_REGISTRY", "FAIL" if problems else "PASS", + "Registry must connect each suite to its parser, schema and execution inputs", + "Unique aliases/requirements and complete executable registry", + "\n".join(problems) or "Registry and schema fragments resolve", + evidence=[ctx.parser_dir / "suite_registry.json"]) + except Exception as error: # A broken registry must still produce a doctor report. + ctx.add("REPO_REGISTRY", "FAIL", "Suite registry cannot be used", + "Valid complete suite registry", str(error)) + registry = {} + metadata_errors = [] + for source in sorted(ctx.parser_dir.glob("*.json")): + try: + load_json(source) + except (OSError, ValueError) as error: + metadata_errors.append(str(source) + ": " + str(error)) + ctx.add("REPO_JSON", "FAIL" if metadata_errors else "PASS", + "Bundled parser metadata must be readable JSON", "No malformed JSON", + "\n".join(metadata_errors) or "Bundled JSON files decode successfully") + support = ("requirements.txt", "test_categoryDT.json", "test_category.json", + "validate.py", "report_ui.py", "generate_acs_summary.py", + "merge_jsons.py", "apply_waivers.py") + missing = [name for name in support if not (ctx.parser_dir / name).is_file()] + ctx.add("REPO_SUPPORT_FILES", "FAIL" if missing else "PASS", + "Shared parser files and mode metadata must be included in the checkout/package", + "All shared support files available", ", ".join(missing) or "All available") + modules = {"chardet", "jinja2", "matplotlib", "jsonschema"} + for entry in registry.get("standalone", {}).get("suite_execution", {}).values(): + modules.update(entry.get("json_dependencies", [])) + available = {} + for module in sorted(modules): + result = ctx.run([ctx.python, "-B", "-c", + "import importlib; importlib.import_module(" + repr(module) + ")"], + directory, "dependency-" + module) + available[module] = result.returncode == 0 + ctx.add("DEPENDENCY", "PASS" if result.returncode == 0 else "BLOCKED", + "Python dependency must import: " + module, "Import succeeds in " + ctx.python, + "Import succeeded" if result.returncode == 0 else + (result.stdout.strip().splitlines()[-1] if result.stdout.strip() else + "Import failed with exit " + str(result.returncode)) + + ". Install the parser requirements in this Python environment: " + + ctx.python + " -m pip install -r " + str(ctx.parser_dir / "requirements.txt"), + evidence=[directory / ("dependency-" + module + ".log")]) + # A missing renderer must not hide policy checks, packaging or JSON probes. + # Each group reports its own remaining file/capability failures. + return {"policy": True, "package": True, "merge": True, + "native": all(available.get(name, False) for name in ("chardet", "jsonschema")), + "raw": all(available.values()), "reports": available.get("jsonschema", False), + "visual": all(available.values())} + + +def selected_groups(args): + """Select requested groups and include package checks when they are needed.""" + names = [name for name, _ in GROUPS] + value = getattr(args, "doctor_checks", None) + chosen = set(names) if value is None else {part.strip() for part in value.split(",")} + if not chosen or not chosen <= set(names): + raise ValueError("--doctor-checks requires a nonempty selection from " + ",".join(names)) + visual = getattr(args, "doctor_visual", False) + if getattr(args, "doctor_browser", None) and not visual: + raise ValueError("--doctor-browser requires --doctor-visual") + if "native" in chosen or visual: + chosen.add("package") + groups = [(name, module) for name, module in GROUPS if name in chosen] + if visual: + groups.append(("visual", "doctor_checks.artifacts")) + return groups + + +def protected_source_root(parser_dir): + """Find the whole checkout or package that Doctor must not write inside.""" + parser_dir = Path(parser_dir).resolve() + for parent in (parser_dir, *parser_dir.parents): + if (parent / ".git").exists(): + return parent + if (parser_dir.name == "log_parser" and parser_dir.parent.name == "common" and + (parser_dir.parent.parent / "LICENSE.md").is_file()): + return parser_dir.parent.parent + return parser_dir + + +def verdict(findings): + """A blocked or empty run is not a pass, even when no check has failed.""" + counts = Counter(finding.status for finding in findings) + if counts["FAIL"]: + return "FAIL", 1 + if counts["BLOCKED"] or not counts["PASS"]: + return "INCOMPLETE", 2 + return "PASS (checked scope)", 0 + + +def render_reports(ctx, metadata): + """Write all findings to JSON and readable text/HTML views of the same run.""" + # Only health runs load the report builder; ordinary parsing just adds flags. + from .report import render_html + status, exit_code = verdict(ctx.findings) + counts = Counter(finding.status for finding in ctx.findings) + payload = dict(metadata, verdict=status, exit_code=exit_code, counts=dict(counts), + findings=[finding.to_dict() for finding in ctx.findings]) + (ctx.output_dir / "doctor.json").write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + lines = ["# Log parser doctor: " + status, "", "Revision: " + metadata["revision"], + "", "Counts: " + json.dumps(dict(counts)), "", + "Synthetic tests are parser-health probes, not hardware certification results.", + "Recommended suites are checked against the non-blocking overall-compliance contract.", + "PASS applies only to the recorded checks. BLOCKED is unverified, never passed.", ""] + lines.append("Counts are assertions, not distinct bugs; one defect can fail multiple scenarios.\n") + titles = {} + for item in ctx.findings: + if item.status == "PASS": + continue + label = "%s [%s] %s %s" % (item.status, item.check_id, item.mode, item.suite) + key = item.status, item.check_id + title = FINDING_GROUP_TITLES.get(item.check_id, item.issue) + if key in titles and titles[key] != title: + # An outer group describes every finding, not whichever file or + # scenario happened to be reported first. Details retain exact text. + title = item.check_id.replace("_", " ").replace(".", " ").capitalize() + titles[key] = title + lines.extend(["## " + label, "", item.issue, "", "Expected: " + item.expected, + "", "Actual: " + item.actual, ""]) + for evidence in item.evidence: + lines.append("Evidence: " + evidence) + (ctx.output_dir / "doctor.md").write_text("\n".join(lines) + "\n", encoding="utf-8") + document = render_html(ctx.findings, metadata, ctx.output_dir, status, counts, titles) + (ctx.output_dir / "index.html").write_text(document, encoding="utf-8") + return status, exit_code, counts + + +def run_health(args, parser_dir=BASE_DIR): + """Run the explicitly requested health checks without changing their inputs.""" + if not 1 <= args.doctor_timeout <= 300: + raise ValueError("--doctor-timeout must be between 1 and 300 seconds") + groups = selected_groups(args) + inputs = [] + modes = (args.mode,) if args.mode else ("DT", "SR") + for value in args.doctor_report: + mode, separator, raw_path = value.partition("=") + if separator != "=" or mode not in {"DT", "SR"} or not raw_path: + raise ValueError("--doctor-report requires DT=/path or SR=/path") + if mode not in modes: + raise ValueError("Report mode %s conflicts with --mode %s" % (mode, args.mode)) + inputs.append((mode, Path(raw_path).expanduser().resolve())) + if args.doctor_output: + # Never overwrite a previous run, supplied report or source directory. + output = Path(args.doctor_output).expanduser().resolve() + for protected in [protected_source_root(parser_dir)] + [path for _, path in inputs]: + if output == protected or protected in output.parents: + raise ValueError("Doctor output must be outside parser sources and supplied reports") + output.mkdir(parents=True, exist_ok=False) + else: + temporary_parent = Path(tempfile.gettempdir()).resolve() + for protected in [protected_source_root(parser_dir)] + [path for _, path in inputs]: + if temporary_parent == protected or protected in temporary_parent.parents: + raise ValueError("Temporary directory is inside parser sources or a supplied report; " + "set --doctor-output to a new directory outside both") + output = Path(tempfile.mkdtemp(prefix="log-parser-health-", dir=temporary_parent)) + ctx = Context(parser_dir, output, modes, args.doctor_timeout, inputs) + ctx.browser = getattr(args, "doctor_browser", None) + if any(group == "package" for group, _ in groups): + # Intent exists even if importing the package-check module later fails. + ctx.package_checked = True + ctx.portable_parser = None + before = file_inventory(ctx.parser_dir) + directory = ctx.case_dir("repository") + revision = "Unknown (not a Git checkout); source hashes are recorded" + worktree = "Not a Git checkout" + if shutil.which("git"): + result = ctx.run(["git", "rev-parse", "HEAD"], directory, "revision") + if result.returncode == 0: + revision = result.stdout.strip() + result = ctx.run(["git", "status", "--short", "--branch"], directory, "worktree") + worktree = result.stdout.strip() + metadata = {"revision": revision, "parser_dir": str(ctx.parser_dir), + "worktree_status": worktree, + "python": ctx.python, "modes": list(modes), + "check_groups": [group for group, _ in groups], + "started_utc": datetime.now(timezone.utc).isoformat(), + "source_sha256": before, + "scope": "Repository, synthetic raw-log/waiver/merge/HTML checks; supplied reports read-only"} + print("Log parser doctor — deep health check", flush=True) + print("Revision: " + revision + "\nModes: " + ", ".join(modes) + "\nEvidence: " + str(output), flush=True) + try: + ready = check_repository(ctx) + except Exception as error: + ctx.add("REPO_CHECK_ERROR", "BLOCKED", "Repository checks could not finish", + "Completed prerequisites", str(error), evidence=[directory]) + ready = False + if not getattr(args, "doctor_visual", False): + ctx.add("VISUAL_COVERAGE", "WARN", "Browser and PDF export checks were not requested", + "Use --doctor-visual for optional rendering smoke checks", + "Static JSON/HTML checks do not verify JavaScript or PDF output") + omitted = sorted({name for name, _ in GROUPS} - {name for name, _ in groups}) + if omitted: + ctx.add("SCOPE_LIMIT", "WARN", "Focused health run; other groups were not checked", + "Omit --doctor-checks for the full default scope", ", ".join(omitted)) + for group, module in groups: + print("Checking " + group + "...", flush=True) + previous = len(ctx.findings) + try: + group_ready = ready.get(group, False) if isinstance(ready, dict) else ready + if group_ready: + getattr(importlib.import_module(module), "run_" + group)(ctx) + else: + ctx.add("CHECK_GROUP", "BLOCKED", group + " checks were not executed", + "Usable dependencies and repository prerequisites", + "Resolve prerequisite errors above, then rerun") + except (Exception, SystemExit) as error: + # A broken check must be visible, but should not hide evidence + # from other independent groups that can still run. + trace = ctx.case_dir(group) / "doctor-error.log" + trace.write_text(traceback.format_exc(), encoding="utf-8") + ctx.add("CHECK_GROUP_ERROR", "BLOCKED", group + " checks did not complete", + "Doctor probe executes and evaluates its result", str(error), evidence=[trace]) + if previous == len(ctx.findings): + ctx.add("ZERO_CHECKS", "BLOCKED", group + " executed no assertions", + "At least one explicit check or coverage warning", "No findings returned") + counts = Counter(item.status for item in ctx.findings[previous:]) + print(group + ": " + str(dict(counts)), flush=True) + after = file_inventory(ctx.parser_dir) + # Compare content, not modification times, to catch accidental source edits. + changed = sorted(key for key in set(before) | set(after) if before.get(key) != after.get(key)) + ctx.add("SOURCE_UNCHANGED", "FAIL" if changed else "PASS", + "Health checks must not change parser source or metadata", + "Identical source hashes before and after checks", ", ".join(changed) or "Unchanged") + metadata["finished_utc"] = datetime.now(timezone.utc).isoformat() + status, code, counts = render_reports(ctx, metadata) + grouped = defaultdict(list) + for item in ctx.findings: + if item.status in {"FAIL", "BLOCKED"}: + grouped[(item.status, item.check_id.split(":")[0])].append(item) + print("\nResult: " + status + " " + str(dict(counts))) + for (severity, rule), items in grouped.items(): + sample = items[0] + print("\n%s [%s] (%d assertions): %s" % (severity, rule, len(items), sample.issue)) + print(" Example %s %s: expected %s; actual %s" % + (sample.mode, sample.suite, sample.expected[:350], sample.actual[:500])) + print("\nOpen " + str(output / "index.html")) + print("All checks and evidence: " + str(output / "doctor.json")) + return code + + +def main(): + """Allow a manual Doctor run even if the normal parser entry point is broken.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--mode", choices=("DT", "SR")) + add_arguments(parser) + args = parser.parse_args() + try: + return run_health(args) + except (ValueError, OSError) as error: + print("Doctor input/output error: " + str(error), file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.dont_write_bytecode = True + sys.exit(main()) diff --git a/common/log_parser/doctor_checks/data/native_cases.json b/common/log_parser/doctor_checks/data/native_cases.json new file mode 100644 index 00000000..5da2c946 --- /dev/null +++ b/common/log_parser/doctor_checks/data/native_cases.json @@ -0,0 +1,1881 @@ +{ + "_copyright": "Copyright (c) 2026, Arm Limited or its affiliates. All rights reserved.", + "_license": "SPDX-License-Identifier: Apache-2.0", + "_description": "Handwritten sample logs and their expected results for optional Doctor checks. Each scenario gives the mode, suites, input files and expected raw JSON records. Expected results are written independently of parser output so a parser mistake cannot define its own passing answer. These are synthetic examples, not hardware results.", + "format_version": 1, + "provenance": { + "source": "log-parser-pr-qa handwritten native scenarios", + "commit": "b6a8a78d1fef3d6e41d2d2aec94006e0a9263c8c", + "note": "Synthetic logs and independently specified raw identities; CI overall-compliance expectations are intentionally not imported.", + "extensions": [ + { + "scenario": "dt_memory_map_routes", + "commit": "decc0aaa9902da57b18d5fd3ec40efa511fb5273", + "source": "Handwritten completed-log examples reviewed against reserved_memory_map_checker.py and dtb_alignment_test.py producer messages; expected identities and counts specified independently of parser output." + }, + { + "scenarios": ["sr_pcie_pass", "sr_pcie_fail", "sr_pcie_skip"], + "commit": "719dab25e12c2d5f36fdc06673d20f0354a851e8", + "source": "Handwritten producer-shaped PCIe audit logs; PJ03164-4076 defines SR-only Recommended results using numeric counts: zero ROM devices means SKIPPED, otherwise zero non-compliant devices means PASSED, otherwise FAILED. Printed Result Summary intentionally disagrees to verify that it does not override those counts." + } + ] + }, + "scenarios": [ + { + "name": "sr_all_report_families", + "mode": "SR", + "suites": [ + "BSA", + "SBSA", + "FWTS", + "SCT", + "BBSR-FWTS", + "BBSR-SCT", + "BBSR-TPM", + "SBMR-IB", + "SBMR-OOB", + "OS-TESTS" + ], + "files": { + "results/uefi/BsaResults.log": "*** Running PE tests ***\nB_PE_01 : 1 : QA passing rule\nResult: PASSED\nB_PE_02 : 2 : QA failing rule\n=== Start tests for rules referenced by B_PE_02 ===\nB_CHILD_01 : 3 : QA failing child rule\nResult: FAILED\n=== End tests for rules referenced by B_PE_02 ===\nResult: FAILED\n", + "results/uefi/SbsaResults.log": "*** Running PE tests ***\nB_PE_01 : 1 : QA passing rule\nResult: PASSED\nB_PE_02 : 2 : QA failing rule\n=== Start tests for rules referenced by B_PE_02 ===\nB_CHILD_01 : 3 : QA failing child rule\nResult: FAILED\n=== End tests for rules referenced by B_PE_02 ===\nResult: FAILED\n", + "results/fwts/FWTSResults.log": "Running tests: uefirtmisc\n====================\nuefirtmisc: QA interface checks\nTest 1 of 2: QA passing interface\nPASSED: Test 1, QA passed\nTest 2 of 2: QA failing interface\nFAILED [HIGH] QA failed\n", + "results/bbsr/fwts/FWTSResults.log": "Running tests: RuntimeServicesTest\n====================\nRuntimeServicesTest: QA interface checks\nTest 1 of 2: QA passing interface\nPASSED: Test 1, QA passed\nTest 2 of 2: QA failing interface\nFAILED [HIGH] QA failed\n", + "results/sct_results/Overall/Summary.log": "BBR ACS 2.1\nResetSystem_Func\nTest Configuration #0\nQA event checks\nTest Entry Point GUID: 29481844-C567-4A8D-B92F-D57B32F039B8\nReturned Status Code: 0\nResetSystem_Func: [FAILURE]\nQA passing event -- PASS\n4E9AA877-2672-4F8C-BA3C-C02F49A68911\n/build/edk2-test/SctPkg/TestCase/UEFI/EFI/BootServices/Test.c:10:Status - Success\nQA failing event -- FAIL\n060234F5-A84A-4DD7-AD5B-64996250F216\n/build/edk2-test/SctPkg/TestCase/UEFI/EFI/BootServices/Test.c:20:Status - Device Error\n", + "results/bbsr/sct_results/Overall/Summary.log": "BBR ACS 2.1\nResetSystem_Func\nTest Configuration #0\nQA event checks\nTest Entry Point GUID: 29481844-C567-4A8D-B92F-D57B32F039B8\nReturned Status Code: 0\nResetSystem_Func: [FAILURE]\nQA passing event -- PASS\n4E9AA877-2672-4F8C-BA3C-C02F49A68911\n/build/edk2-test/SctPkg/TestCase/UEFI/EFI/BootServices/Test.c:10:Status - Success\nQA failing event -- FAIL\n060234F5-A84A-4DD7-AD5B-64996250F216\n/build/edk2-test/SctPkg/TestCase/UEFI/EFI/BootServices/Test.c:20:Status - Device Error\n", + "results/edk2-test-parser/edk2-test-parser.log": "| name | set guid | guid | result | updated by |\n|------|----------|------|--------|------------|\n| QA failing event | 29481844-C567-4A8D-B92F-D57B32F039B8 | 060234F5-A84A-4DD7-AD5B-64996250F216 | FAIL | QA helper reason |\n", + "results/edk2-test-parser/edk2-test-parser-bbsr.log": "| name | set guid | guid | result | updated by |\n|------|----------|------|--------|------------|\n| QA failing event | 29481844-C567-4A8D-B92F-D57B32F039B8 | 060234F5-A84A-4DD7-AD5B-64996250F216 | FAIL | QA helper reason |\n", + "results/bbsr/tpm2/verify_tpm_measurements.log": "Verify QA digest: PASS\nVerify QA event: FAIL\n QA digest does not match\n", + "results/sbmr/sbmr_in_band_logs/output.xml": "\n\nQA command failed\n\n", + "results/sbmr/sbmr_out_of_band_logs/output.xml": "\n\nQA command failed\n\n", + "results/post-script/post-script.log": "INFO QA checks started\nERROR QA required file is missing\nWARNING QA optional file is missing\n", + "os-logs/rhel/cat-etc-os-release.txt": "NAME=\"Red Hat Enterprise Linux\"\nVERSION_ID=\"9.3\"\n", + "os-logs/sle/cat-etc-os-release.txt": "NAME=\"SLES\"\nVERSION_ID=\"15\"\n" + }, + "auxiliary": [ + "edk2_test_parser.json", + "edk2_test_parser-bbsr.json" + ], + "raw": { + "bsa.json": { + "destination": "Suite_Name: BSA", + "assertions": [ + { + "path": [ + "suite_summary", + "Passed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "Failed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "Total Rules Run" + ], + "value": 2 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "testcases", + 0 + ], + "fields": { + "Test_case": "B_PE_01 : 1", + "Test_case_description": "QA passing rule", + "Test_result": "PASSED" + } + }, + { + "path": [ + "test_results", + 0, + "testcases", + 1 + ], + "fields": { + "Test_case": "B_PE_02 : 2", + "Test_case_description": "QA failing rule", + "Test_result": "FAILED" + } + }, + { + "path": [ + "test_results", + 0, + "testcases", + 1, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "B_CHILD_01 : 3", + "sub_Test_Description": "QA failing child rule", + "sub_test_result": "FAILED" + } + } + ] + }, + "sbsa.json": { + "destination": "Suite_Name: SBSA", + "assertions": [ + { + "path": [ + "suite_summary", + "Passed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "Failed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "Total Rules Run" + ], + "value": 2 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "testcases", + 0 + ], + "fields": { + "Test_case": "B_PE_01 : 1", + "Test_case_description": "QA passing rule", + "Test_result": "PASSED" + } + }, + { + "path": [ + "test_results", + 0, + "testcases", + 1 + ], + "fields": { + "Test_case": "B_PE_02 : 2", + "Test_case_description": "QA failing rule", + "Test_result": "FAILED" + } + }, + { + "path": [ + "test_results", + 0, + "testcases", + 1, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "B_CHILD_01 : 3", + "sub_Test_Description": "QA failing child rule", + "sub_test_result": "FAILED" + } + } + ] + }, + "fwts.json": { + "destination": "Suite_Name: SBBR-FWTS", + "assertions": [ + { + "path": [ + "suite_summary", + "total_passed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "total_failed" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1 of 2", + "sub_Test_Description": "QA passing interface", + "sub_test_result": { + "PASSED": 1, + "FAILED": 0, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + }, + { + "path": [ + "test_results", + 0, + "subtests", + 1 + ], + "fields": { + "sub_Test_Number": "2 of 2", + "sub_Test_Description": "QA failing interface", + "sub_test_result": { + "PASSED": 0, + "FAILED": 1, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + } + ] + }, + "bbsr_fwts.json": { + "destination": "Suite_Name: BBSR-FWTS", + "assertions": [ + { + "path": [ + "suite_summary", + "total_passed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "total_failed" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1 of 2", + "sub_Test_Description": "QA passing interface", + "sub_test_result": { + "PASSED": 1, + "FAILED": 0, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + }, + { + "path": [ + "test_results", + 0, + "subtests", + 1 + ], + "fields": { + "sub_Test_Number": "2 of 2", + "sub_Test_Description": "QA failing interface", + "sub_test_result": { + "PASSED": 0, + "FAILED": 1, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + } + ] + }, + "sct.json": { + "destination": "Suite_Name: SBBR-SCT", + "assertions": [ + { + "path": [ + "suite_summary", + "total_passed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "total_failed" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1", + "sub_Test_GUID": "4E9AA877-2672-4F8C-BA3C-C02F49A68911", + "sub_Test_Description": "QA passing event", + "sub_test_result": "PASSED" + } + }, + { + "path": [ + "test_results", + 0, + "subtests", + 1 + ], + "fields": { + "sub_Test_Number": "2", + "sub_Test_GUID": "060234F5-A84A-4DD7-AD5B-64996250F216", + "sub_Test_Description": "QA failing event", + "sub_test_result": "FAILED" + } + } + ] + }, + "bbsr_sct.json": { + "destination": "Suite_Name: BBSR-SCT", + "assertions": [ + { + "path": [ + "suite_summary", + "total_passed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "total_failed" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1", + "sub_Test_GUID": "4E9AA877-2672-4F8C-BA3C-C02F49A68911", + "sub_Test_Description": "QA passing event", + "sub_test_result": "PASSED" + } + }, + { + "path": [ + "test_results", + 0, + "subtests", + 1 + ], + "fields": { + "sub_Test_Number": "2", + "sub_Test_GUID": "060234F5-A84A-4DD7-AD5B-64996250F216", + "sub_Test_Description": "QA failing event", + "sub_test_result": "FAILED" + } + } + ] + }, + "bbsr_tpm.json": { + "destination": "Suite_Name: BBSR-TPM", + "assertions": [ + { + "path": [ + "suite_summary", + "total_passed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "total_failed" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1", + "sub_Test_Description": "Verify QA digest", + "sub_test_result": "PASS" + } + }, + { + "path": [ + "test_results", + 0, + "subtests", + 1 + ], + "fields": { + "sub_Test_Number": "2", + "sub_Test_Description": "Verify QA event", + "sub_test_result": "FAIL" + } + } + ] + }, + "sbmr_ib.json": { + "destination": "Suite_Name: SBMR-IB", + "assertions": [ + { + "path": [ + "suite_summary", + "total_passed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "total_failed" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "Test_cases", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1", + "sub_Test_Description": "QA passing command", + "sub_test_result": "PASSED" + } + }, + { + "path": [ + "test_results", + 0, + "Test_cases", + 0, + "subtests", + 1 + ], + "fields": { + "sub_Test_Number": "2", + "sub_Test_Description": "QA failing command", + "sub_test_result": "FAILED" + } + } + ] + }, + "sbmr_oob.json": { + "destination": "Suite_Name: SBMR-OOB", + "assertions": [ + { + "path": [ + "suite_summary", + "total_passed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "total_failed" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "Test_cases", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1", + "sub_Test_Description": "QA passing command", + "sub_test_result": "PASSED" + } + }, + { + "path": [ + "test_results", + 0, + "Test_cases", + 0, + "subtests", + 1 + ], + "fields": { + "sub_Test_Number": "2", + "sub_Test_Description": "QA failing command", + "sub_test_result": "FAILED" + } + } + ] + }, + "os_test.json": { + "destination": "Suite_Name: OS Tests", + "assertions": [ + { + "path": [ + "test_results", + 0, + "Test_suite" + ], + "value": "os_test" + }, + { + "path": [ + "suite_summary", + "total_passed" + ], + "value": 2 + }, + { + "path": [ + "suite_summary", + "total_failed" + ], + "value": 0 + }, + { + "path": [ + "test_results", + 0, + "subtests", + 0, + "sub_test_result", + "pass_reasons" + ], + "value": [ + "Red Hat Enterprise Linux 9.3" + ] + }, + { + "path": [ + "test_results", + 0, + "subtests", + 1, + "sub_test_result", + "pass_reasons" + ], + "value": [ + "SLES 15" + ] + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1", + "sub_Test_Description": "Is rhel logs present or not", + "sub_test_result": { + "PASSED": 1, + "FAILED": 0, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + }, + { + "path": [ + "test_results", + 0, + "subtests", + 1 + ], + "fields": { + "sub_Test_Number": "2", + "sub_Test_Description": "Is sle logs present or not", + "sub_test_result": { + "PASSED": 1, + "FAILED": 0, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + } + ] + } + } + }, + { + "name": "dt_all_standalone_routes", + "mode": "DT", + "suites": [ + "BSA", + "FWTS", + "SCT", + "BBSR-FWTS", + "BBSR-SCT", + "BBSR-TPM", + "PFDI", + "SCMI", + "POST-SCRIPT", + "DT-KSELFTEST", + "DT-VALIDATE", + "ETHTOOL-TEST", + "READ-WRITE-CHECK-BLK-DEVICES", + "CAPSULE-UPDATE", + "PSCI", + "SMBIOS", + "NETWORK-BOOT", + "RUNTIME-DEV-MAP", + "OS-TESTS" + ], + "files": { + "results/uefi/BsaResults.log": "*** Running PE tests ***\nB_PE_01 : 1 : QA passing rule\nResult: PASSED\nB_PE_02 : 2 : QA failing rule\n=== Start tests for rules referenced by B_PE_02 ===\nB_CHILD_01 : 3 : QA failing child rule\nResult: FAILED\n=== End tests for rules referenced by B_PE_02 ===\nResult: FAILED\n", + "results/uefi/pfdiresults.log": "*** Running PFDI tests ***\nPFDI_01 : 1 : QA passing rule\nResult: PASSED\nPFDI_02 : 2 : QA failing rule\nResult: FAILED\n", + "results/fwts/FWTSResults.log": "Running tests: uefirtmisc\n====================\nuefirtmisc: QA interface checks\nTest 1 of 2: QA passing interface\nPASSED: Test 1, QA passed\nTest 2 of 2: QA failing interface\nFAILED [HIGH] QA failed\n", + "results/bbsr/fwts/FWTSResults.log": "Running tests: uefirtauthvar\n====================\nuefirtauthvar: QA interface checks\nTest 1 of 2: QA passing interface\nPASSED: Test 1, QA passed\nTest 2 of 2: QA failing interface\nFAILED [HIGH] QA failed\n", + "results/bbsr/sct_results/Overall/Summary.log": "BBR ACS 2.1\nResetSystem_Func\nTest Configuration #0\nQA event checks\nTest Entry Point GUID: 29481844-C567-4A8D-B92F-D57B32F039B8\nReturned Status Code: 0\nResetSystem_Func: [FAILURE]\nQA passing event -- PASS\n4E9AA877-2672-4F8C-BA3C-C02F49A68911\n/build/edk2-test/SctPkg/TestCase/UEFI/EFI/BootServices/Test.c:10:Status - Success\nQA failing event -- FAIL\n060234F5-A84A-4DD7-AD5B-64996250F216\n/build/edk2-test/SctPkg/TestCase/UEFI/EFI/BootServices/Test.c:20:Status - Device Error\n", + "results/bbsr/tpm2/verify_tpm_measurements.log": "Verify QA digest: PASS\nVerify QA event: FAIL\n QA digest does not match\n", + "results/linux_acs/scmi_acs_app/arm_scmi_test_log.txt": "**** SCMI Compliance Suite ****\n*** Starting BASE tests ***\n1 : QA passing protocol : CONFORMANT\n2 : QA failing protocol : NON CONFORMANT\n", + "results/post-script/post-script.log": "INFO QA checks started\nERROR QA required file is missing\nWARNING QA optional file is missing\n", + "results/linux_tools/dt_kselftest.log": "selftests: dt: test_unprobed_devices.sh\n# ok 1 node-a\n# not ok 2 node-b\n# ok 3 node-c # SKIP\n", + "results/linux_tools/dt-validate-parser.log": "DeviceTree bindings of Linux kernel version: 6.18\nNon-ignored entries\n-------------------\nnode-a dt-validate error QA missing required property\nnode-b dt-validate warning QA optional property\n", + "results/linux_tools/ethtool-test.log": "Running Networking Checks\nSUMMARY\nDetected Interfaces: 1 (eth0)\nInterface eth0\nBring up: PASSED\nethtool self tests: FAILED (QA self-test failed)\n", + "results/linux_tools/read_write_check_blk_devices.log": "Read block devices tool\nINFO: Block device : /dev/qa\nNo valid partition table found for /dev/qa, treating as raw device.\nPerforming block read on /dev/qa\nBlock read on /dev/qa successful\n****************************************************************\n", + "fw/capsule_test_results.log": "Testing ESRT FW version update\nINFO: QA firmware version is unchanged\nRESULTS: Overall Capsule Update Result: FAILED\n", + "results/linux_tools/psci/psci_kernel.log": "psci: PSCIv1.1 detected in firmware.\n", + "results/sct_results/Overall/Summary.log": "BBR ACS 2.1\nGetTime_Func\nTest Configuration #0\nQA runtime clock check\nTest Entry Point GUID: 00000000-0000-0000-0000-000000000003\nReturned Status Code: 0\nGetTime_Func: [PASS]\nQA clock read -- PASS\n00000000-0000-0000-0000-000000000004\n/build/edk2-test/SctPkg/TestCase/UEFI/EFI/RuntimeServices/Test.c:10:Status - Success\nBBR ACS 2.1\nSmbiosTable\nTest Configuration #0\nQA SMBIOS table check\nSMBIOS table -- PASS\n00000000-0000-0000-0000-000000000001\nQA table found\n", + "results/network_boot/network_boot_results.log": "[INFO] network_boot_checks\nImage URL: PASSED (QA image found)\nEFI System Partition (ESP): FAILED (QA partition missing)\nNetwork_Boot_Result: FAILED\n", + "results/linux_tools/runtime_device_mapping_conflict_test.log": "Testing Runtime Device Mapping Conflict Test\nDEBUG: QA overlapping mapping\nRESULTS: FAILED\n", + "os-logs/linux-Fedora-40/ethtool_test.log": "INFO: No ethernet interfaces detected via ip linux command\n", + "os-logs/linux-ubuntu-24/ethtool_test.log": "INFO: No ethernet interfaces detected via ip linux command\n", + "os-logs/linux-Tumbleweed/ethtool_test.log": "INFO: No ethernet interfaces detected via ip linux command\n" + }, + "raw": { + "bsa.json": { + "destination": "Suite_Name: BSA", + "assertions": [ + { + "path": [ + "suite_summary", + "Passed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "Failed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "Total Rules Run" + ], + "value": 2 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "testcases", + 0 + ], + "fields": { + "Test_case": "B_PE_01 : 1", + "Test_case_description": "QA passing rule", + "Test_result": "PASSED" + } + }, + { + "path": [ + "test_results", + 0, + "testcases", + 1 + ], + "fields": { + "Test_case": "B_PE_02 : 2", + "Test_case_description": "QA failing rule", + "Test_result": "FAILED" + } + }, + { + "path": [ + "test_results", + 0, + "testcases", + 1, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "B_CHILD_01 : 3", + "sub_Test_Description": "QA failing child rule", + "sub_test_result": "FAILED" + } + } + ] + }, + "pfdi.json": { + "destination": "Suite_Name: PFDI", + "assertions": [ + { + "path": [ + "suite_summary", + "Passed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "Failed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "Total Rules Run" + ], + "value": 2 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "testcases", + 0 + ], + "fields": { + "Test_case": "PFDI_01 : 1", + "Test_case_description": "QA passing rule", + "Test_result": "PASSED" + } + }, + { + "path": [ + "test_results", + 0, + "testcases", + 1 + ], + "fields": { + "Test_case": "PFDI_02 : 2", + "Test_case_description": "QA failing rule", + "Test_result": "FAILED" + } + } + ] + }, + "fwts.json": { + "destination": "Suite_Name: EBBR-FWTS", + "assertions": [ + { + "path": [ + "suite_summary", + "total_passed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "total_failed" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1 of 2", + "sub_Test_Description": "QA passing interface", + "sub_test_result": { + "PASSED": 1, + "FAILED": 0, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + }, + { + "path": [ + "test_results", + 0, + "subtests", + 1 + ], + "fields": { + "sub_Test_Number": "2 of 2", + "sub_Test_Description": "QA failing interface", + "sub_test_result": { + "PASSED": 0, + "FAILED": 1, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + } + ] + }, + "bbsr_fwts.json": { + "destination": "Suite_Name: BBSR-FWTS", + "assertions": [ + { + "path": [ + "suite_summary", + "total_passed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "total_failed" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1 of 2", + "sub_Test_Description": "QA passing interface", + "sub_test_result": { + "PASSED": 1, + "FAILED": 0, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + }, + { + "path": [ + "test_results", + 0, + "subtests", + 1 + ], + "fields": { + "sub_Test_Number": "2 of 2", + "sub_Test_Description": "QA failing interface", + "sub_test_result": { + "PASSED": 0, + "FAILED": 1, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + } + ] + }, + "sct.json": { + "destination": "Suite_Name: EBBR-SCT", + "assertions": [ + { + "path": [ + "suite_summary", + "total_passed" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1", + "sub_Test_GUID": "00000000-0000-0000-0000-000000000004", + "sub_Test_Description": "QA clock read", + "sub_test_result": "PASSED" + } + } + ] + }, + "bbsr_sct.json": { + "destination": "Suite_Name: BBSR-SCT", + "assertions": [ + { + "path": [ + "suite_summary", + "total_passed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "total_failed" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1", + "sub_Test_GUID": "4E9AA877-2672-4F8C-BA3C-C02F49A68911", + "sub_Test_Description": "QA passing event", + "sub_test_result": "PASSED" + } + }, + { + "path": [ + "test_results", + 0, + "subtests", + 1 + ], + "fields": { + "sub_Test_Number": "2", + "sub_Test_GUID": "060234F5-A84A-4DD7-AD5B-64996250F216", + "sub_Test_Description": "QA failing event", + "sub_test_result": "FAILED" + } + } + ] + }, + "bbsr_tpm.json": { + "destination": "Suite_Name: BBSR-TPM", + "assertions": [ + { + "path": [ + "suite_summary", + "total_passed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "total_failed" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1", + "sub_Test_Description": "Verify QA digest", + "sub_test_result": "PASS" + } + }, + { + "path": [ + "test_results", + 0, + "subtests", + 1 + ], + "fields": { + "sub_Test_Number": "2", + "sub_Test_Description": "Verify QA event", + "sub_test_result": "FAIL" + } + } + ] + }, + "scmi.json": { + "destination": "Suite_Name: SCMI", + "assertions": [ + { + "path": [ + "suite_summary", + "total_passed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "total_failed" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "testcases", + 0 + ], + "fields": { + "Test_case": "1", + "Test_case_description": "QA passing protocol", + "Test_result": "PASSED" + } + }, + { + "path": [ + "test_results", + 0, + "testcases", + 1 + ], + "fields": { + "Test_case": "2", + "Test_case_description": "QA failing protocol", + "Test_result": "FAILED" + } + } + ] + }, + "post_script.json": { + "destination": "Suite_Name: POST_SCRIPT", + "assertions": [ + { + "path": [ + "suite_summary", + "total_failed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "total_warnings" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1", + "sub_Test_Description": "ERROR QA required file is missing", + "sub_test_result": { + "PASSED": 0, + "FAILED": 1, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + }, + { + "path": [ + "test_results", + 0, + "subtests", + 1 + ], + "fields": { + "sub_Test_Number": "2", + "sub_Test_Description": "WARNING QA optional file is missing", + "sub_test_result": { + "PASSED": 0, + "FAILED": 0, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 1 + } + } + } + ] + }, + "dt_kselftest.json": { + "destination": "Suite_Name: Standalone", + "assertions": [ + { + "path": [ + "suite_summary", + "total_passed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "total_failed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "total_skipped" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1", + "sub_Test_Description": "node-a", + "sub_test_result": { + "PASSED": 1, + "FAILED": 0, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + }, + { + "path": [ + "test_results", + 0, + "subtests", + 1 + ], + "fields": { + "sub_Test_Number": "2", + "sub_Test_Description": "node-b", + "sub_test_result": { + "PASSED": 0, + "FAILED": 1, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + }, + { + "path": [ + "test_results", + 0, + "subtests", + 2 + ], + "fields": { + "sub_Test_Number": "3", + "sub_Test_Description": "node-c", + "sub_test_result": { + "PASSED": 0, + "FAILED": 0, + "SKIPPED": 1, + "ABORTED": 0, + "WARNINGS": 0 + } + } + } + ] + }, + "dt_validate.json": { + "destination": "Suite_Name: Standalone", + "assertions": [ + { + "path": [ + "suite_summary", + "total_failed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "total_warnings" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1", + "sub_Test_Description": "node-a", + "sub_test_result": { + "PASSED": 0, + "FAILED": 1, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + }, + { + "path": [ + "test_results", + 0, + "subtests", + 1 + ], + "fields": { + "sub_Test_Number": "2", + "sub_Test_Description": "node-b", + "sub_test_result": { + "PASSED": 0, + "FAILED": 0, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 1 + } + } + } + ] + }, + "ethtool_test.json": { + "destination": "Suite_Name: Standalone", + "assertions": [ + { + "path": [ + "suite_summary", + "total_passed" + ], + "value": 2 + }, + { + "path": [ + "suite_summary", + "total_failed" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1", + "sub_Test_Description": "Detected Interfaces: eth0", + "sub_test_result": { + "PASSED": 1, + "FAILED": 0, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + }, + { + "path": [ + "test_results", + 0, + "subtests", + 1 + ], + "fields": { + "sub_Test_Number": "2", + "sub_Test_Description": "Bring up interface eth0", + "sub_test_result": { + "PASSED": 1, + "FAILED": 0, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + }, + { + "path": [ + "test_results", + 0, + "subtests", + 2 + ], + "fields": { + "sub_Test_Number": "3", + "sub_Test_Description": "ethtool self-tests on eth0", + "sub_test_result": { + "PASSED": 0, + "FAILED": 1, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + } + ] + }, + "read_write_check_blk_devices.json": { + "destination": "Suite_Name: Standalone", + "assertions": [ + { + "path": [ + "suite_summary", + "total_passed" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1", + "sub_Test_Description": "Read check on Raw device /dev/qa", + "sub_test_result": { + "PASSED": 1, + "FAILED": 0, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + } + ] + }, + "capsule_update.json": { + "destination": "Suite_Name: Standalone", + "assertions": [ + { + "path": [ + "suite_summary", + "total_failed" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1", + "sub_Test_Description": "Testing ESRT FW version update", + "sub_test_result": { + "PASSED": 0, + "FAILED": 1, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + } + ] + }, + "psci.json": { + "destination": "Suite_Name: Standalone", + "assertions": [ + { + "path": [ + "suite_summary", + "total_passed" + ], + "value": 1 + }, + { + "path": [ + "test_results", + 0, + "subtests", + 0, + "sub_test_result", + "pass_reasons" + ], + "value": [ + "PSCI version 1.1 >= 1.0" + ] + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1", + "sub_Test_Description": "PSCI version checker(1.0 or above)", + "sub_test_result": { + "PASSED": 1, + "FAILED": 0, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + } + ] + }, + "smbios_check.json": { + "destination": "Suite_Name: Standalone", + "assertions": [ + { + "path": [ + "suite_summary", + "total_passed" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "00000000-0000-0000-0000-000000000001", + "sub_Test_Description": "QA SMBIOS table check", + "sub_test_result": { + "PASSED": 1, + "FAILED": 0, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + } + ] + }, + "network_boot.json": { + "destination": "Suite_Name: Standalone", + "assertions": [ + { + "path": [ + "suite_summary", + "total_passed" + ], + "value": 1 + }, + { + "path": [ + "suite_summary", + "total_failed" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1", + "sub_Test_Description": "Image URL", + "sub_test_result": { + "PASSED": 1, + "FAILED": 0, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + }, + { + "path": [ + "test_results", + 0, + "subtests", + 1 + ], + "fields": { + "sub_Test_Number": "2", + "sub_Test_Description": "EFI System Partition (ESP)", + "sub_test_result": { + "PASSED": 0, + "FAILED": 1, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + } + ] + }, + "runtime_dev_map.json": { + "destination": "Suite_Name: Standalone", + "assertions": [ + { + "path": [ + "suite_summary", + "total_failed" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1", + "sub_Test_Description": "Testing Runtime Device Mapping Conflict Test", + "sub_test_result": { + "PASSED": 0, + "FAILED": 1, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + } + ] + }, + "ethtool_test_linux-Fedora-40.json": { + "destination": "Suite_Name: OS Tests - ethtool_test_linux-Fedora-40", + "assertions": [ + { + "path": [ + "suite_summary", + "total_failed" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1", + "sub_Test_Description": "No Ethernet Interfaces Detected", + "sub_test_result": { + "PASSED": 0, + "FAILED": 1, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + } + ] + }, + "ethtool_test_linux-ubuntu-24.json": { + "destination": "Suite_Name: OS Tests - ethtool_test_linux-ubuntu-24", + "assertions": [ + { + "path": [ + "suite_summary", + "total_failed" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1", + "sub_Test_Description": "No Ethernet Interfaces Detected", + "sub_test_result": { + "PASSED": 0, + "FAILED": 1, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + } + ] + }, + "ethtool_test_linux-Tumbleweed.json": { + "destination": "Suite_Name: OS Tests - ethtool_test_linux-Tumbleweed", + "assertions": [ + { + "path": [ + "suite_summary", + "total_failed" + ], + "value": 1 + } + ], + "records": [ + { + "path": [ + "test_results", + 0, + "subtests", + 0 + ], + "fields": { + "sub_Test_Number": "1", + "sub_Test_Description": "No Ethernet Interfaces Detected", + "sub_test_result": { + "PASSED": 0, + "FAILED": 1, + "SKIPPED": 0, + "ABORTED": 0, + "WARNINGS": 0 + } + } + } + ] + } + } + }, + { + "name": "sr_pcie_pass", + "mode": "SR", + "suites": ["PCIE-OPTION-ROM-ARCH-AUDIT"], + "files": { + "results/uefi_dump/PcieOptionRomArchAudit.log": "PcieOptionRomArchAudit: report all live PCIe devices and classify option ROM contents\nScanned 3 EFI_PCI_IO handles and found 1 PCIe devices with Option ROM images:\nPCIe devices with ROM : 1\nNon-compliant devices : 0\nBBR (UEFI 6.3.3.1 UEFI Drivers) Result Summary: FAIL\n" + }, + "raw": { + "pcie_option_rom_arch_audit.json": { + "destination": "Suite_Name: Standalone", + "assertions": [ + {"path": ["suite_summary", "total_passed"], "value": 1}, + {"path": ["suite_summary", "total_failed"], "value": 0}, + {"path": ["suite_summary", "total_skipped"], "value": 0}, + {"path": ["test_results", 0, "Test_suite"], "value": "PCIeOptionRomArchAudit"}, + {"path": ["test_results", 0, "Test_case"], "value": "pcie_option_rom_arch_audit"}, + {"path": ["test_results", 0, "test_result"], "value": "PASSED"} + ], + "records": [{ + "path": ["test_results", 0, "subtests", 0], + "fields": { + "sub_Test_Number": "1", + "sub_Test_Description": "PCIe Option ROM UEFI driver architecture compliance", + "sub_test_result": {"PASSED": 1, "FAILED": 0, "SKIPPED": 0, "ABORTED": 0, "WARNINGS": 0, "FAILED_WITH_WAIVER": 0} + } + }] + } + } + }, + { + "name": "sr_pcie_fail", + "mode": "SR", + "suites": ["PCIE-OPTION-ROM-ARCH-AUDIT"], + "files": { + "results/uefi_dump/PcieOptionRomArchAudit.log": "PcieOptionRomArchAudit: report all live PCIe devices and classify option ROM contents\nScanned 3 EFI_PCI_IO handles and found 1 PCIe devices with Option ROM images:\nPCIe devices with ROM : 1\nNon-compliant devices : 1\nBBR (UEFI 6.3.3.1 UEFI Drivers) Result Summary: PASS\n" + }, + "raw": { + "pcie_option_rom_arch_audit.json": { + "destination": "Suite_Name: Standalone", + "assertions": [ + {"path": ["suite_summary", "total_passed"], "value": 0}, + {"path": ["suite_summary", "total_failed"], "value": 1}, + {"path": ["suite_summary", "total_skipped"], "value": 0}, + {"path": ["test_results", 0, "Test_suite"], "value": "PCIeOptionRomArchAudit"}, + {"path": ["test_results", 0, "Test_case"], "value": "pcie_option_rom_arch_audit"}, + {"path": ["test_results", 0, "test_result"], "value": "FAILED"} + ], + "records": [{ + "path": ["test_results", 0, "subtests", 0], + "fields": { + "sub_Test_Number": "1", + "sub_Test_Description": "PCIe Option ROM UEFI driver architecture compliance", + "sub_test_result": {"PASSED": 0, "FAILED": 1, "SKIPPED": 0, "ABORTED": 0, "WARNINGS": 0, "FAILED_WITH_WAIVER": 0} + } + }] + } + } + }, + { + "name": "sr_pcie_skip", + "mode": "SR", + "suites": ["PCIE-OPTION-ROM-ARCH-AUDIT"], + "files": { + "results/uefi_dump/PcieOptionRomArchAudit.log": "PcieOptionRomArchAudit: report all live PCIe devices and classify option ROM contents\nScanned 3 EFI_PCI_IO handles and found 0 PCIe devices with Option ROM images:\nPCIe devices with ROM : 0\nNon-compliant devices : 0\nBBR (UEFI 6.3.3.1 UEFI Drivers) Result Summary: PASS\n" + }, + "raw": { + "pcie_option_rom_arch_audit.json": { + "destination": "Suite_Name: Standalone", + "assertions": [ + {"path": ["suite_summary", "total_passed"], "value": 0}, + {"path": ["suite_summary", "total_failed"], "value": 0}, + {"path": ["suite_summary", "total_skipped"], "value": 1}, + {"path": ["test_results", 0, "Test_suite"], "value": "PCIeOptionRomArchAudit"}, + {"path": ["test_results", 0, "Test_case"], "value": "pcie_option_rom_arch_audit"}, + {"path": ["test_results", 0, "test_result"], "value": "SKIPPED"} + ], + "records": [{ + "path": ["test_results", 0, "subtests", 0], + "fields": { + "sub_Test_Number": "1", + "sub_Test_Description": "PCIe Option ROM UEFI driver architecture compliance", + "sub_test_result": {"PASSED": 0, "FAILED": 0, "SKIPPED": 1, "ABORTED": 0, "WARNINGS": 0, "FAILED_WITH_WAIVER": 0} + } + }] + } + } + }, + { + "name": "dt_memory_map_routes", + "mode": "DT", + "suites": ["RESERVED-MEMORY-MAP", "DTB-ALIGNMENT"], + "files": { + "results/linux_tools/reserved_memory_map_test.log": "Testing Devicetree Reserved Memory Map Compliance Test\nINFO: Reserved Memory Map Compliance Test: PASSED\nINFO: Checking Memory Reservation Block entries\nERROR: Memory Reservation Block entry (0x80000000-0x80001000) is not fully covered by Reserved segments in memmap.\nINFO: Memory Reservation Block Compliance Test: FAILED\nRESULTS: FAILED\n", + "results/linux_tools/dtb_alignment_test.log": "INFO: Starting DTB alignment test\nINFO: DTB address is 0xFCEAD000\nINFO: Required alignment is 8 bytes\nINFO: DTB address 0xFCEAD000 is 8-byte aligned\nRESULT: PASS\n" + }, + "raw": { + "reserved_memory_map.json": { + "destination": "Suite_Name: Standalone", + "assertions": [ + {"path": ["suite_summary", "total_passed"], "value": 1}, + {"path": ["suite_summary", "total_failed"], "value": 1}, + {"path": ["test_results", 0, "Test_suite"], "value": "Devicetree Reserved Memory Validation"}, + {"path": ["test_results", 0, "Test_case"], "value": "reserved_memory_map"} + ], + "records": [ + { + "path": ["test_results", 0, "subtests", 0], + "fields": { + "sub_Test_Number": "1", + "sub_Test_Description": "Reserved Memory Map Compliance Test", + "sub_test_result": {"PASSED": 1, "FAILED": 0, "SKIPPED": 0, "ABORTED": 0, "WARNINGS": 0} + } + }, + { + "path": ["test_results", 0, "subtests", 1], + "fields": { + "sub_Test_Number": "2", + "sub_Test_Description": "Memory Reservation Block Compliance Test", + "sub_test_result": {"PASSED": 0, "FAILED": 1, "SKIPPED": 0, "ABORTED": 0, "WARNINGS": 0} + } + } + ] + }, + "dtb_alignment.json": { + "destination": "Suite_Name: Standalone", + "assertions": [ + {"path": ["suite_summary", "total_passed"], "value": 1}, + {"path": ["suite_summary", "total_failed"], "value": 0}, + {"path": ["test_results", 0, "Test_suite"], "value": "Devicetree Blob Alignment Validation"}, + {"path": ["test_results", 0, "Test_case"], "value": "dtb_alignment"} + ], + "records": [ + { + "path": ["test_results", 0, "subtests", 0], + "fields": { + "sub_Test_Number": "1", + "sub_Test_Description": "Devicetree Blob Alignment Validation", + "sub_test_result": {"PASSED": 1, "FAILED": 0, "SKIPPED": 0, "ABORTED": 0, "WARNINGS": 0} + } + } + ] + } + } + } + ] +} diff --git a/common/log_parser/doctor_checks/merge.py b/common/log_parser/doctor_checks/merge.py new file mode 100644 index 00000000..30e75a2b --- /dev/null +++ b/common/log_parser/doctor_checks/merge.py @@ -0,0 +1,638 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026, Arm Limited or its affiliates. All rights reserved. +# SPDX-License-Identifier : Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Check that merged JSON and HTML show the expected compliance decisions. + +This optional Doctor group builds small sample suite results, runs the checkout's +real merger and HTML helpers, and records expected versus actual results. Expected +answers are written here separately so a parser mistake cannot define its own +passing answer. Samples and findings stay in Doctor's evidence folder; this file +does not repair the parser or change real logs. Raw-log and schema checks live in +other Doctor groups. +""" + +import contextlib +import copy +import html +from html.parser import HTMLParser +import importlib +import itertools +import json +from pathlib import Path +import re +import sys + +from .core import load_json + + +# These reviewed expectations must not be copied from the registry at runtime: +# otherwise an incorrect registry entry would also change the expected answer. +# Suite inventory: CI b6a8a78d1fef3d6e41d2d2aec94006e0a9263c8c. +# DT memory-map requirements: upstream decc0aaa9902da57b18d5fd3ec40efa511fb5273. +# PCIe Option ROM: SR-only Recommended, reviewed in PJ03164-4076/719dab25. +# The scenarios below also check SR rules that become Mandatory when present. + +EXPECTED_REQUIREMENTS = { + "BSA": {"DT": "R", "SR": "M"}, + "SBSA": {"SR": "R"}, + "FWTS": {"DT": "M", "SR": "M"}, + "SCT": {"DT": "M", "SR": "M"}, + "BBSR-FWTS": {"DT": "EM", "SR": "EM"}, + "BBSR-SCT": {"DT": "EM", "SR": "EM"}, + "BBSR-TPM": {"DT": "EM", "SR": "EM"}, + "PFDI": {"DT": "CM"}, + "SCMI": {"DT": "EM"}, + "SBMR-IB": {"SR": "R"}, + "SBMR-OOB": {"SR": "R"}, + "POST-SCRIPT": {"DT": "R"}, + "OS-TESTS": {"DT": "M", "SR": "M"}, + "DT-KSELFTEST": {"DT": "R"}, + "DT-VALIDATE": {"DT": "M"}, + "ETHTOOL-TEST": {"DT": "M"}, + "READ-WRITE-CHECK-BLK-DEVICES": {"DT": "M"}, + "CAPSULE-UPDATE": {"DT": "M"}, + "PSCI": {"DT": "R"}, + "SMBIOS": {"DT": "R"}, + "NETWORK-BOOT": {"DT": "R"}, + "RUNTIME-DEV-MAP": {"DT": "R"}, + "RESERVED-MEMORY-MAP": {"DT": "M"}, + "DTB-ALIGNMENT": {"DT": "M"}, + "PCIE-OPTION-ROM-ARCH-AUDIT": {"SR": "R"}, +} + + +def expected_leaves(leaves): + """Use registered file names, but use our reviewed requirement expectations.""" + result = [] + for suite in leaves: + if suite["canonical"] not in EXPECTED_REQUIREMENTS: + continue # Explicitly reported by POLICY_INVENTORY, never assumed covered. + expected = copy.deepcopy(suite) + expected["requirements"] = dict(EXPECTED_REQUIREMENTS[suite["canonical"]]) + expected["modes"] = list(expected["requirements"]) + result.append(expected) + return result + + +def policy_differences(registry): + """Detect metadata drift and new suites that need independently reviewed tests.""" + leaves = {suite["canonical"]: suite for suite in registry["suites"] + if suite.get("json_output")} + issues = [] + for name in sorted(set(leaves) | set(EXPECTED_REQUIREMENTS)): + expected = EXPECTED_REQUIREMENTS.get(name) + actual = leaves.get(name) + if expected is None: + issues.append((name, "Reviewed requirement contract and fixture", + "New suite has no independent policy expectation")) + elif actual is None: + issues.append((name, expected, "Expected suite missing from registry")) + elif actual.get("requirements") != expected or set(actual.get("modes", [])) != set(expected): + issues.append((name, {"requirements": expected, "modes": sorted(expected)}, + {"requirements": actual.get("requirements"), "modes": actual.get("modes")})) + return issues + + +def run_policy(ctx): + """Report new suites or changed requirements that need a reviewed expectation.""" + source = ctx.parser_dir / "suite_registry.json" + registry = load_json(source) + issues = policy_differences(registry) + if issues: + for name, expected, actual in issues: + ctx.add("POLICY_INVENTORY", "FAIL", + "Registry and independent requirement contract disagree; review before updating expectations", + expected, actual, suite=name, evidence=(source, __file__)) + else: + ctx.add("POLICY_INVENTORY", "PASS", "All suites have independently reviewed base requirements", + "Exact suite/mode/requirement mapping", "%d suites, %d suite/mode routes match" % + (len(EXPECTED_REQUIREMENTS), sum(map(len, EXPECTED_REQUIREMENTS.values()))), + evidence=(source, __file__)) + + +# Sample combinations for the real merger and the visible HTML compliance labels. + +REQUIREMENTS = {"M": "Mandatory", "R": "Recommended", + "CM": "Conditional-Mandatory", "EM": "Extension"} +UNAVAILABLE = {"missing", "empty", "header"} +STATES = ("pass", "fail", "waived", "mixed", "missing", "empty", "header") +HTML_HELPERS = ("_summary_cards", "inject_detail_compliance") + + +def usable_html_module(ctx): + """Check HTML support without stopping the separate merged-JSON checks.""" + try: + ui = importlib.import_module("generate_acs_summary") + if Path(ui.__file__).resolve().parent != ctx.parser_dir.resolve(): + raise ValueError("Refusing cached UI module from another checkout: " + str(ui.__file__)) + missing = [name for name in HTML_HELPERS if not callable(getattr(ui, name, None))] + if not missing: + return ui + reason = "This checkout does not provide " + ", ".join(missing) + except Exception as error: + reason = type(error).__name__ + ": " + str(error) + ctx.add("HTML_COMPLIANCE_CAPABILITY", "BLOCKED", + "Summary/detail compliance HTML coverage is unavailable; merged JSON checks still run.", + "Importable current-checkout HTML compliance helpers", reason, + evidence=(ctx.parser_dir / "generate_acs_summary.py",)) + return None + + +def identity(value): + return re.sub(r"[^A-Z0-9]", "", str(value).upper()) + + +def status(value, overall=False): + """Interpret a public label; do not call the production compliance helpers.""" + value = str(value).strip().lower() + if "not run" in value and not overall: + return "not_run" + for prefix, normalized in (("not compliant", "not_compliant"), + ("compliant with waiver", "waived"), + ("compliant", "compliant"), ("not run", "not_run")): + if value.startswith(prefix): + return normalized + return "unknown" + + +def display_name(key, mode): + if key in ("FWTS", "SCT"): + return ("EBBR-" if mode == "DT" else "SBBR-") + key + return key + + +def oracle(leaves, mode, states, selected=None, override=None, executed=None): + """Calculate the agreed answer without using the parser's compliance code. + + Recommended failures or missing results never block overall SRS compliance. + Required SR OS entries alone affect OS compliance. Executed SBSA and either + executed SBMR interface promote the relevant SR requirements to Mandatory. + Conditional-Mandatory is required when run; extensions have separate results. + When supplied, executed contains independently proven current-run execution; + missing result JSON must not erase that proof. Without it, existing synthetic + scenarios use their known result states. The not_run row describes unavailable + report results, not a claim that a proven execution never happened. + This is an explicit repository contract, not an external certification claim. + """ + applicable = {suite["canonical"]: suite for suite in leaves + if mode in suite["modes"] and mode in suite["requirements"] + and (selected is None or suite["canonical"] in selected)} + if executed is None: + present = {name for name, state in states.items() if state not in UNAVAILABLE} + else: + # Only proof for a suite in this mode can activate its requirements. + # A selected SBMR interface can still depend on its executed peer. + mode_suites = {suite["canonical"] for suite in leaves + if mode in suite["modes"] and mode in suite["requirements"]} + present = set(executed).intersection(mode_suites) + rows = {} + blockers, waivers = False, False + for name, suite in applicable.items(): + requirement = (override or {}).get(name, suite["requirements"][mode]) + if mode == "SR" and ((name == "SBSA" and name in present) or + (name.startswith("SBMR-") and + present.intersection({"SBMR-IB", "SBMR-OOB"}))): + requirement = "M" + state = states.get(name, "missing") + result = "compliant" + if state in UNAVAILABLE: + result = "not_run" + blockers |= requirement == "M" or (requirement == "CM" and name in present) + elif state in ("fail", "mixed", "recommended_fail"): + if not (mode == "SR" and name == "OS-TESTS" and state == "recommended_fail"): + result = "not_compliant" + blockers |= requirement in ("M", "CM") + elif state == "waived": + result = "waived" + waivers |= requirement in ("M", "CM") + elif state != "pass": + raise ValueError("No agreed compliance oracle for state " + state) + rows[name] = {"requirement": REQUIREMENTS[requirement], "status": result} + return rows, "not_compliant" if blockers else "waived" if waivers else "compliant" + + +def payload(name, state): + """Make one small suite input in the nesting that its real parser uses.""" + if state == "missing": + return None + if state == "empty": + return {"suite_summary": {}, "test_results": []} + if state == "header": + return {"test_results": [{"Test_suite": name, "subtests": []}]} + outcomes = {"pass": ["PASSED"], "fail": ["FAILED"], + "waived": ["FAILED (WITH WAIVER)"], + "mixed": ["FAILED (WITH WAIVER)", "FAILED"], + "recommended_fail": ["FAILED"]}[state] + counts = dict.fromkeys(("total_passed", "total_failed", "total_failed_with_waiver", + "total_aborted", "total_skipped", "total_warnings", + "total_ignored"), 0) + keys = {"PASSED": "total_passed", "FAILED": "total_failed", + "FAILED (WITH WAIVER)": "total_failed_with_waiver"} + for result in outcomes: + counts[keys[result]] += 1 + if name == "PCIE-OPTION-ROM-ARCH-AUDIT": + # PCIe reports one parent decision per audit. Its merger reads that + # decision, while its HTML uses the Standalone-style child counters. + entries = [] + for result in outcomes: + record_counts = dict.fromkeys(counts, 0) + record_counts[keys[result]] = 1 + entries.append({ + "Test_suite": "PCIeOptionRomArchAudit", + "Test_case": "pcie_option_rom_arch_audit", + "SRS scope": "Recommended", "Waivable": "yes", + "test_result": result, "test_suite_summary": record_counts, + "subtests": [{"sub_Test_Number": "1", + "sub_Test_Description": "PCIe Option ROM UEFI driver architecture compliance", + "sub_test_result": { + "PASSED": int(result == "PASSED"), + "FAILED": int(result == "FAILED"), + "FAILED_WITH_WAIVER": int(result == "FAILED (WITH WAIVER)"), + "ABORTED": 0, "SKIPPED": 0, "WARNINGS": 0}}], + }) + return {"suite_summary": counts, "test_results": entries} + entry = {"Test_suite": "TIMER" if name in ("BSA", "SBSA", "PFDI") else name, + "Test_case": name, "Waivable": "yes", + "SRS scope": "Recommended" if state == "recommended_fail" else "Required", + "test_suite_summary": dict(counts)} + children = [{"sub_Test_Number": str(index), "sub_Test_Description": "Doctor fixture", + "sub_test_result": result, "reason": "Doctor approved waiver" if + "WAIVER" in result else ""} for index, result in enumerate(outcomes, 1)] + if name in ("BSA", "SBSA", "PFDI"): + # A parent and its child describe one outcome, not two separate tests. + entry["testcases"] = [{"Test_case": str(index), "Test_case_description": "Doctor fixture", + "Test_result": result, "subtests": [children[index - 1]]} + for index, result in enumerate(outcomes, 1)] + elif name.startswith("SBMR-"): + entry["Test_cases"] = [{"Test_case": "Doctor management case", "subtests": children, + "test_case_summary": dict(counts)}] + else: + entry["subtests"] = children + return {"suite_summary": counts, "test_results": [entry]} + + +def merged_records(merged, leaves, mode): + """Read each suite's requirement and compliance from the merged report.""" + summary = merged["Suite_Name: acs_info"]["ACS Results Summary"] + if not isinstance(summary, dict) or "Overall Compliance Result" not in summary: + raise ValueError("Merged report has no ACS compliance summary") + names = {identity(display_name(suite["requirement_key"], mode)): suite["canonical"] + for suite in leaves} + rows = {} + for key, value in summary.items(): + match = re.fullmatch(r"Suite_Name:\s*(.*?)\s*:\s*(.*?)_compliance", key) + if match and identity(match.group(2)) in names: + name = names[identity(match.group(2))] + if name in rows: + raise ValueError("Duplicate compliance label for " + name) + rows[name] = {"requirement": match.group(1).strip(), "status": status(value)} + return rows, summary + + +def differences(expected, actual): + """List missing, unexpected or changed values with both sides for the report.""" + return {key: {"expected": expected.get(key, "absent"), "actual": actual.get(key, "absent")} + for key in sorted(set(expected) | set(actual)) if expected.get(key) != actual.get(key)} + + +class ComplianceHTML(HTMLParser): + """Read visible compliance table cells and badges without a browser.""" + + def __init__(self): + super().__init__(convert_charrefs=True) + self.rows, self.badges, self.row, self.cell = [], [], None, None + self.badge_depth, self.badge_text = 0, "" + + def handle_starttag(self, tag, attrs): + attrs = dict(attrs) + if tag == "tr" and "data-acs-compliance-tone" in attrs: + self.row = [] + if self.row is not None and tag in ("th", "td"): + self.cell = "" + if self.badge_depth: + self.badge_depth += 1 + elif "acs-suite-compliance" in attrs.get("class", "").split(): + self.badge_depth, self.badge_text = 1, "" + + def handle_data(self, data): + if self.cell is not None: + self.cell += data + if self.badge_depth: + self.badge_text += data + + def handle_endtag(self, tag): + if self.cell is not None and tag in ("th", "td"): + self.row.append(" ".join(self.cell.split())) + self.cell = None + if self.row is not None and tag == "tr": + self.rows.append(tuple(self.row)) + self.row = None + if self.badge_depth: + self.badge_depth -= 1 + if not self.badge_depth: + self.badges.append(" ".join(self.badge_text.split())) + + +def aggregate(rows): + """Work out the expected badge for a card containing one or several suites.""" + mandatory = [row for row in rows if row["requirement"] in + ("Mandatory", "Conditional-Mandatory")] + relevant = mandatory or rows + requirements = {row["requirement"] for row in relevant} + requirement = "Mandatory" if "Mandatory" in requirements else " / ".join(sorted(requirements)) + if all(row["status"] == "not_run" for row in rows): + result = "Not Run" + elif any(row["status"] == "not_compliant" or (row["status"] == "not_run" and + row["requirement"] == "Mandatory") for row in relevant): + result = "Not Compliant" + elif any(row["status"] == "waived" for row in relevant): + result = "Compliant with waivers" + else: + result = "Compliant" + return requirement + " (" + result + ")" + + +def check_html(ui, directory, merged_path, leaves, mode, states, expected, standalone): + """Compare generated summary badges and detail rows with our expected labels.""" + output = directory / "html" + output.mkdir() + by_name = {suite["canonical"]: suite for suite in leaves} + collected = {name for name in expected if states.get(name, "missing") not in UNAVAILABLE} + groups = {} + for name in expected: + # SBMR interfaces and Standalone tests share a card but retain their rows. + group = "Standalone" if name in standalone else "SBMR" if name.startswith("SBMR-") else name + groups.setdefault(group, []).append(name) + sources, desired_badges, desired_rows = [], {}, {} + for group, names in groups.items(): + detail = ("sbmr_detailed.html" if group == "SBMR" else + "standalone_tests_detailed.html" if group == "Standalone" else by_name[names[0]]["detailed_html"]) + present = any(name in collected for name in names) + if present: + (output / detail).write_text("

Doctor semantic fixture

", encoding="utf-8") + section = {"Standalone": "standalone_summary", "OS-TESTS": "OS_tests_summary"}.get(group, group.lower() + "_summary") + content = "

" + html.escape(group) + " Test Summary

" if present else "" + candidates = tuple(display_name(by_name[name]["requirement_key"], mode) for name in names) + sources.append((section, group, content, detail, candidates)) + desired_badges[group] = aggregate([expected[name] for name in names]) + for name in names: + row = expected[name] + # Missing mandatory Standalone tests and missing SBMR interfaces must + # remain visible inside an existing combined detail page. + visible = name in collected or (present and (group == "SBMR" or + (group == "Standalone" and row["requirement"] == "Mandatory"))) + if not visible: + continue + component = display_name(name, mode) if name in ("FWTS", "SCT") else name + if name == "PCIE-OPTION-ROM-ARCH-AUDIT": + component = "PCIE_OPTION_ROM_ARCH_AUDIT" + label = {"compliant": "Compliant", "not_compliant": "Not Compliant", + "waived": "Compliant with waivers", "not_run": "Not Run"}[row["status"]] + if row["status"] == "not_run" and row["requirement"] == "Mandatory": + label = "Not Compliant (Not Run)" + desired_rows.setdefault(detail, []).append((component, row["requirement"], label)) + merged = json.loads(merged_path.read_text(encoding="utf-8")) + cards = ui._summary_cards(merged, sources, str(output)) + actual_badges = {} + for card in cards: + parser = ComplianceHTML() + parser.feed(card["content"]) + actual_badges[card["label"]] = parser.badges[0] if len(parser.badges) == 1 else parser.badges + (output / "summary_badges.html").write_text("

Synthetic semantic fixture, not a hardware report.

" + + "".join(card["content"] for card in cards) + "", encoding="utf-8") + ui.inject_detail_compliance(str(merged_path), str(output)) + actual_rows = {} + for page in output.glob("*detailed.html"): + parser = ComplianceHTML() + parser.feed(page.read_text(encoding="utf-8")) + actual_rows[page.name] = sorted(parser.rows) + desired_rows = {name: sorted(rows) for name, rows in desired_rows.items()} + return {"badges": differences(desired_badges, actual_badges), + "tables": differences(desired_rows, actual_rows)} + + +def scenarios(leaves, mode): + """Vary each suite and requirement, then check combined SBMR and BBSR cases.""" + suites = [suite["canonical"] for suite in leaves if mode in suite["requirements"] and mode in suite["modes"]] + baseline = dict.fromkeys(suites, "pass") + for name in suites: + for selected in (None, [name]): + for state in STATES: + yield ("selected" if selected else "full") + "_" + name + "_" + state, \ + {name: state} if selected else {**baseline, name: state}, selected, None + for requirement in REQUIREMENTS: + for state in STATES: + yield "requirement_" + requirement + "_" + state, {**baseline, "FWTS": state}, None, {"FWTS": requirement} + if mode == "SR": + for ib, oob in itertools.product(("pass", "fail", "waived", "missing", "empty"), repeat=2): + yield "SBMR_IB_" + ib + "_OOB_" + oob, {**baseline, "SBMR-IB": ib, "SBMR-OOB": oob}, None, None + for bsa, sbsa in (("pass", "fail"), ("fail", "pass")): + yield "BSA_" + bsa + "_SBSA_" + sbsa, {**baseline, "BSA": bsa, "SBSA": sbsa}, None, None + for name in suites: + yield "recommended_group_" + name, {**baseline, name: "recommended_fail"}, None, None + bbsr = ("BBSR-FWTS", "BBSR-SCT", "BBSR-TPM") + if set(bbsr).issubset(suites): + for values in itertools.product(("pass", "fail", "waived", "missing"), repeat=3): + yield "BBSR_" + "_".join(values), {**baseline, **dict(zip(bbsr, values))}, None, None + + +def run_case(ctx, registry, merger, ui, leaves, standalone, mode, case): + """Run one sample and save its inputs, decisions and HTML comparisons.""" + name, states, selected, override = case + directory = ctx.case_dir("merge/" + mode + "_" + name) + write = lambda path, data: path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") + manifest = {"synthetic": True, "scope": "merger and semantic HTML, not raw-log/schema acceptance", + "mode": mode, "states": states, "selected": selected, "requirement_overrides": override} + write(directory / "scenario.json", manifest) + write(directory / "acs_info.json", {"ACS Results Summary": {"Date": "Doctor synthetic fixture", "Band": + "SystemReady Devicetree band" if mode == "DT" else "SystemReady band"}}) + paths, original = [str(directory / "acs_info.json")], {} + for suite in leaves: + canonical = suite["canonical"] + if canonical not in states: + continue + data = payload(canonical, states[canonical]) + if data is not None: + path = directory / suite["json_output"] + write(path, data) + paths.append(str(path)) + original[path] = data + # The merger stores run settings in module globals. Reset them for every + # sample so a previous sample cannot decide this sample's result. + merger.set_run_mode(mode) + merger._REQUIREMENT_MAP = {} + merger._SELECTED_SUITE_FILTER = merger.build_selected_suite_filter(selected or []) + merger.DT_SRS_SCOPE_TABLE = registry.requirement_table("DT") + merger.SR_SRS_SCOPE_TABLE = registry.requirement_table("SR") + table = merger.DT_SRS_SCOPE_TABLE if mode == "DT" else merger.SR_SRS_SCOPE_TABLE + table[:] = [(key, (override or {}).get(key, requirement)) for key, requirement in table] + merged_path = directory / "merged_results.json" + with (directory / "merge.log").open("w", encoding="utf-8") as stream, contextlib.redirect_stdout(stream): + merger.merge_json_files(paths, str(merged_path)) + merged = json.loads(merged_path.read_text(encoding="utf-8")) + expected, overall = oracle(expected_leaves(leaves), mode, states, selected, override) + actual, summary = merged_records(merged, leaves, mode) + changed = differences(expected, actual) + observation = {"expected_suites": expected, "actual_suites": actual, "expected_overall": overall, + "actual_overall": summary["Overall Compliance Result"], "suite_differences": changed, + "html_check": "not available" if ui is None else "pending"} + write(directory / "observed.json", observation) + focus = ", ".join(name for name, state in states.items() if state != "pass") or "all suites" + evidence = (directory / "scenario.json", directory / "observed.json", merged_path, directory / "html") + empty = any(state in ("empty", "header") for state in states.values()) + changed_expected = {suite: row["expected"] for suite, row in changed.items()} + changed_actual = {suite: row["actual"] for suite, row in changed.items()} + issue = "Empty/header-only input was marked as completed" if changed and empty else "Suite requirements and statuses agree with their evidence" + if changed and not empty: + issue = "Suite requirement or compliance differs from its own result" + ctx.add("MERGE_INCOMPLETE_NOT_GREEN" if empty else "MERGE_SUITE_STATUS", + "FAIL" if changed else "PASS", name + ": " + issue, + changed_expected or "All applicable suite decisions match", changed_actual or "All match", mode, focus, evidence) + actual_overall = status(summary["Overall Compliance Result"], overall=True) + ctx.add("MERGE_OVERALL_POLICY", "PASS" if overall == actual_overall else "FAIL", + name + (": Recommended result incorrectly blocks overall SRS" if overall == "compliant" and actual_overall == "not_compliant" else + ": overall SRS follows Mandatory results; Recommended and Extension are non-blocking"), + overall, summary["Overall Compliance Result"], mode, focus, evidence) + preserved = all(json.loads(path.read_text(encoding="utf-8")) == data for path, data in original.items()) + ctx.add("MERGE_INPUT_PRESERVED", "PASS" if preserved else "FAIL", name + ": merger must not alter input results", + "Input suite JSON values unchanged", "Unchanged" if preserved else "Input suite JSON changed", mode, focus, evidence) + if selected is None and all(name in states for name in ("BBSR-FWTS", "BBSR-SCT", "BBSR-TPM")): + # BBSR is an extension with its own combined result, separate from SRS. + values = [states[name] for name in ("BBSR-FWTS", "BBSR-SCT", "BBSR-TPM")] + wanted = "not_run" if all(value in UNAVAILABLE for value in values) else "not_compliant" if any( + value in UNAVAILABLE or value in ("fail", "mixed", "recommended_fail") for value in values) else "waived" if "waived" in values else "compliant" + got = summary.get("BBSR compliance results", "MISSING") + ctx.add("MERGE_EXTENSION_AGGREGATION", "PASS" if status(got, True) == wanted else "FAIL", + name + ": BBSR aggregates its three members separately from SRS", wanted, got, mode, "BBSR", evidence) + # Keep JSON assertions and their evidence even when the optional HTML stage + # is absent, raises, or renders an incorrect compliance label. + if ui is not None: + try: + html_changes = check_html(ui, directory, merged_path, leaves, mode, states, expected, standalone) + observation.update(html_check="completed", html_differences=html_changes) + ctx.add("HTML_COMPLIANCE_MATCH", "FAIL" if any(html_changes.values()) else "PASS", + name + ": summary badges and detail tables must agree with the independent compliance expectation", + "Exactly one correct badge/row for each applicable card/test", + html_changes if any(html_changes.values()) else "All labels match", mode, focus, evidence) + except Exception as error: + observation.update(html_check="failed", html_error=type(error).__name__ + ": " + str(error)) + ctx.add("HTML_COMPLIANCE_EXECUTION", "FAIL", + name + ": available HTML compliance generation failed; JSON checks were retained", + "Inspectable summary badges and detail compliance tables", observation["html_error"], mode, focus, evidence) + write(directory / "observed.json", observation) + + +def edge_probes(ctx, merger, mode): + """Check nested failure counts and whether invalid input is safely rejected.""" + parent = {"test_result": "FAILED", "subtests": []} + probes = ( + ("SCT parent-only failures", {"test_results": [parent, dict(parent)]}, (2, 0)), + ("SCT failure with outcome-less child header", {"test_results": [ + {"test_result": "FAILED", "subtests": [{"sub_Test_GUID": "unfinished"}]}]}, (1, 0)), + ("Numeric failure and waiver counters", {"test_results": [{"subtests": [ + {"sub_test_result": {"FAILED": 2, "FAILED_WITH_WAIVER": 3}}]}]}, (2, 3)), + ("Waived BSA parent remains authoritative", {"test_results": [{"testcases": [ + {"Test_result": "FAILED (WITH WAIVER)", "subtests": [{"sub_test_result": "FAILED"}]}]}]}, (0, 1)), + ("Failed BSA parent with waived child remains failed", {"test_results": [{"testcases": [ + {"Test_result": "FAILED", "subtests": [{"sub_test_result": "FAILED (WITH WAIVER)"}]}]}]}, (1, 0)), + ) + for index, (issue, data, wanted) in enumerate(probes): + directory = ctx.case_dir("merge/" + mode + "_counter_" + str(index)) + observed = merger.count_fails_in_json(data) + record = {"input": data, "expected_failed_waived": wanted, "actual_failed_waived": observed} + (directory / "observed.json").write_text(json.dumps(record, indent=2), encoding="utf-8") + ctx.add("MERGE_FAILURE_COUNT", "PASS" if tuple(observed) == wanted else "FAIL", issue, + "Failed/waived=" + str(wanted), "Failed/waived=" + str(observed), mode, + "SCT/BBSR-SCT" if issue.startswith("SCT") else "counter contract", (directory / "observed.json",)) + corrupt = {"test_results": "not a result list"} + unknown = payload("SBMR-IB", "pass") + unknown["test_results"][0]["Test_cases"][0]["subtests"][0]["sub_test_result"] = "UNKNOWN" + unknown["suite_summary"]["total_passed"] = 0 + cases = [("BSA", "bsa.json", "invalid result shape", corrupt)] + cases.append(("BSA", "bsa.json", "unknown result counter", {"test_results": [ + {"subtests": [{"sub_test_result": {"PASSED": 1, "UNKNOWN": 1}}]}]})) + if mode == "SR": + cases.append(("SBMR-IB", "sbmr_ib.json", "UNKNOWN outcome", unknown)) + for suite, filename, issue, data in cases: + directory = ctx.case_dir("merge/" + mode + "_invalid_" + suite + "_" + issue.replace(" ", "-")) + source, destination = directory / filename, directory / "merged_results.json" + source.write_text(json.dumps(data, indent=2), encoding="utf-8") + process = ctx.run([ctx.python, "-B", str(ctx.parser_dir / "merge_jsons.py"), "--mode", mode, + "--selected-suites", suite, str(destination), str(source)], directory) + if process.returncode: + controlled = "Traceback (most recent call last)" not in process.stdout + result, actual = ("PASS" if controlled else "FAIL"), "Rejected input; exit " + str(process.returncode) + if not controlled: + actual += " with an uncaught traceback instead of a clear diagnostic" + elif not destination.is_file(): + result, actual = "FAIL", "Exit 0 without a merged result or rejection diagnostic" + else: + summary = json.loads(destination.read_text(encoding="utf-8"))["Suite_Name: acs_info"]["ACS Results Summary"] + value = next((value for key, value in summary.items() if key.endswith(" : " + suite + "_compliance")), "MISSING") + result = "FAIL" if status(value) in ("compliant", "waived") or value == "MISSING" else "PASS" + actual = value + ctx.add("MERGE_INVALID_INPUT_SAFETY", result, suite + ": " + issue + " must not produce a green result", + "Clear rejection or a non-green suite status", actual, mode, suite, (source, directory / "command.log", destination)) + + +def run_merge(ctx): + """Run all reviewed suite/mode cases, not just suites with modified files.""" + original_path = list(sys.path) + sys.path.insert(0, str(ctx.parser_dir)) + merger = None + saved = {} + try: + registry = importlib.import_module("suite_registry") + merger = importlib.import_module("merge_jsons") + for module in (registry, merger): + if Path(module.__file__).resolve().parent != ctx.parser_dir.resolve(): + raise ValueError("Refusing cached module from another checkout: " + str(module.__file__)) + leaves = [suite for suite in registry.load_registry() if suite.get("json_output") and suite.get("requirements")] + # PCIe shares the Standalone report in SR but is deliberately absent + # from the DT-only STANDALONE suite-selection alias. + standalone = {suite["canonical"] for suite in leaves + if suite.get("detailed_html") == "standalone_tests_detailed.html"} + if not leaves: + raise ValueError("Registry contains no testable leaf suites") + ui = usable_html_module(ctx) + for key in ("DT_OR_SR_MODE", "DT_SRS_SCOPE_TABLE", "SR_SRS_SCOPE_TABLE", "_REQUIREMENT_MAP", + "_SELECTED_SUITE_FILTER", "test_category_data", "test_cat_dict"): + saved[key] = copy.deepcopy(getattr(merger, key)) + count, blocked = 0, 0 + for mode in ctx.modes: + for case in scenarios(expected_leaves(leaves), mode): + count += 1 + try: + run_case(ctx, registry, merger, ui, leaves, standalone, mode, case) + except Exception as error: # One broken case must not hide later cases. + blocked += 1 + ctx.add("MERGE_CASE_EXECUTION", "BLOCKED", case[0] + ": cannot finish merged JSON check", + "Merger produces inspectable JSON", type(error).__name__ + ": " + str(error), mode, + evidence=(ctx.case_dir("merge/" + mode + "_" + case[0]),)) + edge_probes(ctx, merger, mode) + ctx.add("MERGE_MATRIX_COVERAGE", "PASS" if count and not blocked else "BLOCKED", "Explicit registry-wide merged JSON matrix executed", + "Nonzero full/selected leaf, requirement, waiver, SBMR and extension probes", str(count - blocked) + " JSON scenarios completed; " + str(blocked) + " blocked; HTML coverage is reported separately") + ctx.add("MERGE_UNAGREED_STATUS_POLICY", "WARN", "All-skipped, warning-only and aborted-only compliance needs an agreed rule", + "Owner-approved expected compliance for these states", "Not claimed covered by the compliance oracle") + except Exception as error: + ctx.add("MERGE_PREREQUISITE", "BLOCKED", "Merger health probes could not start", + "Importable merger and nonempty registry", type(error).__name__ + ": " + str(error)) + finally: + # Leave imported modules as we found them for any later Doctor groups. + if merger is not None: + for key, value in saved.items(): + setattr(merger, key, value) + sys.path[:] = original_path diff --git a/common/log_parser/doctor_checks/probes.py b/common/log_parser/doctor_checks/probes.py new file mode 100644 index 00000000..cf0cc238 --- /dev/null +++ b/common/log_parser/doctor_checks/probes.py @@ -0,0 +1,1426 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026, Arm Limited or its affiliates. All rights reserved. +# SPDX-License-Identifier : Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Check the parser with small known logs, broken logs, waivers and reruns. + +These optional Doctor checks run the real parser commands and compare the raw +JSON, merged compliance and HTML with expected answers written separately. All +sample logs and generated reports stay in Doctor's evidence folder. Real user +logs and parser source files are never changed. Findings include the commands +and output files needed to reproduce a problem. +""" + +import ast +from collections import Counter +from copy import copy +from concurrent.futures import ThreadPoolExecutor +import fnmatch +from html.parser import HTMLParser +import json +from pathlib import Path +import re +import shutil +from xml.etree import ElementTree + +from .core import load_json + + +# The native group uses known complete logs to check each standalone parser route. +# Fixtures originate in CI b6a8a78d1fef3d6e41d2d2aec94006e0a9263c8c. +# It checks raw JSON before merging, so a broken merger cannot hide good parsing. + +DATA_FILE = Path(__file__).with_name("data") / "native_cases.json" +RESULT_FIELDS = {"Test_result", "sub_test_result"} +IDENTITY_FIELDS = {"Test_case", "sub_Test_Number", "sub_Test_GUID"} +DESCRIPTION_FIELDS = {"Test_case_description", "sub_Test_Description"} +KNOWN_STATUSES = {"PASS", "PASSED", "FAIL", "FAILED", "SKIP", "SKIPPED", + "ABORT", "ABORTED", "WARNING", "WARNINGS", "WAIVED", + "FAILED_WITH_WAIVER", "PASSED (PARTIAL)", "PASSED_PARTIAL", + "NOT IMPLEMENTED", "NOT_IMPLEMENTED", "PAL NOT SUPPORTED", + "PAL_NOT_SUPPORTED", "IGNORED"} + + +def result_paths(value, path=()): + """Find parent and child results; matching totals alone can hide lost tests.""" + if isinstance(value, dict): + if RESULT_FIELDS.intersection(value): + yield path + for key, child in value.items(): + yield from result_paths(child, (*path, key)) + elif isinstance(value, list): + for index, child in enumerate(value): + yield from result_paths(child, (*path, index)) + + +def _path(value): + return isinstance(value, list) and bool(value) and all( + isinstance(part, str) or type(part) is int and part >= 0 for part in value) + + +def _relative(value): + return isinstance(value, str) and value and not Path(value).is_absolute() and ( + ".." not in Path(value).parts) and bool(Path(value).parts) and "\\" not in value + + +def _get(data, path): + for part in path: + data = data[part] + return data + + +def _exact(actual, expected): + """Match values and types, so True cannot count as the expected number 1.""" + if type(actual) is not type(expected): + return False + if isinstance(expected, dict): + return actual.keys() == expected.keys() and all( + _exact(actual[key], value) for key, value in expected.items()) + if isinstance(expected, list): + return len(actual) == len(expected) and all( + _exact(left, right) for left, right in zip(actual, expected)) + return actual == expected + + +def contract_issues(data): + """Check that sample logs have clear expected results and safe file paths.""" + issues = [] + if not isinstance(data, dict) or data.get("format_version") != 1: + return ["Expected native fixture format_version 1"] + cases = data.get("scenarios") + if not isinstance(cases, list) or not cases: + return ["At least one meaningful native scenario is required"] + names = set() + for index, case in enumerate(cases): + label = "scenario " + str(index) + if not isinstance(case, dict): + issues.append(label + " must be an object") + continue + name = case.get("name") + if not isinstance(name, str) or not re.fullmatch(r"[a-z0-9_]+", name): + issues.append(label + " has an invalid name") + elif name in names: + issues.append("Duplicate scenario name: " + name) + else: + names.add(name) + label = name + if not isinstance(case.get("mode"), str) or case["mode"] not in {"DT", "SR"}: + issues.append(label + ": mode must be DT or SR") + suites = case.get("suites") + if not isinstance(suites, list) or not suites or not all( + isinstance(suite, str) and suite for suite in suites): + issues.append(label + ": non-empty suites list is required") + elif len(suites) != len(set(suites)): + issues.append(label + ": duplicate selected suite") + files = case.get("files") + if not isinstance(files, dict) or not files: + issues.append(label + ": non-empty native input files are required") + elif any(not _relative(name) or not isinstance(content, str) or not content.strip() + for name, content in files.items()): + issues.append(label + ": unsafe input path or empty/non-text native input") + outputs = case.get("raw") + if not isinstance(outputs, dict) or not outputs: + issues.append(label + ": expected raw output files are required") + continue + for filename, expectation in outputs.items(): + where = label + ": " + filename + if not _relative(filename) or Path(filename).name != filename or not filename.endswith(".json"): + issues.append(where + ": raw output must be a JSON basename") + if not isinstance(expectation, dict): + issues.append(where + ": expectation must be an object") + continue + assertions, records = expectation.get("assertions"), expectation.get("records") + if not isinstance(assertions, list) or not assertions: + issues.append(where + ": independent count assertions are required") + else: + for assertion in assertions: + if not isinstance(assertion, dict) or not _path(assertion.get("path")) or "value" not in assertion: + issues.append(where + ": invalid count/metadata assertion") + if not isinstance(records, list) or not records: + issues.append(where + ": non-empty exact record inventory is required") + continue + seen = set() + for record in records: + if not isinstance(record, dict) or not _path(record.get("path")): + issues.append(where + ": invalid record path") + continue + path = tuple(record["path"]) + if path in seen: + issues.append(where + ": duplicate expected record path " + str(path)) + seen.add(path) + fields = record.get("fields") + if not isinstance(fields, dict) or not all(group.intersection(fields) for group in ( + RESULT_FIELDS, IDENTITY_FIELDS, DESCRIPTION_FIELDS)): + issues.append(where + ": each record needs identity, description and result fields") + continue + for key in RESULT_FIELDS.intersection(fields): + value = fields[key] + if isinstance(value, str): + valid = value in KNOWN_STATUSES + elif isinstance(value, dict): + valid = bool(value) and all(status in KNOWN_STATUSES and type(count) is int + and count >= 0 for status, count in value.items()) + else: + valid = False + if not valid: + issues.append(where + ": invalid expected result status or counter") + return issues + + +def expected_outputs(case, suite): + patterns = [suite.get("json_output", ""), *suite.get("json_output_patterns", [])] + return {name: value for name, value in case["raw"].items() + if any(fnmatch.fnmatchcase(name, pattern) for pattern in patterns if pattern)} + + +def coverage_issues(registry, cases): + """List parser routes that lack a sample log or target an unsupported mode.""" + by_name = {suite["canonical"]: suite for suite in registry["suites"]} + executable = set(registry["standalone"]["suite_execution"]) + issues = [] + for name in sorted(executable - by_name.keys()): + issues.append("Execution route has no registered suite: " + name) + required = {(name, mode) for name in executable if name in by_name + for mode in by_name[name].get("modes", [])} + covered = {(name, case["mode"]) for case in cases for name in case["suites"]} + if not required: + issues.append("No executable suite/mode routes are registered") + for name, mode in sorted(required - covered): + issues.append("Missing independent native fixture: " + mode + "/" + name) + for name, mode in sorted(covered - required): + issues.append("Fixture targets an unknown/unsupported route: " + mode + "/" + name) + for case in cases: + matched = set() + for name in case["suites"]: + suite = by_name.get(name) + if not suite: + continue + outputs = expected_outputs(case, suite) + matched.update(outputs) + if not outputs: + issues.append(case["name"] + "/" + name + ": no independently expected raw output") + if not suite.get("schema"): + issues.append(name + ": no raw schema registered") + for filename in sorted(case["raw"].keys() - matched): + issues.append(case["name"] + ": expected output has no selected suite: " + filename) + for suite in registry["suites"]: + if suite.get("logs_to_json") and suite["canonical"] not in executable: + issues.append(suite["canonical"] + ": parser has no standalone execution route") + return issues + + +def raw_issues(data, expectation): + """Compare every expected test, description, status and count with raw JSON.""" + issues = [] + actual_paths = set(result_paths(data)) + expected_paths = {tuple(record["path"]) for record in expectation["records"]} + missing, extra = expected_paths - actual_paths, actual_paths - expected_paths + if missing or extra: + issues.append("Result inventory differs: missing=" + repr(sorted(missing, key=repr)) + + "; extra=" + repr(sorted(extra, key=repr))) + for assertion in expectation["assertions"]: + try: + actual = _get(data, assertion["path"]) + except (KeyError, IndexError, TypeError): + issues.append("Missing assertion path " + repr(assertion["path"])) + continue + if not _exact(actual, assertion["value"]): + issues.append(repr(assertion["path"]) + ": expected " + repr(assertion["value"]) + + ", actual " + repr(actual)) + for record in expectation["records"]: + try: + actual = _get(data, record["path"]) + except (KeyError, IndexError, TypeError): + continue + for field, expected in record["fields"].items(): + label = repr(record["path"]) + "." + field + if not isinstance(actual, dict) or field not in actual: + issues.append(label + ": missing field") + continue + value = actual[field] + if isinstance(expected, dict) and isinstance(value, dict): + additional = {key: count for key, count in value.items() if key not in expected + and isinstance(count, (int, float)) and count != 0} + if additional: + issues.append(label + ": unexpected nonzero result counters " + repr(additional)) + value = {key: value[key] for key in expected if key in value} + if not _exact(value, expected): + issues.append(label + ": expected " + repr(expected) + ", actual " + repr(value)) + return issues + + +def command_diagnostic(completed): + """Include actionable issue/path text in the report, not just a log link.""" + text = re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", completed.stdout or "") + lines = [line.strip() for line in text.splitlines() if line.strip()] + useful = [line for line in lines if any(marker in line for marker in ( + "issue=", "*at=", "ERROR:", "Error:", "Missing required Python package", "Exception:"))] + chosen = useful[:16] if useful else lines[-8:] + return "Exit " + str(completed.returncode) + ("\n" + "\n".join(chosen) if chosen else "") + + +def _completed_schema_failure(completed, raw_path, suite): + """Distinguish a completed schema check from a crash or unrelated error.""" + output = re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", completed.stdout or "") + lines = [line.strip() for line in output.splitlines() if line.strip()] + tags = re.findall(r"(?m)^\*suite=.*?\bissue=([A-Z_]+):", output) + schema_tags = {"MISSING_KEY", "UNEXPECTED_KEY", "DISALLOWED_VALUE", "TYPE_MISMATCH", "ENUM", "VALIDATION"} + fatal = re.search(r"(?m)^(?:Traceback\b|ERROR:|Error:|(?:\w+Error|Exception):)", output) + return bool(lines and lines[-1] == "Schema validation result: FAIL (1 failed, 0 passed, 0 skipped)" + and "--- Files Checked ---" in lines and suite + ": " + str(raw_path) in lines + and tags and set(tags) <= schema_tags and not fatal) + + +def _check_raw_schema(ctx, directory, output, raw_path, mode, name): + """Keep strict schema evidence and apply Doctor's supplied-category rule.""" + filename = raw_path.name + stem = filename[:-5] + validation = ctx.run([ctx.python, "-B", ctx.parser_dir / "validate.py", "raw", + "--registry", ctx.parser_dir / "suite_registry.json", raw_path], + directory, "schema-" + stem, cwd=directory, + env={"PYTHONPATH": "", "PYTHONNOUSERSITE": "1"}) + evidence = [raw_path, directory / ("schema-" + stem + ".log")] + if validation.returncode not in (0, 1) or ( + validation.returncode == 1 and not _completed_schema_failure(validation, raw_path, name)): + status = "BLOCKED" if "Missing required Python package" in validation.stdout else "FAIL" + ctx.add("NATIVE_RAW_SCHEMA", status, "Strict raw schema validator did not complete normally: " + filename, + "Completed strict validation before Doctor applicability is evaluated", + command_diagnostic(validation), mode, name, evidence) + return + # Missing Test_suite_info is required only when the run supplied a category + # file. Keep all other schema errors and the original validator log visible. + policy = ctx.run([ctx.python, "-B", "-m", "doctor_checks.artifacts", "--schema-policy", + "--registry", ctx.parser_dir / "suite_registry.json", "--report", output, + "--mode", mode, raw_path], directory, "schema-policy-" + stem, cwd=ctx.parser_dir, + env={"PYTHONPATH": "", "PYTHONNOUSERSITE": "1"}) + evidence.append(directory / ("schema-policy-" + stem + ".log")) + if policy.returncode: + ctx.add("NATIVE_RAW_SCHEMA", "BLOCKED", "Doctor schema applicability could not be evaluated: " + filename, + "Completed policy evaluation without modifying the strict schema or raw JSON", + "Strict validator exit " + str(validation.returncode) + "; " + command_diagnostic(policy), + mode, name, evidence) + return + result = json.loads(policy.stdout) + provenance = result["category_provenance"] + errors = result["errors"] + omitted = result["omitted_missing_info_paths"] + if provenance["invalid"]: + ctx.add("NATIVE_CATEGORY_PROVENANCE", "FAIL", "Generated category provenance is invalid", + "Run mode and explicit category snapshot/hash are verifiable", provenance["message"], + mode, name, evidence) + elif provenance["source"] == "unknown" and omitted: + ctx.add("NATIVE_CATEGORY_PROVENANCE", "WARN", "Missing Test_suite_info has unknown category provenance", + "Verified generating-run category choice", provenance["message"] + + "; only the missing-info requirement was not applied", mode, name, evidence) + disagreement = bool(result["strict_error_count"]) != bool(validation.returncode) + actual = "Strict validator exit " + str(validation.returncode) + "; category source: " + provenance["source"] + if omitted: + actual += "; missing Test_suite_info not required at " + str(len(omitted)) + " record(s)" + if disagreement: + actual += "; strict CLI and policy evaluator disagree about original schema validity" + elif errors: + actual += "\n" + "\n".join(error["path"] + ": " + error["message"] for error in errors[:16]) + else: + actual += "; all applicable Doctor schema checks passed" + ctx.add("NATIVE_RAW_SCHEMA", "FAIL" if errors or disagreement else "PASS", + "Generated raw file must satisfy applicable Doctor schema checks: " + filename, + "Registered schema; missing Test_suite_info is required only for an explicitly supplied category", + actual, mode, name, evidence) + + +def _run_route(ctx, case, name, suite): + """Run one known log through the public CLI and check its raw output files.""" + mode = case["mode"] + directory = ctx.case_dir("native/" + mode + "/" + name + "/" + case["name"]) + inputs = directory / "input" + for relative, content in case["files"].items(): + path = inputs / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content, encoding="utf-8") + (inputs / "results").mkdir(parents=True, exist_ok=True) + output = directory / "output" + command = ["bash", ctx.parser_dir / "main_log_parser.sh", "--standalone", "--mode", mode, + "--suite", name, "--input-log", inputs / "results", "--output", output, + "--outputs", "json"] + try: + completed = ctx.run(command, directory, "parser", cwd=directory, + env={"PYTHONPATH": "", "PYTHONNOUSERSITE": "1"}) + except (OSError, RuntimeError) as error: + ctx.add("NATIVE_EXECUTION", "BLOCKED", "Public standalone native fixture did not finish", + "Successful JSON-only generation; raw checks then run independently", str(error), + mode, name, [directory]) + return + status = "PASS" if completed.returncode == 0 else ( + "BLOCKED" if completed.returncode == 3 else "FAIL") + ctx.add("NATIVE_EXECUTION", status, "Public CLI must parse the known native fixture", + "Exit 0", case["name"] + "; " + ("Exit 0" if completed.returncode == 0 + else command_diagnostic(completed)), + mode, name, [directory / "parser.log", directory / "parser.command.json"]) + expected = expected_outputs(case, suite) + json_dir = output / "acs_jsons" + if json_dir.is_dir(): + ctx.native_outputs.append((mode, output)) + generated = {path.name for path in json_dir.glob("*.json")} + auxiliary = set(case.get("auxiliary", [])) + missing = set(expected) - generated + extra = generated - set(expected) - auxiliary + ctx.add("NATIVE_OUTPUT_INVENTORY", "FAIL" if missing or extra or not expected else "PASS", + "Native route must produce exactly its expected suite JSON files", + ", ".join(sorted(expected)), "missing=" + repr(sorted(missing)) + + "; unexpected=" + repr(sorted(extra)), mode, name, [directory]) + for filename, expectation in expected.items(): + raw_path = json_dir / filename + if not raw_path.is_file(): + ctx.add("NATIVE_RAW_IDENTITY", "BLOCKED", "Raw identity check has no input: " + filename, + "Generated raw JSON with exact fixture record inventory", "File was not generated", + mode, name, [directory / "parser.log"]) + continue + try: + issues = raw_issues(load_json(raw_path), expectation) + ctx.add("NATIVE_RAW_IDENTITY", "FAIL" if issues else "PASS", + "Raw test identities, nested paths and statuses must match the native log: " + filename, + str(len(expectation["records"])) + " exact records and independent count assertions", + "\n".join(issues) or "Every expected record and assertion matches", + mode, name, [raw_path, DATA_FILE]) + except (OSError, ValueError, TypeError, KeyError) as error: + ctx.add("NATIVE_RAW_IDENTITY", "FAIL", "Raw JSON cannot be checked: " + filename, + "Strict JSON with independent fixture identities", str(error), mode, name, [raw_path]) + try: + _check_raw_schema(ctx, directory, output, raw_path, mode, name) + except (OSError, RuntimeError, ValueError, TypeError, KeyError) as error: + ctx.add("NATIVE_RAW_SCHEMA", "BLOCKED", "Native raw schema check did not finish: " + filename, + "Completed raw validation", str(error), mode, name, [directory]) + + +def run_native(ctx): + """Run known logs for the requested modes and report any missing coverage.""" + ctx.native_outputs = [] + portable = getattr(ctx, "portable_parser", None) + if getattr(ctx, "package_checked", False) and portable is None: + ctx.add("NATIVE_PACKAGE_PREREQUISITE", "BLOCKED", + "Native routes require the verified standalone package", + "Successful extraction and verification in the package group", + "No verified portable parser is available; source-tree fallback was not used") + return + if portable is not None: + # A shallow copy changes only this group's parser path. Findings still + # go to the same Doctor report, but checks use the extracted package. + ctx = copy(ctx) + ctx.parser_dir = Path(portable).resolve() + try: + data = load_json(DATA_FILE) + problems = contract_issues(data) + except (OSError, ValueError, TypeError) as error: + problems = [str(error)] + ctx.add("NATIVE_FIXTURE_CONTRACT", "FAIL" if problems else "PASS", + "Native fixtures must be independent, meaningful and safe to generate", + "Non-empty exact identities and native inputs; no ambiguous paths or statuses", + "\n".join(problems) or "Fixture contracts are well-formed", evidence=[DATA_FILE]) + if problems: + return + try: + registry = load_json(ctx.parser_dir / "suite_registry.json") + cases = data["scenarios"] + issues = coverage_issues(registry, cases) + by_name = {suite["canonical"]: suite for suite in registry["suites"]} + except (OSError, ValueError, TypeError, KeyError) as error: + ctx.add("NATIVE_ROUTE_COVERAGE", "FAIL", "Native coverage cannot be mapped to the registry", + "Every executable suite/mode has an independent native fixture", str(error)) + return + routes = {(name, case["mode"]) for case in cases for name in case["suites"]} + ctx.add("NATIVE_ROUTE_COVERAGE", "FAIL" if issues else "PASS", + "Every executable suite and supported mode must have a meaningful native fixture", + "No uncovered or unknown routes; new suites require explicit fixture onboarding", + "\n".join(issues) or str(len(routes)) + " independently covered suite/mode routes", + evidence=[DATA_FILE, ctx.parser_dir / "suite_registry.json"]) + executed = Counter() + for case in cases: + if case["mode"] not in ctx.modes: + continue + for name in case["suites"]: + suite = by_name.get(name) + if not suite or name not in registry["standalone"]["suite_execution"] or ( + case["mode"] not in suite.get("modes", [])): + continue + try: + _run_route(ctx, case, name, suite) + except (OSError, ValueError, TypeError, KeyError) as error: + ctx.add("NATIVE_EXECUTION", "BLOCKED", "Native fixture route could not be checked", + "Completed public CLI and raw identity checks", str(error), case["mode"], name) + executed[case["mode"]] += 1 + for mode in ctx.modes: + count = executed[mode] + ctx.add("NATIVE_MODE_EXECUTION", "PASS" if count else "BLOCKED", + "Selected mode must execute native fixture routes", "At least one route attempted", + str(count) + " routes attempted; consult individual verdicts for results", mode=mode) + + +# The raw group checks bad logs, waiver behaviour and old results left by reruns. + +def html_capability(ctx): + """Skip table checks only if unsupported; a broken renderer is still a bug.""" + from .merge import HTML_HELPERS + + source = ctx.parser_dir / "generate_acs_summary.py" + try: + tree = ast.parse(source.read_text(encoding="utf-8"), filename=str(source)) + functions = {node.name for node in tree.body + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))} + missing = sorted(set(HTML_HELPERS) - functions) + if not missing: + return True + reason = "This checkout does not define " + ", ".join(missing) + except (OSError, SyntaxError) as error: + reason = type(error).__name__ + ": " + str(error) + ctx.add("raw.html-capability", "BLOCKED", + "Detailed compliance HTML checks are unavailable; native raw/merged JSON checks still run.", + "Detail compliance generation in this checkout", reason, evidence=(source,)) + return False + +class ReportTables(HTMLParser): + """Read source table cells without requiring a browser or BeautifulSoup.""" + + def __init__(self): + super().__init__(convert_charrefs=True) + self.tables = [] + self.stack = [] + self.row = None + self.cell = None + + def handle_starttag(self, tag, attrs): + if tag == "table": + table = {"class": dict(attrs).get("class", ""), "rows": []} + self.tables.append(table) + self.stack.append(table) + elif tag == "tr" and self.stack: + self.row = [] + elif tag in ("th", "td") and self.row is not None: + self.cell = [] + + def handle_data(self, data): + if self.cell is not None: + self.cell.append(data) + + def handle_endtag(self, tag): + if tag in ("th", "td") and self.cell is not None: + self.row.append(" ".join(" ".join(self.cell).split())) + self.cell = None + elif tag == "tr" and self.row is not None and self.stack: + self.stack[-1]["rows"].append(self.row) + self.row = None + elif tag == "table" and self.stack: + self.stack.pop() + + +def green(value): + """Do not confuse 'Not Compliant' with 'Compliant'.""" + return str(value).strip().lower().startswith("compliant") + + +def counts(raw): + summary = raw.get("suite_summary", {}) if isinstance(raw, dict) else {} + return {name: summary.get("total_" + name, + summary.get("Total_failed_with_waiver" if name == "failed_with_waiver" + else name.title(), 0)) + for name in ("passed", "failed", "failed_with_waiver", "aborted", + "skipped", "warnings", "ignored")} + + +def label_for(suite, mode): + return (("EBBR-" if mode == "DT" else "SBBR-") + suite + if suite in ("SCT", "FWTS") else suite) + + +def suite_status(merged, suite, mode, registry): + summary = merged.get("Suite_Name: acs_info", {}).get("ACS Results Summary", {}) + labels = {label_for(suite, mode), registry[suite]["requirement_key"]} + # DT publishes one OS result per distribution, not a single os_test.json. + # Keep the least successful decision so a passing neighbour cannot hide it. + if suite == "OS-TESTS" and mode == "DT": + statuses = [value for key, value in summary.items() + if key.endswith("_compliance") and " : OS_" in key] + if statuses: + return next((value for value in statuses if not green(value)), "Compliant") + for key, value in summary.items(): + if any(key.endswith(" : " + label + "_compliance") for label in labels): + return value + return None + + +def bsa_log(suite="BSA", status="PASSED"): + prefix = "B" if suite == "BSA" else "S" + return (f" {suite} Architecture Compliance Suite\n Version 1.2.1\n\n" + " *** Running PE tests ***\n\n" + f"{prefix}_PE_01 : 1 : Check Arch symmetry across PE\n" + f" Result: {status}\n\n" + "-------------------- Suite run complete --------------------\n" + "---------- ACS Summary ----------\n Total Rules Run : 1\n" + f" Passed : {int(status == 'PASSED')}\n" + f" Failed : {int(status == 'FAILED')}\n" + " Skipped : 0\n---------------------------------\n" + f" *** {suite} tests complete. Reset the system. ***\n") + + +def fwts_log(suite="FWTS", failed=0): + group = "smccc" if suite == "FWTS" else "uefirtauthvar" + lines = (f"Results generated by fwts: Version V26.01.00.\nRunning tests: {group}\n" + + "-" * 80 + f"\n{group}: Synthetic doctor check.\n" + "-" * 80 + + "\nTest 1 of 1: Synthetic doctor check.\n") + for index in range(failed or 1): + lines += (f"{'FAILED' if failed else 'PASSED'}: Test 1, " + f"synthetic doctor assertion {index + 1}.\n") + return (lines + "\n" + "=" * 80 + f"\n{int(not failed)} passed, {failed} failed, " + "0 warning, 0 aborted, 0 skipped, 0 info only.\n" + "=" * 80 + "\n") + + +def sct_log(suite="SCT", failed=False, parent_only=False): + names = (["CalculateCrc32_Func", "GetVariable_Func"] if suite == "SCT" + else ["GetVariable_Func", "SetVariable_Func"]) + status = "FAIL" if failed else "PASS" + result = "" + for index, name in enumerate(names, 1): + guid = f"00000000-0000-4000-8000-{index:012d}" + result += (f"BBR ACS 2.1.1 (SBBR)\n{name}\nRevision 0x00010001\n" + f"Test Entry Point GUID: {guid}\nTest Configuration #0\n" + "Synthetic doctor check\nTest Started: 09/17/26 05:55a\n") + if not parent_only: + result += (f"Synthetic check {index} -- {status}\n{guid}\n" + f"/synthetic/Test.c:{index}:synthetic doctor result\n") + result += f"\nReturned Status Code: 0x00000000\n{name}: [{status}]\n" + return result + + +def robot_log(status="PASS"): + terminal = f'' if status else "" + return ('' + f'{terminal}' + '') + + +def write_text(path, content): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content, encoding="utf-8") + + +def config_files(folder, mode): + """Create enough synthetic run information for a DT or SR summary report.""" + suffix = "_dt" if mode == "DT" else "" + acs = folder / ("acs_config" + suffix + ".txt") + system = folder / ("system_config" + suffix + ".txt") + band = "SystemReady Devicetree band" if mode == "DT" else "SystemReady band" + write_text(acs, "ACS version: Synthetic doctor\nSRS version: SRS 3.1.1\n" + "BSA version: BSA v1.2\nSBSA version: SBSA v8.0\n" + "SBBR version: BBR v2.1\nEBBR version: EBBR v2.2.0\n" + "BBSR version: BBSR v1.3\nSBMR version: SBMR v2.1\n" + "Device Tree Version: v0.4\nBand: " + band + "\n") + write_text(system, "FW source code: Synthetic doctor fixture\n") + return acs, system + + +def invoke(ctx, registry, mode, suite, name, files, waiver=None): + """Create an isolated sample, run the parser and collect its report evidence.""" + folder = ctx.case_dir("raw/" + mode + "/" + suite + "/" + name) + inputs = folder / "input" / "acs_results" + inputs.mkdir(parents=True, exist_ok=True) + for relative, content in files.items(): + target = (inputs / relative).resolve() + if folder.resolve() not in target.parents: + raise ValueError("Synthetic input escaped its evidence directory") + write_text(target, content) + acs, system = config_files(folder, mode) + output = folder / "output" + command = [ctx.python, "-B", ctx.parser_dir / "standalone_runner.py", + "--mode", mode, "--input-log", inputs, "--suite", suite, + "--output", output, "--outputs", "json,html,summary", + "--acs-config", acs, "--system-config", system] + if waiver is not None: + path = folder / "waiver.json" + write_text(path, json.dumps(waiver, indent=2) + "\n") + command.extend(["--waiver", path]) + completed = ctx.run(command, folder, name="parser") + return observe(registry, mode, suite, output, folder, completed) + + +def observe(registry, mode, suite, output, folder, completed): + """Read what the command actually published, including errors and HTML labels.""" + raw_path = output / "acs_jsons" / registry[suite]["json_output"] + merged_path = output / "acs_jsons" / "merged_results.json" + html_path = output / "html_detailed_summaries" / registry[suite]["detailed_html"] + # Combined SBMR pages retain interface-specific compliance rows. + if suite.startswith("SBMR-"): + combined = html_path.with_name("sbmr_detailed.html") + if combined.is_file(): + html_path = combined + raw_paths = [raw_path] if raw_path.is_file() else [] + if suite == "OS-TESTS" and mode == "DT": + raw_paths = sorted((output / "acs_jsons").glob("ethtool_test_*.json")) + raw_values = [load_json(path) for path in raw_paths] + raw = raw_values[0] if len(raw_values) == 1 else {} + if len(raw_values) > 1: + # These are separate distribution totals; no parent/child rows are added. + raw = {"suite_summary": {"total_" + key: sum(counts(value)[key] for value in raw_values) + for key in counts({})}} + merged = json.loads(merged_path.read_text()) if merged_path.is_file() else {} + tables = ReportTables() + if html_path.is_file(): + tables.feed(html_path.read_text(encoding="utf-8")) + rows = [row for table in tables.tables + if "acs-compliance-table" in table["class"].split() + for row in table["rows"] if len(row) == 3] + label = label_for(suite, mode) + html_status = next((row[2] for row in rows if row[0] == label), None) + # Standalone row labels use visible aliases from registry requirement keys. + if suite == "OS-TESTS" and mode == "DT": + body = [row for row in rows if row[0].casefold() not in ("test suite", "test case")] + if body: + html_status = next((row[2] for row in body if not green(row[2])), "Compliant") + elif html_status is None and not suite.startswith("SBMR-"): + body = [row for row in rows if row[0] not in ("Test suite", "Test case")] + if len(body) == 1: + html_status = body[0][2] + chart_failed = next((int(row[1]) for table in tables.tables + if "acs-compliance-table" not in table["class"].split() + for row in table["rows"] + if len(row) == 2 and row[0] == "Failed" + and row[1].isdigit()), None) + result = {"exit": completed.returncode, "counts": counts(raw), + "status": suite_status(merged, suite, mode, registry), + "html_status": html_status, "html_failed": chart_failed, + "traceback": "Traceback (most recent call last)" in completed.stdout, + "error": next((line.strip() for line in reversed(completed.stdout.splitlines()) + if line.partition(":")[0].endswith(("Error", "Exception"))), ""), + "raw": raw, "log": completed.stdout, "folder": str(folder), + "evidence": [path for path in (folder / "parser.log", folder / "parser.command.json", + *raw_paths, merged_path, html_path) if path.is_file()]} + write_text(folder / "observation.json", json.dumps( + {key: value for key, value in result.items() + if key not in ("raw", "log", "evidence")}, indent=2) + "\n") + return result + + +def brief(observation): + description = (f"exit={observation['exit']}; raw counts={observation['counts']}; " + f"merged={observation['status']!r}; HTML={observation['html_status']!r}; " + f"HTML Failed={observation['html_failed']!r}") + return description + ("; " + observation["error"] if observation.get("error") else "") + + +def control_ok(observation, require_html=True): + """Require a working passing sample before trusting checks with broken logs.""" + return (observation["exit"] == 0 and green(observation["status"]) + and (not require_html or green(observation["html_status"])) + and observation["counts"]["passed"] > 0 + and observation["counts"]["failed"] == 0 + and observation["counts"]["failed_with_waiver"] == 0) + + +def invalid_verdict(observation, require_html=True): + """Check that a broken log is rejected or does not produce a green report.""" + if observation["exit"] in (3, 4): + return "BLOCKED" + if observation["traceback"]: + return "FAIL" + # A later command failure must not excuse a Compliant artifact already saved. + if green(observation["status"]) or green(observation["html_status"]): + return "FAIL" + if observation["exit"] != 0: + return "PASS" if observation["exit"] == 5 else "FAIL" + if observation["status"] is None or (require_html and observation["html_status"] is None): + return "BLOCKED" + return "PASS" + + +def empty_verdict(observation): + """Empty/introductory logs must complete as Not Run with no test outcomes.""" + if observation["exit"] in (3, 4): + return "BLOCKED" + if observation["exit"] != 0 or observation["traceback"]: + return "FAIL" + if green(observation["status"]) or green(observation["html_status"]): + return "FAIL" + not_run = "not run" in str(observation["status"]).casefold() + return "PASS" if not_run and not any(observation["counts"].values()) else "FAIL" + + +def record(ctx, ident, status, issue, expected, observation, mode, suite): + ctx.add(ident, status, issue, expected, brief(observation), mode=mode, + suite=suite, evidence=observation["evidence"]) + + +def record_html(ctx, observation, mode, suite, case, enabled=True): + """Check HTML against merged JSON separately from checking the input log.""" + if not enabled or observation["exit"] != 0 or observation["status"] is None: + return + from .merge import status as compliance_status + + wanted = compliance_status(observation["status"]) + actual = compliance_status(observation["html_status"]) + record(ctx, "raw.html-compliance", "PASS" if wanted != "unknown" and actual == wanted else "FAIL", + case + ": detailed HTML must retain the merged JSON suite decision.", + "A present compliance row matching merged JSON: " + str(observation["status"]), + observation, mode, suite) + + +def family(ctx, registry, mode, suite, relative, good, malformed, control_counts=None, + html_available=True): + """Check a complete log first, then its empty, cut-short or invalid versions.""" + def files(content): + return dict(content) if isinstance(content, dict) else {relative: content} + + positive = invoke(ctx, registry, mode, suite, "positive", files(good)) + ready = control_ok(positive, require_html=False) + expected_control = "At least one passed result, no failures/waivers, Compliant in merged JSON" + if control_counts is not None: + # Post-Script records errors rather than positive INFO lines. Its known + # complete error is a valid control; never fabricate a passing subtest. + expected_counts = {**counts({}), **control_counts} + expected_green = not expected_counts["failed"] + status_text = str(positive["status"]).strip().casefold() + status_matches = (green(positive["status"]) if expected_green else + status_text.startswith("not compliant") and "not run" not in status_text) + ready = (positive["exit"] == 0 and positive["status"] is not None + and status_matches and positive["counts"] == expected_counts) + expected_control = str(expected_counts) + ("; Compliant" if expected_green else "; Not Compliant") + record(ctx, "raw.positive", "PASS" if ready else "BLOCKED", + "A complete native-log control must parse before malformed-log checks are meaningful.", + expected_control, + positive, mode, suite) + record_html(ctx, positive, mode, suite, "Positive control", html_available) + if not ready: + ctx.add("raw.incomplete.coverage", "BLOCKED", + "Malformed-log cases were not evaluated because the positive control failed.", + ", ".join(name for name, _, _ in malformed), "Control unavailable", + mode=mode, suite=suite, evidence=positive["evidence"]) + return set() + evaluated = set() + for name, text, caveat in malformed: + observation = invoke(ctx, registry, mode, suite, name, files(text)) + empty = name in ("empty-log", "header-only") + verdict = empty_verdict(observation) if empty else invalid_verdict(observation, require_html=False) + # Quiet completed dt-validate is valid. Empty input alone cannot prove completion. + if caveat and verdict == "FAIL" and not observation["traceback"]: + verdict = "WARN" + record(ctx, "raw." + name, verdict, + caveat or ("Empty or introductory-only input must be Not Run, not invented test outcomes." + if empty else "Incomplete or unrecognized raw evidence must not become a green result."), + ("Publish Not Run with zero executed outcomes" if empty else + "Reject the input clearly or publish non-green/incomplete status; do not invent a pass"), + observation, mode, suite) + record_html(ctx, observation, mode, suite, name, html_available) + if verdict != "BLOCKED": + evaluated.add(name) + if suite in ("SCT", "BBSR-SCT"): + observation = invoke(ctx, registry, mode, suite, "parent-only-failures", + {relative: sct_log(suite, failed=True, parent_only=True)}) + valid = (observation["exit"] == 0 and observation["counts"]["failed"] == 2 + and observation["status"] is not None) + verdict = ("BLOCKED" if not valid else "FAIL" + if green(observation["status"]) + else "PASS") + record(ctx, "raw.sct-parent-failure", verdict, + "Two explicit failed SCT entries must remain non-compliant when subtest detail is absent.", + "Failed=2 in raw JSON; Not Compliant in merged JSON", + observation, mode, suite) + if observation["exit"] == 0: + record(ctx, "raw.sct-parent-chart", "PASS" if observation["html_failed"] == 2 else "FAIL", + "The detailed chart must preserve both explicit failed SCT entries.", + "Failed=2 in the detailed HTML chart", observation, mode, suite) + record_html(ctx, observation, mode, suite, "Parent-only SCT failures", html_available) + return evaluated + + +def additional_raw_jobs(modes): + """Small producer-format controls for routes the older raw probes missed. + + Text comes from the bundled native fixtures and the DT network, memory-map, + alignment and ethtool producers. Mutations change only Doctor-owned copies: + remove all evidence, keep only introductory text, cut a started check short, + or corrupt the required result field. OS inputs retain their directory shape. + """ + jobs = [] + + def add(mode, suite, relative, good, header, truncated, malformed, expected=None): + if mode not in modes: + return + empty = {name: "" for name in good} if isinstance(good, dict) else "" + cases = [("empty-log", empty, ""), ("header-only", header, ""), + ("truncated-log", truncated, ""), ("malformed-log", malformed, "")] + jobs.append((mode, suite, relative, good, cases, expected)) + + dtb_header = "INFO: Starting DTB alignment test\n" + dtb = (dtb_header + "INFO: DTB address is 0xFCEAD000\n" + "INFO: Required alignment is 8 bytes\n" + "INFO: DTB address 0xFCEAD000 is 8-byte aligned\nRESULT: PASS\n") + add("DT", "DTB-ALIGNMENT", "linux_tools/dtb_alignment_test.log", dtb, dtb_header, + dtb.rsplit("RESULT:", 1)[0], dtb.replace("RESULT: PASS", "RESULT: UNKNOWN"), + {"passed": 1, "failed": 0}) + + network_header = "[INFO] network_boot_checks\n" + network_first = network_header + "Image URL: PASSED (URL Found: http://example.invalid/boot.img)\n" + network = (network_first + "EFI System Partition (ESP): PASSED (detected ESP on the system)\n" + "Logs captured: PASSED (lsblk, blkid and dmesg logs exist)\nNetwork_Boot_Result: PASSED\n") + add("DT", "NETWORK-BOOT", "network_boot/network_boot_results.log", network, network_header, + network_first + "EFI System Partition (ESP): ", + network_first + "EFI System Partition (ESP): UNKNOWN\nNetwork_Boot_Result: UNKNOWN\n", + {"passed": 3, "failed": 0}) + + pfdi_header = "*** Running PFDI tests ***\n" + pfdi_first = pfdi_header + "PFDI_01 : 1 : QA passing rule\nResult: PASSED\n" + add("DT", "PFDI", "uefi/pfdiresults.log", pfdi_first, pfdi_header, + pfdi_first + "PFDI_02 : 2 : QA unfinished rule\n", + pfdi_first + "PFDI_02 : 2 : QA malformed rule\nResult: UNKNOWN\n", + {"passed": 1, "failed": 0}) + + post_header = "INFO : INFO config: using check-sr-results-dt3.yaml\n" + # A complete ERROR line is an independently known result. INFO is deliberately + # not counted as a pass by this producer, so this control expects one failure. + post_error = "ERROR check_file: `/doctor/sample.log' missing\n" + add("DT", "POST-SCRIPT", "post-script/post-script.log", post_header + post_error, + post_header, post_header + "ERROR check_file: `/doctor/sample.log' miss", + post_header + "ERRO? check_file: `/doctor/sample.log' missing\n", + {"passed": 0, "failed": 1, "failed_with_waiver": 0, "warnings": 0}) + + # DT producer (Yocto/meta-woden/recipes-acs/install-files/files/init.sh) + # captures `dmesg | grep psci`. This real kernel introduction survives that + # filter but contains no firmware-version result (timestamps omitted). + psci_header = "psci: probing for conduit method from DT.\n" + add("DT", "PSCI", "linux_tools/psci/psci_kernel.log", + "psci: PSCIv1.1 detected in firmware.\n", psci_header, + "psci: PSCIv1.1 detected in firm", "psci: PSCIv1.2.3 detected in firmware.\n", + {"passed": 1, "failed": 0}) + + memory_header = "Testing Devicetree Reserved Memory Map Compliance Test\n" + memory_first = memory_header + "INFO: Reserved Memory Map Compliance Test: PASSED\n" + memory = (memory_first + "INFO: Checking Memory Reservation Block entries\n" + "INFO: Memory Reservation Block Compliance Test: PASSED\nRESULTS: PASSED\n") + add("DT", "RESERVED-MEMORY-MAP", "linux_tools/reserved_memory_map_test.log", memory, + memory_header, memory_first + "INFO: Checking Memory Reservation Block entries\n", + memory.replace("RESULTS: PASSED", "RESULTS: UNKNOWN"), {"passed": 2, "failed": 0}) + + scmi_header = "**** SCMI Compliance Suite ****\n*** Starting BASE tests ***\n" + scmi_first = scmi_header + "1 : QA passing protocol : CONFORMANT\n" + add("DT", "SCMI", "linux_acs/scmi_acs_app/arm_scmi_test_log.txt", scmi_first, scmi_header, + scmi_first + "2 : QA unfinished protocol\n", scmi_first + "2 : QA invalid protocol : UNKNOWN\n", + {"passed": 1, "failed": 0}) + + smbios_header = "BBR ACS 2.1\nSmbiosTable\nTest Configuration #0\nQA SMBIOS table check\n" + smbios = smbios_header + "SMBIOS table -- PASS\n00000000-0000-0000-0000-000000000001\nQA table found\n" + add("DT", "SMBIOS", "sct_results/Overall/Summary.log", smbios, "BBR ACS 2.1\n", + smbios_header + "SMBIOS table -- ", smbios.replace("-- PASS", "-- UNKNOWN"), + {"passed": 1, "failed": 0}) + + kself_header = "selftests: dt: test_unprobed_devices.sh\n" + kself_first = kself_header + "# ok 1 synthetic passing device check\n" + add("DT", "DT-KSELFTEST", "linux_tools/dt_kselftest.log", kself_first, kself_header, + kself_first + "# not ok 2", kself_first + "# UNKNOWN 2 synthetic missing status\n", + {"passed": 1, "failed": 0}) + + runtime_header = "Testing Runtime Device Mapping Conflict Test\n" + runtime = runtime_header + "RESULTS: PASSED\n" + add("DT", "RUNTIME-DEV-MAP", "linux_tools/runtime_device_mapping_conflict_test.log", + runtime, runtime_header, runtime_header + "DEBUG: Checking device mapping\n", + runtime_header + "RESULTS: UNKNOWN\n", {"passed": 1, "failed": 0}) + + # DT checks three separate OS directories. Corrupt only the final OS for + # partial-input cases, retaining passed neighbours to catch hidden omissions. + os_header = "****************************************************************\nRunning ethtool\n****************************************************************\n" + os_start = (os_header + "INFO: Detected following ethernet interfaces via ip command :\n" + "0: eth0\n\n" + "INFO: Bringing up ethernet interface: eth0\n" + "INFO: Ethernet interface eth0 supports ethtool self test.\n") + os_complete = (os_start + "The test result is PASS\n" + "INFO: Ping to router/gateway[192.0.2.1] for eth0 is successful\n" + "INFO: Ping to www.arm.com is successful\n") + os_paths = ["../os-logs/" + name + "/ethtool_test.log" + for name in ("linux-Fedora-40", "linux-ubuntu-24", "linux-Tumbleweed")] + os_good = dict.fromkeys(os_paths, os_complete) + add("DT", "OS-TESTS", None, os_good, dict.fromkeys(os_paths, os_header), + {**os_good, os_paths[-1]: os_start}, + {**os_good, os_paths[-1]: os_start + "The test result is UNKNOWN\n"}, + {"passed": 15, "failed": 0}) + + # SR's mandatory OS check reads /etc/os-release, not DT's ethtool format. + release_rhel = "../os-logs/rhel/cat-etc-os-release.txt" + release_sle = "../os-logs/sle/cat-etc-os-release.txt" + sr_good = {release_rhel: 'NAME="Red Hat Enterprise Linux"\nVERSION_ID="9.3"\n', + release_sle: 'NAME="SLES"\nVERSION_ID="15"\n', + "post-script/post-script.log": "INFO : OS log validation completed\n"} + add("SR", "OS-TESTS", None, sr_good, + {name: "# OS log capture started\n" for name in sr_good}, + {**sr_good, release_sle: 'NAME="SLES"\nVERSION_ID='}, + {**sr_good, release_sle: 'NAME: "SLES"\nVERSION_ID: "15"\n'}, + {"passed": 2, "failed": 0}) + + pcie_header = ("PcieOptionRomArchAudit: report all live PCIe devices and classify option ROM contents\n") + pcie = (pcie_header + "Scanned 3 EFI_PCI_IO handles and found 1 PCIe devices with Option ROM images:\n" + "PCIe devices with ROM : 1\nNon-compliant devices : 0\n" + "BBR (UEFI 6.3.3.1 UEFI Drivers) Result Summary: FAIL\n") + add("SR", "PCIE-OPTION-ROM-ARCH-AUDIT", "uefi_dump/PcieOptionRomArchAudit.log", pcie, + pcie_header, pcie.split("Non-compliant devices", 1)[0], + pcie.replace("Non-compliant devices : 0", "Non-compliant devices : invalid"), + {"passed": 1, "failed": 0}) + return jobs + + +def waiver_probe(ctx, registry, suite, relative, content, waiver, name, expected, html_available=True): + """Compare the same log before and after its waiver, including exact counts.""" + baseline = invoke(ctx, registry, "DT", suite, name + "-unwaived", {relative: content}) + expected_base = expected[0] + if baseline["exit"] or any(baseline["counts"][key] != value + for key, value in expected_base.items()): + record(ctx, "waiver." + name, "BLOCKED", + "The unwaived native-log control did not establish this waiver case.", + str(expected_base), baseline, "DT", suite) + return + result = invoke(ctx, registry, "DT", suite, name, {relative: content}, waiver) + desired = expected[1] + okay = (result["exit"] == 0 and all(result["counts"][key] == value + for key, value in desired.items())) + if okay: + okay = green(result["status"]) + verdict = "PASS" if okay else "BLOCKED" if result["exit"] in (3, 4) else "FAIL" + record(ctx, "waiver." + name, verdict, expected[2], + str(desired) + "; Compliant in merged JSON", result, "DT", suite) + record_html(ctx, result, "DT", suite, name, html_available) + + +def waiver_idempotence(ctx, registry, html_available=True): + """Check that applying the same waiver twice does not change results again.""" + waiver = {"Suites": [{"Suite": "FWTS", "Reason": "Synthetic doctor idempotence waiver"}]} + first = invoke(ctx, registry, "DT", "FWTS", "waiver-idempotence", + {"fwts/FWTSResults.log": fwts_log(failed=1)}, waiver) + established = (first["exit"] == 0 and first["counts"]["failed"] == 0 + and first["counts"]["failed_with_waiver"] == 1 + and green(first["status"])) + record_html(ctx, first, "DT", "FWTS", "Waiver idempotence control", html_available) + if not established: + record(ctx, "waiver.idempotence", "BLOCKED", + "A valid one-failure waiver must work before repeat application can be checked.", + "One waived failure; zero remaining failures", first, "DT", "FWTS") + return + folder = Path(first["folder"]) + raw = folder / "output/acs_jsons/fwts.json" + second = folder / "second-application.json" + shutil.copy2(raw, second) + result = ctx.run([ctx.python, "-B", ctx.parser_dir / "apply_waivers.py", + "FWTS", second, folder / "waiver.json", + ctx.parser_dir / "test_categoryDT.json", "--quiet"], + folder, "second-application") + after = counts(json.loads(second.read_text())) + ctx.add("waiver.idempotence", "PASS" if result.returncode == 0 + and after == first["counts"] else "FAIL", + "Applying an identical waiver twice must not change totals or invent another waived result.", + str(first["counts"]), f"exit={result.returncode}; second counts={after}", + mode="DT", suite="FWTS", evidence=[raw, second, folder / "second-application.log"]) + + +def stale_rerun(ctx, registry, html_available=True, suite="BSA"): + """Compare a reused output folder with a fresh run after its log is removed.""" + mode = "DT" if Path("/mnt/yocto_image.flag").is_file() else "SR" + if mode not in ctx.modes: + ctx.add("normal.stale-rerun", "BLOCKED", + "The normal wrapper selects its mode using the host Yocto flag; doctor will not change it.", + "Normal rerun in a requested mode", "Host mode is " + mode, + mode=mode, suite=suite) + return + folder = ctx.case_dir("raw/normal-stale-" + mode + "-" + suite) + acs, system = config_files(folder, mode) + inputs = folder / "input" / "acs_results" + relative, content = { + "BSA": ("uefi/BsaResults.log", bsa_log()), + "FWTS": ("fwts/FWTSResults.log", fwts_log()), + "SCT": ("sct_results/Overall/Summary.log", sct_log("SCT")), + }[suite] + log_path = inputs / relative + write_text(log_path, content) + command = ["bash", ctx.parser_dir / "main_log_parser.sh", inputs, acs, system, ""] + first = ctx.run(command, folder, "first") + output = inputs / "acs_summary" + baseline = observe(registry, mode, suite, output, folder / "first", first) + baseline["evidence"] = [folder / "first.log", folder / "first.command.json", *baseline["evidence"]] + record_html(ctx, baseline, mode, suite, "Normal rerun control", html_available) + if not control_ok(baseline, require_html=False): + record(ctx, "normal.stale-rerun", "BLOCKED", + "Normal wrapper positive control failed; stale-result behavior is untested.", + "A fresh passed " + suite + " report", baseline, mode, suite) + return + # Preserve the first report, remove only our sample log, then rerun into the + # same folder. A separate fresh run gives the expected missing-log result. + shutil.copytree(output, folder / "first-report") + # Move only the fixture created here. Never alter user logs or the host flag. + log_path.rename(folder / "saved-input.log") + second = ctx.run(command, folder, "missing-rerun") + rerun = observe(registry, mode, suite, output, folder / "rerun", second) + fresh = folder / "fresh" / "acs_results" + fresh.mkdir(parents=True) + third = ctx.run(["bash", ctx.parser_dir / "main_log_parser.sh", fresh, acs, system, ""], + folder, "fresh-missing") + clean = observe(registry, mode, suite, fresh / "acs_summary", folder / "fresh", third) + valid = clean["status"] is not None and "not run" in str(clean["status"]).lower() + rerun_missing = rerun["status"] is not None and "not run" in str(rerun["status"]).lower() + verdict = ("BLOCKED" if not valid else "PASS" if rerun_missing and second.returncode == 0 else "FAIL") + ctx.add("normal.stale-rerun", verdict, + "Removing the " + suite + " raw log must not reuse the previous run's Compliant JSON.", + "Rerun and fresh missing-input run both show " + suite + " Not Run", + f"first={baseline['status']!r}; rerun={rerun['status']!r}; fresh={clean['status']!r}", + mode=mode, suite=suite, evidence=[folder / "first.log", folder / "missing-rerun.log", + folder / "fresh-missing.log", + folder / "first-report/acs_jsons/merged_results.json", + output / "acs_jsons/merged_results.json", + fresh / "acs_summary/acs_jsons/merged_results.json"]) + + +def conditional_execution_records(suite, text): + """Read completed tests in these small controls, not banners or JSON presence. + + This is deliberately limited to the conditional-rule fixture formats below, + not a replacement parser for arbitrary partner logs. Unknown and skip-only + records do not prove completion here; their policy is checked separately. + """ + if suite in ("SBSA", "PFDI"): + heading = "PE" if suite == "SBSA" else "PFDI" + if f"*** Running {heading} tests ***" not in text: + return [] + rule = r"S_[A-Z0-9_]+" if suite == "SBSA" else r"R[0-9]{4}" + return [(f"{name} : {number}", description.strip(), result) + for name, number, description, result in re.findall( + rf"(?m)^[ \t]*({rule}) : ([0-9]+) : ([^\r\n]+)\r?\n" + r"[ \t]*Result:[ \t]+(PASSED|FAILED)[ \t]*\r?$", text)] + if suite not in ("SBMR-IB", "SBMR-OOB"): + return [] + try: + root = ElementTree.fromstring(text) + except ElementTree.ParseError: + return [] + if root.tag != "robot": + return [] + records = [] + for test in root.iter("test"): + # A keyword or suite can say NOT RUN while its enclosing test ran. + # Only the direct test status belongs to that test. + terminal = test.find("status") + result = terminal.get("status") if terminal is not None else None + name = (test.get("name") or "").strip() + if name and result in ("PASS", "FAIL"): + records.append((name, "PASSED" if result == "PASS" else "FAILED")) + return records + + +def conditional_execution_cases(modes): + """Replay source-backed result records; these are not hardware test runs.""" + # Rule IDs/descriptions and their PASSED results were checked in FR_SBSA.log + # and acs_results_templat_perfect/acs_results/uefi/pfdiresults.log. The grammar + # and IDs also match sysarch-acs 4fdfb75e, val/src/rule_based_execution_helpers.c + # and val/src/rule_metadata.c. Only the relevant records are replayed. + cases = [ + ("SR", "SBSA", "uefi/SbsaResults.log", + "*** Running PE tests ***\n" + "S_L3PE_01 : 23 : Check PE Granule Support\n Result: PASSED\n" + "S_L3PE_02 : 24 : Check for 16-bit ASID support\n Result: PASSED\n", + "Captured SBSA rule/result excerpt; producer grammar checked at sysarch-acs 4fdfb75e."), + ("DT", "PFDI", "uefi/pfdiresults.log", + "*** Running PFDI tests ***\n" + "R0040 : 11 : Check if X5 to X17 are preserved\n Result: PASSED\n" + "R0053 : 1 : Check PFDI Version is returned\n Result: PASSED\n", + "Captured PFDI rule/result excerpt; producer grammar checked at sysarch-acs 4fdfb75e."), + ] + # Robot test names and direct-status layout were checked against saved XML + # and sbmr-acs 35c333f3/70d0a581. IB retains a captured PASS. OOB deliberately + # substitutes PASS for a captured setup FAIL: it is a positive replay, not + # evidence that this OOB hardware test passed or its original body executed. + for interface, folder, category, name in ( + ("IB", "in", "Test Ipmi Shell Inband Interface Check", + "Test Host IPMI Inband Interface Functionality"), + ("OOB", "out_of", "Test Ipmi Outband Boot Select", + "Test IPMI Out-of-Band Boot Device Selection")): + content = (f'' + f'' + '') + cases.append(("SR", "SBMR-" + interface, + f"sbmr/sbmr_{folder}_band_logs/output.xml", content, + "Source-backed Robot identity/layout; " + + ("captured direct test PASS." if interface == "IB" else + "controlled PASS mutation of a captured OOB setup FAIL, not a hardware result."))) + return [case for case in cases if case[0] in modes] + + +def conditional_raw_expectation(suite, records): + """Require exact native result identities and counts before losing the JSON.""" + expected = [] + for index, record in enumerate(records): + if suite in ("SBSA", "PFDI"): + name, description, result = record + path = ["test_results", 0, "testcases", index] + fields = {"Test_case": name, "Test_case_description": description, "Test_result": result} + else: + description, result = record + path = ["test_results", 0, "Test_cases", 0, "subtests", index] + fields = {"sub_Test_Number": str(index + 1), "sub_Test_Description": description, + "sub_test_result": result} + expected.append({"path": path, "fields": fields}) + passed = sum(record[-1] == "PASSED" for record in records) + failed = sum(record[-1] == "FAILED" for record in records) + if suite in ("SBSA", "PFDI"): + summary = {"Total Rules Run": len(records), "Passed": passed, "Failed": failed, + "Total_failed_with_waiver": 0, "Skipped": 0, "Warnings": 0, + "Passed (Partial)": 0, "PAL Not Supported": 0, "Not Implemented": 0} + else: + summary = {**dict.fromkeys(("total_" + key for key in counts({})), 0), + "total_passed": passed, "total_failed": failed} + return {"records": expected, "assertions": [ + {"path": ["suite_summary", key], "value": value} for key, value in summary.items()]} + + +def run_conditional_execution(ctx, registry): + """Check the log-to-merge boundary when executed results are unavailable. + + Keep the successful raw-log control intact and omit its JSON only from a + separate merge command. The current merger sees JSON, not source logs; a + mismatch identifies a pipeline evidence gap, not a raw parser repair. + """ + from .merge import differences, expected_leaves, merged_records, oracle, payload, status + + leaves = expected_leaves(list(registry.values())) + for mode, suite, relative, content, provenance in conditional_execution_cases(ctx.modes): + folder = ctx.case_dir("conditional/" + mode + "/" + suite) + try: + records = conditional_execution_records(suite, content) + control = invoke(ctx, registry, mode, suite, "conditional-control", {relative: content}) + issues = raw_issues(control["raw"], conditional_raw_expectation(suite, records)) + valid = bool(records) and control["exit"] == 0 and not control["traceback"] and not issues + source = Path(control["folder"]) / "input" / "acs_results" / relative + evidence = [source, *control["evidence"]] + ctx.add("raw.conditional-control", "PASS" if valid else "BLOCKED", + "Known executed tests must retain their exact identities and results before JSON is withheld.", + records, issues or brief(control), mode, suite, evidence) + if not valid: + ctx.add("raw.conditional-execution", "BLOCKED", + "Cannot verify conditional requirements without a working native execution control.", + "Verified native execution before the missing-JSON probe", issues or brief(control), + mode, suite, evidence) + continue + + affected = {"SBMR-IB", "SBMR-OOB"} if suite.startswith("SBMR-") else {suite} + states = {item["canonical"]: "missing" if item["canonical"] in affected else "pass" + for item in leaves if mode in item["modes"]} + # Other suites get passing semantic JSON so their failures cannot + # mask this defect. Neither SBMR peer JSON is present in its probe. + executed = {name for name, state in states.items() if state == "pass"} | {suite} + expected, overall = oracle(leaves, mode, states, executed=executed) + info = folder / "acs_info.json" + write_text(info, json.dumps({"ACS Results Summary": {"Band": + "SystemReady Devicetree band" if mode == "DT" else "SystemReady band"}})) + paths = [info] + for item in leaves: + name = item["canonical"] + if states.get(name) == "pass": + path = folder / item["json_output"] + write_text(path, json.dumps(payload(name, "pass"))) + paths.append(path) + scenario = {"mode": mode, "executed_suite": suite, "provenance": provenance, + "raw_records": records, "withheld_json": registry[suite]["json_output"], + "expected_suites": expected, "expected_overall": overall, + "scope": "Controlled direct-merger JSON omission, not observed routine JSON loss. " + "Normal-flow conversion failure is not exercised here. Standalone validates " + "generated JSON before publishing; this probe bypasses that safeguard. " + "Other suites use passing semantic fixtures; original control is unchanged."} + write_text(folder / "scenario.json", json.dumps(scenario, indent=2)) + # Verify the same full-run baseline first. An unrelated failure in + # these supporting fixtures must not be blamed on losing this JSON. + native_path = Path(control["folder"]) / "output" / "acs_jsons" / registry[suite]["json_output"] + baseline_path = folder / "baseline_merged_results.json" + baseline = ctx.run([ctx.python, "-B", ctx.parser_dir / "merge_jsons.py", "--mode", mode, + baseline_path, *paths, native_path], folder, "merge-baseline") + evidence.extend([folder / "scenario.json", folder / "merge-baseline.log", + folder / "merge-baseline.command.json", baseline_path]) + if baseline.returncode or not baseline_path.is_file(): + baseline_issue = command_diagnostic(baseline) + else: + baseline_rows, baseline_summary = merged_records(load_json(baseline_path), leaves, mode) + baseline_expected, baseline_overall = oracle(leaves, mode, {**states, suite: "pass"}, + executed=executed) + baseline_issue = differences(baseline_expected, baseline_rows) + if status(baseline_summary["Overall Compliance Result"], overall=True) != baseline_overall: + baseline_issue = {**baseline_issue, "overall": baseline_summary["Overall Compliance Result"]} + if baseline_issue: + ctx.add("raw.conditional-execution", "BLOCKED", + "Full-run control already differs before JSON is withheld; conditional loss was not isolated.", + "Same supporting inputs and real native JSON match the independent baseline", + baseline_issue, mode, suite, evidence) + continue + destination = folder / "merged_results.json" + process = ctx.run([ctx.python, "-B", ctx.parser_dir / "merge_jsons.py", "--mode", mode, + destination, *paths], folder, "merge-withheld-json") + evidence.extend([folder / "scenario.json", folder / "merge-withheld-json.log", + folder / "merge-withheld-json.command.json", destination]) + if process.returncode or not destination.is_file(): + ctx.add("raw.conditional-execution", "BLOCKED", + "Missing-JSON probe did not publish inspectable compliance decisions.", + "Retained conditional requirement and non-green result, or an explicit missing-result diagnostic", + command_diagnostic(process), mode, suite, evidence) + continue + actual, summary = merged_records(load_json(destination), leaves, mode) + changes = differences(expected, actual) + actual_overall = status(summary["Overall Compliance Result"], overall=True) + unrelated = set(changes) - affected + observation = {"suite_differences": changes, "actual_suites": actual, + "actual_overall": actual_overall, "expected_overall": overall} + write_text(folder / "observed.json", json.dumps(observation, indent=2)) + evidence.append(folder / "observed.json") + ctx.add("raw.conditional-execution", "BLOCKED" if unrelated else + "WARN" if changes or actual_overall != overall else "PASS", + "Unrelated suite decisions changed; conditional loss was not isolated." if unrelated else + "Conditional execution evidence must reach the merger; JSON-only omission cannot establish no execution.", + "Executed " + suite + "; results missing, not proof of no execution. " + + str({name: expected[name] for name in sorted(affected)}) + "; overall=" + overall, + str({name: actual.get(name, "missing") for name in sorted(affected)}) + + "; overall=" + actual_overall + "; all suite differences=" + str(changes) + + "; direct-merger boundary check only; normal-flow conversion failure not tested here", + mode, suite, evidence) + except (OSError, ValueError, RuntimeError, KeyError, TypeError) as error: + ctx.add("raw.conditional-execution", "BLOCKED", + "Conditional execution evidence could not be verified.", + "Source-backed control and an isolated missing-JSON merge", + str(error), mode, suite, (folder,)) + + +def run_raw(ctx): + """Run bad-input, waiver and rerun checks and keep all reproduction evidence.""" + registry = {item["canonical"]: item for item in json.loads( + (ctx.parser_dir / "suite_registry.json").read_text())["suites"]} + run_conditional_execution(ctx, registry) + html_available = html_capability(ctx) + jobs = [] + for mode in ctx.modes: + for suite in ("BSA", "SBSA", "FWTS", "SCT", "BBSR-FWTS", "BBSR-SCT", "BBSR-TPM"): + if mode not in registry[suite]["modes"]: + continue + if suite in ("BSA", "SBSA"): + relative = "uefi/" + ("BsaResults.log" if suite == "BSA" else "SbsaResults.log") + good, header = bsa_log(suite), f" {suite} Architecture Compliance Suite\n" + elif "FWTS" in suite: + relative = ("bbsr/" if suite.startswith("BBSR") else "") + "fwts/FWTSResults.log" + good, header = fwts_log(suite), "Results generated by fwts: Version V26.01.00.\n" + elif "SCT" in suite: + relative = ("bbsr/" if suite.startswith("BBSR") else "") + "sct_results/Overall/Summary.log" + good, header = sct_log(suite), "BBR ACS 2.1.1 (SBBR)\n" + else: + relative = "bbsr/tpm2/verify_tpm_measurements.log" + good, header = "Verify synthetic TPM measurement : PASS\n", "Capture ended before TPM results\n" + malformed = [("empty-log", "", ""), ("header-only", header, "")] + if "FWTS" in suite: + truncated = good.split("\n" + "=" * 80 + "\n", 1)[0] + truncated = truncated.replace("Test 1 of 1:", "Test 1 of 2:") + malformed.append(("truncated-final-subtest", + truncated + "\nTest 2 of 2: Unfinished final check.\n", "")) + jobs.append((mode, suite, relative, good, malformed)) + if "SR" in ctx.modes: + for suite, interface in (("SBMR-IB", "in"), ("SBMR-OOB", "out_of")): + jobs.append(("SR", suite, f"sbmr/sbmr_{interface}_band_logs/output.xml", robot_log(), + [("missing-status", robot_log(None), ""), + ("unknown-status", robot_log("UNKNOWN"), "")])) + if "DT" in ctx.modes: + jobs.extend([ + ("DT", "ETHTOOL-TEST", "linux_tools/ethtool-test.log", + "Running Networking Checks\nSUMMARY\nDetected Interfaces : 1 (eth0)\nInterface eth0\nBring up : PASSED\nEthtool Compliance : PASSED\n", + [("header-only", "Running Networking Checks\n", "")]), + ("DT", "READ-WRITE-CHECK-BLK-DEVICES", "linux_tools/read_write_check_blk_devices.log", + "Read block devices tool\nINFO: Block device : /dev/sda\nINFO: No valid partition table found for sda, treating as raw device.\nINFO: Performing block read on /dev/sda\nINFO: Block read on /dev/sda successful\n", + [("header-only", "Read block devices tool\n", "")]), + ("DT", "CAPSULE-UPDATE", "../fw/capsule_test_results.log", + "Testing ESRT FW version update\nINFO: Synthetic ESRT check\nRESULTS: Overall Capsule Update Result: PASSED\n", + [("missing-terminal-result", "Testing ESRT FW version update\nINFO: Synthetic ESRT check\n", "")]), + ("DT", "DT-VALIDATE", "linux_tools/dt-validate-parser.log", + "DeviceTree bindings of Linux kernel version 6.19\nINFO parse: 0 entries\nNon-ignored entries\n-------------------\n", + [("completion-evidence", "", "An empty DT validation log is accepted without completion evidence; quiet completed validation is a separate valid control. Producer completion policy needs confirmation.")]), + ]) + jobs.extend(additional_raw_jobs(ctx.modes)) + + def execute(job): + mode, suite = job[:2] + try: + evaluated = family(ctx, registry, *job, html_available=html_available) + except (OSError, ValueError, RuntimeError, KeyError) as error: + ctx.add("raw.probe-blocked", "BLOCKED", "Raw probe could not complete.", + "Executed native-log positive and negative controls", str(error), mode=mode, suite=suite) + evaluated = set() + return mode, suite, evaluated + + with ThreadPoolExecutor(max_workers=2) as pool: + # Each job owns a separate folder, so two parser runs cannot share logs. + attempted = list(pool.map(execute, jobs)) + for mode in ctx.modes: + # A scheduled job or a waiver check is not bad-input coverage. List each + # missing category, including cases blocked by a failed complete control. + aliases = {"truncated-final-subtest": "truncated-log", "missing-terminal-result": "truncated-log", + "missing-status": "truncated-log", "unknown-status": "malformed-log", + "completion-evidence": "empty-log"} + categories = {"empty-log", "header-only", "truncated-log", "malformed-log"} + observed = {suite: {aliases.get(name, name) for name in evaluated} + for case_mode, suite, evaluated in attempted if case_mode == mode} + missing = [suite + ": " + ", ".join(sorted(categories - observed.get(suite, set()))) + for suite, item in sorted(registry.items()) + if mode in item["modes"] and item.get("logs_to_json") + and categories - observed.get(suite, set())] + if missing: + ctx.add("raw.coverage", "WARN", + "Some bad-input categories were not evaluated; declared or blocked probes do not count as coverage.", + "A working complete control, then empty, introductory, truncated and malformed checks per route", + "; ".join(missing), mode=mode) + if "DT" in ctx.modes: + suite_waiver = {"Suites": [{"Suite": "FWTS", "Reason": "Synthetic whole-suite doctor waiver"}]} + checks = [ + ("FWTS", "fwts/FWTSResults.log", fwts_log(failed=2), suite_waiver, + "whole-suite-multiple-assertions", + ({"failed": 2}, {"failed": 0, "failed_with_waiver": 2}, + "A whole-suite waiver must cover both failed FWTS assertions, not just one.")), + ("DT-KSELFTEST", "linux_tools/dt_kselftest.log", + "selftests: dt: test_unprobed_devices.sh\n# ok 1 synthetic passing device check\n", + {"Suites": [{"Suite": "Standalone", "TestSuites": [{"TestCase": {"SubTests": [ + {"sub_Test_Description": "synthetic passing device check", "Reason": "Synthetic doctor waiver"}]}}]}]}, + "passed-test-matching-waiver", + ({"passed": 1, "failed": 0}, {"passed": 1, "failed": 0, "failed_with_waiver": 0}, + "A waiver matching an already-passed test must not invent a waived failure.")), + ("RUNTIME-DEV-MAP", "linux_tools/runtime_device_mapping_conflict_test.log", + "Testing Runtime Device Mapping Conflict Test\nDEBUG: Synthetic mapping conflict\nRESULTS: FAILED\n", + {"Suites": [{"Suite": "Standalone", "Reason": "Synthetic whole-suite doctor waiver"}]}, + "runtime-map-whole-suite", + ({"failed": 1}, {"failed": 0, "failed_with_waiver": 1}, + "A valid Runtime Device Map whole-suite waiver must not crash on nested failure reasons.")), + ("DT-KSELFTEST", "linux_tools/dt_kselftest.log", + "selftests: dt: test_unprobed_devices.sh\n# ok 1 synthetic passing device check\n", + {"Suites": [{"Suite": "Standalone", "TestSuites": [{"TestCase": {"SubTests": [ + {"sub_Test_Description": "another test that was not run", "Reason": "Synthetic unmatched waiver"}]}}]}]}, + "unmatched-waiver", + ({"passed": 1, "failed": 0}, {"passed": 1, "failed": 0, "failed_with_waiver": 0}, + "An unmatched waiver must leave the actual passed result unchanged.")), + ] + for args in checks: + try: + waiver_probe(ctx, registry, *args, html_available=html_available) + except (OSError, ValueError, RuntimeError, KeyError) as error: + ctx.add("waiver.probe-blocked", "BLOCKED", "Waiver probe could not complete.", + "Executed before/after waiver comparison", str(error), mode="DT", suite=args[0]) + try: + waiver_idempotence(ctx, registry, html_available=html_available) + except (OSError, ValueError, RuntimeError, KeyError) as error: + ctx.add("waiver.idempotence", "BLOCKED", "Repeated-waiver probe could not complete.", + "Apply the same valid waiver twice without changing counts", str(error), mode="DT", suite="FWTS") + for suite in ("BSA", "FWTS", "SCT"): + try: + stale_rerun(ctx, registry, html_available=html_available, suite=suite) + except (OSError, ValueError, RuntimeError, KeyError) as error: + ctx.add("normal.stale-rerun", "BLOCKED", "Normal rerun probe could not complete.", + "Fresh, missing-input rerun and clean missing-input comparison", str(error), suite=suite) diff --git a/common/log_parser/doctor_checks/report.py b/common/log_parser/doctor_checks/report.py new file mode 100644 index 00000000..87077e91 --- /dev/null +++ b/common/log_parser/doctor_checks/report.py @@ -0,0 +1,1478 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026, Arm Limited or its affiliates. All rights reserved. +# SPDX-License-Identifier : Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Turn recorded Doctor findings into an easy-to-read, self-contained HTML page. + +The input is the completed checks and run details. The output is HTML with plain +explanations, filters and evidence links. This file does not run checks, read +evidence files or change their results. CSS and browser controls are kept here so +the report can be opened without downloading extra assets. +""" + +from collections import Counter, defaultdict +from collections.abc import Mapping +from datetime import datetime, timezone +from html import escape +from pathlib import Path +import json +import re +from urllib.parse import quote +import ast + + +# These helpers explain existing findings. They return text, not new verdicts. +# The HTML renderer below escapes that text before placing it on the page. + +SCHEMA_CHECKS = frozenset({"NATIVE_RAW_SCHEMA", "ARTIFACT.SCHEMA"}) +STATUS_CHECKS = frozenset({"raw.missing-status", "raw.unknown-status"}) +CATEGORY_PROVENANCE_CHECKS = frozenset( + {"NATIVE_CATEGORY_PROVENANCE", "ARTIFACT.CATEGORY_PROVENANCE"}) +SBMR_SUITES = frozenset({"SBMR", "SBMR-IB", "SBMR-OOB"}) + + +def _text(item, name): + """Read text from either a finding object or a saved finding dictionary.""" + value = item.get(name, "") if isinstance(item, Mapping) else getattr(item, name, "") + return "" if value is None else str(value) + + +def _description(title, happened, impact, next_step, category="issues"): + return dict(title=title, happened=happened, impact=impact, + next_step=next_step, category=category) + + +def _short(text, limit=260): + text = " ".join(text.split()) + return text if len(text) <= limit else text[:limit - 1].rstrip() + "…" + + +def _literal(text): + """Read small recorded dictionaries as data; never execute their contents.""" + if not text or len(text) > 100000: + return None + try: + tree = ast.parse(text, mode="eval") + if sum(1 for _ in ast.walk(tree)) > 5000: + return None + return ast.literal_eval(tree) + except (ValueError, TypeError, SyntaxError, RecursionError, MemoryError): + return None + + +def _label(value): + """Translate Doctor's saved status names without deciding compliance again.""" + labels = {"not_run": "Not Run", "not_compliant": "Not Compliant", + "compliant": "Compliant", "waived": "Compliant with waivers"} + if isinstance(value, Mapping): + requirement = str(value.get("requirement", "")) + result = _label(value.get("status", "Not recorded")) + return requirement + " (" + result + ")" if requirement else result + if value is None: + return "Missing" + return labels.get(str(value), str(value)) + + +def _comparisons(item): + """Turn the known JSON/HTML mismatch shapes into readable comparison rows.""" + identifier = _text(item, "check_id") + actual = _literal(_text(item, "actual")) + rows = [] + if identifier == "HTML_COMPLIANCE_MATCH" and isinstance(actual, Mapping): + badges, tables = actual.get("badges"), actual.get("tables") + for name, difference in (badges.items() if isinstance(badges, Mapping) else ()): + if isinstance(difference, Mapping): + rows.append(("Summary card · " + str(name), _label(difference.get("expected")), + _label(difference.get("actual")))) + for page, difference in (tables.items() if isinstance(tables, Mapping) else ()): + if not isinstance(difference, Mapping): + continue + def table_rows(value): + return Counter(tuple(map(str, row)) for row in value + if isinstance(row, (tuple, list)) and len(row) == 3) + expected = table_rows(difference["expected"]) if isinstance( + difference.get("expected"), list) else Counter() + observed = table_rows(difference["actual"]) if isinstance( + difference.get("actual"), list) else Counter() + # Matching rows are noise here. Keep repeated missing/extra rows, + # and pair changed rows by name so the exact difference is visible. + missing, extra = defaultdict(list), defaultdict(list) + for source, target in ((expected - observed, missing), (observed - expected, extra)): + for name, requirement, result in source.elements(): + target[name].append(requirement + " (" + result + ")") + for name in sorted(missing.keys() | extra.keys()): + for index in range(max(len(missing[name]), len(extra[name]))): + rows.append((str(page) + " · " + name, + missing[name][index] if index < len(missing[name]) else "No row expected", + extra[name][index] if index < len(extra[name]) else "Row missing")) + elif identifier in {"MERGE_INCOMPLETE_NOT_GREEN", "MERGE_SUITE_STATUS"}: + expected = _literal(_text(item, "expected")) + if isinstance(expected, Mapping) and isinstance(actual, Mapping): + for name in expected.keys() | actual.keys(): + rows.append(("Merged JSON · " + str(name), + _label(expected.get(name)), _label(actual.get(name)))) + elif identifier in {"MERGE_OVERALL_POLICY", "MERGE_EXTENSION_AGGREGATION"}: + rows.append(("Overall SRS" if identifier == "MERGE_OVERALL_POLICY" else "BBSR extension", + _label(_text(item, "expected")), _label(_text(item, "actual")))) + return sorted(rows) + + +def _scenario(item): + """Explain generated case names, so a reader knows what input was tested.""" + case = _text(item, "issue").split(":", 1)[0] + states = {"pass": "all its tests pass", "fail": "has an unwaived failure", + "mixed": "has one waived failure and one unwaived failure", + "waived": "all its failures are waived", "missing": "its result file is missing", + "empty": "its JSON has no test outcomes", "header": "its JSON has only a suite heading", + "recommended_fail": "has a failed group marked Recommended"} + for prefix, scope in (("full_", "Full run"), ("selected_", "Selected-suite run")): + if case.startswith(prefix): + for state in sorted(states, key=len, reverse=True): + suffix = "_" + state + if case.endswith(suffix): + name = case[len(prefix):-len(suffix)] + return scope + ": " + name + " — " + states[state] + ( + "; other suites pass." if prefix == "full_" else ".") + if case.startswith("requirement_"): + parts = case.split("_", 2) + if len(parts) == 3: + requirements = {"M": "Mandatory", "R": "Recommended", "CM": "Conditional-Mandatory", + "EM": "Extension"} + return "FWTS classified as " + requirements.get(parts[1], parts[1]) + ": " + states.get(parts[2], parts[2]) + "." + if case.startswith("recommended_group_"): + return "Full run: " + case[len("recommended_group_"):] + " has a failed group marked Recommended; other suites pass." + match = re.fullmatch(r"SBMR_IB_(\w+)_OOB_(\w+)", case) + if match: + return "SBMR-IB: " + states.get(match[1], match[1]) + "; SBMR-OOB: " + states.get(match[2], match[2]) + "." + if case.startswith("BBSR_") and len(case.split("_")) == 4: + return "; ".join(name + ": " + states.get(state, state) + for name, state in zip(("BBSR-FWTS", "BBSR-SCT", "BBSR-TPM"), case.split("_")[1:])) + "." + return "" + + +def _probe_counts(item): + match = re.search(r"(?:^|;\s*)raw counts=(\{[^;\n]*\})", _text(item, "actual")) + result = _literal(match[1]) if match else None + return result if isinstance(result, Mapping) else {} + + +def _count_label(counts): + names = {"passed": "passed", "failed": "failed", "failed_with_waiver": "waived", + "aborted": "aborted", "skipped": "skipped", "warnings": "warnings", "ignored": "ignored"} + return ", ".join(str(counts[key]) + " " + label for key, label in names.items() + if key in counts and (key in {"passed", "failed", "failed_with_waiver"} or counts[key])) + + +def _probe_result(item): + """Explain exits, counts and report statuses without calling a rejection a pass.""" + code, fields = _observation(item) + parts = [] + error = re.search(r"\b([A-Za-z]+Error):\s*([^\n;]*)", _text(item, "actual")) + if error: + parts.append("The parser stopped with " + error[1] + ": " + error[2]) + elif _no_report(item): + parts.append("The parser stopped with exit code " + + str(code) + " and produced no compliance report") + elif code is not None and code != 0: + parts.append("The parser exited with code " + str(code)) + counts = _count_label(_probe_counts(item)) + if counts: + parts.append("Generated results: " + counts) + for key, label in (("merged", "Merged JSON"), ("HTML", "HTML")): + if key in fields and fields[key] is not None and fields[key] != "None": + parts.append(label + " says " + str(_status_value(fields[key]))) + return ". ".join(parts) + "." if parts else _short(_text(item, "actual")) + + +def _observation(item): + """Read only the fixed scalar fields emitted by doctor_probes.brief. + + Unknown or repeated fields remain unknown. In particular, raw-count maps + and arbitrary status strings are never evaluated as Python expressions. + """ + fields = {} + for match in re.finditer(r"(?:^|;\s*)(exit|merged|HTML)\s*=\s*([^;\n]*)", + _text(item, "actual")): + key, value = match.groups() + value = value.strip() + if key in fields: + fields[key] = None + else: + fields[key] = value + code = fields.get("exit") + code = int(code) if code is not None and re.fullmatch(r"-?\d{1,9}", code) else None + return code, fields + + +def _no_report(item): + code, fields = _observation(item) + return code is not None and code != 0 and fields.get("merged") == "None" and fields.get("HTML") == "None" + + +def _status_value(value): + if value is None: + return None + if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}: + return value[1:-1] + return value + + +def _has_compliant(item): + _, fields = _observation(item) + return any((_status_value(fields.get(key)) or "").strip().casefold() == "compliant" + for key in ("merged", "HTML")) + + +def _raw_description(items): + """Explain status checks without confusing a stopped run with a green report.""" + sbmr = bool(items) and all(_text(item, "suite") in SBMR_SUITES for item in items) + subject = "SBMR" if sbmr else "Test" + if items and all(_no_report(item) for item in items): + return _description( + subject + " status cases did not produce a completed report", + "Runs with missing or unrecognized test statuses exited with an error. " + "No completed merged result or HTML status was recorded in these cases.", + "This is not evidence of a completed report incorrectly marked Compliant. " + "The original Doctor findings still require investigation.", + "Inspect the parser log and raw result for each case. Check why status handling " + "stopped the run instead of meeting the recorded expected outcome.") + if any(_has_compliant(item) for item in items): + return _description( + subject + " tests with missing or UNKNOWN statuses can produce a Compliant result", + "At least one missing- or unrecognized-status case recorded Compliant in merged JSON " + "or HTML. Other cases may have different outcomes.", + "Incomplete status evidence may be presented as compliant. Inspect each observation; " + "do not assume that all cases completed or had the same result.", + "Trace the affected raw status through the parser and merger. Compare the observed " + "result with the expected rejection or non-green outcome.") + return _description( + subject + " status handling needs investigation", + "Doctor checked how missing or unrecognized test statuses are handled. " + "The individual observations below show the recorded outcomes.", + "A status-handling finding does not by itself prove that a report was incorrectly marked " + "Compliant. Stopped runs and completed reports must be reviewed separately.", + "Compare each exit code and merged/HTML status with its expected outcome, then inspect " + "the linked parser log.") + + +def _coverage_description(items): + """Explain what was not checked without calling it a confirmed parser defect.""" + actual = "\n".join(_text(item, "actual") for item in items) + charts = "aggregate/unmapped chart" in actual + external = "link outside supplied package not inspected" in actual + if charts and not external: + return _description( + "Some combined chart totals were not checked", + "Doctor could not safely match these aggregate charts to raw result count units.", + "These chart comparisons remain unverified. This warning does not establish that " + "the displayed totals are wrong.", + "Add an explicit chart-to-result mapping and count units, then rerun the comparisons.", + "coverage") + if external and not charts: + return _description( + "Links outside the supplied package were not checked", + "Some report links lead outside the supplied package. Doctor did not " + "inspect those targets.", + "Those linked pages remain unverified. This warning does not establish " + "that the links are broken.", + "Provide a self-contained report package or check the external targets separately.", + "coverage") + return _description( + "Some report comparisons remain unverified", + "Doctor could not safely complete all artifact comparisons. The recorded notes identify " + "unmapped charts, out-of-package links, or other comparison limits.", + "These are coverage limits, not proof that the affected values or links are wrong.", + "Review the coverage notes and supply the missing mapping or in-package " + "evidence before rerunning.", + "coverage") + + +WARNING_DESCRIPTIONS = { + "PACKAGE_ENVIRONMENT": ( + "Dependency installation was not retested in a clean environment", + "Doctor used the recorded Python environment without installing or upgrading packages.", + "The run does not prove that dependencies install cleanly or work across " + "every supported Python version.", + "Use separate clean-environment CI jobs to verify dependency installation and " + "supported Python versions."), + "MERGE_UNAGREED_STATUS_POLICY": ( + "Some compliance rules still need owner agreement", + "Expected compliance for all-skipped, warning-only, and aborted-only results " + "is not covered " + "by the agreed compliance checks.", + "Doctor cannot certify those states against a policy that has not been agreed. " + "This warning does not change the existing compliance policy.", + "Agree the expected outcomes with the policy owner, then add explicit checks " + "for those states."), + "raw.coverage": ( + "Some suites still need malformed-log tests", + "The listed suites have no complete malformed/incomplete-log coverage in the " + "raw-input group.", + "Handling of bad input remains unverified for those suites. Native " + "positive-input checks are separate.", + "Add a complete native control plus malformed and incomplete examples for " + "each listed suite."), + "VISUAL_SCOPE": ( + "Rendering checks cover selected examples only", + "Browser and export smoke checks cover a limited set of synthetic report examples.", + "This is not full browser, pagination, paper-size, suite, or hardware certification.", + "Run the additional browser, print, and suite scenarios required for the " + "intended release."), + "VISUAL_COVERAGE": ( + "Browser and PDF checks were not requested", + "This run did not include the optional browser and PDF export checks.", + "Successful data checks do not establish that browser rendering or PDF output works.", + "Run Doctor with --doctor-visual and its required rendering dependencies to " + "check this scope."), + "SCOPE_LIMIT": ( + "This run checked selected groups only", + "The run was focused on selected Doctor groups; other groups were omitted.", + "The verdict applies to the selected checks, not to the untested groups.", + "Review the recorded group selection and run the omitted groups when full " + "coverage is needed."), + "ARTIFACT.INPUT": ( + "No captured report package was checked", + "No real-capture report package was supplied for artifact comparisons.", + "Synthetic probes do not establish the correctness of a captured report package.", + "Supply --doctor-report DT=/path or SR=/path to check a report package read-only."), +} + + +# Each topic names the failed behavior and the place to investigate it. +# Case-specific input and observed values are shown separately below the topic. +FAILURE_DESCRIPTIONS = { + "HTML_COMPLIANCE_MATCH": ( + "HTML compliance labels do not match the expected results", + "Some summary cards or detail-page rows show the wrong requirement or compliance status. " + "Each example below shows what the report should say and what it actually says.", + "A partner can read Compliant for missing or failed results, or see the wrong " + "Mandatory/Recommended label.", + "Check the named summary card or detail row against its merged JSON. If JSON " + "is already wrong, " + "trace the merger; otherwise check how the HTML label is built."), + "HTML_COMPLIANCE_EXECUTION": ( + "Compliance HTML could not be generated", + "The report generator raised an error while building summary badges or detail " + "compliance tables.", + "The recorded JSON checks are available, but this case has no verified compliance HTML.", + "Open the generation error and fix the failing report helper, then rerun the same case."), + "MERGE_INCOMPLETE_NOT_GREEN": ( + "Empty suite results are being treated as completed tests", + "Doctor supplied JSON with no test outcomes, or only a suite heading. The " + "merger did not preserve " + "the expected Not Run status.", + "A suite with no completed results can appear Compliant. Its " + "Mandatory/Recommended requirement " + "must still be retained when marking it Not Run.", + "Check how merge_jsons.py detects completed outcomes. An empty result list or " + "heading alone " + "must not count as successful execution."), + "MERGE_OVERALL_POLICY": ( + "Overall SRS compliance does not follow the requirement rules", + "The overall result differs from the expected result for the supplied " + "Mandatory, Recommended " + "and extension inputs. These cases include both incorrect passes and incorrect failures.", + "Recommended failures or missing Recommended results must not block overall SRS. Missing " + "or failed applicable Mandatory requirements must block it.", + "Compare the expected and recorded overall labels for each case, then check " + "which requirements " + "merge_jsons.py includes in its overall decision."), + "MERGE_EXTENSION_AGGREGATION": ( + "The combined BBSR extension result is wrong", + "The combined BBSR status does not match the supplied BBSR-FWTS, BBSR-SCT and " + "BBSR-TPM results.", + "Missing or failed BBSR members can be hidden by a Compliant extension label. " + "BBSR has its own " + "combined result; it does not decide overall SRS compliance.", + "Check all three BBSR member statuses against the extension aggregation in " + "merge_jsons.py."), + "MERGE_FAILURE_COUNT": ( + "The merger loses explicit SCT failures", + "SCT input contains failed parent tests with no subtest details, but the " + "merger counts fewer failures.", + "The chart can show failures while compliance says Compliant because the " + "merger only counted subtests.", + "Count an explicit failed SCT parent when it has no child results. Keep " + "parent/child counting " + "separate so a parent with failed children is not counted twice."), + "MERGE_INVALID_INPUT_SAFETY": ( + "Invalid result data can still receive Compliant", + "Doctor supplied a malformed result structure. The merger did not reject it " + "or keep its status non-green.", + "An unreadable or unsupported result shape can be mistaken for a successful test run.", + "Check the recorded invalid input and the merger's shape checks before it " + "calculates compliance."), + "MERGE_SUITE_STATUS": ( + "A suite's requirement or compliance status is wrong", + "The merged suite label differs from the expected label for its test results " + "and requirement.", + "The report can misstate whether a suite is required or whether its own tests " + "satisfy compliance.", + "Compare the suite's input outcomes, requirement and waiver state with the " + "merged decision."), + "NATIVE_EXECUTION": ( + "The parser failed while reading a sample log", + "The public standalone command could not finish a known sample. The example " + "below names the " + "suite and the recorded parser error.", + "This input cannot produce a complete report. Any checks that need its output " + "remain unverified.", + "Open parser.log for the affected suite and follow the reported exception to " + "its parser file."), + "NATIVE_OUTPUT_INVENTORY": ( + "Expected parser output files are missing or unexpected files appeared", + "The standalone command's output folder does not contain exactly the expected " + "suite JSON files.", + "Missing output prevents downstream checks. When the parser also failed, " + "these findings can " + "describe consequences of the same error.", + "Compare the named missing/unexpected files with parser.log. Resolve an " + "earlier parser error first."), + "normal.stale-rerun": ( + "A rerun reuses a previous result after its log is removed", + "Doctor parsed a passing suite log, removed that log, and ran the parser " + "again in the same output folder. " + "The rerun kept the earlier Compliant status; a fresh run reported Not Run.", + "A later CI job can display an old passing result for a suite that has no current input.", + "Check how normal runs remove or replace previous suite JSON before " + "regenerating the merged report."), + "raw.sct-parent-failure": ( + "SCT has two failed tests, but compliance says Compliant", + "The raw SCT result contains two explicit failed parent tests with no subtest details. " + "The compliance decision does not match those failures.", + "A partner sees Failed: 2 in the chart and Compliant in the same report.", + "Trace the two failed parent entries from raw SCT JSON into the merger's failure count."), + "waiver.whole-suite-multiple-assertions": ( + "A whole-suite FWTS waiver leaves one failure unwaived", + "The sample contains two failed assertions covered by one whole-suite waiver. " + "Only one assertion " + "is moved into the waived count.", + "The remaining failure makes the suite Not Compliant even though the " + "whole-suite waiver covers both.", + "Check how apply_waivers.py applies a whole-suite waiver to multiple failures " + "in the same test."), + "waiver.runtime-map-whole-suite": ( + "A Runtime Device Map waiver crashes the parser", + "Applying a valid whole-suite waiver to a nested Runtime Device Map failure " + "raises a TypeError.", + "The run stops before it can publish the waived result and complete report.", + "Check how apply_waivers.py combines nested failure reasons with the waiver reason."), + "waiver.passed-test-matching-waiver": ( + "A waiver creates a failure for a test that already passed", + "A waiver matching a passing Standalone test changes its counts as though a " + "failure was waived.", + "The report invents a waived failure instead of preserving the original pass.", + "Apply waivers only to actual failures; leave passing tests and their counts unchanged."), +} + + +def _input_description(identifier): + """Explain the deliberate raw-log mutation without assuming how it ended.""" + if identifier in {"raw.empty-log", "raw.header-only"}: + return _description( + "Empty or introductory-only logs are not reported as Not Run", + "Doctor supplied logs with no completed tests. The parser should report " + "Not Run with zero " + "test outcomes. Some cases instead stop with an error, invent outcomes or " + "report Compliant.", + "These are different problems: a stopped command has no report, while an " + "invented pass or " + "Compliant label can mislead a reader. The examples show which occurred.", + "Check the suite's empty-input handling. Preserve its requirement, publish Not Run, " + "and keep all executed-outcome counts at zero.") + cases = { + "raw.truncated-final-subtest": ("A log ends during a subtest, but the report can still say Compliant", + "One test finishes, another subtest starts, then its final result is missing."), + "raw.truncated-log": ("An unfinished test log can still produce Compliant", + "Doctor cut the log after execution started and before the required final result."), + "raw.missing-terminal-result": ("A test has no final result, but the report can still say Compliant", + "The input has introductory or intermediate test text without a final test result."), + "raw.malformed-log": ("Invalid log content can still produce Compliant", + "Doctor changed a result marker or supplied malformed log data to the native parser."), + } + if identifier not in cases: + return None + title, happened = cases[identifier] + return _description(title, happened, + "A completed passing test can hide another test that has no usable result. " + "A Compliant label is not supported by that incomplete input.", + "Check the changed input against the passing control. Verify required result markers and " + "handle unfinished or invalid input before calculating compliance.") + + +def describe_group(check_ids, items): + """Explain an already-selected display group without changing its findings. + + Related checks may share an explanation, but keep their original severity, + expected results, observations and counts. + """ + items = tuple(items) + ids = {check_ids} if isinstance(check_ids, str) else set(check_ids) + statuses = {_text(item, "status") for item in items} + if ids == {"NATIVE_RAW_IDENTITY"} and statuses == {"BLOCKED"}: + return _description( + "Test contents could not be checked because the parser produced no JSON", + "The earlier parser command did not generate the suite's expected JSON file.", + "Doctor cannot compare its test names, counts and statuses with the sample log.", + "Resolve the parser/output-file failure above, then rerun this check.", "coverage") + if statuses == {"BLOCKED"}: + return _description( + "Checks could not finish", + "Doctor could not complete these checks. The recorded observations " + "identify the missing " + "input, dependency, or other blocker.", + "The affected behavior remains unverified; a blocked check is not a " + "confirmed parser defect.", + "Resolve the recorded blocker and rerun the same checks before drawing a " + "correctness conclusion.", + "coverage") + if statuses == {"PASS"}: + return _description( + "Checks completed successfully", + "The recorded checks met their expected outcomes.", + "This result applies only to the scenarios and evidence checked in this run.", + "Keep the recorded evidence with the run; review any separately reported " + "coverage limits.", + "summaries") + if not items: + return _description( + "No findings in this group", "No observations were supplied for this display group.", + "An empty group does not establish a passing result.", "Review the run scope and recorded findings.", + "coverage") + if ids and ids <= SCHEMA_CHECKS: + return _description( + "Some JSON files do not match the expected format", + "The recorded JSON checks did not satisfy the applicable format requirements. " + "Review the validator messages for missing fields, invalid values, or " + "validation errors.", + "Consumers that require the schema may reject these files. A format-check " + "failure alone " + "does not prove that test outcomes or compliance decisions are wrong.", + "Inspect the named JSON file and field path, then align the producer output with the " + "registered schema. Repeated messages are not necessarily separate defects.") + if ids and ids <= CATEGORY_PROVENANCE_CHECKS: + if statuses == {"WARN"}: + return _description( + "The run's category-file choice is not recorded", + "Test_suite_info is missing, but Doctor could not verify whether a " + "category file was " + "explicitly supplied to the run that produced these results.", + "Doctor did not treat this missing field as a failure because its " + "requirement could " + "not be confirmed. All other format checks remain active.", + "Keep the generating run's category-file record and any explicitly " + "supplied category " + "file with the results, then recheck. Known bundled defaults alone do not make " + "Test_suite_info mandatory or cause this warning.", "coverage") + return _description( + "The run's category-file record cannot be verified", + "Doctor found an invalid record of which category file the generating run used. " + "The recorded error explains what could not be verified.", + "The category-file record cannot be trusted for this conditional requirement. " + "This does not by itself prove that a test outcome is wrong.", + "Check the recorded error against the generating run's saved category " + "file and run record. " + "Do not replace missing run evidence with an assumption about today's " + "bundled defaults.") + if ids and ids <= STATUS_CHECKS: + return _raw_description(items) + if ids == {"raw.conditional-execution"} and statuses == {"WARN"}: + return _description( + "Conditional requirements need execution evidence beyond JSON", + "The raw-log control proves these tests ran. Doctor then deliberately left their " + "generated JSON out of a separate, disposable input passed directly to the merger. " + "This JSON-only replay could not retain the obligation established by the raw logs.", + "Missing result JSON does not mean a test never ran. Executed SR SBSA is Mandatory; " + "either executed SBMR interface makes both interfaces Mandatory. Executed DT PFDI " + "remains applicable as Conditional-Mandatory. Losing those required results must " + "not allow overall Compliant. This controlled fault injection does not establish a " + "public-flow failure: standalone already rejects parser errors and missing generated " + "output. The replay did not test whether normal runs can reach this state.", + "Compare the raw control, the deliberately reduced merge input, and the recorded " + "requirement and compliance labels. Verify the public-flow guards before claiming " + "a parser defect; if this state is reachable, preserve the fact that a required " + "test ran when passing results to the merger.", "coverage") + if ids == {"ARTIFACT.CONSISTENCY"}: + return _description( + "Report-package check summary", + "This records the package-level result across JSON, result identities, " + "HTML, and local links.", + "Package-level result; inspect individual findings before treating it as " + "an additional defect.", + "Open the package evidence and review its individual findings and " + "coverage notes.", "summaries") + if ids == {"ARTIFACT.PARITY"}: + return _description( + "Report details do not match the source results", + "A test identifier, name, or status differs between the compared report " + "and source results.", + "A reader may see a different result description from the raw data. " + "A changed label alone does not establish a changed test outcome.", + "Compare the missing and changed records. Check HTML text escaping when " + "literal angle-bracket " + "text disappears from a test name.") + if statuses == {"FAIL"} and len(ids) == 1: + identifier = next(iter(ids)) + if identifier in FAILURE_DESCRIPTIONS: + return _description(*FAILURE_DESCRIPTIONS[identifier]) + raw_description = _input_description(identifier) + if raw_description: + return raw_description + if statuses == {"WARN"}: + if ids == {"ARTIFACT.COVERAGE"}: + return _coverage_description(items) + if ids == {"raw.completion-evidence"}: + compliant = any(_has_compliant(item) for item in items) + return _description( + "Empty-input completion policy needs confirmation", + ("An empty-input probe recorded Compliant without recorded completion evidence." + if compliant else "The completion-evidence probe needs review; its observations are " + "recorded below."), + "An empty log alone does not prove the producer finished. A quiet but " + "completed validation " + "is a separate valid case.", + "Confirm what establishes producer completion and add separate " + "controls for empty and " + "quiet-but-completed logs.", "coverage") + if len(ids) == 1 and next(iter(ids)) in WARNING_DESCRIPTIONS: + return _description(*WARNING_DESCRIPTIONS[next(iter(ids))], category="coverage") + return _description( + _short(_text(items[0], "issue")) or "A coverage limit or caution needs review", + "Doctor recorded a warning. Review the exact observation before " + "interpreting its cause.", + "This warning is not a passing check or an automatically confirmed defect.", + "Review the expected and observed values and any linked evidence.", "coverage") + return _description( + _short(_text(items[0], "issue")) or "A Doctor check needs investigation", + "The recorded check did not establish its expected outcome; the original " + "details are shown below.", + "The effect depends on the mismatch. Do not infer a wrong compliance result " + "without checking the evidence.", + "Compare expected and observed values, inspect the linked evidence, and rerun " + "the affected check.") + + +def describe_finding(item): + """Return a short case label and an observation grounded in recorded text.""" + identifier, status = _text(item, "check_id"), _text(item, "status") + issue, actual, suite = (_text(item, name) for name in ("issue", "actual", "suite")) + title = _short(issue) or identifier or "Doctor finding" + observed = _short(actual) or "No observation was recorded." + comparisons = _comparisons(item) + scenario = _scenario(item) + if comparisons: + observed = " ".join(where + " should show " + expected + "; the report shows " + recorded + "." + for where, expected, recorded in comparisons[:3]) + title = (suite + ": " if suite else "") + { + "HTML_COMPLIANCE_MATCH": "incorrect compliance label", + "MERGE_INCOMPLETE_NOT_GREEN": "empty results received the wrong status", + "MERGE_SUITE_STATUS": "incorrect requirement or suite status", + "MERGE_OVERALL_POLICY": "incorrect overall SRS result", + "MERGE_EXTENSION_AGGREGATION": "incorrect combined BBSR result", + }[identifier] + return dict(title=title, observed=observed, comparisons=comparisons, scenario=scenario) + if status == "BLOCKED": + if identifier == "NATIVE_RAW_IDENTITY": + title = (suite + ": " if suite else "") + "JSON was not generated" + observed = "Test names and results could not be compared because the expected output file is missing." + return dict(title=title, observed="Check did not complete: " + observed) + if identifier in CATEGORY_PROVENANCE_CHECKS and status == "WARN": + title = "Category-file choice could not be confirmed" + observed = ("Missing Test_suite_info was not treated as a failure because the " + "generating run's " + "category-file choice could not be verified. Other format checks still apply.") + elif identifier in CATEGORY_PROVENANCE_CHECKS and status == "FAIL": + title = "Category-file run record could not be verified" + elif identifier in SCHEMA_CHECKS and status == "FAIL": + filename = re.search(r"[\w.-]+\.json\b", issue) + title = (filename.group(0) if filename else suite or "JSON file") + ": format check failed" + missing = list(dict.fromkeys(re.findall(r"'([^'\r\n]+)' is a required property", actual))) + if missing: + observed = "Validator reports missing required fields: " + ", ".join(missing) + "." + else: + observed = "Validator observation: " + observed + elif identifier == "NATIVE_EXECUTION": + title = (suite + ": " if suite else "") + "parser failed on the sample log" + error = re.search(r"\b([A-Za-z]+Error):\s*([^\n]*)", actual) + code = re.search(r"\bExit (\d+)", actual) + observed = ("The standalone parser stopped" + (" with exit code " + code[1] if code else "") + + (". " + error[1] + ": " + error[2] if error else ". See the recorded command output") + ".") + elif identifier == "NATIVE_OUTPUT_INVENTORY": + title = (suite + ": " if suite else "") + "expected JSON output is missing or unexpected" + messages = [] + for field, label in (("missing", "Missing output"), ("unexpected", "Unexpected output")): + match = re.search(field + r"=(\[[^\n;]*\])", actual) + files = _literal(match[1]) if match else None + if isinstance(files, list) and files: + messages.append(label + ": " + ", ".join(map(str, files))) + observed = ". ".join(messages) + "." if messages else observed + elif identifier == "MERGE_FAILURE_COUNT": + title = (suite + ": " if suite else "") + "SCT parent failures were not counted" + expected_counts = re.search(r"Failed/waived=\((\d+),\s*(\d+)\)", _text(item, "expected")) + actual_counts = re.search(r"Failed/waived=\((\d+),\s*(\d+)\)", actual) + if expected_counts and actual_counts: + observed = ("Input contains " + expected_counts[1] + " failed and " + expected_counts[2] + + " waived tests. The merger counted " + actual_counts[1] + " failed and " + + actual_counts[2] + " waived tests.") + elif identifier == "MERGE_INVALID_INPUT_SAFETY": + title = (suite + ": " if suite else "") + "invalid input accepted" + observed = ("The supplied result structure is invalid. The merger returned " + + _label(actual) + ".") + elif identifier == "raw.conditional-execution" and status == "WARN": + title = (suite + ": " if suite else "") + "JSON-only merge replay after recorded execution" + expected_rows = _literal(_text(item, "expected").split(". ", 1) + [-1].split("; overall=", 1)[0]) + actual_rows = _literal(actual.split("; overall=", 1)[0]) + labels = [] + if isinstance(expected_rows, Mapping) and isinstance(actual_rows, Mapping): + for name in expected_rows: + labels.append(str(name) + " should stay " + _label(expected_rows[name]) + + "; JSON-only replay returned " + _label(actual_rows.get(name))) + expected_overall = re.search(r"; overall=(\w+)", _text(item, "expected")) + actual_overall = re.search(r"; overall=(\w+)", actual) + if expected_overall and actual_overall: + labels.append("Overall SRS should be " + _label(expected_overall[1]) + + "; replay returned " + _label(actual_overall[1])) + observed = ("Controlled merge-boundary replay; public-flow failure not established. " + + (". ".join(labels) + "." if labels else + "Generated JSON was deliberately omitted after raw execution was established. " + "Review the recorded requirement and overall decision below.")) + elif identifier in STATUS_CHECKS: + case = "missing test status" if identifier == "raw.missing-status" else "unrecognized test status" + title = (suite + ": " if suite else "") + case + code, fields = _observation(item) + if _no_report(item): + observed = ("Exit code " + str(code) + + "; no completed merged result or HTML status was recorded.") + elif code is not None: + parts = ["Exit code " + str(code)] + for key, label in (("merged", "merged JSON"), ("HTML", "HTML")): + if key in fields and fields[key] is not None: + value = _status_value(fields[key]) + parts.append( + label + (" status was not recorded" if fields[key] == "None" else " says " + value)) + observed = "; ".join(parts) + "." + elif identifier.startswith("raw.") and identifier not in {"raw.coverage", "raw.positive"}: + names = {"raw.empty-log": "empty log", "raw.header-only": "introductory text only", + "raw.truncated-final-subtest": "log ends during a subtest", + "raw.truncated-log": "log ends before execution finishes", + "raw.missing-terminal-result": "no final test result", + "raw.malformed-log": "malformed log", "raw.sct-parent-failure": "two failed SCT parents", + "raw.completion-evidence": "empty validation log"} + title = (suite + ": " if suite else "") + names.get(identifier, issue) + observed = _probe_result(item) + if identifier in {"raw.empty-log", "raw.header-only"}: + observed = ("No completed tests were supplied. " + + observed + " Expected: Not Run with zero test outcomes.") + elif identifier == "raw.sct-parent-failure": + observed = "Two parent tests explicitly failed. " + observed + elif identifier.startswith("waiver."): + title = (suite + ": " if suite else "") + { + "waiver.whole-suite-multiple-assertions": "only one of two failures was waived", + "waiver.runtime-map-whole-suite": "applying the suite waiver crashed", + "waiver.passed-test-matching-waiver": "a passing test became a waived failure", + }.get(identifier, issue) + observed = _probe_result(item) + expected_counts = _literal(_text(item, "expected").split(";", 1)[0]) + if isinstance(expected_counts, Mapping): + observed = "Expected: " + _count_label(expected_counts) + ". " + observed + elif identifier == "normal.stale-rerun": + title = (suite + ": " if suite else "") + "old result survives after its log is removed" + results = dict(re.findall(r"(first|rerun|fresh)='([^']*)'", actual)) + if len(results) == 3: + observed = ("First run: " + results["first"] + ". Rerun after removing the log: " + results["rerun"] + + ". Fresh run without the log: " + results["fresh"] + ". The rerun retained an old result.") + elif identifier == "ARTIFACT.CONSISTENCY": + match = re.search(r"JSON schema validation failed:\s*(\d+)", actual) + title = "Saved report package: check summary" + if match: + observed = ("This package has " + match[1] + " JSON format findings, listed in the format topic above. " + "This entry summarizes that package's result.") + elif identifier == "ARTIFACT.COVERAGE": + notes = [] + for source, chart in re.findall(r"([^;]+?): aggregate/unmapped chart ([^;]+)", actual): + notes.append("In " + source.strip() + ", the chart " + chart.strip() + + " could not be matched to raw result counts") + observed = ". ".join(notes) + "." if notes else observed + elif identifier == "raw.coverage": + observed = "Bad-input cases not yet checked: " + actual + for key, label in (("empty-log", "empty log"), ("header-only", "introductory text only"), + ("truncated-log", "unfinished log"), ("malformed-log", "invalid log")): + observed = observed.replace(key, label) + elif identifier == "PACKAGE_ENVIRONMENT": + observed = "The current Python environment was used. A fresh dependency installation and other Python versions were not tested." + elif identifier == "MERGE_UNAGREED_STATUS_POLICY": + observed = "There is no agreed expected compliance result for runs containing only skipped tests, warnings or aborted tests." + elif identifier == "ARTIFACT.PARITY" and "HTML" in issue: + for original in re.findall(r"'([^'\r\n]*<[^>\r\n]+>[^'\r\n]*)'", _text(item, "expected")): + displayed = re.sub(r"<[^>]+>", "", original) + if displayed and repr(displayed) in actual: + observed = "Raw test name: " + original + ". Displayed test name: " + displayed + "." + break + return dict(title=title, observed=observed, scenario=scenario) + + +# Keep the page usable offline: all styles and browser controls are embedded. + +STYLE = r""" +:root { + color-scheme: light; + --bg:#f3f6fb; --panel:#fff; --text:#172033; --heading:#102a4c; + --muted:#667085; --line:#d8e1ed; --brand:#163b68; --focus:#1769e0; + --shadow:0 8px 26px rgba(16,42,76,.06); + --fail:#b42318; --fail-soft:#fff1f0; --pass:#168044; --pass-soft:#ecfdf3; + --warn:#945a09; --warn-soft:#fff8e7; --blocked:#6941a5; --blocked-soft:#f4efff; +} +* {box-sizing:border-box} +body {margin:0; background:var(--bg); color:var(--text); font:14px/1.5 Inter,ui-sans-serif,-apple-system,BlinkMacSystemFont,"Segoe UI",Arial,sans-serif} +button,input,select {font:inherit} +button,a,input,select,summary {-webkit-tap-highlight-color:transparent} +button,a,summary {touch-action:manipulation} +button {cursor:pointer} +a {color:#175cd3; text-underline-offset:3px} +a:hover {color:var(--brand)} +:focus-visible {outline:3px solid var(--focus); outline-offset:4px} +summary:focus-visible {outline-offset:-3px} +[hidden] {display:none!important} +.shell {width:calc(100% - 48px); max-width:1360px; margin:24px auto} +.hero {background:linear-gradient(115deg,#0f2c50,#1b4573); color:white; border-radius:16px; padding:23px 26px; box-shadow:var(--shadow)} +.hero-top,.hero-bottom,.section-heading,.toolbar-actions,.group-heading,.finding-heading {display:flex; align-items:center; gap:16px} +.hero-top {justify-content:space-between; align-items:flex-start} +.eyebrow {font-size:11px; font-weight:750; letter-spacing:.16em; color:#c5d9f4; margin:0 0 8px} +h1 {font-size:32px; line-height:1.2; letter-spacing:-.04em; margin:0; font-weight:750} +.hero-description {color:#d0def0; margin:9px 0 0; font-size:14px} +.verdict {border:1px solid rgba(255,255,255,.26); border-radius:12px; padding:11px 16px; background:rgba(255,255,255,.08); min-width:180px} +.verdict-label {display:block; font-size:10px; letter-spacing:.12em; color:#d0def0; font-weight:700; margin-bottom:4px} +.verdict-value {display:flex; align-items:center; gap:9px; font-size:17px; font-weight:750} +.verdict-value::before {content:""; width:9px; height:9px; border-radius:50%; background:#fd9c94; box-shadow:0 0 0 4px rgba(253,156,148,.12)} +.verdict.pass .verdict-value::before {background:#86efac; box-shadow:0 0 0 4px rgba(134,239,172,.12)} +.verdict.blocked .verdict-value::before {background:#dac0ff; box-shadow:0 0 0 4px rgba(218,192,255,.12)} +.hero-bottom {justify-content:space-between; flex-wrap:wrap; margin-top:22px; padding-top:17px; border-top:1px solid rgba(255,255,255,.15)} +.run-meta {display:flex; gap:20px; align-items:center; flex-wrap:wrap; color:#d0def0; font-size:12px; min-width:0} +.run-meta strong {color:white; font-weight:650} +.run-meta code {color:white; font-size:12px} +.exports {display:flex; align-items:center; gap:8px; flex-wrap:wrap} +.button {display:inline-flex; align-items:center; justify-content:center; gap:7px; border:1px solid var(--line); background:white; color:var(--brand); border-radius:9px; padding:9px 13px; text-decoration:none; font-weight:650; white-space:nowrap; line-height:1.4} +.button:hover {background:#edf4ff; color:var(--heading); border-color:#b8cde8} +.hero .button {border-color:rgba(255,255,255,.26); color:white; background:rgba(255,255,255,.08); font-size:12px} +.hero .button:hover {background:rgba(255,255,255,.17)} +.hero .button.primary {background:white; color:var(--brand); border-color:white} +.icon {width:16px; height:16px; fill:none; stroke:currentColor; stroke-width:1.7; stroke-linecap:round; stroke-linejoin:round; flex-shrink:0} +.metrics {display:grid; grid-template-columns:repeat(5,minmax(0,1fr)); gap:10px; margin:16px 0 12px} +.metric {background:var(--panel); border:1px solid var(--line); border-radius:12px; padding:12px 17px; box-shadow:var(--shadow)} +.metric-label {font-size:12px; font-weight:650; color:var(--muted); display:flex; gap:8px; align-items:center} +.metric-dot {width:7px; height:7px; border-radius:50%; background:var(--muted)} +.metric-value {display:block; font-size:26px; letter-spacing:-.04em; line-height:1.3; font-weight:750; margin-top:4px; color:var(--heading); font-variant-numeric:tabular-nums} +.metric.fail .metric-dot {background:var(--fail)} .metric.fail .metric-value {color:var(--fail)} +.metric.pass .metric-dot {background:var(--pass)} .metric.pass .metric-value {color:var(--pass)} +.metric.warn .metric-dot {background:var(--warn)} .metric.warn .metric-value {color:var(--warn)} +.metric.blocked .metric-dot {background:var(--blocked)} .metric.blocked .metric-value {color:var(--blocked)} +.scope-note {display:flex; gap:10px; align-items:flex-start; margin:0 0 17px; color:var(--muted); font-size:12px} +.info-icon {display:inline-flex; align-items:center; justify-content:center; width:19px; height:19px; flex-shrink:0; color:var(--brand); background:#e5eefb; border-radius:50%; font-weight:750} +.scope-note p {margin:0} +.scope-note strong {color:#344054; font-weight:650} +.section-heading {justify-content:space-between; margin-bottom:15px} +h2 {font-size:21px; letter-spacing:-.025em; color:var(--heading); margin:0} +.section-description {margin:4px 0 0; color:var(--muted); font-size:12px} +.review-guide {border:1px solid var(--line); border-radius:13px; background:white; padding:16px 19px; margin:0 0 16px} +.review-guide h2 {font-size:18px} +.review-guide p {margin:5px 0 12px; color:#526176; font-size:13px} +.quick-nav {display:flex; flex-wrap:wrap; gap:8px} +.quick-nav a {display:inline-flex; align-items:center; gap:9px; border:1px solid var(--line); border-radius:7px; padding:6px 11px; color:var(--heading); text-decoration:none; font-size:12px; font-weight:650} +.quick-nav a:hover {background:#f2f6fc} +.quick-nav strong {font-variant-numeric:tabular-nums; border-radius:4px; padding:0 5px; background:#edf2f8} +.findings-section {margin-top:24px; scroll-margin-top:20px} +.findings-section>.section-heading {align-items:flex-start; margin-bottom:11px} +.section-kicker {font-size:10px; text-transform:uppercase; letter-spacing:.11em; color:var(--muted); font-weight:750; margin:0 0 4px} +.group-explanation {display:grid; grid-template-columns:1fr 1fr; gap:10px 22px; margin:0; padding:0 19px 15px} +.group-explanation>div:first-child {grid-column:1/-1} +.group-explanation dt {font-size:11px; font-weight:750; color:var(--muted); margin-bottom:3px} +.group-explanation dd {font-size:13px; color:#344054; margin:0; overflow-wrap:anywhere} +.group-explanation>div:last-child {border-left:2px solid #bdcfe5; padding-left:13px} +.topic-examples {margin:0 19px 14px; border:1px solid #e3eaf3; background:#f7f9fc; border-radius:7px; padding:9px 12px} +.topic-examples h4 {margin:0 0 4px; font-size:11px; color:#62738a} +.topic-examples p {margin:4px 0; font-size:12px; color:#344054; overflow-wrap:anywhere} +.topic-examples strong {color:var(--heading); font-weight:650} +.topic-examples .example {padding:10px 0; border-top:1px solid var(--line)} +.topic-examples .example:first-of-type {border-top:0; padding-top:2px} +.input-scenario {color:#526176; font-size:12px; margin:4px 0 10px; overflow-wrap:anywhere} +.result-comparison {width:100%; border-collapse:collapse; table-layout:fixed; font-size:12px; margin:8px 0} +.result-comparison th,.result-comparison td {padding:8px 10px; border:1px solid var(--line); text-align:left; vertical-align:top; overflow-wrap:anywhere} +.result-comparison th {font-size:10px; color:#526176; background:#edf2f8; font-weight:750} +.result-comparison td {background:white} +.result-comparison td:last-child {background:#fff5f4; font-weight:650; color:var(--fail)} +.result-comparison th:first-child {width:36%} +.technical-data {margin-top:12px; padding-top:10px; border-top:1px solid var(--line)} +.technical-data>summary {font-size:11px; color:var(--muted); font-weight:650; padding:3px 0 8px} +.technical-data>summary::before {content:'+ '; color:var(--brand)} +.technical-data[open]>summary::before {content:'− '} +.group-checks {border-top:1px solid #e5ebf3; background:#fafbfd} +.group-checks>summary {padding:10px 19px; color:var(--brand); font-size:12px; font-weight:650; display:flex; justify-content:space-between; gap:10px} +.group-checks>summary::after {content:'+'; font-size:16px; line-height:1} +.group-checks[open]>summary::after {content:'−'} +.group-checks .group-content {border:0; background:transparent} +.finding-observed {font-size:12px; line-height:1.55; color:#475467; background:#f4f7fb; border-radius:6px; padding:9px 11px; margin:0 0 10px; overflow-wrap:anywhere} +.finding-observed strong {color:var(--heading)} +.original-issue {font-size:12px; color:var(--muted); overflow-wrap:anywhere; margin:6px 0 10px} +.technical-id {font:10px ui-monospace,SFMono-Regular,Consolas,monospace; color:#69788d} +.presentation-note {font-size:11px; color:#dae5f3; margin:12px 0 0} +.filter-panel {background:#fff; border:1px solid var(--line); border-radius:13px; padding:15px 18px; margin-bottom:16px; box-shadow:var(--shadow)} +.filters {display:grid; grid-template-columns:minmax(230px,2.1fr) repeat(3,minmax(130px,1fr)); gap:12px} +.field {display:flex; flex-direction:column; gap:5px; min-width:0} +.field label {font-size:11px; font-weight:700; color:var(--muted)} +.field input,.field select {width:100%; min-width:0; border:1px solid var(--line); border-radius:8px; height:40px; padding:8px 11px; color:var(--text); background:white} +.field input::placeholder {color:#8994a5} +.field input:focus,.field select:focus {border-color:var(--focus)} +.toolbar-bottom {display:flex; justify-content:space-between; gap:12px; align-items:center; flex-wrap:wrap; margin-top:12px} +.match-count {font-size:12px; color:var(--muted); margin:0} +.toolbar-actions {gap:7px} +.toolbar-actions .button {padding:6px 10px; font-size:12px} +.toolbar-actions .quiet {border-color:transparent; background:transparent; color:var(--muted)} +.finding-group {border:1px solid var(--line); border-left:4px solid var(--warn); border-radius:12px; background:white; margin:0 0 13px; box-shadow:var(--shadow); overflow:hidden} +.finding-group.fail {border-left-color:var(--fail)} +.finding-group.blocked {border-left-color:var(--blocked)} +summary {cursor:pointer; list-style:none} +summary::-webkit-details-marker {display:none} +.group-heading {padding:16px 19px 12px; gap:13px; position:relative; align-items:flex-start} +.finding-heading::after {content:""; border-right:1.8px solid #6b7c92; border-bottom:1.8px solid #6b7c92; width:7px; height:7px; transform:rotate(45deg); margin:0 2px 4px 3px; flex-shrink:0; transition:transform .15s} +details[open]>.finding-heading::after {transform:rotate(225deg); margin-top:6px} +.group-copy {flex:1; min-width:0} +.group-title {display:block; font-size:17px; line-height:1.4; font-weight:750; color:var(--heading); overflow-wrap:anywhere; margin:0} +.group-meta {display:flex; align-items:center; gap:9px; flex-wrap:wrap; color:var(--muted); font-size:11px; margin-top:5px} +.affected-list>summary {text-decoration:underline; text-underline-offset:3px} +.affected-list p {margin:6px 0 0; line-height:1.6} +.badge {display:inline-flex; gap:5px; align-items:center; justify-content:center; border-radius:6px; padding:4px 8px; font-size:10px; font-weight:750; letter-spacing:.035em; background:var(--warn-soft); color:var(--warn); min-width:55px; flex-shrink:0} +.badge.fail {background:var(--fail-soft); color:var(--fail)} +.badge.blocked {background:var(--blocked-soft); color:var(--blocked)} +.group-count {font-size:11px; font-weight:650; color:var(--muted); white-space:nowrap; font-variant-numeric:tabular-nums; padding-top:2px} +.group-content {padding:0 20px 18px; border-top:1px solid #e8edf4; background:#fbfcfe} +.group-hint {font-size:11px; color:var(--muted); margin:12px 0 9px} +.finding {border:1px solid #e1e7ef; border-radius:9px; background:white; margin:8px 0 0; overflow:hidden} +.finding-heading {padding:12px 14px; gap:12px} +.finding-heading:hover {background:#f8fafd} +.case-number {font:11px ui-monospace,SFMono-Regular,Consolas,monospace; color:#7b879b; width:22px; flex-shrink:0} +.finding-title {flex:1; min-width:0; color:#344054; font-size:13px; font-weight:650; overflow-wrap:anywhere} +.context-chip {font-size:10px; padding:3px 7px; background:#f0f4fa; color:#4f627d; border-radius:5px; font-weight:650; overflow-wrap:anywhere} +.finding-body {padding:0 16px 16px} +.comparison {display:grid; grid-template-columns:1fr 1fr; gap:12px; padding-top:5px} +.comparison-panel {padding:13px 15px; border:1px solid #e4eaf1; border-radius:9px; background:#f8fafc; min-width:0} +.comparison-panel.actual {background:#fff7f6; border-color:#f2d4d1} +.blocked .comparison-panel.actual {background:#f8f5ff; border-color:#e6dbf7} +.warn .comparison-panel.actual {background:#fffbf0; border-color:#efdfb9} +.comparison h4 {font-size:10px; text-transform:uppercase; letter-spacing:.09em; margin:0 0 8px; color:var(--muted)} +.comparison .actual h4 {color:var(--fail)} +.blocked .actual h4 {color:var(--blocked)} .warn .actual h4 {color:var(--warn)} +.comparison pre {margin:0; white-space:pre-wrap; overflow-wrap:anywhere; max-height:280px; overflow:auto; font:12px/1.65 ui-monospace,SFMono-Regular,Consolas,monospace; color:#344054} +.evidence-heading {font-size:11px; font-weight:700; color:#475467; margin:15px 0 7px} +.evidence-list {display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:7px; list-style:none; padding:0; margin:0} +.evidence-link {display:flex; gap:9px; align-items:flex-start; border:1px solid #e4eaf1; border-radius:7px; padding:9px 10px; color:#245a96; text-decoration:none; min-width:0} +.evidence-link:hover {background:#edf4ff; border-color:#bfd3f2} +.evidence-link .icon {margin-top:2px; width:14px; height:14px} +.evidence-link span {min-width:0} +.evidence-link strong {display:block; font-size:11px; font-weight:650; overflow-wrap:anywhere} +.evidence-link small {display:block; margin-top:1px; font-size:10px; color:var(--muted); overflow-wrap:anywhere} +.no-evidence {font-size:11px; color:var(--muted); margin:12px 0 0} +.empty-state {padding:40px 20px; text-align:center; background:white; border:1px dashed #bfd0e4; border-radius:13px; color:var(--muted)} +.empty-state h3 {font-size:18px; color:var(--heading); margin:0 0 8px} +.empty-state p {margin:0; font-size:13px} +.summary-group {box-shadow:none; background:#fcfdff} +.run-details {margin-top:23px; border-top:1px solid var(--line); padding-top:16px; color:var(--muted)} +.run-details>summary {font-size:12px; font-weight:650; display:inline-flex; gap:8px; align-items:center} +.run-details>summary::before {content:"+"; font-size:16px; color:var(--brand)} +.run-details[open]>summary::before {content:"−"} +.metadata-grid {display:grid; grid-template-columns:1fr 1fr; gap:14px 24px; margin:16px 0} +.metadata-grid>div {min-width:0} +.metadata-grid dt {font-size:10px; letter-spacing:.04em; text-transform:uppercase; font-weight:750; margin-bottom:3px} +.metadata-grid dd {margin:0; color:#344054; overflow-wrap:anywhere; font-size:12px} +.metadata-grid pre {margin:0; font:11px/1.6 ui-monospace,SFMono-Regular,Consolas,monospace; white-space:pre-wrap; overflow-wrap:anywhere; max-height:180px; overflow:auto} +footer {margin-top:22px; display:flex; justify-content:space-between; gap:12px; color:#7c8899; font-size:11px} +.skip-link {position:fixed; top:-60px; left:16px; z-index:10; background:white; padding:12px; border:2px solid var(--focus)} +.skip-link:focus {top:12px} +.js-only {display:none} +.js .js-only {display:flex} +.js .filters {display:grid} +.print-note {display:none} +@media(max-width:900px) { + .shell {width:calc(100% - 36px); margin:18px auto} + .hero {padding:22px} + .filters {grid-template-columns:1fr 1fr} + .metric {padding:14px} + .metric-value {font-size:26px} + .comparison {grid-template-columns:1fr} + .group-explanation {gap:10px 16px} +} +@media(max-width:560px) { + .shell {width:calc(100% - 24px); margin:12px auto} + .hero {padding:20px; border-radius:13px} + .hero-top {flex-direction:column; gap:16px} + h1 {font-size:28px} + .hero-description {font-size:13px} + .verdict {min-width:0; display:flex; align-items:center; gap:13px; padding:7px 11px} + .verdict-label {margin:0; font-size:9px} + .verdict-value {font-size:13px} + .run-meta {gap:8px 14px} + .exports {gap:6px; width:100%} + .hero .button {padding:8px 10px; font-size:11px} + .metrics {grid-template-columns:repeat(2,minmax(0,1fr)); gap:8px; margin-top:12px} + .metric:first-child {grid-column:1/-1; display:flex; justify-content:space-between; align-items:center; padding:10px 15px} + .metric:first-child .metric-value {margin:0; font-size:25px} + .metric {padding:12px 15px} + .metric-value {font-size:26px} + .scope-note {font-size:11px; margin-bottom:18px} + .filter-panel {padding:12px} + .filters {grid-template-columns:1fr 1fr; gap:9px} + .field:first-child {grid-column:1/-1} + .field:last-child {grid-column:1/-1} + .toolbar-bottom {align-items:flex-start} + .toolbar-actions {flex-wrap:wrap} + .group-heading {padding:14px 12px 10px; gap:9px; flex-wrap:wrap} + .group-heading .badge {min-width:49px; padding:3px 6px; font-size:9px} + .group-copy {flex-basis:calc(100% - 75px)} + .group-title {font-size:15px} + .group-count {margin-left:58px; font-size:11px; padding:0} + .group-explanation {grid-template-columns:1fr; padding:0 12px 13px; gap:10px} + .group-explanation>div:last-child {padding-left:10px} + .group-checks>summary {padding:10px 12px} + .review-guide {padding:13px} + .group-content {padding:0 10px 12px} + .finding-heading {padding:11px 10px; gap:8px; flex-wrap:wrap} + .case-number {width:17px} + .finding-title {flex-basis:calc(100% - 60px); font-size:12px} + .finding-heading::after {margin-left:auto} + .context-chip {font-size:9px} + .finding-body {padding:0 10px 12px} + .comparison-panel {padding:11px} + .comparison pre {font-size:11px} + .evidence-list,.metadata-grid {grid-template-columns:1fr} + .section-heading {gap:10px} + h2 {font-size:19px} + footer {flex-direction:column; gap:3px} +} +@media(prefers-reduced-motion:reduce) {*{scroll-behavior:auto!important; transition:none!important}} +@media print { + @page {size:A4; margin:12mm} + :focus-visible {outline:none} + body {background:white; font-size:10pt; -webkit-print-color-adjust:exact; print-color-adjust:exact} + .shell {width:100%; max-width:none; margin:0} + .hero {padding:16px 20px; border-radius:9px; box-shadow:none; break-inside:avoid} + .hero-description {font-size:10pt} + h1 {font-size:24pt} + .hero-bottom {margin-top:12px; padding-top:10px} + .exports,.filter-panel,.skip-link,.run-details,footer,.js-only,.quick-nav {display:none!important} + .metrics {gap:7px; margin:12px 0} + .metric {padding:10px; box-shadow:none; break-inside:avoid} + .metric-value {font-size:21pt} + .metric-label {font-size:8pt} + .scope-note {font-size:8pt; margin-bottom:12px} + .print-note {display:block; font-size:9pt; color:#475467} + .finding-group {box-shadow:none; border-radius:6px; overflow:visible; break-inside:auto} + .group-explanation {font-size:9pt; break-inside:avoid} + .group-explanation dd {font-size:9pt} + .review-guide {padding:10px 13px; break-inside:avoid} + .group-heading {padding:10px 12px; break-after:avoid} + .group-title {font-size:11pt} + .group-content {padding:0 10px 10px; background:white} + .finding {overflow:visible; break-inside:auto} + .finding-heading {padding:9px; break-after:avoid} + .finding-body {padding:0 10px 10px} + .comparison {grid-template-columns:1fr; gap:7px} + .comparison-panel {break-inside:auto} + .comparison pre,.metadata-grid pre {max-height:none; overflow:visible; font-size:8pt} + .evidence-list {grid-template-columns:1fr} + .evidence-link {break-inside:avoid} + .finding-heading::after,.group-checks>summary::after,.group-hint {display:none} + details::details-content {content-visibility:visible!important; height:auto!important} + details>:not(summary) {display:block!important} + .finding-group[hidden],.finding[hidden],.findings-section[hidden] {display:block!important} + .empty-state[hidden] {display:none!important} +} +""" + +SCRIPT = r""" +(function () { + 'use strict'; + document.documentElement.classList.add('js'); + const groups = Array.from(document.querySelectorAll('.finding-group')); + const findings = Array.from(document.querySelectorAll('.finding')); + const sections = Array.from(document.querySelectorAll('.findings-section')); + const detailPanels = Array.from(document.querySelectorAll('#findings details')); + const search = document.getElementById('doctor-search'); + const severity = document.getElementById('severity-filter'); + const mode = document.getElementById('mode-filter'); + const suite = document.getElementById('suite-filter'); + const count = document.getElementById('match-count'); + const empty = document.getElementById('no-matches'); + let printState = null; + function filter() { + // Hide non-matching rows only. Recorded verdicts and totals stay unchanged. + const words = search.value.trim().toLowerCase().split(/\s+/).filter(Boolean); + let visible = 0, visibleGroups = 0; + findings.forEach(function (item) { + const matches = (!severity.value || item.dataset.severity === severity.value) && + (!mode.value || (item.dataset.mode || 'Repository') === mode.value) && + (!suite.value || JSON.parse(item.dataset.suites).includes(suite.value)) && + words.every(word => item.dataset.search.includes(word)); + item.hidden = !matches; + if (matches) visible++; + }); + groups.forEach(function (group) { + const matches = Array.from(group.querySelectorAll('.finding')).filter(item => !item.hidden).length; + group.hidden = !matches; + if (matches) visibleGroups++; + const label = group.querySelector('.group-count'); + const total = Number(group.dataset.total); + label.textContent = (matches === total ? total : matches + ' / ' + total) + (total === 1 ? ' check' : ' checks'); + group.querySelector('.details-count').textContent = matches; + group.querySelector('.details-unit').textContent = matches === 1 ? 'check' : 'checks'; + }); + sections.forEach(section => {section.hidden = !Array.from(section.querySelectorAll('.finding-group')).some(group => !group.hidden);}); + count.textContent = 'Showing ' + visible + ' of ' + findings.length + ' flagged checks across ' + visibleGroups + + (visibleGroups === 1 ? ' topic' : ' topics'); + empty.hidden = visible !== 0 || findings.length === 0; + } + search.addEventListener('input', filter); + [severity, mode, suite].forEach(input => input.addEventListener('change', filter)); + document.getElementById('reset-filters').addEventListener('click', function () { + search.value = severity.value = mode.value = suite.value = ''; filter(); search.focus(); + }); + document.getElementById('expand-all').addEventListener('click', function () { + detailPanels.filter(item => !item.hidden && !item.closest('.finding-group').hidden).forEach(item => {item.open = true;}); + }); + document.getElementById('collapse-all').addEventListener('click', function () { + detailPanels.forEach(item => {item.open = false;}); + }); + function preparePrint() { + if (printState) return; + // Printing includes all flagged checks, even those hidden by a screen filter. + // Save the current view so it can be restored after the print dialog closes. + printState = [...new Set(sections.concat(groups, detailPanels))].map(item => [item, item.open, item.hidden]); + printState.forEach(([item]) => {item.hidden = false; if (item.tagName === 'DETAILS') item.open = true;}); + groups.forEach(function (group) { + const total = Number(group.dataset.total); + group.querySelector('.group-count').textContent = total + (total === 1 ? ' check' : ' checks'); + group.querySelector('.details-count').textContent = total; + group.querySelector('.details-unit').textContent = total === 1 ? 'check' : 'checks'; + }); + empty.hidden = true; + } + function finishPrint() { + if (!printState) return; + printState.forEach(([item, open, hidden]) => {if (item.tagName === 'DETAILS') item.open = open; item.hidden = hidden;}); + printState = null; filter(); + } + window.addEventListener('beforeprint', preparePrint); + window.addEventListener('afterprint', finishPrint); + document.getElementById('print-report').addEventListener('click', function () {window.print();}); + filter(); +})(); +""" + + +# HTML rendering of the unchanged findings and explanation text. + + +def _icon(kind): + paths = { + "download": '', + "print": '', + "file": '', + } + return '' + + +def _evidence_link(value, output_dir): + """Link to recorded evidence, preferring portable paths inside the report folder.""" + path = Path(value) + try: + relative = path.relative_to(output_dir).as_posix() + href = quote(relative, safe="/") + display = relative + except ValueError: + href = path.as_uri() if path.is_absolute() else quote(str(path), safe="/") + display = str(path) + return ('
  • ' + _icon("file") + + '' + escape(path.name or str(path)) + '' + escape(display) + + '
  • ') + + +def _options(values, label): + return '' + ''.join( + '' + for value in sorted(values)) + + +def _topic_key(item): + """Combine related display topics without merging or dropping assertions.""" + if item.check_id in SCHEMA_CHECKS: + return "json-format" + if item.check_id in STATUS_CHECKS: + return "input-status" + return item.check_id + + +def _suite_names(value): + return sorted({name.strip() for name in value.split(",") if name.strip()}) + + +def _comparison_html(rows): + if not rows: + return "" + return ('' + '' + ''.join( + '' + ''.join('' for value in row) + '' + for row in rows) + '
    WhereShould showReport shows
    ' + escape(str(value)) + '
    ') + + +def _finding_html(item, number, output_dir, topic_title, original_title): + """Show one check's explanation beside its unchanged technical evidence.""" + explanation = describe_finding(item) + searchable = ' '.join(map(str, (topic_title, original_title, item.check_id, item.issue, + item.expected, item.actual, item.mode, item.suite, + explanation["title"], explanation["observed"], *item.evidence))).lower() + chips = ''.join('' + escape(value) + '' + for value in (item.mode or "Repository", item.suite) if value) + evidence = ('

    Logs, files and reproduction ' + 'commands

      ' + + ''.join(_evidence_link(value, output_dir) for value in item.evidence) + '
    ' + if item.evidence else '

    No evidence files recorded for this check.

    ') + scenario = ('

    Input checked: ' + escape(explanation["scenario"]) + + '

    ') if explanation.get("scenario") else '' + readable = _comparison_html(explanation.get("comparisons")) or ( + '

    What Doctor found: ' + escape(explanation["observed"]) + '

    ') + return ('
    ' + + f'{number:02d}' + '' + escape(explanation["title"]) + + '' + chips + '
    ' + scenario + + readable + + '
    Original check data

    ' + + escape(item.check_id) + '
    ' + escape(item.issue) + '

    ' + + '

    Expected ' + 'by the check

    ' +
    +            escape(item.expected) + '

    Recorded result

    ' +
    +            escape(item.actual) + '
    ' + evidence + '
    ') + + +def render_html(findings, metadata, output_dir, status, counts, group_titles): + """Build the HTML page without recalculating any check result or total.""" + output_dir = Path(output_dir) + findings = list(findings) + # Successful checks remain in doctor.json. The review page focuses on failures, + # blocked checks and warnings so readers can find what needs attention. + actionable = [item for item in findings if item.status != "PASS"] + groups = defaultdict(list) + for item in actionable: + groups[item.status, _topic_key(item)].append(item) + section_definitions = ( + ("issues", "Failed checks", "Start here", + "These checks failed. Each topic explains the observation and what to investigate."), + ("blocked", "Checks that could not run", "Not verified", + "These checks were blocked. They are not counted as passed."), + ("warnings", "Warnings and coverage limits", "Review next", + "These need a policy decision, more test coverage or an environment check. A " + "warning is not proof of a parser defect."), + ("summaries", "Report package summaries", "Read with the findings above", + "These are package-level results. They can repeat individual findings and " + "are not automatically additional bugs."), + ) + section_cards = defaultdict(list) + section_counts = defaultdict(int) + for (severity, topic), items in sorted(groups.items(), key=lambda row: row[0]): + check_ids = sorted({item.check_id for item in items}) + description = describe_group(check_ids, items) + section = ("summaries" if description["category"] == "summaries" else + "blocked" if severity == "BLOCKED" else + "warnings" if severity == "WARN" else "issues") + modes = ' / '.join(sorted({item.mode or "Repository" for item in items})) + suites = sorted({name for item in items for name in _suite_names(item.suite)}) + context = modes + (' · ' + ', '.join(suites) if suites else ' · Report / repository checks') + if "ARTIFACT.SCHEMA" in check_ids and suites: + context += ' · plus saved report files' + context_html = escape(context) + if len(suites) > 6: + context_html = (escape(modes) + ' ·
    ' + + str(len(suites)) + ' affected suites

    ' + + escape(', '.join(suites)) + '

    ') + rows = ''.join(_finding_html(item, number, output_dir, description["title"], + group_titles.get((item.status, item.check_id), item.issue)) + for number, item in enumerate(items, 1)) + explanations = ''.join('
    ' + label + '
    ' + escape(description[key]) + '
    ' + for label, key in (("What happened", "happened"), + ("Why it matters", "impact"), ("Next step", "next_step"))) + examples, seen = [], set() + # A short preview helps readers understand the topic. Every underlying + # assertion is still available in the expandable evidence section. + for item in items: + observation = describe_finding(item) + if observation["observed"] in seen: + continue + seen.add(observation["observed"]) + label = ' · '.join(value for value in (item.mode, item.suite) if value) + scenario = ('

    ' + escape(observation["scenario"]) + '

    ' + if observation.get("scenario") else '') + readable = (_comparison_html(observation.get("comparisons")) or + '

    ' + escape(observation["observed"]) + '

    ') + examples.append('

    ' + escape(label or observation["title"]) + + '

    ' + scenario + readable + '
    ') + if len(examples) == 3: + break + example_html = ('

    Examples from this run

    ' + + ''.join(examples) + '
    ') + section_cards[section].append( + '
    ' + severity + + '

    ' + escape(description["title"]) + + '

    Affected: ' + context_html + + '
    ' + str(len(items)) + + (' check' if len(items) == 1 else ' checks') + '
    ' + + explanations + '
    ' + example_html + '
    View ' + + '' + str(len(items)) + ' ' + + '' + ('check' if len(items) == 1 else 'checks') + '' + + ' & supporting evidence
    ' + + '

    Original check IDs, expected results and recorded ' + 'observations are preserved below.

    ' + + rows + '
    ') + section_counts[section] += len(items) + + section_html, nav_html = [], [] + for key, title, kicker, subtitle in section_definitions: + if not section_cards[key]: + continue + identifier = key + "-section" + nav_html.append('' + title + '' + + str(section_counts[key]) + '') + section_html.append('
    ' + + '

    ' + kicker + '

    ' + + title + '

    ' + subtitle + '

    ' + + ''.join(section_cards[key]) + '
    ') + + revision = str(metadata.get("revision") or "Not recorded") + short_revision = revision[:12] if len(revision) >= 12 and all( + char in '0123456789abcdefABCDEF' for char in revision) else revision + modes = ' / '.join(metadata.get("modes") or []) or "Not recorded" + started = str(metadata.get("started_utc") or "Not recorded") + try: + parsed = datetime.fromisoformat(started.replace('Z', '+00:00')) + if parsed.tzinfo is not None: + parsed = parsed.astimezone(timezone.utc) + started = parsed.strftime('%d %b %Y · %H:%M UTC') + except ValueError: + pass + total = sum(counts.values()) + metrics = ['
    Total ' + 'checks' + f'{total:,}' + '
    '] + for key, label in (("PASS", "Passed"), ("FAIL", "Failed checks"), ("WARN", "Warnings"), ("BLOCKED", "Not verified")): + number = counts.get(key, 0) + metrics.append('
    ' + label + + '' + f'{number:,}' + '
    ') + empty_message = ('

    No findings to ' + 'review

    All recorded checks passed. ' + 'See the JSON report for every assertion and its ' + 'evidence.

    ' if total else + '

    No checks were ' + 'recorded

    This run is incomplete; ' + 'a lack of findings is not a passing result.

    ') + fields = (("Revision", revision), ("Modes", modes), + ("Check groups", ', '.join(metadata.get("check_groups") or []) or "Not recorded"), + ("Started", started), ("Parser source", metadata.get("parser_dir")), + ("Python", metadata.get("python")), ("Scope", metadata.get("scope")), + ("Worktree", metadata.get("worktree_status"))) + metadata_html = ''.join('
    ' + name + '
    ' + escape(str(value or "Not recorded")) +
    +                            '
    ' for name, value in fields) + tone = 'fail' if status == 'FAIL' else 'blocked' if status == 'INCOMPLETE' else 'pass' + human_status = "Needs attention" if status == "FAIL" else "Checks incomplete" if status == "INCOMPLETE" else "Checked scope passed" + presentation_note = ('

    ' + escape(str(metadata["presentation_note"])) + '

    ' + if metadata.get("presentation_note") else '') + guide = ('

    What needs attention?

    ' + '

    Start with the failed topics, then review warnings. Several ' + 'failed checks can describe the same problem. ' + 'Package summaries are listed separately. Open the evidence only when ' + 'you need the technical detail.

    ' + '
    ') if actionable else '' + return ('' + '' + 'Log parser doctor · Health report' + '
    ' + '

    SYSTEMREADY ACS · REPOSITORY HEALTH

    ' + '

    Log parser health report

    What ' + 'happened, why it matters, and what to check next.

    ' + '
    DOCTOR RESULT · ' + escape(status) + + '' + human_status + + '
    ' + 'Revision ' + escape(short_revision) + '' + 'Modes ' + + escape(modes) + 'Tested ' + escape(started) + '
    ' + '
    ' + presentation_note + '
    ' + '
    ' + ''.join(metrics) + '
    ' + '

    ' + 'These are parser-health checks, not hardware test ' + 'results. Counts are assertions, not distinct bugs. ' + 'Blocked checks have not been verified.

    ' + guide + + '
    ' + '
    ' + '
    ' + '
    ' + '
    ' + '
    ' + '

    ' + 'Showing all ' + str(len(actionable)) + + ' flagged checks

    ' + '' + '' + '
    ' + '
    ' + '' + (''.join(section_html) if groups else empty_message) + + '
    ' + '
    Run details & ' + 'provenance
    SYSTEMREADY ACS · LOG PARSER DOCTOR' + 'All recorded results are retained. Explanations do not change ' + 'check outcomes.
    ' + '') diff --git a/common/log_parser/standalone_runner.py b/common/log_parser/standalone_runner.py index c7a3eea6..b8730bf3 100755 --- a/common/log_parser/standalone_runner.py +++ b/common/log_parser/standalone_runner.py @@ -14,9 +14,16 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Portable, strict suite-wise SystemReady log parser orchestration.""" +"""Run selected SystemReady log parsers and publish their requested reports. + +This entry point checks inputs, calls the existing suite parsers, then applies +waivers and builds JSON, HTML or PDF output. Doctor is a separate, optional +path: --doctor checks readiness, and --doctor --health runs deeper checks. +Normal parsing never waits for a successful Doctor health report. +""" import argparse +import hashlib import json import os import re @@ -1023,6 +1030,29 @@ def copy_run_configs(stage, args): raise StandaloneError(f"Cannot copy current run configuration: {error}", EXIT_OUTPUT) from error +def record_category_provenance(stage, args, test_category): + """Record which category file was used so Doctor does not have to guess.""" + category = {"source": "explicit" if args.test_category else "bundled"} + effective = test_category + try: + config_dir = stage / "config" + config_dir.mkdir(exist_ok=True) + if args.test_category: + # Parse using the saved copy too. Its checksum then proves which + # content was used, even if the original file changes later. + content = Path(test_category).read_bytes() + effective = config_dir / "test_category.json" + effective.write_bytes(content) + category.update(path="config/test_category.json", sha256=hashlib.sha256(content).hexdigest()) + # This is run metadata, not a health check or a compliance decision. + (config_dir / "parser_run.json").write_text(json.dumps({ + "format_version": 1, "mode": args.mode, "test_category": category, + }, indent=2) + "\n", encoding="utf-8") + except OSError as error: + raise StandaloneError(f"Cannot record current run category: {error}", EXIT_OUTPUT) from error + return effective + + def publish_output(target, stage, roots, direct_inputs=()): try: validate_output_target(target, roots, direct_inputs) @@ -1073,6 +1103,9 @@ def build_parser(): action="store_true", help="Validate registry, dependencies, inputs, and output readiness, then exit", ) + # Add the optional flags to help output without starting any Doctor checks. + from doctor import add_arguments + add_arguments(parser) parser.add_argument("--list-suites", action="store_true", help="List suites and exit") parser.add_argument( "--version", @@ -1222,9 +1255,28 @@ def main(): sys.stdout.reconfigure(line_buffering=True) validate_python_version() signal.signal(signal.SIGTERM, handle_termination) - _, standalone = load_registry_data(DEFAULT_REGISTRY) parser = build_parser() args = parser.parse_args() + if args.health: + # Health checks use their own disposable inputs, not a normal parse. + # Dispatch before loading the registry so Doctor can report damage to it. + if not args.doctor: + parser.error("--health requires --doctor") + if any((args.suites, args.input_logs, args.output, args.outputs, args.schema, + args.acs_config, args.system_config, args.waiver, args.test_category, + args.list_suites)): + parser.error("Health checks use disposable fixtures; use --doctor-report MODE=PATH " + "for existing reports, not parsing/input options") + from doctor import run_health + sys.dont_write_bytecode = True + try: + return run_health(args, BASE_DIR) + except (ValueError, OSError) as error: + raise StandaloneError("Doctor input/output error: " + str(error), EXIT_INPUT) from error + if (args.doctor_output or args.doctor_report or args.doctor_timeout != 60 or + args.doctor_checks or args.doctor_visual or args.doctor_browser): + parser.error("--doctor-* health options require --doctor --health") + _, standalone = load_registry_data(DEFAULT_REGISTRY) registry = load_registry() if args.list_suites: @@ -1307,6 +1359,7 @@ def main(): print(f" Test category : {test_category}") if args.doctor: + # The quick precheck stops here; it does not parse logs or publish results. for canonical in selected: resolved = resolve_suite_inputs( canonical, @@ -1325,6 +1378,8 @@ def main(): check_output_readiness(Path(args.output)) print(" Output destination READY") print("Standalone preflight result: PASS") + print("Readiness only: log contents and compliance were not evaluated. " + "Use --doctor --health for repository correctness checks.") return 0 target, stage = prepare_output(Path(args.output), roots, direct_paths) @@ -1335,6 +1390,8 @@ def main(): if "html" in outputs: html_dir.mkdir(parents=True) copy_run_configs(stage, args) + # Keep evidence of category selection for a later, optional Doctor run. + test_category = record_category_provenance(stage, args, test_category) results = [] missing_suites = [] diff --git a/docs/log_parser_guide.md b/docs/log_parser_guide.md index 4a52beb1..dd7b3987 100644 --- a/docs/log_parser_guide.md +++ b/docs/log_parser_guide.md @@ -1,5 +1,9 @@ # SystemReady ACS Log Parser Guide +This guide explains how to turn ACS logs into reports, choose parser options, +and investigate problems. Doctor is an optional manual health check; it is +not required before parsing logs, committing changes, or opening a pull request. + ## Contents 1. [Purpose](#purpose) @@ -708,6 +712,183 @@ Use the same mode, input, suites, output stages, schema flag, configs, waiver, and output path planned for the real run. Then remove only `--doctor`. This ensures the preflight checks the dependencies and files for the intended run. +#### Repository health and result correctness + +Use `--doctor --health` to run **deeper, isolated correctness checks**. This is +separate from the fast readiness preflight above. It does not repair parser +code, apply real platform waivers, or modify supplied reports. Synthetic logs, +waivers, parser outputs and reproduction commands are kept in a new directory. + +From the repository root, using the Python environment containing +`common/log_parser/requirements.txt` dependencies: + +```bash +bash common/log_parser/main_log_parser.sh --standalone --doctor --health \ + --doctor-output /path/to/new-doctor-results +``` + +Both DT and SR are checked by default. `--mode DT` or `--mode SR` restricts the +scope. No suite, input log or ACS configuration arguments are required. To also +validate existing generated report packages (read-only): + +```bash +bash common/log_parser/main_log_parser.sh --standalone --doctor --health \ + --doctor-output /path/to/new-doctor-results \ + --doctor-report DT=/path/to/DT/report-package \ + --doctor-report SR=/path/to/SR/report-package +``` + +The output directory must not already exist or be inside a supplied report or +the parser source directory. Without `--doctor-output`, a new temporary directory +is created and its location is printed. `--doctor-timeout 60` sets the timeout +per external command, not a total time limit. + +The health checks cover registry and syntax integrity; supported suite/mode +compliance combinations; mandatory, recommended and extension behavior; +waivers; incomplete inputs; merged JSON and HTML agreement; and selected/full +run consistency. Small synthetic fixtures exercise known failure patterns. +Supplied report checks add schema validation and static report consistency +checks against real captures. Expected compliance is checked independently of +the merger's answer: recommended failures/missing results are non-blocking for +overall SRS, while suite-level failures remain visible. Changes to this policy +need owner agreement, not silently updated expected values. + +Doctor also reuses independent contracts from the PR QA work: + +- An explicitly reviewed requirement map detects accidental registry policy + changes. New suites and modes need their own expected requirements and native + log fixtures; they cannot silently fall outside health coverage. +- Native fixtures cover 25 executable entries / 32 DT/SR routes, including the + SR-only, Recommended PCIe Option ROM suite. Its pass, fail and skip examples + have independent expected results; an absent Recommended PCIe result must + not block overall compliance. Newly registered routes still require their + own expected requirements and sample logs. Exact test + IDs, descriptions, statuses, nested paths and record inventories are checked, + not only totals. Swapping a passing and failing test must fail even if totals + remain unchanged. Raw-schema checks run separately from identity checks. +- Bad-input checks use a complete control before testing empty, introductory-only, + truncated and malformed examples. They include the DT utility, PFDI, SCMI and + OS routes and SR OS/PCIe routes. An unusable control is reported as BLOCKED, + not accepted as passing coverage. Each finding retains the input, command + and observed JSON/HTML decision; these checks do not fix the parser. +- Conditional-requirement checks keep execution evidence separate from JSON + availability. Source-backed SBSA, SBMR IB/OOB and PFDI records are replayed and + their exact parsed results checked before their JSON is deliberately omitted + from a separate merge. Executed SBSA stays Mandatory; execution of either SBMR + interface makes both Mandatory; executed PFDI remains applicable + Conditional-Mandatory. Missing results must not erase those obligations or + become green. Empty files and banners alone are not execution proof. These + controlled direct-merger probes warn about lost execution context; they do + not establish a public-flow failure or routine JSON loss. Standalone already + checks generated JSON before publishing, and normal-flow conversion failure + is not injected by this probe. Report-package-only checks cannot independently + establish execution when original logs are unavailable. None of these checks + establishes hardware certification. +- The real `package_standalone.sh` archive and SHA-256 are checked, extracted + outside the checkout, and compared against the runtime files. Native probes + use that extracted parser with checkout imports disabled. Doctor does not + install dependencies or claim a fresh-environment installation test. +- Supplied artifacts are checked for ambiguous JSON, changed raw-to-merged + records, HTML result identity/count mismatches and broken local links. These + checks never rewrite a report to make it pass. + +For a focused rerun, select groups explicitly: + +```bash +bash common/log_parser/main_log_parser.sh --standalone --doctor --health \ + --doctor-checks policy,package,native \ + --doctor-output /path/to/new-native-health-results +``` + +Groups are `policy`, `package`, `native`, `merge`, `raw` and `reports`. +`native` automatically includes `package`. Omit `--doctor-checks` to run all +default groups. An unavailable prerequisite blocks its affected group, not +unrelated checks. Missing newer HTML compliance features are reported separately +while JSON compliance scenarios still run. A focused PASS is not a full health +PASS; the selected and omitted groups are recorded. + +Optional browser and PDF smoke checks use synthetic FWTS pass/fail/waiver +reports for each selected mode, Chromium at desktop/mobile widths, and the +public PDF export. Install Chromium and the optional `pypdf` module separately; +`weasyprint` is already listed in the parser requirements: + +```bash +bash common/log_parser/main_log_parser.sh --standalone --doctor --health \ + --doctor-visual --doctor-browser /absolute/path/to/chromium \ + --doctor-output /path/to/new-visual-health-results +``` + +`--doctor-browser` can be omitted if `chromium` or `chromium-browser` is on PATH. +Requested visual checks with missing dependencies are BLOCKED, never silently +passed. These checks cover UI initialization, visible counts, search/filter +behavior, horizontal overflow, and PDF identity/compliance/count preservation. +They do not certify every suite's layout, browser, paper size or pagination. +Supplied reports are never executed in a browser; only disposable synthetic +reports are used for these checks. + +Open `index.html` for plain-language topics showing **what happened**, **why it +matters**, **next steps**, and examples from the run. Expand a topic for the +original check IDs, expected/actual results, and evidence links. Search and +status/mode/suite filters narrow the evidence; the recorded totals stay unchanged. +Package-level summaries are separated from the individual findings they repeat. +`doctor.md` contains readable findings; `doctor.json` contains +every assertion, including passes, the source revision/hashes and coverage +warnings. The evidence directory includes synthetic input files and command +logs. These are diagnostic fixtures, **not real hardware test results**. + +Doctor requires missing `Test_suite_info` only when a category file was explicitly +supplied to the generating run. New standalone outputs record that choice in +`config/parser_run.json`; explicit categories are copied into the output and +the parser consumes that snapshot. Doctor verifies its recorded checksum before +using it as evidence. Bundled defaults do not trigger the missing-info requirement. +Older reports with no category record receive a warning when this requirement +cannot be decided, rather than guessing what was supplied. Invalid category +records fail the provenance check. Existing malformed `Test_suite_info` values +and all other schema requirements remain checked. This is Doctor's applicability +rule; it does not change schema files, raw result data, or strict `--schema` / +`validate.py` validation. Native checks retain the strict validator log separately. + +| Doctor status | Meaning | +|---|---| +| PASS | This recorded assertion matched its expected result. | +| FAIL | A reproducible result or repository defect violated the checked contract. | +| BLOCKED | A dependency, timeout or probe problem prevented verification. | +| WARN | A policy or coverage limit needs separate review. | + +Exit code **0** means the executed scope passed; **1** means at least one +failure was found; **2** means checks were incomplete with no confirmed failure. +Invalid wrapper arguments use the standalone CLI's input-error handling. +Existing bugs therefore make the doctor fail even when the doctor's own unit +tests pass. Missing dependencies and zero executed checks never count as green. + +Doctor is a manually invoked health tool, separate from automatic PR CI. It +does not depend on staged/unstaged files and is not automatically installed as +a Git hook or CI gate. Archive its full output directory even when it exits +nonzero. Run on real DT/SR report packages as well as synthetic fixtures. +The implementation and its sample data live in `common/log_parser/doctor_checks/`. +The small `common/log_parser/doctor.py` launcher preserves existing commands and +imports used by the standalone runner. Packaging includes this folder automatically; +normal parsing does not load the check groups or start health checks. +Full browser/print coverage, actual hardware execution and unresolved +all-skipped/aborted-result policies still require separate validation. A passing +doctor cannot guarantee the absence of every possible parser defect. + +If an import or syntax error prevents the normal wrapper from starting, invoke +the independent entry point so it can report that repository damage: + +```bash +python3 -B common/log_parser/doctor.py --health \ + --doctor-output /path/to/new-doctor-results +``` + +The doctor's own positive/negative controls can be run independently of known +production parser bugs: + +```bash +python3 -B -m unittest discover -s common/acs_test_framework_runner \ + -p 'test_doctor*.py' -v +``` + ### Output Selection Default standalone stages are: