#!/usr/bin/env python3 """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. About a minute and a half on PyPy. """ 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" / "ym2612_python" WORK = ROOT / "validation" / "build" / "faults" RUNGS = { "test_contract.py": "rung 0", "test_measured.py": "rung 1", "test_manuals.py": "rung 2", "test_community.py": "rung 4", "test_provisional.py": "provisional", } # (what is broken, file, text to find, replacement, every occurrence?) FAULTS: tuple[tuple[str, str, str, str, bool], ...] = ( ("no 17-bit wrap after detune", "operator.py", "& 0x1FFFF", "& 0xFFFFFF", True), ("high F-number byte applied at once", "chip.py", " self.fnum_latch[latch] = value & 0x3F\n", " self.fnum_latch[latch] = value & 0x3F\n channel.block = value >> 3 & 7\n", False), ("timers at the YM2612 manual's rate (72 clocks)", "chip.py", " self.timer_a_counter += 1\n", " self.timer_a_counter += 2\n", False), ("CSM acts in mode 01", "chip.py", " if self.channel3_mode == 2:", " if self.channel3_mode == 1:", False), ("SSG-EG factor 6", "operator.py", "attenuation += 4 * increment", "attenuation += 6 * increment", False), ("SSG-EG inversion by exclusive-or with $1FF", "operator.py", "level = (SSG_THRESHOLD - level) & 0x3FF", "level = (level ^ 0x1FF) & 0x3FF", False), ("decay cut back to the sustain level", "operator.py", " phase = self.envelope_phase = SUSTAIN\n", " phase = self.envelope_phase = SUSTAIN\n attenuation = self.attenuation = level << 5\n", False), ("carriers summed before the cut to 9 bits", "chip.py", " value = out4 >> 5\n if wiring[6]:\n value += out1 >> 5\n if wiring[7]:\n value += out2 >> 5\n if wiring[8]:\n value += out3 >> 5\n", " value = (out4 + out1 * wiring[6] + out2 * wiring[7] + out3 * wiring[8]) >> 5\n", False), ("accumulator wraps", "chip.py", " if value > high_limit:\n value = high_limit\n", " if value > high_limit:\n value -= 512\n", False), ("one detune entry moved", "tables.py", "(2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 10, 11, 12,", "(2, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 10, 12, 12,", False), ("envelope step patterns shifted by one", "tables.py", " rows.append(slow[rate & 3])", " rows.append(slow[rate & 3][1:] + slow[rate & 3][:1])", False), ("linear attack", "operator.py", "attenuation + ((~attenuation * increment) >> 4)", "max(0, attenuation - 16 * increment)", False), ("exponent table scaled as the OPL's", "operator.py", "(EXPONENT[total & 0xFF] << 2) >> (total >> 8)", "(EXPONENT[total & 0xFF] << 1) >> (total >> 8)", False), ("modulation not shifted", "chip.py", "(out1 * wiring[0]) >> 1", "(out1 * wiring[0])", True), ("key-on resets the attenuation", "operator.py", " self.envelope_phase = ATTACK\n self.phase = 0\n", " self.envelope_phase = ATTACK\n self.attenuation = 0x3FF\n self.phase = 0\n", False), ("key-on leaves the phase alone", "operator.py", " self.envelope_phase = ATTACK\n self.phase = 0\n", " self.envelope_phase = ATTACK\n", False), ("BUSY lasts a sample", "chip.py", "BUSY_CLOCKS = 192", "BUSY_CLOCKS = 144", False), ("envelope advances every sample", "chip.py", "self.envelope_divider == 3", "self.envelope_divider == 1", False), ("feedback from one store", "chip.py", "(older + newer) >> (10 - feedback)", "(newer + newer) >> (10 - feedback)", False), ("no delayed modulation paths", "chip.py", "DELAYED_MODULATION = True", "DELAYED_MODULATION = False", False), ("DAC scaled by four", "chip.py", "(self.dac_data - 0x80) << 1", "(self.dac_data - 0x80) << 2", False), ("register operator order 1, 2, 3, 4", "chip.py", "REGISTER_SLOT_TO_OPERATOR = (0, 2, 1, 3)", "REGISTER_SLOT_TO_OPERATOR = (0, 1, 2, 3)", False), ("block shifts left only", "operator.py", "increment = (f_number << self.block) >> 1", "increment = f_number << self.block", False), ("attack does not stall at rate 62", "operator.py", " if rate < 62:\n", " if rate < 64:\n", False), ("total level added before the inversion", "operator.py", " level = self.attenuation\n if self.ssg & SSG_ENABLE and self.inverted():", " level = self.attenuation + (self.total_level << 3)\n if self.ssg & SSG_ENABLE and self.inverted():", False), ("tremolo triangle not doubled", "chip.py", " triangle <<= 1\n", "", False), ("timer flag set without the enable bit", "chip.py", " if self.timer_enable & 1:\n self.status_flags |= 1", " self.status_flags |= 1", False), ("the YM3438 given the ladder", "variant.py", " ladder=False,", " ladder=True,\n ladder_positive=4,\n ladder_negative=-3,\n ladder_idle=4,\n status_ports=(True, True, True, True),\n accumulator_max=255,\n)\n_UNUSED = dict(", 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 ym2612_python; print(ym2612_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: bool = False ) -> Path: parent = WORK / f"{index:02d}" target = parent / "ym2612_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())