#!/usr/bin/env python3 # SPDX-License-Identifier: GPL-3.0-or-later """mesen2-runner's smoke test: no commercial ROMs, only programs built here. python3 -I tests/smoke.py [--lib PATH] Part 1 needs nothing: the version line, the exit codes for usage errors and missing inputs, the input-script reader, the frame decoder and the NES trace parser. Part 2 needs a MesenCore.so (``--lib``, ``MESEN_CORE``, or ``build.sh``'s): it builds a two-instruction NES, PC Engine and SNES program (an endless loop each), runs ``run.py`` on each and checks the manifest, the picture and, for the NES, the instruction trace. Part 3 runs MesenCE's own build (``build.sh --core mesence``) when it exists. Exit 0 when every part that could run passed. """ from __future__ import annotations import argparse import gzip import json import os import subprocess import sys import tempfile import zipfile from pathlib import Path HERE = Path(__file__).resolve().parents[1] sys.path.insert(0, str(HERE)) from mesen2_runner import api, cli, inputs, lua # noqa: E402 RUN = [sys.executable, "-I", str(HERE / "run.py")] failures: list[str] = [] def check(ok: bool, what: str) -> None: print(("ok " if ok else "FAIL ") + what) if not ok: failures.append(what) def nes_rom() -> bytes: """NROM-128: JMP $C000 at $C000, every vector at $C000, CHR zeros.""" prg = bytearray(0x4000) prg[0:3] = bytes([0x4C, 0x00, 0xC0]) for at in (0x3FFA, 0x3FFC, 0x3FFE): prg[at : at + 2] = (0xC000).to_bytes(2, "little") return b"NES\x1a\x01\x01\x00\x00" + bytes(8) + bytes(prg) + bytes(0x2000) def pce_rom() -> bytes: """One 8 KB bank (mapped at $E000 on power-on): BRA to itself, reset vector $E000.""" rom = bytearray(0x2000) rom[0:2] = bytes([0x80, 0xFE]) for at in range(0x1FF6, 0x2000, 2): rom[at : at + 2] = (0xE000).to_bytes(2, "little") return bytes(rom) def fds_image() -> bytes: """A one-side fwNES image: the disk info block's signature, the rest zeros (no game).""" side = bytearray(65500) side[0:15] = b"\x01*NINTENDO-HVC*" return b"FDS\x1a\x01" + bytes(11) + bytes(side) def fds_test_bios() -> bytes: """An 8 KiB stand-in for the player's BIOS, written here (not Nintendo's): JMP $E000 at $E000, every vector $E000. The runner checks only its size.""" bios = bytearray(0x2000) bios[0:3] = bytes([0x4C, 0x00, 0xE0]) for at in (0x1FFA, 0x1FFC, 0x1FFE): bios[at : at + 2] = (0xE000).to_bytes(2, "little") return bytes(bios) def snes_rom(cx4: bool = False) -> bytes: """32 KB LoROM: auto-joypad read on (LDA #1, STA $4200), then BRA to itself; a header, every vector $8000. ``cx4``: the header names the Cx4 (ROM type $F3, chip $10).""" rom = bytearray(0x8000) rom[0:7] = bytes([0xA9, 0x01, 0x8D, 0x00, 0x42, 0x80, 0xFE]) rom[0x7FC0:0x7FD5] = b"MESEN2 RUNNER SMOKE " rom[0x7FD5], rom[0x7FD6], rom[0x7FD7] = 0x20, 0x00, 0x08 # LoROM, ROM only, 256 KB class if cx4: rom[0x7FD6], rom[0x7FBF] = 0xF3, 0x10 for at in range(0x7FE4, 0x8000, 2): rom[at : at + 2] = (0x8000).to_bytes(2, "little") total = sum(rom) & 0xFFFF rom[0x7FDC:0x7FDE] = (total ^ 0xFFFF).to_bytes(2, "little") rom[0x7FDE:0x7FE0] = total.to_bytes(2, "little") return bytes(rom) def part1(tmp: Path) -> None: out = subprocess.run([*RUN, "--version"], capture_output=True, text=True) check(out.returncode == 0 and out.stdout.startswith("mesen2-runner ") and "b9fa69d" in out.stdout and "4b8a196" in out.stdout, "--version names the tool and both pins") # fmt: skip # 0.4.0: --core names a pinned core's own build; MESEN_CORE does not override it. check(api.find_library(None, core="mesence") == api.OWN_BUILDS["mesence"] and api.find_library(Path("x.so"), core="mesence") == Path("x.so"), "--core mesence finds MesenCE's own build; --lib still wins") # fmt: skip try: cli.line_args({"core": "mesence"}) check(False, "a batch line may not name the core") except cli.Usage: check(True, "a batch line may not name the core") out = subprocess.run([*RUN, "--machine", "nes", "--rom", str(tmp / "none.nes"), "--out", str(tmp / "o"), "--core", "mame"], capture_output=True, text=True) # fmt: skip check(out.returncode == 2, "an unknown --core is a usage error (2)") out = subprocess.run([*RUN, "--machine", "nes"], capture_output=True, text=True) check(out.returncode == 2, "a missing --rom is a usage error (2)") out = subprocess.run([*RUN, "--machine", "nes", "--rom", str(tmp / "none.nes"), "--out", str(tmp / "o")], capture_output=True, text=True) # fmt: skip check(out.returncode == 3, "a missing ROM is a missing input (3)") script = tmp / "in.jsonl" script.write_text('{"frame": 5, "port": 1, "buttons": ["start", "a"]}\n' '{"frame": 9, "buttons": []}\n') # fmt: skip records = inputs.read(script, "nes") check(records == [(5, 1, ("a", "start")), (9, 1, ())], "input script read") check("emu.setInput" in inputs.lua(records), "input script as Lua") bad = tmp / "bad.jsonl" bad.write_text('{"frame": 1, "buttons": ["run"]}\n') try: inputs.read(bad, "nes") check(False, "a PC Engine button refused for the NES") except inputs.InputError: check(True, "a PC Engine button refused for the NES") values = [0, 1, 63, 64, 511, 4095] text = "".join(lua.ALPHABET[(v // 64) % 64] + lua.ALPHABET[v % 64] for v in values) check(lua.decode_frames({"L7.0": text, "E7": "1"}) == {7: values}, "base64-line frame decoded") line = "PC:C000 OP:4C 00 C0 |A:00 X:00 Y:00 S:FD P:24 CYC:7 SL:-1 DOT:21 FR:0" m = cli.NES_INSN.search(line) check(bool(m) and m.group(2).split() == ["4C", "00", "C0"], "NES trace line parsed") # 0.2.0's options, without a library. rom = tmp / "loop.nes" rom.write_bytes(nes_rom()) for extra, what in ((["--no-sprites"], "--no-sprites refused for nes (2)"), (["--reset-at", "10"], "--reset-at at or past --frames refused (2)"), (["--power-on-ram", "noise"], "an unknown --power-on-ram refused (2)")): # fmt: skip out = subprocess.run([*RUN, "--machine", "nes", "--rom", str(rom), "--out", str(tmp / "o"), "--frames", "10", *extra], capture_output=True, text=True) # fmt: skip check(out.returncode == 2, what) out = subprocess.run([*RUN, "--batch", str(tmp / "none.jsonl")], capture_output=True, text=True) check(out.returncode == 3, "a missing batch file is a missing input (3)") check(cli.line_args({"machine": "nes", "frames_out": True, "frames": 5, "lua": None}) == ["--machine", "nes", "--frames-out", "--frames", "5"], "a batch line as options") # fmt: skip try: cli.line_args({"lib": "x"}) check(False, "a batch line may not name the library") except cli.Usage: check(True, "a batch line may not name the library") image = tmp / "disk.fds" image.write_bytes(fds_image()) check(cli.is_fds(image) and not cli.is_fds(rom), "an FDS image recognised") bios = tmp / "bios.bin" bios.write_bytes(fds_test_bios()) zipped = tmp / "bios.zip" with zipfile.ZipFile(zipped, "w") as archive: archive.writestr("bios.rom", fds_test_bios()) check(cli.fds_bios(bios)[0] == cli.fds_bios(zipped)[0] == fds_test_bios(), "the FDS BIOS read loose and from a zip") # fmt: skip saved = os.environ.pop(cli.FDS_BIOS_VARIABLE, None) try: cli.fds_bios(None) check(False, f"no --fds-bios and no {cli.FDS_BIOS_VARIABLE}: a missing input") except cli.Missing: check(True, f"no --fds-bios and no {cli.FDS_BIOS_VARIABLE}: a missing input") finally: if saved is not None: os.environ[cli.FDS_BIOS_VARIABLE] = saved check("]==]" in lua.full_log_lua(tmp / "log") and "RUN-DONE" in lua.done_last_lua(9, "RUN-DONE") and "emu.reset()" in lua.reset_lua(4), "the full-log, last-marker and reset scripts") # fmt: skip def part2(tmp: Path, lib: Path) -> None: for machine, name, rom in (("nes", "loop.nes", nes_rom()), ("pce", "loop.pce", pce_rom()), ("snes", "loop.sfc", snes_rom())): # fmt: skip path = tmp / name path.write_bytes(rom) out = tmp / f"run-{machine}" traces = ["--trace", "insn"] if machine == "nes" else [] done = subprocess.run([*RUN, "--machine", machine, "--rom", str(path), "--out", str(out), "--frames", "10", "--frames-out", "--lib", str(lib), "--timeout", "60", *traces], capture_output=True, text=True) # fmt: skip check(done.returncode == 0, f"{machine}: run.py exits 0") try: record = json.loads((out / "manifest.json").read_text()) except (OSError, ValueError): check(False, f"{machine}: manifest.json written") continue check(record["status"] == "ok" and record["evidence"] == "OBSERVED" and record["contract"] == 1, f"{machine}: manifest status ok, OBSERVED") # fmt: skip check((out / "frame-000010.png").exists(), f"{machine}: frame-000010.png written") if machine == "nes": with gzip.open(out / "insn.jsonl.gz", "rt") as f: rows = [json.loads(x) for x in f] check(len(rows) > 1000 and {r["pc"] for r in rows} == {0xC000} and rows[0]["op"] == [0x4C, 0x00, 0xC0], "nes: every traced instruction is the loop") # fmt: skip check(rows[-1]["frame"] <= 11, "nes: the trace ends with the last frame") part2_new(tmp, lib) def tool(tmp: Path, lib: Path, name: str, *args: str, env: dict | None = None): """One run.py run into ``tmp/name``: its exit status, manifest (or {}) and folder.""" out = tmp / name done = subprocess.run([*RUN, "--out", str(out), "--lib", str(lib), "--timeout", "120", *args], capture_output=True, text=True, env=env) # fmt: skip try: record = json.loads((out / "manifest.json").read_text()) except (OSError, ValueError): record = {} return done.returncode, record, out def script(tmp: Path, name: str, text: str) -> str: path = tmp / name path.write_text(text) return str(path) def log_of(out: Path) -> list[str]: path = out / "script-log.txt" return path.read_text().splitlines() if path.exists() else [] def part2_new(tmp: Path, lib: Path) -> None: """0.2.0's options, each on a program built here.""" nes, snes, pce = (str(tmp / n) for n in ("loop.nes", "loop.sfc", "loop.pce")) # The full script log: 100 lines a frame for 10 frames, nothing after the last frame. rows = script(tmp, "rows.lua", "local n = 0\nemu.addEventCallback(function()\n n = n + 1\n" " for i = 1, 100 do emu.log('ROW ' .. n .. ' ' .. i) end\n" "end, emu.eventType.endFrame)\n") # fmt: skip code, record, out = tool(tmp, lib, "log", "--machine", "nes", "--rom", nes, "--frames", "10", "--lua", rows) # fmt: skip lines = log_of(out) check(code == 0 and len(lines) == 1000 and lines[0] == "ROW 1 1" and lines[-1] == "ROW 10 100", "--lua: all 1000 lines in script-log.txt, none past the last frame") # fmt: skip # The player's lines in the runner's own formats are kept (famicom-python logs frames as # L and E lines and DONE, as the runner's NES frame script does). alike = script(tmp, "alike.lua", "emu.addEventCallback(function()\n emu.log('L1.0 abc') " "emu.log('E1 1') emu.log('DONE') emu.log('PIXELS 1 000000')\n" "end, emu.eventType.endFrame)\n") # fmt: skip for machine, rom in (("nes", nes), ("snes", snes)): code, record, out = tool(tmp, lib, f"alike-{machine}", "--machine", machine, "--rom", rom, "--frames", "3", "--frames-out", "--lua", alike) # fmt: skip check(code == 0 and log_of(out) == ["L1.0 abc", "E1 1", "DONE", "PIXELS 1 000000"] * 3 and (out / "frame-000003.png").exists(), f"{machine} --lua: lines in the runner's formats kept, the frame still right") # fmt: skip # --power-on-ram: work RAM read at the end of frame 1. peek = ("local seen = false\nemu.addEventCallback(function()\n if not seen then seen = true; " "emu.log('RAM ' .. emu.read({at}, emu.memType.{mem})) end\n" "end, emu.eventType.endFrame)\n") for machine, rom, at, mem in (("nes", nes, "0x0000", "nesMemory"), ("snes", snes, "0x7E0000", "snesMemory")): # fmt: skip lua_ram = script(tmp, f"ram-{machine}.lua", peek.format(at=at, mem=mem)) seen = {} for ram in ("zeros", "ones"): code, record, out = tool(tmp, lib, f"ram-{machine}-{ram}", "--machine", machine, "--rom", rom, "--frames", "3", "--lua", lua_ram, "--power-on-ram", ram) # fmt: skip seen[ram] = (log_of(out) or ["?"])[0] check(code == 0 and record.get("power_on", {}).get("ram") == ram, f"{machine} --power-on-ram {ram}: recorded in the manifest") # fmt: skip check(seen == {"zeros": "RAM 0", "ones": "RAM 255"}, f"{machine} --power-on-ram: work RAM powers on as asked") # fmt: skip # --reset-at 5: one reset, where Mesen2 takes it (the SNES after frame 5's end-of-frame # event, the NES after frame 6's, OBSERVED 2026-11-24), the same in two runs; pce refused. lua_reset = script(tmp, "reset.lua", "local n = 0\nemu.addEventCallback(function() n = n + 1 " "end, emu.eventType.endFrame)\nemu.addEventCallback(function() " "emu.log('RESET after ' .. n) end, emu.eventType.reset)\n") # fmt: skip code, _, _ = tool(tmp, lib, "reset-pce", "--machine", "pce", "--rom", pce, "--frames", "10", "--reset-at", "5") # fmt: skip check(code == 2, "pce --reset-at refused (2)") for machine, rom, after in (("nes", nes, 6), ("snes", snes, 5)): results = [] for n in (1, 2): code, record, out = tool(tmp, lib, f"reset-{machine}-{n}", "--machine", machine, "--rom", rom, "--frames", "10", "--reset-at", "5", "--frames-out", "--lua", lua_reset) # fmt: skip results.append((code, log_of(out), (out / "frame-000010.png").read_bytes() if (out / "frame-000010.png").exists() else None)) # fmt: skip check(results[0][0] == 0 and results[0][1] == [f"RESET after {after}"] and results[0] == results[1], f"{machine} --reset-at 5: one reset after frame {after}, the same in two runs") # fmt: skip # --no-sprites (pce). code, record, out = tool(tmp, lib, "pce-nosprites", "--machine", "pce", "--rom", pce, "--frames", "5", "--frames-out", "--no-sprites") # fmt: skip check(code == 0 and "off" in record.get("sprites", ""), "pce --no-sprites: run and recorded") # --fds-bios: a disk image with the stand-in BIOS; its copy is not kept; without it, 3. disk, bios = str(tmp / "disk.fds"), str(tmp / "bios.zip") code, record, out = tool(tmp, lib, "fds", "--machine", "nes", "--rom", disk, "--frames", "5", "--fds-bios", bios) # fmt: skip roles = {i["role"]: i for i in record.get("inputs", [])} check(code == 0 and roles.get("bios", {}).get("size") == 0x2000 and not (out / "work" / "home" / "Firmware" / "disksys.rom").exists(), "nes --fds-bios: an FDS image runs; the BIOS recorded, its copy removed") # fmt: skip env = {k: v for k, v in os.environ.items() if k != cli.FDS_BIOS_VARIABLE} code, _, _ = tool(tmp, lib, "fds-none", "--machine", "nes", "--rom", disk, env=env) check(code == 3, "an FDS image without a BIOS is a missing input (3)") env[cli.FDS_BIOS_VARIABLE] = str(tmp / "bios.bin") code, record, _ = tool(tmp, lib, "fds-env", "--machine", "nes", "--rom", disk, "--frames", "5", env=env) # fmt: skip check(code == 0 and any(i.get("from") == cli.FDS_BIOS_VARIABLE for i in record.get("inputs", [])), f"the FDS BIOS from {cli.FDS_BIOS_VARIABLE}") # fmt: skip # snes-cx4 --input: Start from frame 3 to 5 seen in the auto-joypad register. cart = tmp / "cx4.sfc" cart.write_bytes(snes_rom(cx4=True)) presses = tmp / "presses.jsonl" presses.write_text('{"frame": 3, "port": 1, "buttons": ["start"]}\n' '{"frame": 5, "port": 1, "buttons": []}\n') # fmt: skip joy = script(tmp, "joy.lua", "local n = 0\nemu.addEventCallback(function()\n n = n + 1\n" " if emu.read(0x4219, emu.memType.snesMemory) ~= 0 then emu.log('JOY ' .. n) end\n" "end, emu.eventType.endFrame)\n") # fmt: skip code, record, out = tool(tmp, lib, "cx4-input", "--machine", "snes-cx4", "--rom", str(cart), "--frames", "8", "--input", str(presses), "--lua", joy) # fmt: skip check(code == 0 and log_of(out) == ["JOY 4", "JOY 5"], "snes-cx4 --input: the press read by the game in frames 4 and 5") # fmt: skip # --batch: three runs in one process, each as a run of its own would give. lines = [{"machine": "nes", "rom": nes, "out": str(tmp / "b1"), "frames": 10, "frames-out": True}, {"machine": "snes", "rom": snes, "out": str(tmp / "b2"), "frames": 10, "frames-out": True}, {"machine": "nes", "rom": nes, "out": str(tmp / "b3"), "frames": 10, "frames-out": True, "lua": rows}] # fmt: skip listing = tmp / "batch.jsonl" listing.write_text("".join(json.dumps(x) + "\n" for x in lines)) done = subprocess.run([*RUN, "--batch", str(listing), "--lib", str(lib)], capture_output=True, text=True) # fmt: skip summary = [json.loads(x) for x in done.stdout.splitlines() if x.startswith('{"batch_line"')] single = {"b1": tmp / "run-nes", "b2": tmp / "run-snes", "b3": tmp / "run-nes"} same = all((tmp / b / "frame-000010.png").exists() and (tmp / b / "frame-000010.png").read_bytes() == (s / "frame-000010.png").read_bytes() for b, s in single.items()) # fmt: skip check(done.returncode == 0 and [s["exit"] for s in summary] == [0, 0, 0] and same and log_of(tmp / "b3") == log_of(tmp / "log"), "--batch: three runs in one process, each the same as alone") # fmt: skip part2_030(tmp, lib) def part2_030(tmp: Path, lib: Path) -> None: """0.3.0's options: emu.stop's code, --until, snes --frames-at, audio ending at --frames.""" nes, snes, pce = (str(tmp / n) for n in ("loop.nes", "loop.sfc", "loop.pce")) stop = script(tmp, "stop.lua", "local n = 0\nemu.addEventCallback(function()\n n = n + 1\n" " emu.log('F ' .. n)\n if n == 5 then emu.stop(3) end\n" "end, emu.eventType.endFrame)\n") # fmt: skip for machine, rom in (("nes", nes), ("snes", snes), ("pce", pce)): code, record, out = tool(tmp, lib, f"stop-{machine}", "--machine", machine, "--rom", rom, "--frames", "10", "--frames-out", "--lua", stop) # fmt: skip check(code == 0 and record.get("status") == "ok" and record.get("end") == {"by": "script-stop", "frame": 5, "stop_code": 3} and log_of(out) == [f"F {n}" for n in range(1, 6)] and (out / "frame-000005.png").exists(), f"{machine} emu.stop(3) at frame 5: exit 0, the code and frame in the manifest, " "the log and picture end there") # fmt: skip # The picture where emu.stop ended the run is the one a run of that many frames gives. code, _, out = tool(tmp, lib, "nes-5", "--machine", "nes", "--rom", nes, "--frames", "5", "--frames-out") # fmt: skip check((out / "frame-000005.png").read_bytes() == (tmp / "stop-nes" / "frame-000005.png").read_bytes(), "nes: the stopped run's last picture equals a 5-frame run's") # fmt: skip until = script(tmp, "until.lua", "local n = 0\nemu.addEventCallback(function()\n n = n + 1\n" " emu.log('F ' .. n)\n if n == 4 then emu.log('RESULT ok') end\n" "end, emu.eventType.endFrame)\n") # fmt: skip for frames, reached in (("10", True), ("3", False)): code, record, out = tool(tmp, lib, f"until-{frames}", "--machine", "snes", "--rom", snes, "--frames", frames, "--lua", until, "--until", "log:RESULT") # fmt: skip end = record.get("end", {}) check(code == 0 and end.get("reached") is reached and end.get("frame") == (4 if reached else 3) and end.get("until") == "log:RESULT", f"--until log:RESULT with --frames {frames}: {'reached at frame 4' if reached else 'not reached'}") # fmt: skip code, _, _ = tool(tmp, lib, "until-nolua", "--machine", "nes", "--rom", nes, "--until", "log:X") check(code == 2, "--until without --lua is a usage error (2)") code, record, out = tool(tmp, lib, "snes-at", "--machine", "snes", "--rom", snes, "--frames", "10", "--frames-at", "4,7", "--frames-out") # fmt: skip _, _, four = tool(tmp, lib, "snes-4", "--machine", "snes", "--rom", snes, "--frames", "4", "--frames-out") # fmt: skip check(code == 0 and all((out / f"frame-{f:06d}.png").exists() for f in (4, 7, 10)) and (out / "frame-000004.png").read_bytes() == (four / "frame-000004.png").read_bytes(), "snes --frames-at 4,7: frames 4, 7 and 10 written, frame 4 as a 4-frame run's") # fmt: skip waves = [] for n in (1, 2): code, record, out = tool(tmp, lib, f"audio-{n}", "--machine", "nes", "--rom", nes, "--frames", "30", "--audio-out") # fmt: skip waves.append((code, (out / "audio.wav").read_bytes() if (out / "audio.wav").exists() else b"")) check(waves[0][0] == 0 and len(waves[0][1]) > 44 and waves[0] == waves[1], "--audio-out: the same recording in two runs (it ends at frame 30)") # fmt: skip def part3(tmp: Path) -> None: """0.4.0: the second pinned core, MesenCE, through ``--core mesence`` (its own build).""" path = tmp / "loop.nes" path.write_bytes(nes_rom()) out = tmp / "run-mesence" done = subprocess.run([*RUN, "--machine", "nes", "--rom", str(path), "--out", str(out), "--frames", "10", "--frames-out", "--core", "mesence", "--timeout", "60", "--trace", "insn"], capture_output=True, text=True) # fmt: skip try: record = json.loads((out / "manifest.json").read_text()) except (OSError, ValueError): record = {} upstream = record.get("upstream", {}) check(done.returncode == 0 and record.get("status") == "ok" and upstream.get("name") == "MesenCE" and upstream.get("commit") == "4b8a196e299b3de297b204fd1208d2981562c89b" and upstream.get("patches") == [] and upstream["library"]["built_by"] == "build.sh", "--core mesence: MesenCE at its pin, unpatched, in the manifest") # fmt: skip check((out / "frame-000010.png").exists(), "--core mesence: frame-000010.png written") try: with gzip.open(out / "insn.jsonl.gz", "rt") as f: rows = [json.loads(x) for x in f] except OSError: rows = [] check(len(rows) > 1000 and {r["pc"] for r in rows} == {0xC000}, "--core mesence: the NES pad numbering and trace work (every instruction the loop)") # fmt: skip def main() -> int: p = argparse.ArgumentParser() p.add_argument("--lib", type=Path) a = p.parse_args() with tempfile.TemporaryDirectory(prefix="mesen2-smoke-") as scratch: tmp = Path(scratch) part1(tmp) lib = api.find_library(a.lib) if lib is None or not lib.exists(): print("skip part 2: no MesenCore.so (run build.sh, set MESEN_CORE or pass --lib)") else: part2(tmp, lib) if api.OWN_BUILDS["mesence"].exists(): part3(tmp) else: print("skip part 3: MesenCE not built (build.sh --core mesence)") print(f"{len(failures)} failed" if failures else "smoke passed") return 1 if failures else 0 if __name__ == "__main__": raise SystemExit(main())