"""tools/d3d12_run_fps.py on synthetic logs: the frame line read, the buckets, the comparison, and no log text printed. python -I tests/test_d3d12_run_fps.py Each test writes a small log by hand in the shape the D3D12 runtime's frame line has (the format string in d3d12/crates/leonida-gpu/src/host.rs); no game files, no GPU. """ import argparse import contextlib import io import json import os import sys import tempfile import time import unittest HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(HERE) sys.path.insert(0, os.path.join(ROOT, "tools")) import d3d12_run_fps as run_fps # A line the tool must never print: it stands for text the title itself would put in a log. SECRET = "Synthetic Title Text 42" STAMP = "2026-11-28T20:00:00.000000Z" def frame_text(fps, draws, preparing=20.0, copies_ms=8.0, copies_mb=40.0, textures_ms=1.0, textures_mb=2.0, gpu=1.5, back_ms=3.0, back_mb=0.5, ms=None): """The frame line's own text, as the runtime's format string writes it.""" ms = 1000.0 / fps if ms is None else ms return (f"{fps:.1f} fps, {ms:.1f} ms/frame ({preparing:.1f} preparing: copies {copies_ms:.1f} ms " f"{copies_mb:.1f} MB, textures {textures_ms:.1f} ms {textures_mb:.1f} MB; {gpu:.1f} on the GPU; " f"{back_ms:.1f} copying back {back_mb:.1f} MB), {draws} draws/frame, dropped 3 without a host pipeline " f"(0 being made) and 7 indirect") def frame_line(fps, draws, colour=False, **fields): """One frame line with the timestamp, level and target that come before it.""" text = frame_text(fps, draws, **fields) if colour: # as a terminal shows it: dimmed stamp and target, a green level, and a code inside the line itself dim, green, off = "\x1b[2m", "\x1b[32m", "\x1b[0m" text = text.replace(" fps,", f" fps{off},", 1) return f"{dim}{STAMP}{off} {green} INFO{off} {dim}leonida_gpu::host{off}{dim}:{off} {text}" return f"{STAMP} INFO leonida_gpu::host: {text}" def write_log(folder, name, lines, encoding="utf-8", end="\n"): path = os.path.join(folder, name) with open(path, "wb") as f: f.write(("\n".join(lines) + end).encode(encoding)) return path def run_tool(*argv): out = io.StringIO() with contextlib.redirect_stdout(out): code = run_fps.main(list(argv)) return code, out.getvalue() class ReadSamples(unittest.TestCase): def test_the_frame_line_is_read_field_by_field(self): line = frame_line(20.0, 4321, preparing=31.5, copies_ms=12.5, copies_mb=61.0, textures_ms=2.5, textures_mb=17.0, gpu=0.4, back_ms=5.5, back_mb=0.9) with tempfile.TemporaryDirectory() as tmp: (s,) = run_fps.read_samples(write_log(tmp, "a.log", [line])) self.assertEqual(s, {"fps": 20.0, "frame_ms": 50.0, "preparing_ms": 31.5, "copies_ms": 12.5, "copies_mb": 61.0, "textures_ms": 2.5, "textures_mb": 17.0, "gpu_wait_ms": 0.4, "copy_back_ms": 5.5, "copy_back_mb": 0.9, "draws": 4321}) self.assertIsInstance(s["draws"], int) def test_other_lines_colour_codes_and_a_truncated_last_line(self): whole = frame_line(15.0, 9000) lines = [ f"{STAMP} INFO leonida_gpu::host: host D3D12 device ready", frame_line(30.0, 12), frame_line(18.0, 6000, colour=True), f"{STAMP} INFO leonida_hle: {SECRET}", whole[:whole.index(" draws/frame")], # a crash cut the last line short, just before what ends the match ] with tempfile.TemporaryDirectory() as tmp: samples = run_fps.read_samples(write_log(tmp, "a.log", lines)) self.assertEqual([(s["fps"], s["draws"]) for s in samples], [(30.0, 12), (18.0, 6000)]) def test_a_frame_line_counts_only_where_the_logger_wrote_it(self): text = frame_text(20.0, 4000) lines = [ f"{STAMP} INFO leonida_gpu::host: {frame_text(21.0, 4100)}", # the runtime's own message frame_text(22.0, 4200), # the message alone f"{STAMP} INFO victory_gpu::host: {frame_text(23.0, 4300)}", # the forks this runtime came from f"{STAMP} INFO leonida_hle: the title says: {text}", # the same words in another message f"{STAMP} INFO leonida_gpu::host: before it, {text}", # not at the message's start f"{STAMP} WARN leonida_gpu::host: {text}", # not the INFO line f"{STAMP} INFO leonida_gpu::hostile: {text}", # another target " " + text, # not at the line's start f"{SECRET} {text}", ] with tempfile.TemporaryDirectory() as tmp: samples = run_fps.read_samples(write_log(tmp, "a.log", lines)) self.assertEqual([(s["fps"], s["draws"]) for s in samples], [(21.0, 4100), (22.0, 4200), (23.0, 4300)]) def test_a_last_line_without_its_end_is_skipped(self): first, last = frame_line(20.0, 4000), frame_line(15.0, 9000) after_draws = last[:last.index(" draws/frame") + len(" draws/frame")] # the cut falls after the draw count with tempfile.TemporaryDirectory() as tmp: cut = run_fps.read_samples(write_log(tmp, "a.log", [first, after_draws], end="")) cut_with_end = run_fps.read_samples(write_log(tmp, "b.log", [first, after_draws])) whole_no_end = run_fps.read_samples(write_log(tmp, "c.log", [first, last], end="")) whole = run_fps.read_samples(write_log(tmp, "d.log", [first, last])) wide = run_fps.read_samples(write_log(tmp, "e.log", [first, last], encoding="utf-16", end="")) only_first = [(20.0, 4000)] self.assertEqual([(s["fps"], s["draws"]) for s in cut], only_first) self.assertEqual([(s["fps"], s["draws"]) for s in cut_with_end], only_first) # ends before ", dropped" self.assertEqual([(s["fps"], s["draws"]) for s in whole_no_end], only_first) # whole, but not finished self.assertEqual([(s["fps"], s["draws"]) for s in wide], only_first) self.assertEqual([(s["fps"], s["draws"]) for s in whole], only_first + [(15.0, 9000)]) def test_a_utf16_log_reads_the_same(self): lines = [frame_line(20.0, 4000), frame_line(10.0, 9500)] with tempfile.TemporaryDirectory() as tmp: plain = run_fps.read_samples(write_log(tmp, "a.log", lines)) wide = run_fps.read_samples(write_log(tmp, "b.log", lines, encoding="utf-16")) self.assertEqual(plain, wide) self.assertEqual(len(wide), 2) def test_only_what_the_format_string_writes_is_a_frame_line(self): good = frame_text(20.0, 4000) lines = [ "-" + good, # a sign in front: not the runtime's line "1e3" + good[4:], # "1e3 fps": the 3 alone must not read as the rate "." + good, # ".20.0 fps" "v" + good, # a word running into the number good.replace("4000 draws", "4" * 400 + " draws"), # a draws count no frame has "9" * 400 + good[4:], # a rate no frame has "7" * 400000, # a long run of digits must cost no time to refuse good, # the one real line, with nothing before it ] with tempfile.TemporaryDirectory() as tmp: began = time.perf_counter() samples = run_fps.read_samples(write_log(tmp, "a.log", lines)) took = time.perf_counter() - began self.assertEqual([(s["fps"], s["draws"]) for s in samples], [(20.0, 4000)]) self.assertLess(took, 5.0) class Summarize(unittest.TestCase): def test_menus_are_left_out_and_buckets_take_their_draws(self): lines = [frame_line(30.0, 13)] * 4 # a menu: under the first edge lines += [frame_line(f, 4000) for f in (24.0, 26.0, 28.0)] lines += [frame_line(f, 9500) for f in (12.0, 14.0)] lines += [frame_line(20.0, 5000)] # an edge belongs to the bucket it starts with tempfile.TemporaryDirectory() as tmp: s = run_fps.summarize(run_fps.read_samples(write_log(tmp, "a.log", lines))) self.assertEqual((s["frame_lines"], s["in_world"], s["min_draws"]), (10, 6, 1000)) self.assertEqual(s["fps"], {"median": 22.0, "slowest_tenth": 12.0, "fastest_tenth": 28.0}) by = {b["draws"]: (b["samples"], b["median_fps"]) for b in s["buckets"]} self.assertEqual(by, {"1000-2999": (0, None), "3000-4999": (3, 26.0), "5000-6999": (1, 20.0), "7000-8999": (0, None), "9000+": (2, 13.0)}) self.assertEqual(s["medians"]["draws"], 4500.0) def test_tenths_are_by_nearest_rank(self): twenty = [float(v) for v in range(1, 21)] # a tenth of twenty is two samples self.assertEqual(run_fps.tenth(twenty), 2.0) self.assertEqual(run_fps.tenth(twenty, fastest=True), 19.0) eleven = [float(v) for v in range(1, 12)] # a tenth of eleven is two: rounded up, not down self.assertEqual(run_fps.tenth(eleven), 2.0) self.assertEqual(run_fps.tenth(eleven, fastest=True), 10.0) self.assertEqual(run_fps.tenth([7.0]), 7.0) self.assertEqual(run_fps.tenth([3.0, 9.0]), 3.0) self.assertEqual(run_fps.tenth([3.0, 9.0], fastest=True), 9.0) def test_the_first_edge_is_where_the_world_starts(self): rest = dict.fromkeys((f for f in run_fps.FIELDS if f not in ("fps", "draws")), 1.0) samples = [{"fps": fps, "draws": draws, **rest} for fps, draws in ((30.0, 500), (20.0, 1500), (10.0, 2500))] s = run_fps.summarize(samples, edges=(1000, 2000)) self.assertEqual((s["in_world"], s["min_draws"]), (2, 1000)) self.assertEqual([(b["draws"], b["samples"]) for b in s["buckets"]], [("1000-1999", 1), ("2000+", 1)]) s = run_fps.summarize(samples, edges=(0, 2000)) self.assertEqual((s["in_world"], s["min_draws"]), (3, 0)) self.assertEqual([(b["draws"], b["samples"]) for b in s["buckets"]], [("0-1999", 2), ("2000+", 1)]) def test_a_log_without_frame_lines(self): with tempfile.TemporaryDirectory() as tmp: log = write_log(tmp, "a.log", [f"{STAMP} INFO leonida_gpu::host: nothing yet"]) s = run_fps.summarize(run_fps.read_samples(log)) code, text = run_tool(log) self.assertEqual((s["frame_lines"], s["in_world"], s["fps"], s["medians"]), (0, 0, None, None)) self.assertEqual(code, 0) self.assertEqual(text, "0 frame lines, 0 in the world (1000+ draws a frame)\n") class OneRun(unittest.TestCase): LINES = ( [frame_line(30.0, 13)] + [frame_line(f, 4000, preparing=30.0, copies_ms=12.0, copies_mb=50.0, textures_ms=2.0, textures_mb=6.0, gpu=0.5, back_ms=5.0, back_mb=0.7) for f in (24.0, 26.0, 28.0)] + [frame_line(12.0, 9500, preparing=44.0, copies_ms=20.0, copies_mb=80.0, textures_ms=3.0, textures_mb=9.0, gpu=1.5, back_ms=7.0, back_mb=1.1)] + [f"{STAMP} INFO leonida_hle: {SECRET}"] ) def test_the_whole_text_of_one_run(self): with tempfile.TemporaryDirectory() as tmp: code, text = run_tool(write_log(tmp, "a.log", self.LINES)) self.assertEqual(code, 0) self.assertEqual(text, ( "5 frame lines, 4 in the world (1000+ draws a frame)\n" "frame rate: median 25.0 fps, slowest tenth 12.0, fastest tenth 28.0\n" "a frame (medians): 40.1 ms; preparing 30.0 ms (copies 12.0 ms, 50.0 MB; textures 2.0 ms, 6.0 MB); " "waiting on the GPU 0.5 ms; copying back 5.0 ms, 0.7 MB; 4000 draws\n" "by draws a frame:\n" " 1000-2999 - fps (0 samples)\n" " 3000-4999 26.0 fps (3 samples)\n" " 5000-6999 - fps (0 samples)\n" " 7000-8999 - fps (0 samples)\n" " 9000+ 12.0 fps (1 sample)\n" )) def test_edges_and_json_through_the_command_line(self): with tempfile.TemporaryDirectory() as tmp: log = write_log(tmp, "a.log", self.LINES) code, text = run_tool(log, "--edges", "0,5000") json_code, as_json = run_tool(log, "--edges", "0,5000", "--json") self.assertEqual((code, json_code), (0, 0)) self.assertIn("5 frame lines, 5 in the world (0+ draws a frame)\n", text) self.assertIn(" 0-4999 27.0 fps (4 samples)\n", text) self.assertIn(" 5000+ 12.0 fps (1 sample)\n", text) data = json.loads(as_json) self.assertEqual(sorted(data), ["a"]) self.assertEqual(data["a"]["fps"], {"median": 26.0, "slowest_tenth": 12.0, "fastest_tenth": 30.0}) self.assertEqual(data["a"]["buckets"], [{"draws": "0-4999", "samples": 4, "median_fps": 27.0}, {"draws": "5000+", "samples": 1, "median_fps": 12.0}]) # The text gives every median the JSON gives. self.assertEqual(sorted(data["a"]["medians"]), sorted(f for f in run_fps.FIELDS if f != "fps")) self.assertIn("textures 2.0 ms, 6.0 MB", text) self.assertIn("copying back 5.0 ms, 0.7 MB", text) for out in (text, as_json): self.assertNotIn(SECRET, out) self.assertNotIn(tmp, out) class Compare(unittest.TestCase): def logs(self, tmp): # Run A stands in a quiet place most of the time, run B in a busy one: B is faster in both places, and # its plain median is lower all the same. a = [frame_line(20.0, 4000)] * 8 + [frame_line(10.0, 9500)] * 5 b = [frame_line(25.0, 4000)] * 5 + [frame_line(12.0, 9500)] * 9 + [frame_line(18.0, 6000)] * 2 return write_log(tmp, "a.log", a), write_log(tmp, "b.log", b) def test_like_for_like_where_the_plain_medians_mislead(self): with tempfile.TemporaryDirectory() as tmp: a, b = (run_fps.summarize(run_fps.read_samples(p)) for p in self.logs(tmp)) self.assertEqual((a["fps"]["median"], b["fps"]["median"]), (20.0, 12.0)) # the misleading reading c = run_fps.compare(a, b) rows = {r["draws"]: r for r in c["buckets"]} self.assertAlmostEqual(rows["3000-4999"]["change_percent"], 25.0) self.assertAlmostEqual(rows["9000+"]["change_percent"], 20.0) self.assertIsNone(rows["5000-6999"]["change_percent"]) # B alone was there, twice self.assertIsNone(rows["1000-2999"]["change_percent"]) # neither was self.assertEqual((c["compared"], c["b_faster"], c["b_slower"]), (2, 2, 0)) back = run_fps.compare(b, a) # and the other way round, B is the slower self.assertEqual((back["compared"], back["b_faster"], back["b_slower"]), (2, 0, 2)) def test_a_bucket_needs_its_samples_in_both_runs(self): with tempfile.TemporaryDirectory() as tmp: a, b = (run_fps.summarize(run_fps.read_samples(p)) for p in self.logs(tmp)) self.assertEqual(run_fps.compare(a, b, min_samples=6)["compared"], 0) # 5 and 5 in the two buckets self.assertEqual(run_fps.compare(a, b, min_samples=2)["compared"], 2) # 6000 draws: A has none def test_a_run_that_stood_still_is_not_divided_by(self): with tempfile.TemporaryDirectory() as tmp: hung = write_log(tmp, "a.log", [frame_line(0.04, 4000, ms=25000.0)] * 5) # prints as 0.0 fps fine = write_log(tmp, "b.log", [frame_line(10.0, 4000)] * 5) a, b = (run_fps.summarize(run_fps.read_samples(p)) for p in (hung, fine)) c = run_fps.compare(a, b) self.assertEqual(a["buckets"][1]["median_fps"], 0.0) self.assertEqual((c["compared"], c["buckets"][1]["change_percent"]), (0, None)) def test_text_and_json_say_the_same_and_print_no_log_text(self): with tempfile.TemporaryDirectory() as tmp: a, b = self.logs(tmp) with open(a, "ab") as f: f.write(f"{STAMP} INFO leonida_hle: {SECRET}\n".encode()) code, text = run_tool(a, "--compare", b) json_code, as_json = run_tool(a, "--compare", b, "--json") few_code, few = run_tool(a, "--compare", b, "--min-samples", "2") self.assertEqual((code, json_code, few_code), (0, 0, 0)) data = json.loads(as_json) self.assertEqual(sorted(data), ["a", "b", "compare"]) self.assertEqual((data["compare"]["compared"], data["compare"]["min_samples"]), (2, 5)) self.assertEqual((data["a"]["in_world"], data["b"]["in_world"]), (13, 16)) self.assertIn("run A: 13 frame lines, 13 in the world (1000+ draws a frame)\n", text) self.assertIn("run B: 16 frame lines, 16 in the world (1000+ draws a frame)\n", text) self.assertTrue(text.endswith( "B against A, by draws a frame (median fps, samples):\n" " 1000-2999 A - (0) B - (0) not compared\n" " 3000-4999 A 20.0 (8) B 25.0 (5) +25%\n" " 5000-6999 A - (0) B 18.0 (2) not compared\n" " 7000-8999 A - (0) B - (0) not compared\n" " 9000+ A 10.0 (5) B 12.0 (9) +20%\n" "buckets compared (5+ samples in both runs): 2; B faster in 2, slower in 0\n")) self.assertIn("buckets compared (2+ samples in both runs): 2; B faster in 2, slower in 0\n", few) for out in (text, as_json, few): self.assertNotIn(SECRET, out) self.assertNotIn("leonida_hle", out) self.assertNotIn(STAMP[:10], out) self.assertNotIn(tmp, out) class CommandLine(unittest.TestCase): def fails(self, *argv): err = io.StringIO() with contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as stop: run_fps.main(list(argv)) self.assertEqual(stop.exception.code, 2) return err.getvalue() def test_a_missing_log_is_refused_without_its_path(self): with tempfile.TemporaryDirectory() as tmp: log = write_log(tmp, "a.log", [frame_line(20.0, 4000)]) missing = os.path.join(tmp, "none.log") first = self.fails(missing) second = self.fails(log, "--compare", missing) self.assertIn("cannot read the log:", first) self.assertIn("cannot read the second log:", second) for err in (first, second): self.assertNotIn(tmp, err) self.assertNotIn("none.log", err) def test_bad_options_are_refused(self): with tempfile.TemporaryDirectory() as tmp: log = write_log(tmp, "a.log", [frame_line(20.0, 4000)]) self.assertIn("ascending", self.fails(log, "--edges", "3000,1000")) self.assertIn("ascending", self.fails(log, "--edges=-5,1000")) self.assertIn("whole numbers", self.fails(log, "--edges", "1000,many")) self.assertIn("whole numbers", self.fails(log, "--edges", "")) self.assertIn("a whole number, 1 or more", self.fails(log, "--compare", log, "--min-samples", "0")) self.assertIn("a whole number, 1 or more", self.fails(log, "--compare", log, "--min-samples=-2")) self.assertIn("--min-samples needs --compare", self.fails(log, "--min-samples", "3")) def test_no_error_gives_back_what_was_typed(self): with tempfile.TemporaryDirectory() as tmp: log = write_log(tmp, "a.log", [frame_line(20.0, 4000)]) other = write_log(tmp, "other.log", [frame_line(21.0, 4000)]) errors = [ self.fails(log, other), # the second log without --compare self.fails(log, other, os.path.join(tmp, "third.log")), self.fails(log, "--compare", other, "--min-samples", other), self.fails(log, "--edges", other), self.fails(log, "--unknown", other), self.fails(log, "--comp", other), # no abbreviations: not --compare ] self.assertIn("1 argument not understood: one log, and a second after --compare", errors[0]) self.assertIn("2 arguments not understood", errors[1]) self.assertIn("argument --min-samples: a whole number, 1 or more", errors[2]) self.assertIn("argument --edges: whole numbers separated by commas", errors[3]) for err in errors: self.assertNotIn(tmp, err) self.assertNotIn("other.log", err) self.assertNotIn("third.log", err) def test_an_error_of_argparses_own_is_rewritten_from_fixed_texts(self): # argparse quotes a value given to a flag that takes none, before any of the tool's own checks can run. for marker in ("synthetic-private-name", "zqv's " + '"quoted"', "zqx wvy"): with tempfile.TemporaryDirectory() as tmp: log = write_log(tmp, "a.log", [frame_line(20.0, 4000)]) cases = { "argument --json: takes no value": self.fails(log, f"--json={marker}"), "argument -h/--help: takes no value": self.fails(log, f"--help={marker}"), "argument --edges: whole numbers separated by commas": self.fails(log, f"--edges={marker}"), "argument --min-samples: a whole number, 1 or more": self.fails(log, "--compare", log, f"--min-samples={marker}"), "1 argument not understood": self.fails(log, f"--{marker}"), "cannot read the log:": self.fails(os.path.join(tmp, marker)), } for expected, err in cases.items(): self.assertIn(expected, err) self.assertNotIn(marker, err) self.assertNotIn(marker.split()[0], err) self.assertNotIn(tmp, err) with tempfile.TemporaryDirectory() as tmp: log = write_log(tmp, "a.log", [frame_line(20.0, 4000)]) self.assertIn("argument --compare: needs a value", self.fails(log, "--compare")) self.assertIn("argument --edges: needs a value", self.fails(log, "--edges")) self.assertIn("a log is needed", self.fails()) self.assertIn("a log is needed", self.fails("--json")) def test_a_message_argparse_may_gain_later_is_not_let_through(self): # Messages the list does not know (another Python's wording, a new check) must not carry their text out. parser = run_fps._Parser(prog="tool") parser.add_argument("--json", action="store_true") cases = (("argument --json: a new wording about 'typed text'", "argument --json: not understood"), ("a new message about typed text", "the arguments were not understood")) for message, expected in cases: err = io.StringIO() with contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as stop: parser.error(message) self.assertEqual(stop.exception.code, 2) self.assertIn(expected, err.getvalue()) self.assertNotIn("typed text", err.getvalue()) def test_the_fixed_texts_are_the_argument_types_own(self): # A text one of the types raises and the parser does not know would come out as "not understood". said = [] for kind, text in ((run_fps._edges, "x"), (run_fps._edges, "3,1"), (run_fps._samples, "0")): with self.assertRaises(argparse.ArgumentTypeError) as refused: kind(text) said.append(str(refused.exception)) self.assertEqual(sorted(said), sorted(run_fps._Parser.FIXED)) if __name__ == "__main__": unittest.main()