# SPDX-License-Identifier: MIT """Rung 0: the contract with the boards (docs/api.md, docs/validation.md). Not a judge of the chip: these keep the core usable by sms-python and megadrive-python as api.md describes it. """ from __future__ import annotations import dataclasses import random from pathlib import Path import pytest from helpers import SEGA_PARTS, variant_id, write_tone, write_volume import sn76489_python from sn76489_python import ( CLOCKS_PER_SAMPLE, GAME_GEAR_PSG, SEGA_VDP_PSG, SN76489, SN76489AN, YM7101_PSG, PSGVariant, ) ALL = (SN76489AN, SEGA_VDP_PSG, GAME_GEAR_PSG, YM7101_PSG) def random_stream(seed: int, writes: int = 300) -> list[tuple[int, int, int]]: """(input clocks to run first, port, byte); port 1 is the stereo register.""" rng = random.Random(seed) return [ (rng.randrange(0, 700), 1 if rng.random() < 0.05 else 0, rng.randrange(256)) for _ in range(writes) ] def play(psg: SN76489, stream) -> None: for clocks, port, value in stream: psg.run(clocks) if port: psg.write_stereo(value) else: psg.write(value) def test_the_names_api_md_lists_are_the_public_surface(): # api.md: the import block. assert sorted(sn76489_python.__all__) == sorted( [ "SN76489", "PSGVariant", "CLOCKS_PER_SAMPLE", "SN76489AN", "SEGA_VDP_PSG", "GAME_GEAR_PSG", "YM7101_PSG", ] ) assert CLOCKS_PER_SAMPLE == 16 # spec 4.1, 4.3 def test_the_default_variant_is_the_master_systems(): # Carried from the seed, whose tests build `PSG()` for a Master System. assert SN76489().variant is SEGA_VDP_PSG @pytest.mark.parametrize("variant", ALL, ids=variant_id) def test_one_pair_per_sixteen_input_clocks(variant): # api.md: "one entry per CLOCKS_PER_SAMPLE input clocks". psg = SN76489(variant) psg.run(15) assert psg.take_samples() == [] psg.run(1) assert len(psg.take_samples()) == 1 psg.run(3_579_545) assert len(psg.take_samples()) == 3_579_545 // 16 psg.run(16 - 3_579_545 % 16) assert len(psg.take_samples()) == 1 assert psg.take_samples() == [] # taking clears @pytest.mark.parametrize("variant", ALL, ids=variant_id) def test_levels_run_from_zero_to_four(variant): # api.md: "levels from 0.0 to 4.0 (four channels at full volume)". psg = SN76489(variant) play(psg, random_stream(1)) for channel in range(4): write_volume(psg, channel, 0) psg.run(16 * 20_000) samples = psg.take_samples() assert all(0.0 <= side <= 4.0 for pair in samples for side in pair) assert max(pair[0] for pair in samples) == 4.0 assert all(isinstance(pair, tuple) and len(pair) == 2 for pair in samples) @pytest.mark.parametrize("variant", ALL, ids=variant_id) def test_any_split_of_a_run_gives_the_same_samples(variant): # validation.md rung 0: `run(a)` then `run(b)` equals `run(a + b)`. rng = random.Random(7) stream = random_stream(2) whole, pieces = SN76489(variant), SN76489(variant) for clocks, port, value in stream: whole.run(clocks) remaining = clocks while remaining: step = rng.randrange(1, remaining + 1) pieces.run(step) remaining -= step for psg in (whole, pieces): psg.write_stereo(value) if port else psg.write(value) assert whole.take_samples() == pieces.take_samples() assert vars(whole) == vars(pieces) def plain(value) -> bool: if isinstance(value, bool | int | float): return True if isinstance(value, list | tuple | bytearray): return all(plain(item) for item in value) return False @pytest.mark.parametrize("variant", ALL, ids=variant_id) def test_state_is_plain_attributes_and_copies_out_and_back(variant): # api.md: "state must be plain attributes (numbers, lists, bytearrays); a # frozen dataclass is taken for configuration". psg = SN76489(variant) stream = random_stream(3) play(psg, stream[:150]) state = {name: value for name, value in vars(psg).items() if name != "variant"} assert all(plain(value) for value in state.values()), state assert not hasattr(psg, "__slots__") restored = SN76489(variant) for name, value in state.items(): setattr(restored, name, list(value) if isinstance(value, list) else value) psg.take_samples() restored.take_samples() play(psg, stream[150:]) play(restored, stream[150:]) assert psg.take_samples() == restored.take_samples() def test_an_instance_stays_under_pypys_eighty_attributes(): # validation.md rung 0: PyPy turns a larger instance into a dict. assert len(vars(SN76489())) < 80 def test_a_variant_is_a_frozen_value_of_plain_fields(): # api.md: "a variant is a value, not a subclass". assert dataclasses.is_dataclass(PSGVariant) with pytest.raises(dataclasses.FrozenInstanceError): SEGA_VDP_PSG.lfsr_bits = 15 # type: ignore[misc] for variant in ALL: for field in dataclasses.fields(variant): assert plain(getattr(variant, field.name)) or field.name == "name" assert type(SN76489(GAME_GEAR_PSG)) is type(SN76489(SN76489AN)) def test_the_logic_never_asks_which_variant_it_is(): # The brief: "Variant differences are data on PSGVariant, never # `if variant is ...` branches". source = Path(sn76489_python.__file__).with_name("chip.py").read_text() for forbidden in ("variant is", "variant ==", "variant.name ==", "variant in", "isinstance"): assert forbidden not in source def test_stereo_is_readable(): # api.md: "psg.stereo: the stereo register, readable by tests". psg = SN76489(GAME_GEAR_PSG) psg.write_stereo(0x5A) assert psg.stereo == 0x5A def test_write_test_exists_only_on_the_mega_drives_part(): # Decision D7 (provenance.md), correcting api.md. mega_drive = SN76489(YM7101_PSG) mega_drive.write_test(0x0200) assert mega_drive.test == 1 for variant in (SN76489AN, SEGA_VDP_PSG, GAME_GEAR_PSG): with pytest.raises(AttributeError): SN76489(variant).write_test(0x0200) @pytest.mark.parametrize("variant", SEGA_PARTS, ids=variant_id) def test_a_measured_volume_curve_is_a_table_a_board_passes_in(variant): # Decision D11: the core ships the ideal table; a board replaces it as data. flat = tuple(1.0 if step < 15 else 0.0 for step in range(16)) psg = SN76489(dataclasses.replace(variant, volume_table=flat)) write_tone(psg, 0, 1) write_volume(psg, 0, 9) psg.run(16 * 4) assert max(pair[0] for pair in psg.take_samples()) == 1.0