#!/usr/bin/env python3 """Rung 6: can the tests fail? Seeded faults, each caught by some rung. Each fault is one textual change to a copy of the package under the git-ignored ``validation/build/faults/``. The test suite runs against each copy until its first failure (PYTHONPATH ahead of the repository's ``src``; pytest's own ``pythonpath`` setting is overridden so the copy is what the tests import). The unbroken copy runs first and must pass. PYPY_GC_NURSERY=1M .venv-pypy/bin/python -I validation/faults.py Exit status 1 if the unbroken copy fails or any fault goes unnoticed. """ from __future__ import annotations import os import shutil import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] PACKAGE = ROOT / "src" / "tms9918_python" WORK = ROOT / "validation" / "build" / "faults" # (what is broken, file, text to find, replacement) FAULTS: tuple[tuple[str, str, str, str], ...] = ( ("name table row stride 16 instead of 32", "tables.py", "return (r2 & 0x0F) << 10 | (line >> 3) << 5 | column", "return (r2 & 0x0F) << 10 | (line >> 3) << 4 | column"), ("Graphics I colour byte per 4 names", "tables.py", "return r3 << 6 | name >> 3", "return r3 << 6 | name >> 2"), ("Text area at 8 pixels in", "tables.py", "TEXT_LEFT = 19 - 13", "TEXT_LEFT = 8"), ("register 1 keeps bit 2", "tables.py", "REGISTER_MASKS = (0x03, 0xFB,", "REGISTER_MASKS = (0x03, 0xFF,"), ("CPU window every 8 memory cycles in the pattern modes", "_schedule.py", "second_is_cpu = g % 4 == 0", "second_is_cpu = g % 2 == 0"), ("4K mux skipped", "tables.py", " if mode_16k:\n column, row", " if True:\n column, row"), ("no 4K roll-over", "tables.py", " if not mode_16k and roll_over_4k:", " if False:"), ("C3 gate ignored", "tables.py", " if colour_mask_masks_patterns:\n pattern_mask", " if False:\n pattern_mask"), ("Graphics II thirds ignored for colours", "chip.py", " char = (line >> 6) << 8 | self._name\n addr = T.graphics2_colour_address", " char = self._name\n addr = T.graphics2_colour_address"), ("Multicolor low nibble on the left", "chip.py", "left, right = pattern >> 4, pattern & 0x0F", "right, left = pattern >> 4, pattern & 0x0F"), ("flip-flop not cleared by a data write", "chip.py", " # Any data-port access clears the flip-flop [Young 2.3].\n self._second = False\n", " # Any data-port access clears the flip-flop [Young 2.3].\n"), ("read-ahead not refilled by a data read", "chip.py", " value = self.read_ahead\n self._request(_READ, 0)\n return value", " value = self.read_ahead\n self.addr = (self.addr + 1) & 0x3FFF\n return value"), ("a data write leaves the read-ahead alone", "chip.py", " self.read_ahead = value\n self._request(_WRITE, value)", " self._request(_WRITE, value)"), ("register write keeps the address", "chip.py", " self.addr = (value & 0x3F) << 8 | self._first\n if value & 0x80:", " if not value & 0x80:\n self.addr = (value & 0x3F) << 8 | self._first\n if value & 0x80:"), ("status read leaves C set", "chip.py", " self.status &= T.STATUS_NUMBER\n return value", " self.status &= T.STATUS_NUMBER | T.STATUS_C\n return value"), ("/INT ignores IE", "chip.py", "return bool(self.status & T.STATUS_F and self.regs[1] & T.R1_IE)", "return bool(self.status & T.STATUS_F)"), ("F one line late", "chip.py", "flag_dot: tuple[int, int] = (191, 266),", "flag_dot: tuple[int, int] = (192, 266),"), ("5S without the F gate", "chip.py", " if not status & T.STATUS_F:\n status |= T.STATUS_5S", " if True:\n status |= T.STATUS_5S"), ("five sprites a line", "chip.py", "if len(self._eval_found) < 4:", "if len(self._eval_found) < 5:"), ("terminator ignored", "chip.py", " if y == 0xD0:\n", " if y == 0x1D0:\n"), ("sprite Y without the + 1", "chip.py", " dy = self._eval_target - top - 1\n", " dy = self._eval_target - top\n"), ("early clock 16 pixels", "chip.py", "x -= 32 # early clock", "x -= 16 # early clock"), ("higher sprite number in front", "chip.py", "if 0 <= px < 256 and colour and not colours[px]:", "if 0 <= px < 256 and colour:"), ("visible columns only for C by default", "chip.py", "offscreen_collisions: bool = True,", "offscreen_collisions: bool = False,"), ("no VDP delay", "variants.py", "access_delay: int = 16", "access_delay: int = 2"), ("VATT rejects: the VDP delay restarts on every access", "chip.py", 'lost_access: str = "newer",', 'lost_access: str = "restart",'), ("Multicolor colour slots as CPU windows (TI table 2-2 reading)", "_schedule.py", "MULTICOLOR_LINE = GRAPHICS_LINE", "MULTICOLOR_LINE = _pattern_mode_line(colour_fetch=False)"), ("TMS9929A at 262 lines", "variants.py", "PAL_LAYOUT = VerticalLayout(192, 51, 3, 3, 13, 51)", "PAL_LAYOUT = VerticalLayout(192, 24, 3, 3, 13, 27)"), ) # fmt: skip def make_copy(index: int, fault: tuple[str, str, str, str] | None) -> Path: parent = WORK / f"{index:02d}" if parent.exists(): trash = ROOT / "trash" / "faults-build" trash.mkdir(parents=True, exist_ok=True) parent.rename(trash / f"{index:02d}-{os.getpid()}") shutil.copytree(PACKAGE, parent / "tms9918_python", ignore=shutil.ignore_patterns("__pycache__")) # fmt: skip if fault is not None: _, name, old, new = fault path = parent / "tms9918_python" / name text = path.read_text() if text.count(old) != 1: sys.exit(f"fault {index}: text found {text.count(old)} times in {name}") path.write_text(text.replace(old, new)) return parent def run_suite(parent: Path) -> tuple[bool, list[str]]: env = dict(os.environ, PYTHONPATH=str(parent), PYTHONDONTWRITEBYTECODE="1") check = subprocess.run( [sys.executable, "-c", "import tms9918_python; print(tms9918_python.__file__)"], env=env, capture_output=True, text=True, check=True, ) # fmt: skip if str(parent) not in check.stdout: sys.exit(f"the copy at {parent} is not what imports") result = subprocess.run( [sys.executable, "-m", "pytest", "-q", "--no-header", "-p", "no:cacheprovider", "-o", "pythonpath=tests", "-rf", "--tb=no", "-x"], cwd=ROOT, env=env, capture_output=True, text=True, check=False, ) # fmt: skip # -x: the run stops at the first failing test (files run rung by rung, fastest first), # so the report names the first test that caught the fault. failed = [line.split(" ", 1)[1].split(" - ")[0] for line in result.stdout.splitlines() if line.startswith(("FAILED", "ERROR"))] # fmt: skip return result.returncode == 0, failed def main() -> int: WORK.mkdir(parents=True, exist_ok=True) ok, failed = run_suite(make_copy(0, None)) print(f"unbroken copy: {'passes' if ok else 'FAILS ' + ', '.join(failed)}") if not ok: return 1 missed = 0 for i, fault in enumerate(FAULTS, 1): ok, failed = run_suite(make_copy(i, fault)) status = "MISSED" if ok else "caught by " + ", ".join(failed) missed += ok print(f"{i:2d}. {fault[0]}: {status}") sys.stdout.flush() print(f"{len(FAULTS) - missed} of {len(FAULTS)} faults caught") return 1 if missed else 0 if __name__ == "__main__": sys.exit(main())