Files
mandy/tests/test_leonida_launcher.py
OreoFR f1e9718e95 launcher, play scripts: review fixes of #3272 (card mask kept out of the F1 file, -Adapter for auto FG, Linux cache and binds, clear-cache race, unreadable binds kept)
merzleckeier's reviews at 02:35, 02:47 and 02:58 and DeadlyChirp's 02:46 note:
1. The AMD/Intel card filter named NoDlss, NoFrameGen and SmoothMotion in
   -Chosen, so a real PLAY rewrote leonida-settings.txt without the F1
   menu's DLSS, DLSS frame generation and Smooth Motion. The launcher now
   passes -CardMask (card_mask) instead; play-d3d12.ps1 hands it over and
   play-nvidia.ps1 leaves those settings out of this start only, keeping
   them in the menu file (and says so); the menu's FSR stays.
2. play-nvidia.ps1's automatic DLSS frame generation looked at every card:
   with -Adapter it now judges the cards whose name holds it (all when none
   does), so an AMD card chosen beside an RTX 4070 gets none; the card
   mask's NoFrameGen also keeps it off.
3. Clear shader cache on Linux looked under the Windows data folder: it now
   uses play-linux.sh's LEONIDA_CACHE_DIR or ${XDG_DATA_HOME:-~/.local/share}
   /leonida/cache.
4. After the confirmation, clear_cache asks game_running() again, not only
   its own process.
5. Linux PLAY passes the extra variables (the Controls page's binds, the
   advanced options, Advanced winning) in play-linux.sh's environment
   (`env NAME=value sh play-linux.sh ...`); none were passed before.
6. The Controls page keeps entries it cannot read beside its rows
   (split_kbm_binds) and writes them back after them: adding a row no longer
   drops a saved list with an unknown entry. Its note called t() with a
   `text=` value, which crashed the page as soon as it showed one: the
   placeholder is {entries} now, in de/es/fr/pt too.

Tests: test_card_mask_leaves_the_menus_nvidia_values_out_and_in_the_file
(dry runs, a real start with Start-Process stubbed keeping the menu file,
AMD + RTX 4070 with -Adapter each way and with the mask); card_mask and
-CardMask in play_command; LinuxPlayTests; SplitBindsTests with a guard
that no t() call passes text=. Launcher suite OK (1 skip), win launchers
12 OK, docs links, line endings, check_no_game_data. Counter-tests: the
mask ignored, the adapter filter off, the Linux env/cache, split and
card_mask reverted each fail their tests; the guard regex matches the old
source. Real window (isolated APPDATA): the game started during the
confirmation leaves the cache and says close the game first; adding H to
`both:G=Square;vehicle:N=FutureAction` saves G, H and the unknown entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 04:15:54 +01:00

1782 lines
107 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""tools/leonida_launcher.py: settings, the command line and the mod list (no display, no game data).
python -I tests/test_leonida_launcher.py -v
"""
import contextlib
import io
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tools"))
import leonida_launcher as launcher # noqa: E402
def settings(**changes):
value = dict(launcher.DEFAULTS, game_dir="D:/Games/GTA")
value.update(changes)
return value
class SettingsTests(unittest.TestCase):
def test_round_trip_and_line_endings(self):
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "sub", "launcher.json")
launcher.save_settings(settings(dlss=False, resolution="1080", data_dir="E:/d"), path)
with open(path, "rb") as f:
raw = f.read()
self.assertNotIn(b"\r", raw)
self.assertTrue(raw.endswith(b"}\n"))
loaded = launcher.load_settings(path)
self.assertFalse(loaded["dlss"])
self.assertEqual((loaded["resolution"], loaded["data_dir"]), ("1080", "E:/d"))
def test_missing_or_broken_file_gives_defaults(self):
with tempfile.TemporaryDirectory() as tmp:
self.assertEqual(launcher.load_settings(os.path.join(tmp, "none.json")), launcher.DEFAULTS)
bad = os.path.join(tmp, "bad.json")
Path(bad).write_text("{not json", encoding="utf-8")
self.assertEqual(launcher.load_settings(bad), launcher.DEFAULTS)
def test_wrong_types_and_unknown_keys_are_dropped(self):
got = launcher.normalise({"dlss": "yes", "resolution": "999", "game_dir": 5, "extra": 1, "log": True})
self.assertEqual(got["dlss"], True)
self.assertEqual(got["resolution"], "")
self.assertEqual(got["game_dir"], "")
self.assertTrue(got["log"])
self.assertNotIn("extra", got)
self.assertEqual(launcher.normalise([1]), launcher.DEFAULTS)
def test_game_folder_check(self):
with tempfile.TemporaryDirectory() as tmp:
self.assertFalse(launcher.game_exe_present(tmp))
Path(tmp, launcher.EXPECTED_EXE).write_bytes(b"")
self.assertTrue(launcher.game_exe_present(tmp))
self.assertFalse(launcher.game_exe_present(""))
class CommandTests(unittest.TestCase):
def test_default_windows_command(self):
command = launcher.play_command(settings(), repo="R", windows=True)
self.assertEqual(command[:6], ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File",
os.path.join("R", "scripts", "play-d3d12.ps1")])
self.assertEqual(command[6:], ["-Game", "D:/Games/GTA"])
def test_every_option_maps_to_its_switch(self):
command = launcher.play_command(
settings(data_dir="E:/d", dlss=False, ray_tracing=True, smooth_motion=True, precompile=False,
series_x=True, quality=True, resolution="1440", capture=True, log=True),
repo="R", windows=True)
self.assertEqual(command[6:], ["-Game", "D:/Games/GTA", "-Data", "E:/d", "-NoDlss", "-RayTracing",
"-SmoothMotion", "-NoPrecompile", "-SeriesX", "-Quality",
"-Resolution", "1440", "-Capture", "-Log"])
def test_the_newer_switches(self):
got = launcher.switch_args(settings(series_s=True, series_x=True, dlss_mode="balanced", frame_gen=3,
resolution="1080", aspect="21:9", present_scale="stretch",
adapter="5070"))
# Series S wins over Series X, and -Resolution is left out with a DLSS mode, as the script asks
self.assertEqual(got, ["-SeriesS", "-Dlss", "balanced", "-FrameGen", "3", "-Aspect", "21:9",
"-PresentScale", "stretch", "-Adapter", "5070"])
self.assertEqual(launcher.switch_args(settings(dlss=False, dlss_mode="quality", resolution="1080")),
["-NoDlss", "-Resolution", "1080"])
self.assertEqual(launcher.switch_args(settings(present_scale="stretch")), []) # only with -Aspect
def test_the_newer_settings_are_checked(self):
got = launcher.normalise({"frame_gen": False, "dlss_mode": "max", "aspect": "21:9; calc", "adapter": 'a"b',
"present_scale": "fill", "series_s": True, "series_x": True})
self.assertEqual((got["frame_gen"], got["dlss_mode"], got["aspect"], got["adapter"], got["present_scale"]),
(0, "", "", "", ""))
self.assertEqual((got["series_s"], got["series_x"]), (True, False))
kept = launcher.normalise({"frame_gen": 4, "dlss_mode": "ultra", "aspect": " auto ", "adapter": "#1"})
self.assertEqual((kept["frame_gen"], kept["dlss_mode"], kept["aspect"], kept["adapter"]),
(4, "ultra", "auto", "#1"))
def test_only_switches_changed_since_the_last_play_are_chosen(self):
first = launcher.switch_args(settings(frame_gen=4, dlss_mode="performance", smooth_motion=True))
# The first PLAY has nothing to compare with: none chosen, the F1 menu's values stand.
self.assertEqual(launcher.chosen_switches(first, ""), [])
last = json.dumps(first)
# The same options again: none chosen.
self.assertEqual(launcher.chosen_switches(first, last), [])
# A changed value, a switch turned on and one turned off: those three.
now = launcher.switch_args(settings(frame_gen=2, dlss_mode="performance", log=True))
self.assertEqual(launcher.chosen_switches(now, last), ["FrameGen", "Log", "SmoothMotion"])
# A broken record counts as none.
self.assertEqual(launcher.chosen_switches(now, "not json"), [])
def test_play_command_names_the_chosen_switches(self):
s = settings(game_dir=r"C:\g", frame_gen=2)
command = launcher.play_command(s, repo="R", windows=True, chosen=["FrameGen"])
self.assertEqual(command[command.index("-Chosen") + 1], "FrameGen")
none = launcher.play_command(s, repo="R", windows=True, chosen=[])
self.assertEqual(none[none.index("-Chosen") + 1], "none")
self.assertNotIn("-Chosen", launcher.play_command(s, repo="R", windows=True))
text = (ROOT / "scripts" / "play-d3d12.ps1").read_text(encoding="utf-8")
self.assertIn("$Chosen", text)
def test_switches_exist_in_the_script(self):
text = (ROOT / "scripts" / "play-d3d12.ps1").read_text(encoding="utf-8")
every = settings(dlss=False, ray_tracing=True, smooth_motion=True, precompile=False, series_x=True,
quality=True, resolution="720", capture=True, log=True, aspect="32:9",
present_scale="fit", adapter="#1", frame_gen=2)
newer = settings(series_s=True, dlss_mode="quality", precompile_all=True)
for arg in launcher.switch_args(every) + launcher.switch_args(newer):
if arg.startswith("-") and arg[1:].isalpha():
self.assertIn("$" + arg[1:], text, arg)
self.assertIn("$Game", text)
self.assertIn("$Data", text)
def test_precompile_all_only_with_the_precompile(self):
defaults = launcher.normalise({})
self.assertTrue(defaults["precompile_all"])
self.assertEqual(launcher.switch_args(defaults), [])
saved = launcher.normalise({"precompile_all": False})
self.assertEqual(launcher.switch_args(saved), ["-PrecompileUsed"])
off = launcher.normalise({"precompile": False})
self.assertFalse(off["precompile_all"])
self.assertEqual(launcher.switch_args(off), ["-NoPrecompile"])
def test_linux_command(self):
command = launcher.play_command(settings(game_dir="/g", series_x=True, dlss=False), repo="/r",
windows=False)
self.assertEqual(command, ["sh", os.path.join("/r", "scripts", "play-linux.sh"),
os.path.join("/g", launcher.EXPECTED_EXE), "--series-x"])
def test_no_game_folder_is_refused(self):
with self.assertRaises(ValueError):
launcher.play_command(settings(game_dir=" "), windows=True)
def test_tools(self):
self.assertEqual(launcher.tool_command("get_dlss", repo="R", windows=True)[:2], ["cmd", "/c"])
self.assertTrue(launcher.tool_command("build", repo="R", windows=True)[-1].endswith("build-nvidia.ps1"))
with self.assertRaises(ValueError):
launcher.tool_command("build", windows=False)
with self.assertRaises(ValueError):
launcher.tool_command("nope", windows=True)
def test_state_follows_the_scripts_messages(self):
state = "Starting"
for line, want in (("Series S, 720p. F1 in the game: settings.\n", "Starting"),
("Precompiling shaders (minutes) ...\n", "Preparing shaders"),
(" 1000 shaders\n", "Preparing shaders"),
("log: x.log\n", "Running")):
state = launcher.state_for_line(state, line)
self.assertEqual(state, want, line)
self.assertEqual(launcher.state_for_line("Starting", "Building the layer (a few minutes) ...\n"),
"Building the runtime")
class ForCardTests(unittest.TestCase):
"""Without an NVIDIA card PLAY passes DLSS, its mode, DLSS frame generation's multiplier and Smooth Motion off."""
AMD = {"known": True, "nvidia": False, "vendor": "amd", "vram": 16 << 30}
NVIDIA = {"known": True, "nvidia": True, "vendor": "nvidia", "vram": 12 << 30}
UNKNOWN = {"known": False, "nvidia": True, "vendor": "", "vram": 0}
def settings(self, **over):
return launcher.normalise(dict({"dlss": True, "dlss_mode": "quality", "frame_gen": 2, "smooth_motion": True,
"resolution": "1440"}, **over))
def test_amd_card_gets_no_dlss(self) -> None:
saved = self.settings()
args = launcher.switch_args(launcher.for_card(saved, self.AMD))
self.assertIn("-NoDlss", args)
for gone in ("-Dlss", "-FrameGen", "-SmoothMotion"):
self.assertNotIn(gone, args)
self.assertIn("-Resolution", args) # no DLSS mode: the resolution is passed again
self.assertEqual(saved, self.settings()) # the saved settings keep their values
def test_fsr_frame_generation_stays_on_amd(self) -> None:
args = launcher.switch_args(launcher.for_card(self.settings(fsr_frame_gen=True), self.AMD))
self.assertIn("-FsrFrameGen", args)
self.assertIn("-NoDlss", args)
def test_frame_generation_off_stays_off_on_amd(self) -> None:
args = launcher.switch_args(launcher.for_card(self.settings(no_frame_gen=True), self.AMD))
self.assertIn("-NoFrameGen", args)
def test_resolution_live_on_amd_with_a_saved_dlss_mode(self) -> None:
values = {"rt": "off", "dlss": True, "dlss_mode": "quality", "fg_mode": "dlss", "frame_gen": "0",
"aspect": "", "precompile_all": False, "advanced": ""}
enabled, _ = launcher.settings_rules(values, self.AMD, launch(console="series-s", rt="off"))
self.assertTrue(enabled["resolution"]) # PLAY passes -Resolution there (no DLSS mode on AMD)
enabled, _ = launcher.settings_rules(values, self.NVIDIA, launch(console="series-s", rt="off"))
self.assertFalse(enabled["resolution"]) # with DLSS's mode the script wants it left out
def test_card_mask_names_the_menus_nvidia_switches(self) -> None:
self.assertEqual(launcher.card_mask(self.AMD), ["NoDlss", "NoFrameGen", "SmoothMotion"])
for card in (self.NVIDIA, self.UNKNOWN):
self.assertEqual(launcher.card_mask(card), [])
# Through play_command: -CardMask carries them, and -Chosen does not (a name there would remove the menu's
# value from its file).
command = launcher.play_command(self.settings(game_dir="D:\\Games"), repo="R", windows=True, chosen=[],
mask=launcher.card_mask(self.AMD))
self.assertEqual(command[command.index("-CardMask") + 1], "NoDlss,NoFrameGen,SmoothMotion")
self.assertEqual(command[command.index("-Chosen") + 1], "none")
command = launcher.play_command(self.settings(game_dir="D:\\Games"), repo="R", windows=True, chosen=[],
mask=launcher.card_mask(self.NVIDIA))
self.assertNotIn("-CardMask", command)
def test_a_resolution_above_series_s_output_stays_out_without_dlss(self) -> None:
# Series S with DLSS Quality and a saved 1440 (left out by the mode): on AMD it would come back and stop the
# script (Series S outputs 1080 lines), so it stays out; 1080 or less comes back.
args = launcher.switch_args(launcher.for_card(self.settings(series_s=True, resolution="1440"), self.AMD))
self.assertNotIn("-Resolution", args)
args = launcher.switch_args(launcher.for_card(self.settings(series_s=True, resolution="720"), self.AMD))
self.assertEqual(args[args.index("-Resolution") + 1], "720")
# Series X outputs up to 2160: kept.
args = launcher.switch_args(launcher.for_card(self.settings(series_s=False, series_x=True,
resolution="1440"), self.AMD))
self.assertIn("-Resolution", args)
# Without a DLSS mode it was passed already: for_card leaves it as it was.
args = launcher.switch_args(launcher.for_card(self.settings(series_s=True, dlss_mode="",
resolution="1440"), self.AMD))
self.assertIn("-Resolution", args)
def test_nvidia_and_unknown_cards_unchanged(self) -> None:
for card in (self.NVIDIA, self.UNKNOWN):
saved = self.settings()
self.assertEqual(launcher.switch_args(launcher.for_card(saved, card)), launcher.switch_args(saved))
self.assertIn("-Dlss", launcher.switch_args(launcher.for_card(saved, card)))
class ModsAndPicturesTests(unittest.TestCase):
def test_list_and_toggle_mods(self):
with tempfile.TemporaryDirectory() as tmp:
mod = Path(tmp, "alpha")
mod.mkdir()
manifest = mod / "mod.json"
manifest.write_text(json.dumps({"name": "Alpha", "archetype_swaps": [{"from": "a_b", "to": "c_d"}]}),
encoding="utf-8")
Path(tmp, "broken").mkdir()
Path(tmp, "broken", "mod.json").write_text("{", encoding="utf-8")
Path(tmp, "notamod").mkdir()
rows, errors = launcher.list_mods(tmp)
self.assertEqual([(r["folder"], r["name"], r["enabled"], r["swaps"]) for r in rows],
[("alpha", "Alpha", True, 1)])
self.assertEqual(len(errors), 1)
launcher.set_mod_enabled(rows[0]["path"], False)
self.assertFalse(json.loads(manifest.read_text(encoding="utf-8"))["enabled"])
self.assertNotIn(b"\r", manifest.read_bytes())
self.assertFalse(launcher.list_mods(tmp)[0][0]["enabled"])
self.assertEqual(launcher.list_mods(os.path.join(tmp, "missing")), ([], []))
class FakeGit:
"""`git -C repo <args>` answered from a table of the first argument; records each call."""
def __init__(self, answers):
self.answers = answers
self.calls = []
def __call__(self, repo, *args, timeout=60):
self.calls.append(args)
code, out = self.answers.get(args[0], (0, ""))
if callable(out):
out = out(args)
return launcher.subprocess.CompletedProcess(["git", *args], code, out, "")
class UpdateTests(unittest.TestCase):
def repo(self, tmp, git=True):
if git:
os.mkdir(os.path.join(tmp, ".git"))
return tmp
def test_a_zip_copy_is_offered_the_update(self):
with tempfile.TemporaryDirectory() as tmp:
status = launcher.update_status(self.repo(tmp, git=False), FakeGit({}))
self.assertEqual(status["kind"], "zip")
self.assertIn("Update Mandy", launcher.update_note(status))
def test_git_is_found_where_git_for_windows_installs_it(self):
# A launcher started before Git was installed has a PATH without it.
env = {"ProgramFiles": r"C:\Program Files", "LOCALAPPDATA": r"C:\Users\p\AppData\Local"}
machine = os.path.join(r"C:\Program Files", "Git", "cmd", "git.exe")
user = os.path.join(r"C:\Users\p\AppData\Local", "Programs", "Git", "cmd", "git.exe")
none = lambda _name: None
self.assertEqual(launcher.find_git(True, which=lambda _n: "C:/x/git.exe", isfile=lambda _p: False, env=env),
"C:/x/git.exe")
self.assertEqual(launcher.find_git(True, which=none, isfile=lambda p: p == machine, env=env), machine)
self.assertEqual(launcher.find_git(True, which=none, isfile=lambda p: p == user, env=env), user)
self.assertIsNone(launcher.find_git(True, which=none, isfile=lambda _p: False, env=env))
self.assertIsNone(launcher.find_git(False, which=none, isfile=lambda _p: True, env=env))
def test_git_is_installed_with_winget_or_the_way_is_said(self):
ran, found = [], iter([None, "C:/Git/cmd/git.exe"])
with contextlib.redirect_stdout(io.StringIO()):
got = launcher.install_git(True, run=lambda c: ran.append(c) or 0, find=lambda: next(found),
winget=lambda: "C:/winget.exe")
self.assertEqual(got, "C:/Git/cmd/git.exe")
self.assertEqual(ran, [["C:/winget.exe", *launcher.GIT_WINGET]])
self.assertIn("Git.Git", launcher.GIT_WINGET)
self.assertIn("--silent", launcher.GIT_WINGET)
for windows, winget in ((True, lambda: None), (False, lambda: "C:/winget.exe")):
ran.clear()
out = io.StringIO()
with contextlib.redirect_stdout(out):
got = launcher.install_git(windows, run=lambda c: ran.append(c) or 0, find=lambda: None, winget=winget)
self.assertIsNone(got)
self.assertEqual(ran, [])
self.assertIn("install", out.getvalue())
# winget ran but no git.exe appeared: said, None.
out = io.StringIO()
with contextlib.redirect_stdout(out):
self.assertIsNone(launcher.install_git(True, run=lambda c: 5, find=lambda: None, winget=lambda: "w"))
self.assertIn("code 5", out.getvalue())
def test_a_zip_copy_without_git_asks_before_installing(self):
installs, converted = [], []
saved = launcher.zip_to_clone
launcher.zip_to_clone = lambda *a, **k: converted.append(a) or (0, False)
try:
with tempfile.TemporaryDirectory() as tmp, contextlib.redirect_stdout(io.StringIO()):
def update(**kw):
kw.setdefault("get_git", lambda: installs.append(1) or "git")
return launcher.run_update(tmp, FakeGit({}), **kw)
# Not allowed and not asked (the window passes --install-git; a pipe cannot be asked), or refused.
self.assertEqual(update(find=lambda: None), 1)
self.assertEqual(update(find=lambda: None, ask=lambda: False), 1)
self.assertEqual((installs, converted), ([], []))
# Asked and accepted, or allowed: installed, then converted.
self.assertEqual(update(find=lambda: None, ask=lambda: True), 0)
self.assertEqual(update(find=lambda: None, install=True), 0)
# The install failed: nothing converted.
self.assertEqual(update(find=lambda: None, install=True, get_git=lambda: None), 1)
# Git there: no install.
self.assertEqual(update(find=lambda: "git"), 0)
finally:
launcher.zip_to_clone = saved
self.assertEqual((len(installs), len(converted)), (2, 3))
def test_the_window_passes_install_git(self):
self.assertEqual(launcher.update_command("C:/mandy", install_git=True)[-2:], ["C:/mandy", "--install-git"])
self.assertEqual(launcher.update_command("C:/mandy")[-1], "C:/mandy")
def test_the_count_is_one_per_merged_pull_request(self):
# rev-list answers 9 for every commit, 2 for the first-parent ones: the launcher shows 2.
git = FakeGit({"rev-list": (0, lambda a: "2" if "--first-parent" in a else "9")})
with tempfile.TemporaryDirectory() as tmp:
status = launcher.update_status(self.repo(tmp), git)
self.assertEqual((status["kind"], status["behind"]), ("behind", 2))
def test_behind_counts_the_new_commits_after_a_fetch(self):
git = FakeGit({"rev-list": (0, "3\n")})
with tempfile.TemporaryDirectory() as tmp:
status = launcher.update_status(self.repo(tmp), git)
self.assertEqual((status["kind"], status["behind"]), ("behind", 3))
self.assertIn(("fetch", "--quiet"), git.calls)
self.assertIn("3 new commit", launcher.update_note(status))
self.assertEqual(launcher.update_note({"kind": "current", "behind": 0}), "")
def test_behind_lists_what_is_new(self):
log = ("abc1234\x1fMerge pull request #3097 from OreoFR/feat/compare-on-sender\x1f"
"d3d12 host: compare on the sender thread\n\nlonger text\n\x1e\n"
"def5678\x1fdocs: a fix straight on main\x1f\x1e\n")
git = FakeGit({"rev-list": (0, "2\n"), "log": (0, log)})
with tempfile.TemporaryDirectory() as tmp:
status = launcher.update_status(self.repo(tmp), git)
self.assertEqual(status["changes"], [
{"title": "d3d12 host: compare on the sender thread", "pr": 3097, "hash": "abc1234"},
{"title": "docs: a fix straight on main", "pr": None, "hash": "def5678"}])
log_call = [c for c in git.calls if c[0] == "log"][0]
self.assertIn("--first-parent", log_call)
self.assertEqual(log_call[-1], "HEAD..@{u}")
self.assertEqual(launcher.change_line(status["changes"][0]), "#3097 d3d12 host: compare on the sender thread")
self.assertEqual(launcher.change_line(status["changes"][1]), "docs: a fix straight on main")
self.assertEqual(len(launcher.change_line({"title": "x" * 200, "pr": None}, limit=40)), 40)
# A merge without a body keeps its subject; a log that fails leaves the list empty, still behind.
self.assertEqual(launcher.parse_changes("a1\x1fMerge pull request #5 from x/y\x1f\x1e")[0]["title"],
"Merge pull request #5 from x/y")
with tempfile.TemporaryDirectory() as tmp:
failed = launcher.update_status(self.repo(tmp), FakeGit({"rev-list": (0, "4\n"), "log": (128, "")}))
self.assertEqual((failed["kind"], failed["behind"], failed["changes"]), ("behind", 4, []))
def test_a_failed_fetch_or_no_upstream_is_said_not_raised(self):
with tempfile.TemporaryDirectory() as tmp:
repo = self.repo(tmp)
self.assertEqual(launcher.update_status(repo, FakeGit({"rev-parse": (128, "")}))["kind"], "noupstream")
failed = launcher.update_status(repo, FakeGit({"fetch": (128, "no network")}))
self.assertEqual(failed["kind"], "error")
self.assertIn("no network", launcher.update_note(failed))
def test_update_rebuilds_only_when_d3d12_moved(self):
heads = iter(["aaa", "bbb", "aaa", "bbb"])
for d3d12_changed in (False, True):
built = []
git = FakeGit({"rev-list": (0, "2"), "rev-parse": (0, lambda a: "origin/main" if "@{u}" in a else next(heads)),
"diff": (1 if d3d12_changed else 0, "")})
with tempfile.TemporaryDirectory() as tmp:
code = launcher.run_update(self.repo(tmp), git, build=lambda: built.append(1) or 0, windows=True)
self.assertEqual(code, 0)
self.assertIn(("pull", "--ff-only"), git.calls)
self.assertEqual(built, [1] if d3d12_changed else [])
def test_a_pull_that_cannot_fast_forward_stops_without_a_build(self):
built = []
git = FakeGit({"rev-list": (0, "1"), "pull": (128, "Not possible to fast-forward")})
with tempfile.TemporaryDirectory() as tmp:
code = launcher.run_update(self.repo(tmp), git, build=lambda: built.append(1) or 0, windows=True)
self.assertNotEqual(code, 0)
self.assertEqual(built, [])
def test_the_update_command_is_this_file_in_isolated_mode(self):
command = launcher.update_command("C:/mandy")
self.assertEqual(command[1:2] + command[3:], ["-I", "--update", "C:/mandy"])
self.assertTrue(command[2].endswith("leonida_launcher.py"))
def test_the_check_can_be_turned_off(self):
self.assertTrue(launcher.DEFAULTS["check_updates"])
self.assertFalse(launcher.normalise({"check_updates": False})["check_updates"])
@unittest.skipIf(shutil.which("git") is None, "git is not installed")
class ZipToCloneTests(unittest.TestCase):
"""A zip copy made a clone with the real git: a bare repository as the origin, the "zip" an older version with
one file the player edited, one they added and the repository's ignored builds."""
@staticmethod
def run_git(cwd, *args):
done = subprocess.run(["git", "-C", cwd, "-c", "user.name=t", "-c", "user.email=t@example.invalid",
"-c", "commit.gpgsign=false", *args], capture_output=True, text=True, check=False)
if done.returncode != 0:
raise AssertionError(f"git {args}: {done.stderr}")
return done.stdout.strip()
@staticmethod
def write(root, files):
for rel, text in files.items():
path = os.path.join(root, *rel.split("/"))
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w", encoding="utf-8", newline="\n") as f:
f.write(text)
@staticmethod
def read(root, rel):
with open(os.path.join(root, *rel.split("/")), encoding="utf-8") as f:
return f.read().replace("\r\n", "\n")
def origin(self, tmp):
work = os.path.join(tmp, "work")
os.mkdir(work)
self.run_git(work, "init", "-q")
self.run_git(work, "symbolic-ref", "HEAD", "refs/heads/main")
old = {"a.txt": "one\n", "d3d12/x.rs": "old\n", "tools/t.py": "t1\n", ".gitignore": "target/\n"}
self.write(work, old)
self.run_git(work, "add", "-A")
self.run_git(work, "commit", "-q", "-m", "first")
self.write(work, {"a.txt": "two\n", "d3d12/x.rs": "new\n", "docs/new.md": "new page\n"})
self.run_git(work, "add", "-A")
self.run_git(work, "commit", "-q", "-m", "second")
bare = os.path.join(tmp, "origin.git")
subprocess.run(["git", "clone", "-q", "--bare", work, bare], capture_output=True, check=True)
return work, bare, old
def test_a_zip_copy_becomes_a_clone_and_keeps_what_was_changed(self):
with tempfile.TemporaryDirectory() as tmp:
work, bare, old = self.origin(tmp)
copy = os.path.join(tmp, "mandy-main")
os.mkdir(copy)
self.write(copy, dict(old, **{"tools/t.py": "t1 with my edit\n", "game_path.txt": "D:/Games\n",
"target/build.bin": "built\n", "mine.txt": "my notes\n"}))
backup = os.path.join(tmp, "backup")
out = io.StringIO()
with contextlib.redirect_stdout(out):
code, d3d12 = launcher.zip_to_clone(copy, backup=backup, url=bare, branch="main")
self.assertEqual(code, 0, out.getvalue())
self.assertTrue(d3d12)
self.assertEqual(self.run_git(copy, "rev-parse", "HEAD"), self.run_git(work, "rev-parse", "HEAD"))
self.assertEqual(self.run_git(copy, "rev-parse", "--abbrev-ref", "@{u}"), "origin/main")
self.assertEqual(self.run_git(copy, "status", "--porcelain", "--untracked-files=no"), "")
# The repository's version is in place, new files included ...
for rel, text in {"a.txt": "two\n", "d3d12/x.rs": "new\n", "tools/t.py": "t1\n",
"docs/new.md": "new page\n"}.items():
self.assertEqual(self.read(copy, rel), text, rel)
# ... every file that differed was kept first, the player's edit with the zip's old ones ...
for rel, text in {"a.txt": "one\n", "d3d12/x.rs": "old\n", "tools/t.py": "t1 with my edit\n"}.items():
self.assertEqual(self.read(backup, rel), text, rel)
self.assertFalse(os.path.exists(os.path.join(backup, "docs", "new.md")))
# ... and what git does not track is untouched.
for rel, text in {"game_path.txt": "D:/Games\n", "target/build.bin": "built\n",
"mine.txt": "my notes\n"}.items():
self.assertEqual(self.read(copy, rel), text, rel)
# Next time it is a clone: the usual update sees a new commit and pulls it.
self.assertEqual(launcher.update_status(copy)["kind"], "current")
self.write(work, {"a.txt": "three\n"})
self.run_git(work, "commit", "-q", "-am", "third")
self.run_git(work, "push", "-q", bare, "main")
with contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(launcher.run_update(copy, windows=False), 0)
self.assertEqual(self.read(copy, "a.txt"), "three\n")
def test_a_failed_download_leaves_the_zip_copy_as_it_was(self):
with tempfile.TemporaryDirectory() as tmp:
_work, _bare, old = self.origin(tmp)
copy = os.path.join(tmp, "mandy-main")
os.mkdir(copy)
self.write(copy, old)
out = io.StringIO()
with contextlib.redirect_stdout(out):
code, _ = launcher.zip_to_clone(copy, backup=os.path.join(tmp, "b"),
url=os.path.join(tmp, "no-such-repository"), branch="main")
self.assertNotEqual(code, 0)
self.assertIn("zip copy again", out.getvalue())
self.assertFalse(os.path.exists(os.path.join(copy, ".git")))
self.assertEqual(launcher.update_status(copy)["kind"], "zip")
for rel, text in old.items():
self.assertEqual(self.read(copy, rel), text, rel)
def collide(self, tmp, local):
"""An origin whose last commit tracks a file `layout` and a folder `settings`, and a zip copy of its first
commit with `local` added; zip_to_clone's code and output."""
work, bare, old = self.origin(tmp)
self.write(work, {"layout": "the repository's layout\n", "settings/defaults.txt": "defaults\n"})
self.run_git(work, "add", "-A")
self.run_git(work, "commit", "-q", "-m", "third")
self.run_git(work, "push", "-q", bare, "main")
copy = os.path.join(tmp, "mandy-main")
os.mkdir(copy)
self.write(copy, dict(old, **local))
out = io.StringIO()
with contextlib.redirect_stdout(out):
code, _ = launcher.zip_to_clone(copy, backup=os.path.join(tmp, "backup"), url=bare, branch="main")
return copy, code, out.getvalue()
def test_a_local_folder_where_the_repository_has_a_file_stops_it(self):
with tempfile.TemporaryDirectory() as tmp:
copy, code, out = self.collide(tmp, {"layout/local-notes.txt": "my notes\n"})
self.assertNotEqual(code, 0, out)
self.assertIn("layout", out)
self.assertEqual(self.read(copy, "layout/local-notes.txt"), "my notes\n")
self.assertFalse(os.path.exists(os.path.join(copy, ".git")))
self.assertEqual(launcher.update_status(copy)["kind"], "zip")
def test_a_local_file_where_the_repository_has_a_folder_stops_it(self):
with tempfile.TemporaryDirectory() as tmp:
copy, code, out = self.collide(tmp, {"settings": "my settings\n"})
self.assertNotEqual(code, 0, out)
self.assertIn("settings", out)
self.assertEqual(self.read(copy, "settings"), "my settings\n")
self.assertFalse(os.path.exists(os.path.join(copy, ".git")))
self.assertEqual(self.read(copy, "a.txt"), "one\n") # nothing was written
def test_zip_collisions(self):
with tempfile.TemporaryDirectory() as tmp:
self.write(tmp, {"dir/inside.txt": "x", "file": "y", "ok/a.txt": "z"})
self.assertEqual(launcher.zip_collisions(tmp, ["dir", "file/sub.txt", "ok/a.txt", "ok/new.txt",
"missing/new.txt"]), ["dir", "file"])
class ClearShaderCacheTests(unittest.TestCase):
"""Tools > Clear shader cache: the data folder's cache-2 goes, the saves in data/ and anything else stay; refused
while the game runs."""
def make(self, root):
for rel in ("cache-2/images/leonida-image-1.dll", "cache-2/shaders/a.bin", "data/7952987A/saves/x/0",
"leonida-settings.txt"):
path = os.path.join(root, *rel.split("/"))
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "wb") as f:
f.write(b"x" * 1000)
os.chmod(os.path.join(root, "cache-2", "shaders", "a.bin"), 0o444) # read-only, as some cache files are
def test_only_the_cache_goes(self):
with tempfile.TemporaryDirectory() as tmp:
self.make(tmp)
settings = launcher.normalise({"data_dir": tmp})
self.assertEqual(launcher.shader_cache_dir(settings), os.path.join(tmp, "cache-2"))
self.assertEqual(launcher.folder_size(launcher.shader_cache_dir(settings)), 2000)
done, message = launcher.clear_shader_cache(settings, running=lambda: False)
self.assertTrue(done, message)
self.assertFalse(os.path.exists(os.path.join(tmp, "cache-2")))
self.assertTrue(os.path.isfile(os.path.join(tmp, "data", "7952987A", "saves", "x", "0")))
self.assertTrue(os.path.isfile(os.path.join(tmp, "leonida-settings.txt")))
# Again: already empty, nothing else touched.
done, message = launcher.clear_shader_cache(settings, running=lambda: False)
self.assertTrue(done)
self.assertIn("already empty", message)
def test_refused_while_the_game_runs(self):
with tempfile.TemporaryDirectory() as tmp:
self.make(tmp)
done, message = launcher.clear_shader_cache(launcher.normalise({"data_dir": tmp}), running=lambda: True)
self.assertFalse(done)
self.assertIn("Close the game", message)
self.assertTrue(os.path.isdir(os.path.join(tmp, "cache-2", "images")))
def test_the_name_is_the_start_scripts(self):
script = (Path(launcher.REPO) / "scripts" / "play-d3d12.ps1").read_text(encoding="utf-8")
self.assertIn(f'$env:LEONIDA_CACHE_DIR = Join-Path $Data "{launcher.SHADER_CACHE}"', script)
def test_the_default_data_folder_and_sizes(self):
default = launcher.shader_cache_dir(launcher.normalise({}))
self.assertEqual(default, os.path.join(launcher.local_data_dir(), "Leonida", "d3d12", "cache-2"))
self.assertEqual(launcher.size_text(512), "512 B")
self.assertEqual(launcher.size_text(3 << 30), "3.0 GB")
self.assertEqual(launcher.size_text(1536 << 20), "1.5 GB")
class ControlsTests(unittest.TestCase):
"""The Controls page's binds: LEONIDA_KBM_BINDS in kbm.rs's syntax, read back into rows, keys from Tk's events."""
def test_round_trip(self):
text = "both:R=none;both:G=Square;foot:V=RB;vehicle:Up=RT;foot:Numpad0=LeftY+;both:MouseRight=LT"
rows = launcher.parse_kbm_binds(text)
self.assertEqual(rows[:3], [("both", "R", "none"), ("both", "G", "Square"), ("foot", "V", "RB")])
self.assertEqual(launcher.kbm_binds_text(rows), text)
# Any case, spaces, kbm.rs's other names: read into the page's spelling.
self.assertEqual(launcher.parse_kbm_binds(" Both : g = x ; FOOT:num3=a; vehicle:return=y;foot:escape=b"),
[("both", "G", "Square"), ("foot", "Numpad3", "Cross"), ("vehicle", "Enter", "Triangle"),
("foot", "Esc", "Circle")])
self.assertEqual(launcher.parse_kbm_binds(""), [])
self.assertEqual(launcher.kbm_binds_text([("both", "", "Square"), ("foot", "Q", "RB")]), "foot:Q=RB")
# Unreadable or reserved: None, so the page keeps the text instead.
for bad in ("G=Square", "feet:G=RT", "foot:F13=RT", "foot:G=Jump", "both:F1=A", "both:CapsLock=LT",
"foot:Numpad10=RT", "foot:G"):
self.assertIsNone(launcher.parse_kbm_binds(bad), bad)
def test_keys_of_events(self):
cases = {"a": "A", "Z": "Z", "5": "5", "F5": "F5", "F12": "F12", "KP_0": "Numpad0", "KP_9": "Numpad9",
"KP_Up": "Up", "Up": "Up", "Left": "Left", "space": "Space", "Return": "Enter", "KP_Enter": "Enter",
"Escape": "Esc", "Tab": "Tab", "BackSpace": "Backspace", "Shift_L": "LShift", "Shift_R": "RShift",
"Control_L": "LCtrl", "Control_R": "RCtrl", "Prior": "PageUp", "Next": "PageDown",
"Alt_L": "LAlt", "Caps_Lock": "CapsLock", "F1": "F1"}
for keysym, name in cases.items():
self.assertEqual(launcher.kbm_key_of_event(keysym), name, keysym)
self.assertEqual(launcher.kbm_key_of_event("", 1), "MouseLeft")
self.assertEqual(launcher.kbm_key_of_event("", 3), "MouseRight")
for keysym, button in (("", 2), ("F13", 0), ("eacute", 0), ("XF86AudioPlay", 0), ("semicolon", 0)):
self.assertIsNone(launcher.kbm_key_of_event(keysym, button), keysym)
def test_reserved_keys(self):
self.assertEqual(set(launcher.KBM_RESERVED), {"F1", "F3", "F4", "F8", "F9", "LAlt", "RAlt", "CapsLock"})
for keysym in ("F1", "F3", "F4", "F8", "F9", "Alt_L", "Alt_R", "Caps_Lock"):
self.assertIn(launcher.kbm_key_of_event(keysym), launcher.KBM_RESERVED, keysym)
for keysym in ("F2", "F5", "F12", "r"):
self.assertNotIn(launcher.kbm_key_of_event(keysym), launcher.KBM_RESERVED, keysym)
def test_settings_and_play(self):
self.assertEqual(launcher.normalise({})["kbm_binds"], "")
self.assertEqual(launcher.normalise({"kbm_binds": 5})["kbm_binds"], "")
self.assertEqual(launcher.normalise({"kbm_binds": "both:G=Square"})["kbm_binds"], "both:G=Square")
s = launcher.normalise({"kbm_binds": "both:R=none;both:G=Square"})
self.assertEqual(launcher.extra_variables(s)["LEONIDA_KBM_BINDS"], "both:R=none;both:G=Square")
self.assertNotIn("LEONIDA_KBM_BINDS", launcher.extra_variables(launcher.normalise({"kbm_binds": " "})))
# A LEONIDA_KBM_BINDS typed in the advanced options wins.
s["advanced"] = "LEONIDA_KBM_BINDS=foot:V=RB"
self.assertEqual(launcher.extra_variables(s)["LEONIDA_KBM_BINDS"], "foot:V=RB")
# PLAY passes it with -More, and Copy my info lists it.
command = launcher.play_command(launcher.normalise({"game_dir": "D:\\G", "kbm_binds": "both:G=Square"}),
repo="R", windows=True)
self.assertIn("LEONIDA_KBM_BINDS='both:G=Square'", command[-1])
info = launcher.info_text(launcher.normalise({"kbm_binds": "both:G=Square"}), "abc", [], "3.12", "8.6",
"Windows 11")
self.assertIn("LEONIDA_KBM_BINDS=both:G=Square", info)
def test_every_name_is_the_runtimes(self):
"""Each scope, key and action the page can write is one kbm.rs reads (its key_named, action_named and the
scopes of entry()), and the reserved keys are its RESERVED ones: the names are taken from kbm.rs's text."""
import re
source = Path(os.environ.get("LEONIDA_KBM_RS") or
ROOT / "d3d12" / "crates" / "leonida-hle" / "src" / "modules" / "gameinput" / "kbm.rs")
text = source.read_text(encoding="utf-8") if source.is_file() else ""
if "fn key_named" not in text:
self.skipTest("kbm.rs has no LEONIDA_KBM_BINDS yet (#3276 not merged): set LEONIDA_KBM_RS to its file")
def literals(function):
body = text[text.index(f"fn {function}("):]
body = body[:body.index("\n}\n")]
return {w for arm in re.findall(r'^\s*((?:"[^"]+"\s*\|?\s*)+)=>', body, re.M)
for w in re.findall(r'"([^"]+)"', arm)}
keys = literals("key_named")
actions = literals("action_named")
for name in launcher.KBM_NAMED_KEYS + launcher.KBM_RESERVED:
if not (name.startswith("F") and name[1:].isdigit()):
self.assertIn(name.lower(), keys, name)
self.assertIn('strip_prefix("numpad")', text)
self.assertIn("(1..=12).contains(&n)", text)
for name, _label in launcher.KBM_ACTIONS:
if name != "none":
self.assertIn(name.lower(), actions, name)
self.assertIn('eq_ignore_ascii_case("none")', text)
self.assertEqual(set(launcher.KBM_ACTION_ALIASES), {"a", "b", "x", "y"} & actions)
for scope in launcher.KBM_SCOPES:
self.assertIn(f'"{scope}" => Scope::', text)
reserved = text[text.index("const RESERVED"):]
reserved = reserved[:reserved.index("];")]
for word in ("F1 opens", "F3 shows", "F4 opens", "F8 is", "F9 is", "VK_LMENU", "VK_RMENU", "VK_CAPITAL"):
self.assertIn(word, reserved)
self.assertEqual(reserved.count("(VK_"), 8)
class LinuxPlayTests(unittest.TestCase):
"""Linux PLAY: play-linux.sh gets the Controls page's binds and the advanced options in its environment (the
runtime inherits it), Advanced winning; the shader cache is the one play-linux.sh uses (review of #3272)."""
def test_variables_reach_play_linux(self):
settings = launcher.normalise({"game_dir": "/games/gta", "kbm_binds": "both:G=Square",
"advanced": "LEONIDA_HW_RT=1"})
command = launcher.play_command(settings, repo="/r", windows=False)
self.assertEqual(command[0], "env")
self.assertIn("LEONIDA_KBM_BINDS=both:G=Square", command)
self.assertIn("LEONIDA_HW_RT=1", command)
self.assertEqual(command[command.index("sh"):][:2], ["sh", os.path.join("/r", "scripts", "play-linux.sh")])
# Advanced wins over the Controls page.
settings = launcher.normalise({"game_dir": "/games/gta", "kbm_binds": "both:G=Square",
"advanced": "LEONIDA_KBM_BINDS=both:H=Cross"})
command = launcher.play_command(settings, repo="/r", windows=False)
self.assertIn("LEONIDA_KBM_BINDS=both:H=Cross", command)
self.assertNotIn("LEONIDA_KBM_BINDS=both:G=Square", command)
# Nothing to pass: the script alone, as before.
command = launcher.play_command(launcher.normalise({"game_dir": "/games/gta"}), repo="/r", windows=False)
self.assertEqual(command[0], "sh")
def test_the_linux_cache_is_play_linux_shs(self):
settings = launcher.normalise({"data_dir": "/ignored"})
self.assertEqual(launcher.shader_cache_dir(settings, windows=False,
environ={"XDG_DATA_HOME": "/x", "HOME": "/h"}),
os.path.join("/x", "leonida", "cache"))
self.assertEqual(launcher.shader_cache_dir(settings, windows=False, environ={"HOME": "/h"}),
os.path.join("/h", ".local", "share", "leonida", "cache"))
self.assertEqual(launcher.shader_cache_dir(settings, windows=False,
environ={"LEONIDA_CACHE_DIR": "/c", "HOME": "/h"}), "/c")
self.assertEqual(launcher.shader_cache_dir(settings, windows=True),
os.path.join("/ignored", launcher.SHADER_CACHE))
script = (Path(launcher.REPO) / "scripts" / "play-linux.sh").read_text(encoding="utf-8")
self.assertIn("data=${XDG_DATA_HOME:-$HOME/.local/share}/leonida", script)
self.assertIn("LEONIDA_CACHE_DIR=${LEONIDA_CACHE_DIR:-$data/cache}", script)
class SplitBindsTests(unittest.TestCase):
"""Entries the Controls page cannot read are kept beside the rows it edits (review of #3272)."""
def test_no_t_call_passes_text(self):
# t(text, **values): a placeholder named {text} made t() fail with two values for `text` (the Controls page
# crashed as soon as it showed an entry it cannot read).
source = (Path(launcher.__file__)).read_text(encoding="utf-8")
self.assertNotRegex(source, r"\bt\((?:[^()]|\([^()]*\))*\btext=")
self.assertEqual(launcher.t("Kept as saved (the page cannot read it): {entries}", entries="x:Y=Z"),
"Kept as saved (the page cannot read it): x:Y=Z")
def test_readable_and_kept(self):
rows, kept = launcher.split_kbm_binds("both:G=Square;vehicle:N=FutureAction; foot:F1=A ;foot:V=RB")
self.assertEqual(rows, [("both", "G", "Square"), ("foot", "V", "RB")])
self.assertEqual(kept, ["vehicle:N=FutureAction", "foot:F1=A"])
self.assertEqual(launcher.split_kbm_binds(""), ([], []))
class OutputPumpTests(unittest.TestCase):
"""Issue #3175: with -Log off the runtime's stderr comes through the pipe, and the window's pump drained the whole
queue in one turn with one insert per line, so the window stopped answering clicks while it caught up."""
def queued(self, items):
lines = launcher.queue.Queue()
for item in items:
lines.put(item)
return lines
def test_a_turn_takes_at_most_the_batch_and_leaves_the_rest_queued(self):
game = object()
lines = self.queued(("line", game, f"{i}\n") for i in range(launcher.OUTPUT_BATCH * 3 + 5))
turn = launcher.take_output(lines)
# One insert's worth: the whole batch in one item, in order, and the rest left for the next turns.
self.assertEqual(len(turn), 1)
self.assertEqual(turn[0][:2], ("lines", game))
self.assertEqual(turn[0][2], [f"{i}\n" for i in range(launcher.OUTPUT_BATCH)])
self.assertEqual(lines.qsize(), launcher.OUTPUT_BATCH * 2 + 5)
self.assertEqual(launcher.take_output(lines, limit=3)[0][2],
[f"{launcher.OUTPUT_BATCH + i}\n" for i in range(3)])
self.assertEqual(launcher.take_output(self.queued([])), [])
def test_runs_are_joined_per_process_and_kept_in_order(self):
old, new = object(), object()
status = {"kind": "current", "behind": 0}
lines = self.queued([("line", old, "a\n"), ("line", old, "b\n"), ("exit", old, 0), ("update", None, status),
("line", old, "late\n"), ("line", new, "c\n"), ("line", new, "d\n")])
turn = launcher.take_output(lines)
self.assertEqual([(k, p, v) for k, p, v in turn],
[("lines", old, ["a\n", "b\n"]), ("exit", old, 0), ("update", None, status),
("lines", old, ["late\n"]), ("lines", new, ["c\n", "d\n"])])
self.assertTrue(lines.empty())
# The two tests above are #3192's (1mshy), as written there; those below are this launcher's.
def test_info_and_rail_items_keep_their_place(self):
game = object()
lines = self.queued([("line", game, "a\n"), ("info", None, "info"), ("line", game, "b\n"),
("rail", None, "abc1234"), ("line", game, "c\n"), ("line", game, "d\n")])
self.assertEqual(launcher.take_output(lines),
[("lines", game, ["a\n"]), ("info", None, "info"), ("lines", game, ["b\n"]),
("rail", None, "abc1234"), ("lines", game, ["c\n", "d\n"])])
def test_a_flood_of_10001_lines_is_one_insert_a_turn(self):
game = object()
lines = self.queued(("line", game, "x\n") for _ in range(10_001))
turns = []
while not lines.empty():
turns.append(launcher.take_output(lines))
self.assertEqual([len(turn) for turn in turns], [1] * 6) # 5 full batches and the last line
self.assertEqual(sum(len(turn[0][2]) for turn in turns), 10_001)
self.assertEqual(launcher.OUTPUT_RESUME_MS, 10)
def test_the_window_pump_goes_through_take_output(self):
# The pump lives in run_gui (Tk only): its source must take the queue through take_output, never drain it
# line by line, and come back after OUTPUT_RESUME_MS while more is queued.
import ast
tree = ast.parse((ROOT / "tools" / "leonida_launcher.py").read_text(encoding="utf-8"))
pumps = [n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == "pump"]
self.assertEqual(len(pumps), 1)
calls = {c.func.id if isinstance(c.func, ast.Name) else getattr(c.func, "attr", "")
for c in ast.walk(pumps[0]) if isinstance(c, ast.Call)}
self.assertIn("take_output", calls)
self.assertNotIn("get_nowait", calls)
self.assertIn("OUTPUT_RESUME_MS", {n.id for n in ast.walk(pumps[0]) if isinstance(n, ast.Name)})
class EffectiveConsoleTests(unittest.TestCase):
"""The Play card's commit-limit warning follows the profile the next PLAY runs: the launcher's when it was changed
since the last PLAY (-Chosen), else the F1 menu's LEONIDA_MENU_CONSOLE (play-nvidia.ps1)."""
LOW, RAM = 40 * 1024 ** 3, 32 * 1024 ** 3
def unchanged(self, **values):
s = settings(**values)
s["last_switches"] = launcher.json.dumps(launcher.switch_args(s))
return s
def warns(self, s, menu):
x = launcher.effective_console(s, menu, windows=True) == "series-x"
return launcher.memory_note(x, self.LOW, self.RAM, short=True) is not None
def test_an_unchanged_launcher_profile_leaves_the_f1_menus(self):
s = self.unchanged(series_s=True)
self.assertEqual(launcher.effective_console(s, {"LEONIDA_MENU_CONSOLE": "series-x"}, windows=True), "series-x")
self.assertTrue(self.warns(s, {"LEONIDA_MENU_CONSOLE": "series-x"}))
x = self.unchanged(series_x=True)
self.assertEqual(launcher.effective_console(x, {"LEONIDA_MENU_CONSOLE": "series-s"}, windows=True), "series-s")
self.assertFalse(self.warns(x, {"LEONIDA_MENU_CONSOLE": "series-s"}))
def test_a_profile_changed_since_the_last_play_wins(self):
s = settings(series_s=True)
s["last_switches"] = launcher.json.dumps(launcher.switch_args(settings())) # Series X at the last PLAY
self.assertEqual(launcher.effective_console(s, {"LEONIDA_MENU_CONSOLE": "series-x"}, windows=True), "series-s")
self.assertFalse(self.warns(s, {"LEONIDA_MENU_CONSOLE": "series-x"}))
x = settings()
x["last_switches"] = launcher.json.dumps(launcher.switch_args(settings(series_s=True)))
self.assertTrue(self.warns(x, {"LEONIDA_MENU_CONSOLE": "series-s"}))
# Another option changed since: the profile still counts as unchanged.
other = self.unchanged(series_s=True)
other["dlss"] = False
self.assertTrue(self.warns(other, {"LEONIDA_MENU_CONSOLE": "series-x"}))
def test_without_a_menu_console_the_launchers(self):
for s in (self.unchanged(series_s=True), settings(series_s=True)):
self.assertEqual(launcher.effective_console(s, {}, windows=True), "series-s")
self.assertFalse(self.warns(s, {}))
self.assertFalse(self.warns(s, {"LEONIDA_MENU_CONSOLE": ""})) # unset: the command line's
self.assertFalse(self.warns(s, {"LEONIDA_MENU_CONSOLE": "xbox"}))
self.assertEqual(launcher.effective_console(self.unchanged(), {}, windows=True), "series-x")
def test_the_first_play_follows_the_menu(self):
# No last PLAY: the launcher passes -Chosen none, so play-d3d12.ps1 counts nothing as typed.
s = settings(series_s=True)
self.assertEqual(launcher.chosen_switches(launcher.switch_args(s), s["last_switches"]), [])
self.assertIn("none", launcher.play_command(s, repo="R", windows=True, chosen=[]))
self.assertEqual(launcher.effective_console(s, {"LEONIDA_MENU_CONSOLE": "Series-X"}, windows=True),
"series-x")
def test_linux_reads_no_menu_file(self):
s = settings(series_x=False)
self.assertEqual(launcher.effective_console(s, {"LEONIDA_MENU_CONSOLE": "series-x"}, windows=False),
"series-s")
class NvidiaCacheNoteTests(unittest.TestCase):
def test_the_note_names_the_setting_and_where_it_is(self):
note = launcher.NVIDIA_CACHE_NOTE
for words in ("Shader Cache Size", "Unlimited", "Global Settings", "not per program"):
self.assertIn(words, note)
class AdvancedOptionTests(unittest.TestCase):
def test_pairs_are_read_and_the_rest_is_reported(self):
values, wrong = launcher.parse_advanced(
"LEONIDA_SUBMIT_SENDER=1; LEONIDA_TIMELINE='420+480,20,t.txt'\nPATH=C:\\x;nothing; lower_case=1;"
'LEONIDA_Q="a"b"')
self.assertEqual(values, {"LEONIDA_SUBMIT_SENDER": "1", "LEONIDA_TIMELINE": "420+480,20,t.txt"})
self.assertEqual(wrong, ["PATH=C:\\x", "nothing", "lower_case=1", 'LEONIDA_Q="a"b"'])
self.assertEqual(launcher.parse_advanced(""), ({}, []))
def test_variables_go_to_more_through_command(self):
s = settings(game_dir=r"C:\it's here", advanced="LEONIDA_X=o'k", dred=True)
command = launcher.play_command(s, repo="R", windows=True, chosen=["Log"], extra={"LEONIDA_Y": "2"})
self.assertEqual(command[:5], ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command"])
self.assertEqual(len(command), 6)
script = os.path.join("R", "scripts", "play-d3d12.ps1")
self.assertEqual(command[5], "& " + launcher.ps_quote(script) + " -Game 'C:\\it''s here' -Chosen 'Log' "
"-More @{LEONIDA_X='o''k'; LEONIDA_D3D12_DRED='1'; LEONIDA_Y='2'}; exit $LASTEXITCODE")
# Nothing to pass: the plain -File command, as before.
self.assertIn("-File", launcher.play_command(settings(advanced="junk"), repo="R", windows=True))
def test_typographic_quotes_are_doubled(self):
# PowerShell ends a single-quoted string at U+2018-U+201B too.
self.assertEqual(launcher.ps_quote("Tony’s; x"), "'Tony’’s; x'")
self.assertEqual(launcher.ps_quote("a'b‘c"), "'a''b‘‘c'")
def test_the_script_takes_more_as_a_table(self):
text = (ROOT / "scripts" / "play-d3d12.ps1").read_text(encoding="utf-8")
self.assertIn("[hashtable]$More", text)
self.assertIn("$NoFrameGen", text)
def test_frame_generation_off(self):
self.assertEqual(launcher.switch_args(settings(no_frame_gen=True)), ["-NoFrameGen"])
# Off in Settings wins over a multiplier saved earlier; FSR replaces DLSS's.
self.assertEqual(launcher.switch_args(settings(no_frame_gen=True, frame_gen=2)), ["-NoFrameGen"])
self.assertEqual(launcher.switch_args(settings(fsr_frame_gen=True, frame_gen=2)), ["-FsrFrameGen"])
self.assertEqual(launcher.switch_args(settings(frame_gen=2)), ["-FrameGen", "2"])
def test_frame_limit_goes_to_more_and_advanced_wins(self):
self.assertEqual(launcher.extra_variables(settings()), {})
self.assertEqual(launcher.extra_variables(settings(fg_limit="40")), {"LEONIDA_FG_LIMIT_FPS": "40"})
self.assertEqual(launcher.extra_variables(settings(fg_limit="40", advanced="LEONIDA_FG_LIMIT_FPS=28")),
{"LEONIDA_FG_LIMIT_FPS": "28"})
self.assertEqual(launcher.normalise({"fg_limit": "999"})["fg_limit"], "")
text = (ROOT / "scripts" / "play-d3d12.ps1").read_text(encoding="utf-8")
self.assertIn("$FsrFrameGen", text)
def test_new_settings_are_checked(self):
got = launcher.normalise({"language": "xx", "dred": "yes", "advanced": 3, "no_frame_gen": 1})
self.assertEqual((got["language"], got["dred"], got["advanced"], got["no_frame_gen"]), ("", False, "", False))
kept = launcher.normalise({"language": "fr", "dred": True, "advanced": "LEONIDA_A=1"})
self.assertEqual((kept["language"], kept["dred"], kept["advanced"]), ("fr", True, "LEONIDA_A=1"))
class NewControlsTests(unittest.TestCase):
"""The frame generation multiplier, the window shape with how the picture fills it, and the graphics card: the
lists Settings offers and the switches they give (scripts/play-d3d12.ps1, d3d12/scripts/play-nvidia.ps1)."""
def test_the_multiplier_goes_with_dlss_frame_generation_only(self):
# Mode DLSS (neither flag) with a multiplier: -FrameGen n; FSR and Off drop it (-NoFrameGen wins over both).
for n in (2, 3, 4, 5, 6):
self.assertEqual(launcher.switch_args(settings(frame_gen=n)), ["-FrameGen", str(n)])
self.assertEqual(launcher.switch_args(settings(frame_gen=3, fsr_frame_gen=True)), ["-FsrFrameGen"])
self.assertEqual(launcher.switch_args(settings(frame_gen=3, no_frame_gen=True)), ["-NoFrameGen"])
self.assertEqual(launcher.switch_args(settings(frame_gen=3, no_frame_gen=True, fsr_frame_gen=True)),
["-NoFrameGen"])
self.assertEqual(launcher.switch_args(settings(frame_gen=0)), []) # Auto: the script's own choice
def test_the_multiplier_list_is_what_the_scripts_take(self):
options = launcher.frame_gen_options()
self.assertEqual([v for v, _ in options], ["0", "2", "3", "4", "5", "6"])
self.assertEqual(dict(options)["2"], "2x")
self.assertTrue(all("RTX 50" in label for v, label in options if v in "3456"))
wrapper = (ROOT / "scripts" / "play-d3d12.ps1").read_text(encoding="utf-8")
self.assertIn("[ValidateSet(0, 2, 3, 4, 5, 6)][int]$FrameGen", wrapper)
nvidia = (ROOT / "d3d12" / "scripts" / "play-nvidia.ps1").read_text(encoding="utf-8")
self.assertIn("[ValidateRange(2, 6)][int]$FrameGen", nvidia)
def test_an_old_file_with_frame_gen_2_shows_2x(self):
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "launcher.json")
Path(path).write_text('{"game_dir": "D:/g", "frame_gen": 2}', encoding="utf-8")
loaded = launcher.load_settings(path)
self.assertEqual(loaded["frame_gen"], 2)
self.assertEqual(dict(launcher.frame_gen_options())[str(loaded["frame_gen"])], "2x")
self.assertEqual(launcher.switch_args(loaded), ["-FrameGen", "2"])
def test_window_shape_and_how_the_picture_fills_it(self):
self.assertEqual(launcher.switch_args(settings(aspect="21:9")), ["-Aspect", "21:9"])
self.assertEqual(launcher.switch_args(settings(aspect="auto", present_scale="stretch")),
["-Aspect", "auto", "-PresentScale", "stretch"])
self.assertEqual(launcher.switch_args(settings(present_scale="stretch")), []) # only with -Aspect
# Every shape offered is one the script's pattern takes; a saved shape of another kind stays a choice.
nvidia = (ROOT / "d3d12" / "scripts" / "play-nvidia.ps1").read_text(encoding="utf-8")
self.assertIn("[ValidatePattern('" + launcher.ASPECT.pattern + "')][string]$Aspect", nvidia)
values = [v for v, _ in launcher.aspect_options("")]
self.assertEqual(values, ["", "auto", "21:9", "32:9", "16:10"])
self.assertTrue(all(launcher.ASPECT.match(v) for v in values if v))
self.assertEqual(launcher.aspect_options("2.39")[-1], ("2.39", "2.39"))
self.assertEqual(len(launcher.aspect_options("21:9")), 5)
def test_the_card_list_from_the_registry(self):
entries = [
{"DriverDesc": "Intel(R) Arc(TM) Graphics", "MatchingDeviceId": r"PCI\VEN_8086&DEV_7D55"},
{"DriverDesc": "NVIDIA GeForce RTX 4070 Laptop GPU", "MatchingDeviceId": r"pci\ven_10de&dev_2820"},
{"DriverDesc": "nvidia geforce rtx 4070 laptop gpu", "MatchingDeviceId": r"pci\ven_10de&dev_2820"},
{"DriverDesc": "Microsoft Basic Render Driver"},
{"DriverDesc": "Microsoft Basic Display Adapter", "MatchingDeviceId": r"PCI\CC_0300"},
{"DriverDesc": "Parsec Virtual Display Adapter", "MatchingDeviceId": r"Root\Parsec\VDA"},
{"DriverDesc": " ", "MatchingDeviceId": r"PCI\VEN_1002"},
{"MatchingDeviceId": r"PCI\VEN_1002"},
{"DriverDesc": 7},
"not a dict",
{"DriverDesc": "AMD Radeon RX 7800 XT"},
]
self.assertEqual(launcher.display_adapters(lambda: entries),
["Intel(R) Arc(TM) Graphics", "NVIDIA GeForce RTX 4070 Laptop GPU", "AMD Radeon RX 7800 XT"])
def broken():
raise OSError("no registry")
self.assertEqual(launcher.display_adapters(broken), [])
self.assertEqual(launcher.display_adapters(lambda: []), [])
self.assertEqual(launcher.read_display_class(windows=False), [])
def test_a_card_is_stored_as_text_the_script_and_adapter_take(self):
self.assertEqual(launcher.adapter_value("NVIDIA GeForce RTX 5070"), "NVIDIA GeForce RTX 5070")
self.assertEqual(launcher.adapter_value("Intel(R) Arc(TM) Graphics"), "Intel(R) Arc(TM) Graphics")
# Characters ADAPTER refuses: the longest part it takes, which the card's name still contains (the runtime
# looks for the text in each card's name).
odd = "Radeon® RX 7800 XT Graphics"
self.assertEqual(launcher.adapter_value(odd), "RX 7800 XT Graphics")
long = "A" * 70
self.assertEqual(launcher.adapter_value(long), "A" * 64)
for name in (odd, long, "NVIDIA GeForce RTX 5070", '"quoted"; calc'):
value = launcher.adapter_value(name)
self.assertTrue(launcher.ADAPTER.match(value), name)
self.assertIn(value.lower(), name.lower())
self.assertEqual(launcher.adapter_value("®™"), "")
options = launcher.adapter_options(["NVIDIA GeForce RTX 5070", "®™"], "")
self.assertEqual(options, [("", "Default"), ("NVIDIA GeForce RTX 5070", "NVIDIA GeForce RTX 5070")])
# A saved value no card gives (an index, a card taken out) is kept as a choice.
self.assertEqual(launcher.adapter_options([], "#1"), [("", "Default"), ("#1", "#1")])
self.assertEqual(launcher.switch_args(settings(adapter="NVIDIA GeForce RTX 5070")),
["-Adapter", "NVIDIA GeForce RTX 5070"])
def test_the_default_command_is_unchanged(self):
fresh = launcher.normalise({"game_dir": "D:/Games/GTA"})
self.assertEqual((fresh["frame_gen"], fresh["aspect"], fresh["present_scale"], fresh["adapter"]),
(0, "", "", ""))
command = launcher.play_command(fresh, repo="R", windows=True)
self.assertEqual(command, ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File",
os.path.join("R", "scripts", "play-d3d12.ps1"), "-Game", "D:/Games/GTA"])
GB = 1024 ** 3
def card_class(*cards):
"""Display class entries (read_display_class) for (name, memory in GB or None) pairs, on the PCI bus."""
entries = []
for name, memory in cards:
entry = {"DriverDesc": name, "MatchingDeviceId": r"PCI\VEN_0000&DEV_0000"}
if memory is not None:
entry[launcher.CARD_MEMORY] = int(memory * GB)
entries.append(entry)
return entries
def rule_values(**changes):
values = {"rt": "hw", "dlss": True, "dlss_mode": "", "fg_mode": "dlss", "aspect": "", "precompile_all": False}
values.update(changes)
return values
def launch(console="series-x", rt="hw", frame_gen=0, advanced="", menu=None, last=None, fg_mode="dlss", **extra):
"""launch_values (Windows) of the launcher's settings for those choices and the F1 menu's file `menu`. The switches
are those of the last PLAY (nothing changed since) unless `last` gives the settings the last PLAY had."""
s = settings(series_s=console == "series-s", hardware_rt=rt == "hw", frame_gen=frame_gen, advanced=advanced,
no_frame_gen=fg_mode == "off", fsr_frame_gen=fg_mode == "fsr", **extra)
s["last_switches"] = json.dumps(launcher.switch_args(s if last is None else last))
return launcher.launch_values(s, menu or {}, windows=True)
def rules(card, console="series-x", rt="hw", frame_gen=0, advanced="", menu=None, last=None, **values):
"""settings_rules for the controls `values` (rt and fg_mode included) over launch() of the same choices."""
values = rule_values(rt=rt, **values)
return launcher.settings_rules(values, card, launch(console, rt, frame_gen, advanced, menu, last,
values["fg_mode"]))
class SettingsRulesTests(unittest.TestCase):
"""settings_rules: frame generation with ray tracing as play-nvidia.ps1 of #3230 decides it (Series X under 20 GB
of video memory off unless LEONIDA_FG_WITH_RT=1, =0 off everywhere, never the automatic 2x), and the NVIDIA-only
controls greyed without an NVIDIA card. The registry is stubbed: no hardware is read."""
CHOOSE = "With ray tracing, frame generation runs only when asked: choose 2x"
MEMORY = "Series X with ray tracing needs 20 GB of video memory for frame generation"
UNLOCKED = "Frame generation with ray tracing: unlocked in Advanced (LEONIDA_FG_WITH_RT=1)"
OFF = "Frame generation is off with ray tracing: LEONIDA_FG_WITH_RT=0 in Advanced"
NVIDIA = "DLSS and Smooth Motion need an NVIDIA RTX card"
UNTESTED = "Not tested on AMD/Intel cards yet"
def test_the_matrix_of_console_memory_and_unlock(self):
rows = []
for console in ("series-s", "series-x"):
for memory in (8, 16, 24):
card = launcher.card_facts(card_class(("NVIDIA GeForce RTX 4070", memory)))
for unlock in (None, "1", "0"):
for multiplier in (2, 0):
advanced = "" if unlock is None else f"LEONIDA_FG_WITH_RT={unlock}"
enabled, notes = rules(card, console, advanced=advanced, frame_gen=multiplier)
held = unlock == "0" or (console == "series-x" and memory < 20 and unlock != "1")
name = (console, memory, unlock, multiplier)
rows.append(name)
self.assertEqual(enabled["fg_mode"], not held, name)
self.assertEqual(enabled["frame_gen"], not held, name)
self.assertEqual(enabled["fg_limit"], not held, name)
lines = notes["fg"][0].split("\n") if notes["fg"] else []
if unlock == "0":
self.assertEqual(notes["fg"], (self.OFF, True), name)
elif held:
self.assertEqual(notes["fg"], (self.MEMORY, True), name)
else:
unlocked = console == "series-x" and memory < 20 and unlock == "1"
want = ([self.UNLOCKED] if unlocked else []) + ([self.CHOOSE] if multiplier == 0 else [])
self.assertEqual(lines, want, name)
self.assertFalse(notes["fg"] and notes["fg"][1], name) # muted, not a warning
# Nothing NVIDIA-only greyed on an NVIDIA card, and no card or ray tracing note.
self.assertTrue(enabled["dlss"] and enabled["fg_dlss"] and enabled["smooth_motion"], name)
self.assertIsNone(notes["nvidia"], name)
self.assertIsNone(notes["rt"], name)
self.assertEqual(len(rows), 2 * 3 * 3 * 2)
def test_without_ray_tracing_nothing_changes(self):
card = launcher.card_facts(card_class(("NVIDIA GeForce RTX 4060", 8)))
for advanced in ("", "LEONIDA_FG_WITH_RT=0", "LEONIDA_FG_WITH_RT=1"):
enabled, notes = rules(card, rt="off", advanced=advanced)
self.assertTrue(enabled["fg_mode"] and enabled["frame_gen"] and enabled["fg_limit"], advanced)
self.assertIsNone(notes["fg"], advanced)
def test_the_script_rule(self):
self.assertEqual(launcher.fg_with_rt(False, "series-x", 8 * GB, None), "")
self.assertEqual(launcher.fg_with_rt(True, "series-x", 8 * GB, " 0 "), "off")
self.assertEqual(launcher.fg_with_rt(True, "series-s", 8 * GB, "0"), "off")
self.assertEqual(launcher.fg_with_rt(True, "series-x", 20 * GB - 1, None), "memory")
self.assertEqual(launcher.fg_with_rt(True, "series-x", 20 * GB, None), "asked") # -lt 20GB in the script
self.assertEqual(launcher.fg_with_rt(True, "series-x", 0, None), "asked") # unknown: not held back
self.assertEqual(launcher.fg_with_rt(True, "series-x", 8 * GB, "1"), "unlocked")
self.assertEqual(launcher.fg_with_rt(True, "series-s", 8 * GB, "1"), "asked")
self.assertEqual(launcher.fg_with_rt(True, "series-x", 8 * GB, "2"), "memory") # only 1 unlocks
def test_fsr_or_off_gives_no_choose_note(self):
card = launcher.card_facts(card_class(("NVIDIA GeForce RTX 4070", 8)))
for mode in ("fsr", "off"):
enabled, notes = rules(card, "series-s", fg_mode=mode)
self.assertTrue(enabled["fg_mode"], mode)
self.assertFalse(enabled["frame_gen"], mode)
self.assertIsNone(notes["fg"], mode)
self.assertFalse(rules(card, "series-s", fg_mode="off")[0]["fg_limit"])
def test_the_20_gb_rule_reads_the_largest_card_as_the_script(self):
# play-nvidia.ps1's $vram is the largest qwMemorySize of the display class, whatever -Adapter names: an 8 GB
# card chosen beside a 24 GB one keeps frame generation with ray tracing on Series X, as the launch does.
entries = card_class(("NVIDIA GeForce RTX 4090", 24), ("NVIDIA GeForce RTX 4060", 8))
for adapter in ("", "RTX 4060", "nvidia geforce rtx 4060", "#1"):
card = launcher.card_facts(entries, adapter)
self.assertEqual(card["vram"], 24 * GB, adapter)
self.assertTrue(rules(card, frame_gen=2)[0]["fg_mode"], adapter)
# With the 8 GB card alone, both hold it back.
only = launcher.card_facts(card_class(("NVIDIA GeForce RTX 4060", 8)), "RTX 4060")
self.assertFalse(rules(only, frame_gen=2)[0]["fg_mode"])
# A binary qwMemorySize, a value of another kind, and none at all.
self.assertEqual(launcher.card_memory((16 * GB).to_bytes(8, "little")), 16 * GB)
self.assertEqual(launcher.card_memory("16"), 0)
self.assertEqual(launcher.card_memory(True), 0)
# Exactly eight bytes, as play-nvidia.ps1 reads it: a shorter or longer array is no size.
self.assertEqual(launcher.card_memory((8 * GB).to_bytes(8, "little")[:5]), 0)
self.assertEqual(launcher.card_memory((8 * GB).to_bytes(9, "little")), 0)
self.assertEqual(launcher.card_facts(card_class(("NVIDIA GeForce RTX 3090", None)))["vram"], 0)
# The largest of the class counts every subkey, as the script's does.
entries = card_class(("NVIDIA GeForce RTX 4060", 8)) + [{"DriverDesc": "Parsec Virtual Display Adapter",
"MatchingDeviceId": r"Root\Parsec\VDA",
launcher.CARD_MEMORY: 24 * GB}]
self.assertEqual(launcher.card_facts(entries)["vram"], 24 * GB)
self.assertEqual(launcher.card_facts(entries, "RTX 4060")["vram"], 24 * GB)
# The script reads it that way (a static look, so that a change there shows here).
script = (ROOT / "d3d12" / "scripts" / "play-nvidia.ps1").read_text(encoding="utf-8")
self.assertIn("'HardwareInformation.qwMemorySize'", script)
self.assertIn("[uint64]$q -gt $vram) { $vram = [uint64]$q }", script)
def test_nvidia_amd_intel_and_a_chosen_card(self):
nvidia = launcher.card_facts(card_class(("NVIDIA GeForce RTX 5070", 12)))
amd = launcher.card_facts(card_class(("AMD Radeon RX 7800 XT", 16)))
intel = launcher.card_facts(card_class(("Intel(R) Arc(TM) B580 Graphics", 12)))
both = card_class(("Intel(R) Arc(TM) Graphics", None), ("NVIDIA GeForce RTX 4070 Laptop GPU", 8))
nvidia_only = ("dlss", "dlss_mode", "smooth_motion", "fg_dlss", "frame_gen")
for name, card, vendor in (("nvidia", nvidia, "nvidia"), ("amd", amd, "amd"), ("intel", intel, "intel"),
("default of both", launcher.card_facts(both), "nvidia"),
("Intel chosen", launcher.card_facts(both, "Intel(R) Arc(TM) Graphics"), "intel"),
("NVIDIA chosen", launcher.card_facts(both, "RTX 4070"), "nvidia")):
self.assertEqual(card["vendor"], vendor, name)
enabled, notes = rules(card, "series-s", rt="off")
on_nvidia = vendor == "nvidia"
for key in nvidia_only:
self.assertEqual(enabled[key], on_nvidia, (name, key))
self.assertTrue(enabled["fg_mode"] and enabled["fg_limit"], name) # FSR stays
self.assertEqual(notes["nvidia"], None if on_nvidia else self.NVIDIA, name)
self.assertEqual(notes["rt"], None if on_nvidia else self.UNTESTED, name) # ray tracing never greyed
# With ray tracing on Series S: no "choose 2x" without DLSS frame generation to choose it for.
enabled, notes = rules(card, "series-s")
self.assertEqual(notes["fg"], (self.CHOOSE, False) if on_nvidia else None, name)
# Another maker: DLSS greyed (no NVIDIA card), no ray-tracing note.
other = launcher.card_facts(card_class(("Qualcomm Adreno X1-85 GPU", 4)))
enabled, notes = rules(other, "series-s", rt="off")
self.assertFalse(enabled["dlss"])
self.assertIsNone(notes["rt"])
def test_nothing_read_greys_nothing(self):
for entries in ([], [{"DriverDesc": "Microsoft Basic Render Driver"}], ["not a dict"]):
card = launcher.card_facts(entries)
self.assertFalse(card["known"])
enabled, notes = rules(card, rt="off")
self.assertTrue(all(enabled[k] for k in ("dlss", "dlss_mode", "smooth_motion", "fg_dlss", "frame_gen")))
self.assertEqual((notes["nvidia"], notes["rt"]), (None, None))
# Video memory unknown: Series X with ray tracing is not held back.
self.assertTrue(rules(card)[0]["fg_mode"])
def broken():
raise OSError("no registry")
self.assertEqual(launcher.read_entries(broken), [])
self.assertEqual(launcher.read_entries(lambda: None), [])
def test_the_launcher_never_adds_the_unlock(self):
for series in ({"series_s": True}, {"series_x": True}, {}):
for frame_gen in (0, 2):
value = settings(hardware_rt=True, frame_gen=frame_gen, **series)
self.assertNotIn("LEONIDA_FG_WITH_RT", launcher.extra_variables(value))
self.assertNotIn("LEONIDA_FG_WITH_RT", " ".join(launcher.play_command(value, repo="R", windows=True)))
# Typed in Advanced, it is passed as typed.
value = settings(hardware_rt=True, advanced="LEONIDA_FG_WITH_RT=1")
self.assertEqual(launcher.extra_variables(value), {"LEONIDA_FG_WITH_RT": "1"})
class LaunchValuesTests(unittest.TestCase):
"""launch_values: the ray tracing, frame generation, LEONIDA_FG_WITH_RT and console play-nvidia.ps1 will hold, in
its order (the launcher's switches, the F1 menu's file for what no switch changed since the last PLAY took, -More
last), and settings_rules greying from them rather than from the Ray tracing control alone."""
CARD8 = launcher.card_facts(card_class(("NVIDIA GeForce RTX 4060", 8)))
MENU_ON = "Hardware ray tracing is on from the F1 menu"
def greyed(self, **choices):
return not rules(self.CARD8, frame_gen=2, **choices)[0]["fg_mode"]
def test_hardware_rt_from_the_f1_menu_greys_with_the_control_off(self):
values = launch(rt="off", frame_gen=2, menu={"LEONIDA_HW_RT": "1"})
self.assertEqual((values["LEONIDA_HW_RT"], values["from"]["LEONIDA_HW_RT"]), ("1", "menu"))
enabled, notes = rules(self.CARD8, rt="off", frame_gen=2, menu={"LEONIDA_HW_RT": "1"})
self.assertFalse(enabled["fg_mode"] or enabled["frame_gen"] or enabled["fg_limit"])
self.assertEqual(notes["fg"], (SettingsRulesTests.MEMORY, True))
self.assertEqual(notes["rt"], self.MENU_ON)
# Software ray tracing the menu saved does the same.
enabled, notes = rules(self.CARD8, rt="off", frame_gen=2, menu={"LEONIDA_BVH_BUILDER": "1"})
self.assertFalse(enabled["fg_mode"])
self.assertEqual(notes["rt"], "Ray tracing is on from the F1 menu")
def test_hardware_rt_from_advanced_greys_with_the_control_off(self):
self.assertTrue(self.greyed(rt="off", advanced="LEONIDA_HW_RT=1"))
notes = rules(self.CARD8, rt="off", frame_gen=2, advanced="LEONIDA_HW_RT=1")[1]
self.assertEqual(notes["rt"], "Hardware ray tracing is on from Advanced")
self.assertTrue(self.greyed(rt="off", advanced="LEONIDA_BVH_BUILDER=1"))
# Advanced wins over the menu file, both ways.
self.assertTrue(self.greyed(rt="off", advanced="LEONIDA_HW_RT=1", menu={"LEONIDA_HW_RT": ""}))
self.assertFalse(self.greyed(rt="off", advanced="LEONIDA_HW_RT=0", menu={"LEONIDA_HW_RT": "1"}))
enabled, notes = rules(self.CARD8, frame_gen=2, advanced="LEONIDA_HW_RT=0")
self.assertTrue(enabled["fg_mode"])
self.assertEqual(notes["rt"], "Hardware ray tracing is off from Advanced")
def test_ray_tracing_off_everywhere_greys_nothing(self):
for menu in ({}, {"LEONIDA_HW_RT": ""}, {"LEONIDA_BVH_BUILDER": "", "LEONIDA_FG_WITH_RT": "0"}):
enabled, notes = rules(self.CARD8, rt="off", frame_gen=2, menu=menu)
self.assertTrue(enabled["fg_mode"] and enabled["frame_gen"] and enabled["fg_limit"], menu)
self.assertEqual((notes["fg"], notes["rt"]), (None, None), menu)
def test_a_switch_changed_since_the_last_play_wins_over_the_f1_menu(self):
# play-nvidia.ps1's -RayTracing takes LEONIDA_BVH_BUILDER: an older launcher's software ray tracing at the
# last PLAY, Off now, drops the menu's value; unchanged, the menu's stands.
older = settings(ray_tracing=True, frame_gen=2)
self.assertFalse(self.greyed(rt="off", menu={"LEONIDA_BVH_BUILDER": "1"}, last=older))
self.assertTrue(self.greyed(rt="off", menu={"LEONIDA_BVH_BUILDER": "1"}))
# The profile: Series S chosen since the last PLAY wins over the menu's Series X (the 20 GB rule is Series X's).
before = settings(frame_gen=2, hardware_rt=True)
self.assertFalse(self.greyed(console="series-s", menu={"LEONIDA_MENU_CONSOLE": "series-x"}, last=before))
self.assertTrue(self.greyed(console="series-s", menu={"LEONIDA_MENU_CONSOLE": "series-x"}))
self.assertEqual(launch("series-s", menu={"LEONIDA_MENU_CONSOLE": "series-x"}, last=before)["console"],
"series-s")
# Frame generation: -FrameGen 2 chosen now replaces the menu's Off (an empty value), unchanged it does not.
values = launch(frame_gen=2, menu={"LEONIDA_FRAME_GEN": ""}, last=settings(hardware_rt=True))
self.assertEqual((values["LEONIDA_FRAME_GEN"], values["from"]["LEONIDA_FRAME_GEN"]), ("2", "launcher"))
self.assertNotIn("LEONIDA_FRAME_GEN", launch(frame_gen=2, menu={"LEONIDA_FRAME_GEN": ""}))
def test_hardware_rt_is_not_in_the_scripts_switch_table(self):
# $switchSettings has no HardwareRT: the menu file's LEONIDA_HW_RT stands even over a control changed since
# the last PLAY, either way (the launch does the same; see the cross-check of this change).
before = settings(hardware_rt=True, frame_gen=2)
self.assertTrue(self.greyed(rt="off", menu={"LEONIDA_HW_RT": "1"}, last=before))
enabled, notes = rules(self.CARD8, frame_gen=2, menu={"LEONIDA_HW_RT": ""}, last=settings(frame_gen=2))
self.assertTrue(enabled["fg_mode"])
self.assertEqual(notes["rt"], "Hardware ray tracing is off from the F1 menu")
def test_the_menu_files_unlock_and_frame_generation(self):
values = launch(frame_gen=2, menu={"LEONIDA_FG_WITH_RT": "1"})
self.assertEqual(values["from"]["LEONIDA_FG_WITH_RT"], "menu")
enabled, notes = rules(self.CARD8, frame_gen=2, menu={"LEONIDA_FG_WITH_RT": "1"})
self.assertTrue(enabled["fg_mode"])
self.assertEqual(notes["fg"][0], "Frame generation with ray tracing: unlocked in the F1 menu's file "
"(LEONIDA_FG_WITH_RT=1)")
enabled, notes = rules(self.CARD8, "series-s", frame_gen=2, menu={"LEONIDA_FG_WITH_RT": "0"})
self.assertEqual(notes["fg"], ("Frame generation is off with ray tracing: LEONIDA_FG_WITH_RT=0 in the F1 "
"menu's file", True))
self.assertFalse(self.greyed(menu={"LEONIDA_FG_WITH_RT": "0"}, advanced="LEONIDA_FG_WITH_RT=1"))
# A multiplier the menu saved is asked for: no "choose 2x" under the Auto control.
self.assertEqual(rules(self.CARD8, "series-s")[1]["fg"], (SettingsRulesTests.CHOOSE, False))
self.assertIsNone(rules(self.CARD8, "series-s", menu={"LEONIDA_FRAME_GEN": "2"})[1]["fg"])
def test_linux_reads_neither_the_menu_nor_advanced(self):
s = settings(advanced="LEONIDA_HW_RT=1")
values = launcher.launch_values(s, {"LEONIDA_HW_RT": "1", "LEONIDA_MENU_CONSOLE": "series-x"}, windows=False)
self.assertNotIn("LEONIDA_HW_RT", values)
self.assertEqual(values["console"], "series-s")
self.assertEqual(launcher.launch_values(settings(hardware_rt=True), {}, windows=False)["LEONIDA_HW_RT"], "1")
def test_the_switch_table_is_the_scripts(self):
script = (ROOT / "d3d12" / "scripts" / "play-nvidia.ps1").read_text(encoding="utf-8")
block = script.split("$switchSettings = @{", 1)[1].split("\n}", 1)[0]
table = {}
for line in block.splitlines():
name, sep, names = line.strip().partition(" = ")
if sep and not name.startswith("#"):
table[name] = tuple(n.strip().strip("'") for n in names.split(","))
watched = set(launcher.LAUNCH_KEYS) | {"LEONIDA_MENU_CONSOLE"}
ours = {k: v for k, v in launcher.LAUNCH_SWITCH_SETTINGS.items() if k != "SeriesS"}
self.assertEqual({k: v for k, v in table.items() if watched & set(v)}, ours)
self.assertEqual(launcher.LAUNCH_SWITCH_SETTINGS["SeriesS"], table["SeriesX"]) # play-d3d12.ps1 renames it
SWITCHES_SNIPPET = """# The D3D12 runtime's `LEONIDA_*` variables
It is **not** a list of recommended settings.
## leonida
| Name | Kind | A/B | L | F | Named in | In the code's words |
|---|---|---|---|---|---|---|
| `LEONIDA_AB` | see the code | | | yes | `leonida/leonida.rs` +41 | `LEONIDA_AB=&lt;s&gt;,&lt;n&gt;`: A &amp; B |
| `LEONIDA_D3D12_DRED` | off unless set and not `0` | | yes | yes | `leonida/replay.rs` +8 | Whether DRED is on. |
## leonida-gpu
| Name | Kind | A/B | L | F | Named in | In the code's words |
|---|---|---|---|---|---|---|
| `LEONIDA_AHEAD_INDEX` | on, `0` turns it off | yes | | | `leonida-gpu/watch.rs` | `x=&lt;a&gt;\\|&lt;b&gt;` or `0` |
| `LEONIDA_lower` | see the code | | | | `x.rs` | not a name the advanced options take |
| `LEONIDA_SHORT` | see the code |
| `LEONIDA_EMPTY` | see the code | | | | `scripts/play-nvidia.ps1` | |
## Only in tests
Read by test code alone: `LEONIDA_A`, `LEONIDA_B`.
"""
class AdvancedModeTests(unittest.TestCase):
"""The Advanced mode window's pure parts: reading d3d12/docs/switches.md and writing edits into the advanced
options (settings["advanced"]) that PLAY passes to -More."""
def test_the_table_is_read_with_its_sections_and_escapes(self):
rows = launcher.parse_switches(SWITCHES_SNIPPET)
self.assertEqual([r["name"] for r in rows],
["LEONIDA_AB", "LEONIDA_D3D12_DRED", "LEONIDA_AHEAD_INDEX", "LEONIDA_EMPTY"])
self.assertEqual([r["section"] for r in rows], ["leonida", "leonida", "leonida-gpu", "leonida-gpu"])
ab, dred, ahead, empty = rows
self.assertEqual(ab["text"], "LEONIDA_AB=<s>,<n>: A & B")
self.assertEqual((ab["kind"], ab["ab"], ab["launcher"], ab["findings"]), ("see the code", False, False, True))
self.assertEqual(dred["kind"], launcher.KIND_OFF_UNLESS_SET)
self.assertEqual((dred["launcher"], dred["findings"]), (True, True))
self.assertEqual(ahead["kind"], launcher.KIND_ON_UNLESS_ZERO)
self.assertTrue(ahead["ab"])
self.assertEqual(ahead["text"], "x=<a>|<b> or 0") # an escaped | stays in the cell
self.assertEqual(empty["text"], "")
self.assertEqual(launcher.parse_switches(""), [])
def test_a_missing_file_reads_as_none(self):
with tempfile.TemporaryDirectory() as tmp:
self.assertIsNone(launcher.read_switches(tmp))
os.makedirs(os.path.join(tmp, "d3d12", "docs"))
Path(launcher.switches_file(tmp)).write_text(SWITCHES_SNIPPET, encoding="utf-8")
self.assertEqual(len(launcher.read_switches(tmp)), 4)
def test_the_repositorys_list_reads_whole(self):
"""Every LEONIDA_* row of switches.md is read, and the kinds are the generator's own words. The rows are
counted, not the header's "N names": a row added by hand (main's LEONIDA_TITLE_RANGE, 683 rows under a
header of 682) must not fail the launcher."""
import re
path = ROOT / "d3d12" / "docs" / "switches.md"
if not path.is_file():
self.skipTest("no d3d12/docs/switches.md")
text = path.read_text(encoding="utf-8")
rows = launcher.parse_switches(text)
self.assertEqual(len(rows), len(re.findall(r"^\| `LEONIDA_[A-Z0-9_]+` \|", text, re.M)))
self.assertGreater(len(rows), 600)
self.assertEqual(len({r["name"] for r in rows}), len(rows))
generator = (ROOT / "tools" / "d3d12_switches.py").read_text(encoding="utf-8").replace("`", "")
for kind in (launcher.KIND_OFF_UNLESS_SET, launcher.KIND_ON_UNLESS_ZERO):
self.assertIn(f'"{kind}"', generator)
self.assertIn("not** a list of recommended", text)
def test_edits_add_update_and_remove_pairs(self):
text = "LEONIDA_A=1; LEONIDA_B=2"
self.assertEqual(launcher.merge_advanced(text, {}), text)
self.assertEqual(launcher.merge_advanced("", {"LEONIDA_X": "1"}), "LEONIDA_X=1")
self.assertEqual(launcher.merge_advanced(text, {"LEONIDA_C": " 3 "}), "LEONIDA_A=1; LEONIDA_B=2; LEONIDA_C=3")
self.assertEqual(launcher.merge_advanced(text, {"LEONIDA_A": "9"}), "LEONIDA_A=9; LEONIDA_B=2")
self.assertEqual(launcher.merge_advanced(text, {"LEONIDA_A": ""}), "LEONIDA_B=2")
self.assertEqual(launcher.merge_advanced(text, {"LEONIDA_B": None, "LEONIDA_A": ""}), "")
# A name twice: the first place takes the value, the later pair goes (parse_advanced kept the last one).
self.assertEqual(launcher.merge_advanced("LEONIDA_A=1;LEONIDA_A=2", {"LEONIDA_A": "5"}), "LEONIDA_A=5")
# Removing a name that is not there changes nothing but the separators.
self.assertEqual(launcher.merge_advanced("LEONIDA_A=1\nLEONIDA_B=2", {"LEONIDA_Z": ""}),
"LEONIDA_A=1; LEONIDA_B=2")
def test_unknown_pairs_and_wrong_parts_are_kept_as_typed(self):
text = "LEONIDA_NOT_LISTED='a b'; junk; lower=1; LEONIDA_Q=\"x\"y\"; LEONIDA_A=1"
merged = launcher.merge_advanced(text, {"LEONIDA_A": "2", "LEONIDA_NEW": "on"})
self.assertEqual(merged, "LEONIDA_NOT_LISTED='a b'; junk; lower=1; LEONIDA_Q=\"x\"y\"; LEONIDA_A=2; "
"LEONIDA_NEW=on")
values, wrong = launcher.parse_advanced(merged)
self.assertEqual(values, {"LEONIDA_NOT_LISTED": "a b", "LEONIDA_A": "2", "LEONIDA_NEW": "on"})
self.assertEqual(wrong, ["junk", "lower=1", 'LEONIDA_Q="x"y"'])
def test_values_that_cannot_be_passed_are_refused(self):
for value in ('a"b', '"', "a;b", "a\nb", "a\x00"):
self.assertTrue(launcher.advanced_value_problem(value), repr(value))
with self.assertRaises(ValueError):
launcher.merge_advanced("LEONIDA_A=1", {"LEONIDA_A": value})
for value in ("1", "o'k", "420+480,20,t.txt", "C:\\x y", "a|b<c>"):
self.assertEqual(launcher.advanced_value_problem(value), "", repr(value))
with self.assertRaises(ValueError):
launcher.merge_advanced("", {"PATH": "1"})
# Removing a pair whose value parse_advanced refuses is allowed: that is how it gets fixed.
self.assertEqual(launcher.merge_advanced('LEONIDA_Q="a"b"', {"LEONIDA_Q": ""}), "")
def test_the_value_hint_is_the_format_after_the_name(self):
hint = launcher.value_hint
# A bare number is an example, not a format: no hint (the field shows "value").
self.assertEqual(hint("LEONIDA_FPS_LINE", "Whether the line is shown (LEONIDA_FPS_LINE=0: not; the menu changes it)."), "")
self.assertEqual(hint("LEONIDA_AB", "LEONIDA_AB=<seconds>,<switch>[,<switch>..]: turns each switch on, then "
"off, every <seconds>"), "<seconds>,<switch>[,<switch>..]")
self.assertEqual(hint("LEONIDA_CAPTURE", "Saves frames to LEONIDA_CAPTURE=<folder>, one file each."),
"<folder>")
self.assertEqual(hint("LEONIDA_FG_LIMIT_FPS", "LEONIDA_FG_LIMIT_FPS=<n>: Reflex holds the frames **shown** to "
"n a second"), "<n>")
# A space inside <...> belongs to the format; a colon inside the format stays.
self.assertEqual(hint("LEONIDA_TELEPORT", "LEONIDA_TELEPORT=<delay s>,<x>,<y>,<z> moves the player"),
"<delay s>,<x>,<y>,<z>")
self.assertEqual(hint("LEONIDA_POKE", "LEONIDA_POKE=<rva>:<byte>,... writes bytes"), "<rva>:<byte>,...")
self.assertEqual(hint("LEONIDA_ASPECT", "LEONIDA_ASPECT=21:9|32:9|<decimal>|auto: the ratio"),
"21:9|32:9|<decimal>|auto")
# The sentence's own punctuation is not part of it.
self.assertEqual(hint("LEONIDA_X", "(set LEONIDA_X=<n>). Then"), "<n>")
self.assertEqual(hint("LEONIDA_X", "LEONIDA_X=flag|off) picks"), "flag|off")
self.assertEqual(hint("LEONIDA_X", "LEONIDA_X=<0..1>.... sharper"), "<0..1>")
self.assertEqual(hint("LEONIDA_X", 'LEONIDA_X="<s>:<command>;..." runs'), "<s>:<command>;...")
# Another name that ends the same, or no NAME= at all: no hint.
self.assertEqual(hint("LEONIDA_AB", "LEONIDA_FG_AB=1 does"), "")
self.assertEqual(hint("LEONIDA_X", "Reads LEONIDA_X once at start."), "")
self.assertEqual(hint("LEONIDA_X", ""), "")
long = hint("LEONIDA_X", "LEONIDA_X=<time constant in ms>[,<jump factor>[,<floor>]] smooths")
self.assertEqual(len(long), launcher.HINT_LIMIT)
self.assertTrue(long.startswith("<time constant in ms>[,") and long.endswith("…"), long)
def test_the_shown_description_drops_markdown(self):
text = "LEONIDA_FG_LIMIT_FPS=<n>: Reflex holds the frames **shown** to n a `second`"
self.assertEqual(launcher.plain_description(text), "LEONIDA_FG_LIMIT_FPS=<n>: Reflex holds the frames shown "
"to n a second")
self.assertEqual(launcher.plain_description(""), "")
rows = launcher.parse_switches("## s\n| `LEONIDA_FG_LIMIT_FPS` | see the code | no | no | no | x | a **b** |\n")
self.assertEqual(rows[0]["text"], "a **b**") # what is stored keeps it
def test_edits_reach_more_and_the_default_command_is_unchanged(self):
default = launcher.play_command(settings(), repo="R", windows=True)
self.assertEqual(default, ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File",
os.path.join("R", "scripts", "play-d3d12.ps1"), "-Game", "D:/Games/GTA"])
self.assertEqual(launcher.DEFAULTS["advanced"], "")
# Nothing set, then cleared again: the advanced options are empty and PLAY is the same command.
cleared = launcher.merge_advanced(launcher.merge_advanced("", {"LEONIDA_X": "1"}), {"LEONIDA_X": ""})
self.assertEqual(launcher.play_command(settings(advanced=cleared), repo="R", windows=True), default)
two = launcher.merge_advanced("", {"LEONIDA_CARD_AWAKE": "1", "LEONIDA_D3D12_DRED": "1"})
command = launcher.play_command(settings(advanced=two), repo="R", windows=True)
self.assertTrue(command[5].endswith(" -More @{LEONIDA_CARD_AWAKE='1'; LEONIDA_D3D12_DRED='1'}; "
"exit $LASTEXITCODE"), command[5])
class MenuSettingsTests(unittest.TestCase):
"""What the in-game F1 menu saved (d3d12/leonida-settings.txt), read as play-nvidia.ps1 reads it."""
def write(self, repo, raw):
os.makedirs(os.path.join(repo, "d3d12"), exist_ok=True)
with open(os.path.join(repo, "d3d12", launcher.MENU_FILE), "wb") as f:
f.write(raw)
def test_comments_crlf_empty_values_and_duplicates(self):
with tempfile.TemporaryDirectory() as repo:
self.write(repo, b"# Saved by the F1 menu; play.ps1 applies these after its own settings.\r\n"
b"\r\n"
b"LEONIDA_FRAME_GEN=2\r\n"
b" # LEONIDA_HW_RT=1\r\n"
b"LEONIDA_UPSCALE = dlss \r\n"
b"LEONIDA_FPS_CAP=60\r\n"
b"LEONIDA_ASPECT=\r\n"
b"not a setting\r\n"
b"LEONIDA_FPS_CAP=120\r\n"
b"LEONIDA_RELAY=1")
got = launcher.read_menu_settings(repo)
self.assertEqual(got, {"LEONIDA_FRAME_GEN": "2", "LEONIDA_UPSCALE": "dlss", "LEONIDA_FPS_CAP": "120",
"LEONIDA_ASPECT": "", "LEONIDA_RELAY": "1"})
self.assertEqual(list(got), ["LEONIDA_FRAME_GEN", "LEONIDA_UPSCALE", "LEONIDA_FPS_CAP", "LEONIDA_ASPECT",
"LEONIDA_RELAY"])
def test_a_missing_file_or_folder_reads_as_nothing(self):
with tempfile.TemporaryDirectory() as repo:
self.assertEqual(launcher.read_menu_settings(repo), {})
os.makedirs(os.path.join(repo, "d3d12", launcher.MENU_FILE)) # a folder of that name
self.assertEqual(launcher.read_menu_settings(repo), {})
self.assertFalse(launcher.clear_menu_settings(repo))
self.assertTrue(os.path.isdir(os.path.join(repo, "d3d12", launcher.MENU_FILE)))
def test_lines_and_notes(self):
values = {"LEONIDA_FRAME_GEN": "2", "LEONIDA_UPSCALE": "dlss", "LEONIDA_FPS_CAP": "60",
"LEONIDA_BVH_BUILDER": "1", "LEONIDA_ASPECT": "", "LEONIDA_RELAY": "1"}
self.assertEqual(launcher.menu_lines(values),
["Frame generation: 2x", "Upscaler: DLSS", "Frame rate cap: 60",
"Ray tracing (real lighting): On", "Window shape: unset", "LEONIDA_RELAY: 1"])
self.assertEqual(launcher.menu_note("fg_mode", values), "F1 menu: Frame generation: 2x")
self.assertEqual(launcher.menu_note("dlss", values), "F1 menu: DLSS")
self.assertEqual(launcher.menu_note("rt", values), "F1 menu: Ray tracing (real lighting): On")
self.assertEqual(launcher.menu_note("profile", values), "")
self.assertEqual(launcher.menu_note("profile", {"LEONIDA_MENU_CONSOLE": "series-s"}), "F1 menu: Series S")
self.assertEqual(launcher.menu_note("resolution", values), "")
# Every variable named here is one of the menu's (ITEMS in menu.rs).
items = (ROOT / "d3d12" / "crates" / "leonida-gpu" / "src" / "host" / "menu.rs").read_text(encoding="utf-8")
for names in launcher.MENU_FOR_OPTION.values():
for name in names:
self.assertIn(f'var: "{name}"', items)
for name in launcher.MENU_LABELS:
self.assertIn(f'var: "{name}"', items)
def test_clear_deletes_only_that_file(self):
with tempfile.TemporaryDirectory() as repo:
self.write(repo, b"LEONIDA_FRAME_GEN=2\r\n")
beside = [os.path.join(repo, "d3d12", n) for n in ("leonida-settings.txt.tmp", "other.txt")]
beside.append(os.path.join(repo, launcher.MENU_FILE))
for path in beside:
Path(path).write_text("keep", encoding="utf-8")
self.assertTrue(launcher.clear_menu_settings(repo))
self.assertFalse(os.path.exists(launcher.menu_file(repo)))
self.assertTrue(all(os.path.isfile(p) for p in beside))
self.assertFalse(launcher.clear_menu_settings(repo)) # nothing left to delete
self.assertEqual(launcher.read_menu_settings(repo), {})
class LanguageTests(unittest.TestCase):
def texts(self):
"""Every text the window translates: the literal first argument of each t() call, and the texts passed to
t() by name (the cache note, About, the states, the F1 menu's setting names)."""
import ast
tree = ast.parse((ROOT / "tools" / "leonida_launcher.py").read_text(encoding="utf-8"))
found, named = set(), {}
for node in ast.walk(tree):
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "t" and node.args:
arg = node.args[0]
if isinstance(arg, ast.Constant) and isinstance(arg.value, str):
found.add(arg.value)
if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):
named[node.targets[0].id] = node.value
found |= {ast.literal_eval(named["NVIDIA_CACHE_NOTE"]), ast.literal_eval(named["ABOUT"])}
found |= set(ast.literal_eval(named["STATE_TEXTS"]))
found |= set(ast.literal_eval(named["MENU_LABELS"]).values())
# The Controls page's action labels and its default keys' lines.
found |= {label for _name, label in ast.literal_eval(named["KBM_ACTIONS"])}
found |= {does for _keys, does in ast.literal_eval(named["KBM_DEFAULTS"])}
return found
def test_every_language_translates_every_text(self):
import string
def fields(text):
return sorted(f for _, f, _, _ in string.Formatter().parse(text) if f)
texts = self.texts()
self.assertGreater(len(texts), 100)
for code in launcher.LANGUAGE_NAMES:
if code == "en":
continue
path = ROOT / "tools" / "launcher_i18n" / f"{code}.json"
raw = path.read_bytes()
data = json.loads(raw.decode("utf-8"))
self.assertEqual(set(data), texts, f"{code}: missing {sorted(texts - set(data))[:3]}, "
f"stale {sorted(set(data) - texts)[:3]}")
for english, translated in data.items():
self.assertEqual(fields(english), fields(translated), f"{code}: {english!r}")
self.assertTrue(translated.strip(), f"{code}: {english!r}")
self.assertTrue(raw.endswith(b"}\n"))
self.assertNotIn(b"\r", raw)
def test_pick_and_load(self):
self.assertEqual(launcher.pick_language("de", "fr"), "de")
self.assertEqual(launcher.pick_language("", "fr"), "fr")
self.assertEqual(launcher.pick_language("", "ja"), "en")
self.assertEqual(launcher.load_strings("en"), {})
self.assertEqual(launcher.load_strings("zz"), {})
with tempfile.TemporaryDirectory() as tmp:
Path(tmp, "fr.json").write_text('{"Play": "Jouer", "Bad": 3, "Empty": ""}', encoding="utf-8")
self.assertEqual(launcher.load_strings("fr", tmp), {"Play": "Jouer"})
Path(tmp, "de.json").write_text("[1]", encoding="utf-8")
self.assertEqual(launcher.load_strings("de", tmp), {})
def test_t_falls_back_to_english_and_fills_fields(self):
saved = dict(launcher.STRINGS)
try:
launcher.STRINGS.clear()
self.assertEqual(launcher.t("Found {exe}.", exe="a.exe"), "Found a.exe.")
launcher.STRINGS["Found {exe}."] = "Trouvé : {exe}."
self.assertEqual(launcher.t("Found {exe}.", exe="a.exe"), "Trouvé : a.exe.")
self.assertEqual(launcher.t("Untranslated"), "Untranslated")
finally:
launcher.STRINGS.clear()
launcher.STRINGS.update(saved)
def test_locale_variables_name_the_language(self):
saved = {k: os.environ.get(k) for k in ("LC_ALL", "LC_MESSAGES", "LANG", "LANGUAGE")}
try:
for k in saved:
os.environ.pop(k, None)
os.environ["LANG"] = "pt_BR.UTF-8"
self.assertEqual(launcher.system_language(windows=False), "pt")
finally:
for k, v in saved.items():
if v is None:
os.environ.pop(k, None)
else:
os.environ[k] = v
class HelpInfoTests(unittest.TestCase):
def test_nvidia_driver_number(self):
self.assertEqual(launcher.nvidia_driver("32.0.16.2147"), "621.47")
self.assertEqual(launcher.nvidia_driver("32.0.15.6094"), "560.94")
self.assertEqual(launcher.nvidia_driver("1.2"), "")
self.assertEqual(launcher.nvidia_driver("a.b.c.d"), "")
def test_info_names_no_folder(self):
s = settings(game_dir=r"C:\Users\someone\GTA", frame_gen=2, advanced="LEONIDA_A=1")
text = launcher.info_text(s, "abc1234 2026-12-02", [("NVIDIA GeForce RTX 4070", "32.0.16.2147"),
("Intel(R) Arc(TM) B580", "32.0.101.6979")],
"3.12.10 (64bit)", "8.6", "Windows 11")
self.assertIn("Mandy: abc1234 2026-12-02", text)
self.assertIn("GPU: NVIDIA GeForce RTX 4070, driver 621.47 (32.0.16.2147)", text)
self.assertIn("GPU: Intel(R) Arc(TM) B580, driver 32.0.101.6979", text)
self.assertIn("-FrameGen 2", text)
self.assertIn("LEONIDA_A=1", text)
self.assertNotIn("someone", text)
self.assertIn("Game folder found: no", text)
def test_version_of_a_zip_copy(self):
with tempfile.TemporaryDirectory() as tmp:
self.assertEqual(launcher.leonida_version(tmp), "zip copy")
class MemoryNoteTests(unittest.TestCase):
GIB = 1 << 30
def test_only_series_x_under_the_threshold_gets_a_note(self):
low, ram = 58 * self.GIB, 32 * self.GIB
self.assertIsNone(launcher.memory_note(False, low, ram))
self.assertIsNone(launcher.memory_note(False, low, ram, short=True))
note = launcher.memory_note(True, low, ram)
self.assertIn("32 GB of RAM", note)
self.assertIn("58.0 GB", note)
self.assertIn("59 GB", note)
self.assertIn("Series S", note)
self.assertIn("80 GB", note)
self.assertIn("58.0 GB", launcher.memory_note(True, low, ram, short=True))
self.assertIsNone(launcher.memory_note(True, launcher.SERIES_X_COMMIT_BYTES, ram))
self.assertIsNotNone(launcher.memory_note(True, launcher.SERIES_X_COMMIT_BYTES - 1, ram))
self.assertIsNone(launcher.memory_note(True, 80 * self.GIB, 48 * self.GIB))
self.assertIsNone(launcher.memory_note(True, None, ram))
self.assertIsNone(launcher.memory_note(True, None, None, short=True))
self.assertEqual(launcher.SERIES_X_COMMIT_BYTES, 64 * self.GIB)
def test_the_page_file_steps_name_a_size_when_the_ram_is_known(self):
steps = launcher.page_file_steps(32 * self.GIB)
self.assertIn("sysdm.cpl", steps)
self.assertIn("49152 MB", steps) # 80 - 32 GB
self.assertIn("50176 MB", launcher.page_file_steps(int(31.9 * self.GIB))) # rounded up to a whole GB
self.assertNotIn(" MB as initial", launcher.page_file_steps(None))
self.assertIn("windows-memory.md", launcher.page_file_steps(None))
@unittest.skipUnless(os.name == "nt", "GlobalMemoryStatusEx is Windows'")
def test_commit_limit_is_read_on_windows(self):
limit, ram = launcher.commit_limit_bytes(), launcher.physical_memory_bytes()
self.assertIsInstance(limit, int)
self.assertGreater(limit, 0)
self.assertIsInstance(ram, int)
self.assertGreaterEqual(limit, ram // 2)
def test_nothing_is_read_off_windows(self):
self.assertIsNone(launcher.commit_limit_bytes(windows=False))
self.assertIsNone(launcher.physical_memory_bytes(windows=False))
def test_the_note_never_changes_the_play_command(self):
saved = launcher.commit_limit_bytes
try:
launcher.commit_limit_bytes = lambda *a, **k: 58 * self.GIB
command = launcher.play_command(settings(), repo="R", windows=True)
finally:
launcher.commit_limit_bytes = saved
self.assertEqual(command, ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File",
os.path.join("R", "scripts", "play-d3d12.ps1"), "-Game", "D:/Games/GTA"])
self.assertNotIn("-SeriesS", launcher.switch_args(settings()))
def test_info_names_the_ram_and_the_commit_limit(self):
text = launcher.info_text(settings(), "abc", [], "3.12", "8.6", "Windows 11",
(58 * self.GIB, 32 * self.GIB))
self.assertIn("Memory: 32.0 GB RAM, commit limit (RAM + page file) 58.0 GB", text)
self.assertIn("Memory: ? GB RAM", launcher.info_text(settings(), "abc", [], "3.12", "8.6", "Linux"))
class LauncherBatTests(unittest.TestCase):
def test_it_looks_for_tk_and_offers_the_same_python_as_build(self):
launcher_bat = (ROOT / "Launcher.bat").read_text(encoding="ascii").splitlines()
build_bat = (ROOT / "Build.bat").read_text(encoding="ascii").splitlines()
self.assertTrue(any("import tkinter" in line for line in launcher_bat))
pinned = [line for line in build_bat if line.startswith(('set "PYURL=', 'set "PYSHA='))]
self.assertEqual(len(pinned), 2)
for line in pinned:
self.assertIn(line, launcher_bat)
self.assertTrue(any("Include_tcltk=1" in line for line in launcher_bat))
self.assertTrue(any("LEONIDA_PY_INSTALL_DRYRUN" in line for line in launcher_bat))
def test_an_update_that_replaces_it_while_it_runs_ends_cleanly(self):
# cmd reads the next line of a running batch file from the byte where it stopped. The Launcher.bat before
# the overhaul stopped at byte 749 (after its python line, CRLF): there the new file must hold only :: lines
# (labels, skipped from any byte) up to a plain exit, and its own python line must end the script itself.
# That exit is `exit /b` with no code: an update run from the console keeps git's or the build's code there.
raw = (ROOT / "Launcher.bat").read_bytes()
if b"\r\n" not in raw: # a checkout without the CRLF attribute applied
raw = raw.replace(b"\n", b"\r\n")
start = raw.index(b"goto :start\r\n") + len(b"goto :start\r\n")
stop = raw.index(b"exit /b\r\n:start\r\n")
self.assertLess(start, 749)
self.assertGreater(stop, 749 + 200)
self.assertTrue(all(line and set(line) == {":"} for line in raw[start:stop].decode("ascii").split("\r\n")[:-1]))
run = [line for line in raw.decode("ascii").split("\r\n") if "leonida_launcher.py" in line and "PY_EXE" in line]
self.assertEqual(len(run), 1)
self.assertIn("&& exit /b 0 ||", run[0])
# The launcher's own exit code (git's or the build's with --update) goes back to the caller, and the whole
# error path is on that line: no label the replacing file would have to keep.
self.assertIn('call set "RC=%%errorlevel%%"', run[0])
self.assertIn("exit /b !RC!", run[0])
self.assertNotIn("call :", run[0])
if __name__ == "__main__":
unittest.main()