# SPDX-License-Identifier: MIT """Shared helpers: tiny cartridges, a System with a 32X in the slot, and the user's boot ROMs when they are where the user keeps them (never copied: tests that need them skip without them).""" from __future__ import annotations import os from pathlib import Path import pytest from megadrive_python.cartridge import Cartridge from megadrive_python.machine import MACHINES from megadrive_python.system import System from sega32x_python import BootROMs, Sega32X #: Where the user keeps the three boot ROMs (docs/validation.md, "Boot ROMs verified"): #: the ``SEGA32X_BIOS_DIR`` environment variable; tests that need them skip without it. BIOS_DIR = Path(os.environ.get("SEGA32X_BIOS_DIR", "/nonexistent-set-SEGA32X_BIOS_DIR")) STACK = 0x00FFFE00 CODE = 0x200 #: A stand-in 68000 boot ROM for tests that must not need the user's: 64 vectors in the #: shape of Sega's (vector n at $880200 + 6(n - 1), Manual 3.1: "ROM contents are at #: 88 0200h, 88 0206h, 88 020Ch... (6-byte JUMP commands arranged into a jump table)"), #: made here; vector 0, the stack pointer, is 0. SYNTHETIC_VECTORS = bytes(4) + b"".join( (0x880200 + 6 * (n - 1)).to_bytes(4, "big") for n in range(1, 64) ) def image(code: str, *, at: int = CODE, size: int = 0x10000) -> bytes: """A ROM: the two reset vectors, a "SEGA" header at $100, and ``code`` (hex) at ``at``.""" rom = bytearray(size) rom[0:4] = STACK.to_bytes(4, "big") rom[4:8] = at.to_bytes(4, "big") rom[0x100:0x110] = b"SEGA 32X " program = bytes.fromhex(code.replace(" ", "")) rom[at : at + len(program)] = program return bytes(rom) def system_with_32x( code: str = "60fe", *, vector_rom: bytes | None = SYNTHETIC_VECTORS, rom: bytes | None = None, machine: str = "genesis", ) -> tuple[System, Sega32X]: device = Sega32X(Cartridge(rom if rom is not None else image(code)), vector_rom=vector_rom) system = System(MACHINES[machine], None, slot=device) # type: ignore[arg-type] system.board.fm.enabled = False return system, device def run(system: System, instructions: int) -> None: for _ in range(instructions): system.step() def ram_long(system: System, address: int) -> int: ram = system.board.ram offset = address & 0xFFFF return int.from_bytes(ram[offset : offset + 4], "big") def ram_word(system: System, address: int) -> int: ram = system.board.ram offset = address & 0xFFFF return int.from_bytes(ram[offset : offset + 2], "big") @pytest.fixture def user_boot_roms() -> BootROMs: if not BIOS_DIR.is_dir(): pytest.skip(f"the user's boot ROMs are not at {BIOS_DIR}") return BootROMs.load(BIOS_DIR)