# SPDX-License-Identifier: MIT """Run a Lynx Hardware Tests ROM (drhelius, MIT) to its results and judge them. The suites are built from source (``scripts/build_lynx_tests.py``); each one's ``run_tests`` fills ``g_results`` before the result screen is drawn. This harness boots the ROM through the real boot ROM, runs until ``run_tests`` returns, reads ``g_results`` (address from the cc65 label file) and judges it with the suite's own expectation table, parsed from its ``main.c``: - ``k_expected_results``: one set of accepted values per result byte (``EXPECT(a, b, ...)``), grouped into tests by ``k_test_offsets`` / ``k_test_counts`` where the suite has them, else evenly; - ``timers2``: a test passes when its result byte is 0. The expected values are the tests' author's record of real consoles (tier 3). """ from __future__ import annotations import re from dataclasses import dataclass, field from pathlib import Path from lynx_python import bootrom from lynx_python.board import Lynx from lynx_python.cart import load from lynx_python.machine import DEFAULT, Machine ROOT = Path(__file__).resolve().parents[2] BUILD = ROOT / "tests" / "test_roms" / "build" SOURCE = ROOT / "reference" / "src" / "lynx-tests" TICKS_PER_SECOND = 16_000_000 @dataclass class Suite: name: str results: int names: list[str] expected: list[tuple[int, ...]] groups: list[tuple[int, int]] # (offset, count) per test zero_is_pass: bool = False #: Sprite suites: per test a 16-bit Timer 1/3 duration window and two CRC bytes #: (video, collision), laid out timing low, high, CRC 1, CRC 2 (sprites*/main.c). timings: list[tuple[int, int]] = field(default_factory=list) @dataclass class Outcome: suite: str machine: str results: bytes passed: list[bool] = field(default_factory=list) finished: bool = True #: Sprite suites: the CRC checks alone (function, milestone 4) per test. function: list[bool] = field(default_factory=list) def summary(self) -> str: text = f"{sum(self.passed)}/{len(self.passed)}" if self.function: text += f" (CRCs {sum(self.function)}/{len(self.function)})" return text def _c_block(text: str, name: str) -> str | None: match = re.search(rf"{name}\s*\[[^\]]*\]\s*=\s*\{{(.*?)\}};", text, re.DOTALL) return match.group(1) if match else None def _ints(text: str) -> list[int]: return [int(v, 0) for v in re.findall(r"0x[0-9A-Fa-f]+|\b\d+\b", text)] def parse_suite(name: str) -> Suite: text = (SOURCE / name / "main.c").read_text(encoding="utf-8") defines = dict(re.findall(r"#define\s+(\w+)\s+(\d+)", text)) tests = int(defines["TEST_COUNT"]) results = int(defines.get("RESULT_COUNT", tests)) names_block = _c_block(text, "k_test_names") or "" names = re.findall(r'"([^"]*)"', names_block) block = _c_block(text, "k_expected_results") timing_block = _c_block(text, "k_expected_timings") if block is None and timing_block is not None: crcs = re.sub(r"/\*.*?\*/", "", _c_block(text, "k_expected_crcs") or "", flags=re.DOTALL) expected = [] timings = [ tuple(_ints(args))[:2] for args in re.findall(r"EXPECT_RANGE16\(([^)]*)\)", timing_block) ] crc_values = [tuple(_ints(args)) for args in re.findall(r"EXPECT\(([^)]*)\)", crcs)] for t in range(tests): expected.extend([(), (), crc_values[2 * t], crc_values[2 * t + 1]]) groups = [(4 * t, 4) for t in range(tests)] return Suite(name, results, names, expected, groups, timings=timings) if block is None: groups = [(t, 1) for t in range(tests)] return Suite(name, results, names, [], groups, zero_is_pass=True) block = re.sub(r"/\*.*?\*/", "", block, flags=re.DOTALL) expected = [tuple(_ints(args)) for args in re.findall(r"EXPECT\(([^)]*)\)", block)] offsets = _c_block(text, "k_test_offsets") counts = _c_block(text, "k_test_counts") if offsets is not None and counts is not None: groups = list(zip(_ints(offsets), _ints(counts), strict=True)) else: per = len(expected) // tests groups = [(t * per, per) for t in range(tests)] return Suite(name, results, names, expected, groups) def symbols(name: str) -> dict[str, int]: table = {} for line in (BUILD / name / f"{name}.sym").read_text().splitlines(): parts = line.split() if len(parts) == 3 and parts[0] == "al": table[parts[2].lstrip(".")] = int(parts[1], 16) return table def boot(name: str, machine: Machine = DEFAULT) -> Lynx: description = load(BUILD / name / f"{name}.lnx") board = Lynx(description.payload, description.bank0_block, machine=machine, boot_rom=bootrom.find()) # fmt: skip board.reset() return board def run(name: str, machine: Machine = DEFAULT, seconds: float = 30.0, board=None) -> Outcome: suite = parse_suite(name) labels = symbols(name) entry, results_at = labels["_run_tests"], labels["_g_results"] board = board or boot(name, machine) cpu = board.cpu limit = board.tick + int(seconds * TICKS_PER_SECOND) step = board.step while cpu.pc != entry and board.tick < limit: step() ret = None if cpu.pc == entry: s = cpu.s ret = ( (board.ram[0x100 + ((s + 1) & 0xFF)] | (board.ram[0x100 + ((s + 2) & 0xFF)] << 8)) + 1 ) & 0xFFFF while cpu.pc != ret and board.tick < limit: step() finished = ret is not None and cpu.pc == ret data = bytes(board.ram[results_at : results_at + suite.results]) outcome = Outcome(name, machine.name, data, finished=finished) for t, (offset, count) in enumerate(suite.groups): if not finished: # The results are untouched RAM (zeros); a suite whose expectations are # zero would otherwise "pass" without running. outcome.passed.append(False) if suite.timings: outcome.function.append(False) continue if suite.zero_is_pass: outcome.passed.append(data[offset] == 0) continue if suite.timings: crc_ok = data[offset + 2] in suite.expected[offset + 2] and ( data[offset + 3] in suite.expected[offset + 3] ) low, high = suite.timings[t] duration = data[offset] | (data[offset + 1] << 8) outcome.function.append(crc_ok) outcome.passed.append(crc_ok and low <= duration <= high) continue ok = all( i < len(suite.expected) and data[i] in suite.expected[i] for i in range(offset, offset + count) ) outcome.passed.append(ok) return outcome def report(outcome: Outcome) -> str: suite = parse_suite(outcome.suite) lines = [ f"{outcome.suite} on {outcome.machine}: {outcome.summary()} tests pass" + ("" if outcome.finished else " (run_tests did not return)") ] for t, ((offset, count), ok) in enumerate(zip(suite.groups, outcome.passed, strict=True)): name = suite.names[t] if t < len(suite.names) else f"test {t + 1}" got = outcome.results[offset : offset + count].hex(" ").upper() want = "" if suite.timings: low, high = suite.timings[t] duration = outcome.results[offset] | (outcome.results[offset + 1] << 8) crcs = ( "/".join(f"{v:02X}" for v in suite.expected[offset + 2]) + " " + "/".join(f"{v:02X}" for v in suite.expected[offset + 3]) ) crc = "CRC ok" if outcome.function[t] else f"CRC want {crcs}" want = f" time {duration:04X} in {low:04X}-{high:04X}? {crc}" elif not ok and suite.expected: want = " want " + " ".join( "/".join(f"{v:02X}" for v in suite.expected[i]) if i < len(suite.expected) else "?" for i in range(offset, offset + count) ) lines.append(f" {t + 1:2} {'PASS' if ok else 'FAIL'} {name:<16} {got}{want}") return "\n".join(lines)