#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Can each rung fail? Break the core on purpose and see which tests notice. docs/validation.md: "Before a rung is called passed, break the model on purpose in ways that rung should catch ... and see it fail." Each fault below is one textual change to a copy of the package (under the git-ignored validation/build/faults/); the test suite is run against the copy and the test files with failures are listed. The unbroken copy is run first and must pass. python validation/faults.py Exit status 1 if the unbroken copy fails or any fault goes unnoticed by every rung. """ from __future__ import annotations import os import re import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] PACKAGE = ROOT / "src" / "sn76489_python" WORK = ROOT / "validation" / "build" / "faults" RUNGS = { "test_contract.py": "rung 0", "test_capture.py": "rung 1", "test_manuals.py": "rung 2", "test_community.py": "rung 3", "test_provisional.py": "provisional", } # (what is broken, file, text to find, replacement, every occurrence?) FAULTS: tuple[tuple[str, str, str, str, bool], ...] = ( ("discrete chip: noise taps moved", "variants.py", "white_noise_taps=0x0003", "white_noise_taps=0x0005", False), ("discrete chip: 16 stages", "variants.py", "lfsr_bits=15", "lfsr_bits=16", False), ("Sega parts: the discrete chip's taps", "variants.py", "white_noise_taps=0x0009", "white_noise_taps=0x0003", True), ("Sega parts: 15 stages", "variants.py", "lfsr_bits=16", "lfsr_bits=15", True), ("volume table shifted one step", "variants.py", "10 ** (-0.1 * step)", "10 ** (-0.1 * (step + 1))", False), ("data bytes to attenuation and noise ignored", "variants.py", "data_byte_reaches_all_registers: bool = True", "data_byte_reaches_all_registers: bool = False", False), ("Sega parts loud at power-on", "variants.py", "power_on_attenuation: int = 15", "power_on_attenuation: int = 0", False), ("discrete chip: tone value 0 as on Sega's", "variants.py", "tone_zero_period=1024,", "tone_zero_period=1,", False), ("register 3 latched at power-on", "variants.py", "power_on_latch: int = 0", "power_on_latch: int = 3", False), ("no reset of the shift register on a noise write", "chip.py", " self.lfsr = 1 << (self.variant.lfsr_bits - 1)\n", " pass\n", False), ("divide by 8 instead of 16", "chip.py", "CLOCKS_PER_SAMPLE = 16", "CLOCKS_PER_SAMPLE = 8", False), ("tone period one tick long", "chip.py", "counter0 = period0\n", "counter0 = period0 + 1\n", False), ("fixed noise rates halved", "chip.py", "noise_period = 0x10 << rate", "noise_period = 0x20 << rate", False), ("noise at rate 3 shifts on both edges", "chip.py", "shift = follows_tone and output2 == shift_level", "shift = follows_tone", False), ("periodic noise fed back like white", "chip.py", "else 0x0001", "else 0x0003", False), ("noise bit taken one stage early", "chip.py", "noise_bit = lfsr & 1", "noise_bit = (lfsr >> 1) & 1", False), ("stereo: left reads the right-hand bits", "chip.py", "stereo & (0x10 << channel)", "stereo & (0x01 << channel)", False), ("tone data byte lands in the low bits", "chip.py", "((value & 0x3F) << 4)", "(value & 0x3F)", False), ("latch byte does not write the tone", "chip.py", "(self.tone[channel] & 0x3F0) | (value & 0x0F)", "self.tone[channel]", False), ("a new tone value restarts the count", "chip.py", " self.tone[channel] = (self.tone[channel] & 0x00F) | ((value & 0x3F) << 4)\n", " self.tone[channel] = (self.tone[channel] & 0x00F) | ((value & 0x3F) << 4)\n self.counters[channel] = 0\n", False), ("test override ignored", "chip.py", "overridden = self.test & 1", "overridden = 0", False), ("noise divider not kept between runs", "chip.py", " self.noise_counter = noise_counter\n", "", False), ) # fmt: skip def run_tests(package_parent: Path, check_import: bool = False) -> tuple[bool, set[str]]: """Run the suite against the package under ``package_parent``. PYTHONPATH comes before the editable install on the path, so the copy is what the tests import; ``check_import`` proves it once. """ environment = dict(os.environ, PYTHONPATH=str(package_parent), PYTHONDONTWRITEBYTECODE="1") if check_import: check = subprocess.run( [sys.executable, "-c", "import sn76489_python; print(sn76489_python.__file__)"], env=environment, capture_output=True, text=True, check=True, ) # fmt: skip if str(package_parent) not in check.stdout: sys.exit(f"the copy at {package_parent} is not the package under test") result = subprocess.run( [sys.executable, "-m", "pytest", "-q", "--no-header", "-p", "no:cacheprovider", "-o", "pythonpath=tests", "-rfE", "--tb=no"], cwd=ROOT, env=environment, capture_output=True, text=True, check=False, ) # fmt: skip failed = set(re.findall(r"^(?:FAILED|ERROR) tests/(test_\w+\.py)", result.stdout, re.MULTILINE)) return result.returncode == 0, failed def make_copy( index: int, file: str = "", find: str = "", replacement: str = "", every=False ) -> Path: parent = WORK / f"{index:02d}" target = parent / "sn76489_python" target.mkdir(parents=True, exist_ok=True) for source in PACKAGE.glob("*.py"): text = source.read_text() if source.name == file: count = text.count(find) if count == 0 or (count > 1 and not every): sys.exit(f"fault {index}: {find!r} occurs {count} times in {file}") text = text.replace(find, replacement) (target / source.name).write_text(text) return parent def main() -> int: passed, failed = run_tests(make_copy(0), check_import=True) if not passed: print(f"the unbroken copy fails: {sorted(failed)}") return 1 print("unbroken copy: all tests pass\n") caught = dict.fromkeys(RUNGS, 0) unnoticed = [] for index, (what, file, find, replacement, every) in enumerate(FAULTS, start=1): passed, failed = run_tests(make_copy(index, file, find, replacement, every)) if not passed and not failed: failed = set(RUNGS) # the suite could not even be collected for name in failed: caught[name] += 1 seen_by = ", ".join(RUNGS[name] for name in RUNGS if name in failed) or "NOBODY" if not failed: unnoticed.append(what) print(f"{index:2d}. {what}: {seen_by}") print() for name, rung in RUNGS.items(): print(f"{rung} ({name}): notices {caught[name]} of {len(FAULTS)} faults") print(f"unnoticed by every rung: {len(unnoticed)} {unnoticed if unnoticed else ''}") return 1 if unnoticed else 0 if __name__ == "__main__": sys.exit(main())