refactor: split the full-screen tests by subject

test_install_tui.py held 16,850 lines. Its 100 test classes move whole into fourteen test_tui_* modules, the shared states, manifests and pseudo-terminal into tests/tuisupport.py. Methods one class borrowed from another live in holder classes there. CI and pr_checks.py run every new module on Python 3.8.
This commit is contained in:
Abdessamad Derraz committed 2026-11-24 07:37:15 +01:00
1 parent bedfeec772
commit c3b67d5485
25 files changed
+17467 -16862

No files matched your search

+1 -1
View File
@@ -355,7 +355,7 @@ jobs:
if: ${{ !cancelled() }}
env:
RETROBIOS_OFFLINE: "1"
run: python3.8 -m unittest tests.test_install_tui -v
run: python3.8 -m unittest -v tests.test_tui_card_counts tests.test_tui_card_setups tests.test_tui_card_space tests.test_tui_choices tests.test_tui_devices tests.test_tui_flow tests.test_tui_folders tests.test_tui_line_mode tests.test_tui_mouse tests.test_tui_packs tests.test_tui_pty tests.test_tui_screens tests.test_tui_terminal tests.test_tui_views
# deploy-site.yml runs this after the merge, and a dead link or a stray
# heading failed it there with nothing in front of it. Run whatever the
+2 -1
View File
@@ -105,7 +105,8 @@ python scripts/generate_site.py # the pages the site
npm ci --prefix website # the site's packages, Node 24
npm run build --prefix website # the built site
python scripts/run_tests.py --jobs 4 # the suite, one process per module
python3.8 -m unittest tests.test_install_tui # the full screen on the installer's floor
# the full screen on the installer's floor
python3.8 -m unittest tests.test_tui_card_counts tests.test_tui_card_setups tests.test_tui_card_space tests.test_tui_choices tests.test_tui_devices tests.test_tui_flow tests.test_tui_folders tests.test_tui_line_mode tests.test_tui_mouse tests.test_tui_packs tests.test_tui_pty tests.test_tui_screens tests.test_tui_terminal tests.test_tui_views
python scripts/validate_site.py --site-dir website/dist # links and page budgets
```
+2 -1
View File
@@ -111,7 +111,8 @@ max-returns = 10
"tests/__init__.py" = ["UP"]
"tests/sources.py" = ["UP"]
"tests/netguard/*.py" = ["UP"]
"tests/test_install_tui.py" = ["UP"]
"tests/test_tui_*.py" = ["UP"]
"tests/tuisupport.py" = ["UP"]
"tests/test_install_app.py" = ["UP"]
"tests/test_install_selection.py" = ["UP"]
"tests/test_install_offline.py" = ["UP"]
+12 -1
View File
@@ -23,6 +23,16 @@ class Step:
may_fail: bool = False
# The full-screen tests, run again on the installer's Python floor.
TUI_MODULES = (
"tests.test_tui_card_counts", "tests.test_tui_card_setups", "tests.test_tui_card_space",
"tests.test_tui_choices", "tests.test_tui_devices", "tests.test_tui_flow",
"tests.test_tui_folders", "tests.test_tui_line_mode", "tests.test_tui_mouse",
"tests.test_tui_packs", "tests.test_tui_pty", "tests.test_tui_screens",
"tests.test_tui_terminal", "tests.test_tui_views",
)
# The order of validate.yml: data fetched, site generated and built, then the
# suite, its 3.8 run and the built-site check.
STEPS: tuple[Step, ...] = (
@@ -50,7 +60,8 @@ STEPS: tuple[Step, ...] = (
needs="npm", provider="Node 24", env={"NODE_DISABLE_COMPILE_CACHE": "1"}),
Step("python scripts/run_tests.py --jobs 4", "the suite, one process per module",
env={"RETROBIOS_OFFLINE": "1"}),
Step("python3.8 -m unittest tests.test_install_tui", "the full screen on the installer's floor",
Step("python3.8 -m unittest " + " ".join(TUI_MODULES),
"the full screen on the installer's floor",
needs="python3.8", provider="a Python 3.8 with pyte",
env={"RETROBIOS_OFFLINE": "1"}),
Step("python scripts/validate_site.py --site-dir website/dist", "links and page budgets"),
+19 -2
View File
@@ -439,6 +439,24 @@ def render_readme(inputs: ReadmeInputs) -> str:
return "\n".join(lines) + "\n"
# Past this width a command takes its comment on the line above: the 3.8 run
# names fourteen modules, and aligning on it pushed every comment off the page.
STEP_WIDTH = 72
def check_lines() -> str:
"""The checks of pr_checks.py, each with what it covers."""
commands = [(prchecks.shown(step), step.why) for step in prchecks.STEPS]
width = max(len(command) for command, _ in commands if len(command) <= STEP_WIDTH)
lines = []
for command, why in commands:
if len(command) > STEP_WIDTH:
lines += [f"# {why}", command]
else:
lines.append(f"{command:<{width}} # {why}")
return "\n".join(lines)
def ci_install_lines() -> tuple[str, str]:
"""The pip lines the test job of validate.yml runs, verbatim.
@@ -464,8 +482,7 @@ def contributing_text(
.md for the site); *site_words* names the site from where the text is read.
"""
pip_line, floor_line = ci_install_lines()
width = max(len(prchecks.shown(step)) for step in prchecks.STEPS)
steps = "\n".join(f"{prchecks.shown(step):<{width}} # {step.why}" for step in prchecks.STEPS)
steps = check_lines()
return f"""{title}
## Add a BIOS file
+2 -2
View File
@@ -142,8 +142,8 @@ class TheChecklistInstallsWhatCiInstalls(unittest.TestCase):
section = text.split("## Before opening a PR", 1)[1].split("\n## ", 1)[0]
for tool, step in (("shellcheck", "shellcheck --version"),
("bwrap", "bwrap --ro-bind"),
("python3.8 -m unittest tests.test_install_tui",
"python3.8 -m unittest tests.test_install_tui")):
("python3.8 -m unittest tests.test_tui_",
"python3.8 -m unittest -v tests.test_tui_")):
with self.subTest(tool=tool):
self.assertIn(step, workflow)
self.assertIn(tool, section)
+1 -1
View File
@@ -29,7 +29,7 @@ from pathlib import Path
import install
from tests import test_install_games as games
from tests.test_install_tui import DOWN, UP, Pty, pty, pyte
from tests.tuisupport import DOWN, UP, Pty, pty, pyte
REPO_ROOT = Path(__file__).resolve().parent.parent
+2 -2
View File
@@ -1011,7 +1011,7 @@ class OneOfflineVocabulary(Scratch):
def test_the_command_suggested_keeps_the_offline_setting(self):
"""Sudo does not pass RETROBIOS_INSTALL_OFFLINE on."""
from tests import test_install_tui as tui
from tests import tuisupport as tui
args = tui._args(platform="retroarch", declared_only=False, offline=False)
hint = install.Invocation()
@@ -1046,7 +1046,7 @@ class OneOfflineVocabulary(Scratch):
def test_the_screen_says_missing_not_failed(self):
"""On the full screen: "Finished with errors, 20 failed"."""
from tests import test_install_tui as tui
from tests import tuisupport as tui
reason = f"not fetched: {install.OFFLINE_WORDS}"
left = [{"dest": f"f{n}.bin", "reason": reason} for n in range(20)]
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+881
View File
@@ -0,0 +1,881 @@
"""The device and emulator screens, the board registry and the app on a card."""
from __future__ import annotations
import tests
import contextlib
import io
import json
import os
import queue
import re
import shutil
import tempfile
import unittest
import zipfile
from pathlib import Path
from unittest import mock
import install
from tests.netguard import module_guard
from tests.tuisupport import (
_app_card, _args, CHECK, checked_state, device_state, fresh_state, golden_states_result,
in_full, _installed_state, MANIFEST, press, REPO_ROOT, result_states, SYSTEM_DIR, TARGETS,
)
# No connection off the loopback and no card of the host reaches a test,
# in this process or one it starts: the module fails at its end when one is tried.
setUpModule, tearDownModule = module_guard("test_tui_devices")
class TheSetupFilterKnowsDevices(unittest.TestCase):
"""The filter found nothing for steam deck, r36s,
trimui or retroid, and miyoo found RetroArch with muOS, JELOS... beside it."""
TYPED = {
"steam deck": {"retroarch", "batocera", "emudeck", "retrodeck"},
# MinUI and MyMinUI list their devices, and on
# a computer an Android device is no RetroArch of this machine's.
"r36s": {"retroarch", "rocknix", "myminui"},
"rg35xx": {"retroarch", "rocknix", "knulli", "minui", "myminui"},
"trimui": {"retroarch", "knulli", "minui", "nextui"},
"retroid": {"rocknix", "knulli"},
"miyoo": {"retroarch", "knulli", "minui", "myminui"},
"anbernic": {"retroarch", "rocknix", "amberelec", "knulli", "minui", "myminui"},
"odin": {"rocknix"},
"ayn": {"retroarch", "rocknix"},
"rp5": {"rocknix", "knulli"},
"rog ally": {"retroarch", "emudeck", "retrobat", "bizhawk"},
"onion": {"retroarch"},
}
def rows(self, needle: str) -> list:
state = fresh_state()
state.stack = ["platforms"]
state.filters["platforms"] = needle
return [row for row in install.tui_rows(state)
if row.action in ("platform", "cardsystem")]
def test_each_device_finds_every_setup_it_runs(self):
for needle, setups in self.TYPED.items():
with self.subTest(needle=needle):
self.assertEqual({row.value[0] if row.action == "cardsystem" else row.value
for row in self.rows(needle)}, setups)
def test_the_right_column_names_what_matched(self):
rows = self.rows("miyoo")
# MiyooCFW stayed on the
# RetroArch row, which opened this computer's folder.
self.assertNotIn("retroarch", [row.value for row in rows if row.action == "platform"])
self.assertEqual([row.label for row in rows if row.action == "cardsystem"],
["Allium, SD card", "Koriki, SD card", "MiyooCFW, SD card",
"Onion, SD card", "spruceOS, SD card"])
spruce = {row.label: row for row in rows}["spruceOS, SD card"]
self.assertEqual(spruce.right, "Miyoo A30, Miyoo Flip, Miyoo Mini, Miyoo Mini Plus, "
"Miyoo Mini Flip")
# Cut at a comma, never inside a name ("Miyoo ...s").
self.assertIn("Miyoo A30, Miyoo Flip, +3", spruce.narrow)
line = str(install._row_line(spruce, False, 60))
self.assertTrue(line.rstrip().endswith(("+1", "+2", "+3", "+4")), line)
deck = {row.value: row for row in self.rows("steam deck")}
self.assertEqual(deck["retroarch"].right, "Steam Deck")
self.assertEqual({row.value: row for row in self.rows("")}["retroarch"].right, "")
def test_the_handheld_lists_are_the_guides(self):
try:
import yaml
except ImportError:
self.skipTest("pyyaml is not installed")
guides = yaml.safe_load((REPO_ROOT / "platforms" / "_guides.yml").read_text())
for system in guides["handheld_guide"]["systems"]:
if system.get("devices"):
with self.subTest(system=system["name"]):
self.assertEqual(install._SETUP_DEVICES[system["name"]],
tuple(str(name) for name in system["devices"]))
class AppOnTheCard(unittest.TestCase):
"""The RetroBIOS app offered on the result screen and in the options."""
def setUp(self):
patcher = mock.patch.dict(os.environ)
patcher.start()
self.addCleanup(patcher.stop)
os.environ.pop(install.OFFLINE_VARIABLE, None)
def fields(self, card_root: Path, ok: bool = True) -> dict:
return {"event": "app", "system": "muOS", "folder": str(card_root), "ok": ok,
"reason": "" if ok else "it could not be downloaded: no connection",
"dests": ["ARCHIVE/RetroBIOS.muxapp"],
"written": ["ARCHIVE/RetroBIOS.muxapp"] if ok else [], "kept": []}
def test_the_result_offers_it_and_exit_stays_the_default(self):
root, bios = _app_card(self, "muOS")
state = _installed_state(bios)
rows = install.tui_rows(state)
self.assertEqual([row.action for row in rows], ["exit", "addapp"])
self.assertEqual(rows[1].label, install.APP_OFFER)
screen = "\n".join(install.tui_view(state, 80, 24))
self.assertIn(install.APP_OFFER, screen)
self.assertIn("A/Enter Exit", screen)
self.assertEqual(press(state, "enter"), [])
self.assertEqual(state.exit_code, 0)
def test_choosing_it_puts_it_then_says_what_it_did(self):
root, bios = _app_card(self, "muOS")
state = _installed_state(bios)
effects = press(state, "down", "enter")
self.assertEqual(effects, [("app", install.card_app(bios))])
self.assertTrue(state.app_running)
screen = "\n".join(install.tui_view(state, 80, 24))
self.assertIn("Putting RetroBIOS on the card...", screen)
# Nothing ends the screen while the card is written.
self.assertEqual(press(state, "enter", "esc"), [])
self.assertIsNone(state.exit_code)
install.tui_receive(state, ("app", self.fields(root)))
self.assertEqual(install.tui_rows(state), [])
screen = "\n".join(install.tui_view(state, 80, 24))
self.assertIn("RetroBIOS is on the muOS card: 1 file written", screen)
self.assertIn("Archive Manager", screen)
self.assertIn("--add-app", install.tui_command(state))
press(state, "enter")
self.assertEqual(state.exit_code, 0)
def test_a_failure_is_said_and_ends_on_1(self):
root, bios = _app_card(self, "KNULLI")
state = _installed_state(bios)
press(state, "down", "enter")
install.tui_receive(state, ("app", {**self.fields(root, ok=False), "system": "KNULLI"}))
_title, lines = install.tui_outcome(state)
self.assertTrue(any("could not be put on the KNULLI card" in line for line in lines))
press(state, "enter")
self.assertEqual(state.exit_code, 1)
def test_space_and_b_never_put_it(self):
_root, bios = _app_card(self, "muOS")
state = _installed_state(bios)
self.assertEqual(press(state, "down", " "), [])
self.assertFalse(state.app_running)
press(state, "esc")
self.assertEqual(state.exit_code, 0)
def test_no_offer_where_it_cannot_go(self):
_root, muos = _app_card(self, "muOS")
_root, onion = _app_card(self, "Onion")
cases = {
"failed install": _installed_state(muos, 1, [{"dest": "a", "reason": "x"}]),
"plain folder": _installed_state(SYSTEM_DIR),
"no launcher": _installed_state(onion),
}
offline = _installed_state(muos)
for name, state in cases.items():
with self.subTest(case=name):
self.assertEqual(install.tui_rows(state), [])
offline.offline = True
self.assertEqual(install.tui_rows(offline), [])
_title, lines = install.tui_outcome(cases["no launcher"])
self.assertIn(install.no_python_words("Onion"), lines)
def test_put_by_the_install_itself_no_second_offer(self):
root, bios = _app_card(self, "muOS")
state = _installed_state(bios)
install._take_event(state, self.fields(root))
self.assertEqual(install.tui_rows(state), [])
self.assertIn("RetroBIOS is on the muOS card", "\n".join(install.tui_outcome(state)[1]))
def test_the_options_row_sets_the_flag_of_the_install_only(self):
_root, bios = _app_card(self, "muOS")
state = _installed_state(bios)
state.stack = ["plan", "options"]
rows = install.tui_rows(state)
row = next(row for row in rows if row.action == "addapp")
self.assertEqual((row.label, row.right), ("Put RetroBIOS on this card: no", "--add-app"))
state.focus["options"] = rows.index(row)
press(state, "enter")
self.assertTrue(state.add_app)
self.assertIn("--add-app", install.tui_argv(state, "install", "py", "install.py"))
for run in ("check", "confirm", "preview"):
self.assertNotIn("--add-app", install.tui_argv(state, run, "py", "install.py"))
self.assertIn("--add-app", install.tui_command(state))
press(state, "left")
self.assertFalse(state.add_app)
plain = _installed_state(SYSTEM_DIR)
plain.stack = ["plan", "options"]
self.assertFalse(any(row.action == "addapp" for row in install.tui_rows(plain)))
def test_offline_on_the_screen_drops_the_flag_before_its_effect(self):
_root, bios = _app_card(self, "muOS")
state = _installed_state(bios)
state.add_app = True
with mock.patch.dict(os.environ):
os.environ.pop(install.OFFLINE_VARIABLE, None)
state.offline = True
argv = install.tui_argv(state, "install", "py", "install.py")
self.assertIn("--offline", argv)
self.assertNotIn("--add-app", argv)
def test_the_command_line_flag_ticks_the_row(self):
_root, bios = _app_card(self, "ROCKNIX")
state, _effects = install.tui_start(_args(add_app=True, platform="rocknix",
dest=bios), "linux", detect=False)
self.assertTrue(state.add_app)
class OneDeviceRegistry(unittest.TestCase):
"""One device spelled
several ways found one system, one press took it, MinUI listed brands."""
def found(self, typed: str, os_type: str = "linux") -> set:
return {row.value[1] if row.action == "cardsystem" else row.value
for row in install.setup_list([], set(), typed, os_type)}
def test_one_spelling_per_device(self):
keys = {}
for name in install._DEVICES:
keys.setdefault(install._device_key(name), []).append(name)
self.assertEqual({key: names for key, names in keys.items() if len(names) > 1}, {})
for system, devices in install._SETUP_DEVICES.items():
with self.subTest(system=system):
self.assertEqual([name for name in devices if name not in install._DEVICES], [])
def test_every_spelling_finds_every_system_that_runs_it(self):
rk2023 = {"dArkOS", "ArkOS", "KOLOS", "JELOS", "rocknix"}
cubexx = {"muOS", "knulli", "rocknix", "minui"}
flip2 = {"knulli", "rocknix"}
for typed, systems in (("Powkiddy RK2023", rk2023), ("RK2023", rk2023),
("rk-2023", rk2023), ("RG CubeXX", cubexx),
("RGCUBEXX", cubexx), ("Anbernic RG CubeXX", cubexx),
("Retroid Pocket Flip 2", flip2), ("flip2", flip2)):
with self.subTest(typed=typed):
self.assertEqual(self.found(typed), systems)
self.assertIn("ArkOS", self.found("Anbernic RG353V"))
self.assertTrue({"Onion", "minui", "myminui", "Allium"} <= self.found("Miyoo Mini"))
self.assertTrue({"Onion", "minui"} <= self.found("Miyoo Mini+"))
self.assertIn("minui", self.found("TrimUI Brick"))
self.assertIn("Anbernic stock firmware", self.found("rg35xx"))
self.assertIn("JELOS", self.found("rgb10 max 3"))
def test_android_is_this_machine_only_on_android(self):
self.assertNotIn("retroarch", self.found("android"))
self.assertNotIn("retroarch", self.found("retroid pocket 5"))
self.assertIn("retroarch", self.found("android", "android"))
def test_a_device_several_systems_run_is_never_taken_in_one_press(self):
out = io.StringIO()
with mock.patch.object(install, "_ask",
side_effect=["Powkiddy RK2023", "", "0", "35", "q"]), \
mock.patch.object(install, "detect_os", return_value="linux"), \
contextlib.redirect_stdout(out), self.assertRaises(SystemExit):
install._choose_platform("Which?", "retroarch")
text = out.getvalue()
self.assertIn("5 setups run on 'Powkiddy RK2023':", text)
# Enter after the matches takes none, and 0 and 35 are numbers.
self.assertEqual(text.count("Type a number from 1 to 34"), 3)
self.assertNotIn("run on '0'", text)
self.assertNotIn("run on '35'", text)
def test_the_line_menu_is_the_screen_list_numbered(self):
for setups in ([], [("retroarch", SYSTEM_DIR, "RetroArch")]):
with self.subTest(found=bool(setups)):
rows = install.setup_list(setups, set(), "", "linux")
self.assertEqual([name for name, _label in install._line_setups(setups, None,
"linux")],
[install._row_name(row) for row in rows])
labels = dict(install._line_setups())
self.assertIn("RG28XX", labels["minui"])
self.assertNotIn("(Anbernic, Miyoo", labels["minui"])
self.assertIn("RG35XX Plus", labels["Anbernic stock firmware"])
self.assertNotIn("RetroArch files", labels["JELOS"])
def test_forty_columns_keep_the_name_whole_and_a_device_count(self):
rows = {row.label: row for row in install.setup_list([], set(), "", "linux")}
for label in ("KNULLI, SD card", "ROCKNIX, SD card", "CrossMix-OS, SD card",
"AmberELEC, SD card", "JELOS, SD card"):
with self.subTest(row=label):
line = str(install._row_line(rows[label], False, 38))
self.assertIn(label, line)
self.assertTrue(line.rstrip() != (" " + label).rstrip(), line)
# its one device, cut, where "1 device" named none.
self.assertTrue(str(install._row_line(rows["CrossMix-OS, SD card"], False, 38))
.rstrip().endswith("TrimUI Smar..."))
class TheAndroidResultReadsWhole(unittest.TestCase):
"""A run on Android 17 under Termux: the result named /sdcard and
/storage/emulated/0 for one storage, saves/<core> read as a folder named
<core>, a backup path and the restore command were split inside a word,
and the game data line named no folder."""
def setUp(self):
self.root = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.root, True)
for patcher in (mock.patch.dict(install._SPELLED, {}, clear=True),):
patcher.start()
self.addCleanup(patcher.stop)
def test_one_storage_is_named_one_way(self):
real = self.root / "storage" / "emulated" / "0"
(real / "RetroArch" / "system").mkdir(parents=True)
link = self.root / "sdcard"
link.symlink_to(real)
bios = link / "RetroArch" / "system"
self.assertEqual(install._destination_path(bios, "a.bin"),
real.resolve() / "RetroArch" / "system" / "a.bin")
kept = install.KeptFiles()
run = kept.plan(install._kept_slot(bios, "a.bin")[0], 3)
folder = kept.summary()[0]["folder"]
self.assertTrue(folder.startswith(str(link / "RetroArch" / "retrobios-backup")),
folder)
self.assertEqual(install.shown_path(run), folder)
self.assertNotIn(str(real), install.shown_path(real.resolve() / "RetroArch" / "saves"))
def test_a_folder_per_core_is_said_in_words(self):
where = "/sdcard/RetroArch/saves/<core>"
line = install.saves_line("RetroArch", 106, where)
self.assertEqual(line, "106 files read from RetroArch's save directory go to a "
"folder per core under /sdcard/RetroArch/saves")
self.assertEqual(install.save_where_words("/s/saves/<system>"),
("a folder per system under", "/s/saves"))
state = checked_state()
screen = install._saves_lines(state, {"files": 106, "folder": where})
self.assertNotIn("<core>", " ".join(screen))
self.assertIn("a folder per core under:", screen[0])
def result(self, cols: int) -> list:
state = _installed_state(Path("/sdcard/RetroArch/system"))
state.summary["kept"] = [{"folder": "/sdcard/RetroArch/retrobios-backup/"
"20261027-223524", "files": 3, "bytes": 10}]
state.cols, state.rows = cols, 40
return install.tui_view(state, cols, 40)
@in_full
def test_a_path_or_a_command_is_never_split_inside_a_word(self):
full = "/sdcard/RetroArch/retrobios-backup/20261027-223524"
for cols in (40, 50, 80):
with self.subTest(cols=cols):
lines = [str(line).strip() for line in self.result(cols)]
words = [word for line in lines for word in line.split()]
self.assertIn("--restore", words)
# The command keeps it whole where its line holds it, cut to
# its last folders and said so where not.
if cols >= 60:
self.assertIn(full, words)
else:
self.assertIn(install.TUI_SHORTENED, lines)
# Prose breaks it after a separator only, never inside a name:
# glued again, it is whole.
self.assertIn(full, re.sub(r"/ ", "/", " ".join(lines)))
self.assertFalse(any(line.endswith(("retrobios-ba", "20261027-"))
for line in lines), lines)
state = _installed_state(Path("/sdcard/RetroArch/system"))
command = install._styled(f"curl -fsSL {install.BOOTSTRAP_URL} | sh -s -- --restore "
"'/storage/emulated/0/a b/20261027-223524'", "command")
state.stack.append("result")
pieces = install._text_lines([command], 38, whole=True)
joined = [str(piece).strip() for piece in pieces if piece.style != "cont"]
# The address never cut, the option with its value, each line but
# the last ending with the shell's continuation.
self.assertIn(f"{install.BOOTSTRAP_URL} \\", joined)
self.assertTrue(any(line.startswith("--restore '") for line in joined), joined)
self.assertTrue(all(len(str(piece)) <= 38 for piece in pieces), pieces)
def test_a_long_line_folds_in_the_terminal(self):
terminal = install._TuiTerminal.__new__(install._TuiTerminal)
terminal.frame, written = [], []
terminal.write = written.append
long = install._styled("x" * 50, "long")
terminal.draw([long, install._styled("", "cont"), install._styled("next")], 40)
out = "".join(written)
self.assertIn("x" * 50, out)
self.assertNotIn("\x1b[2;1H", out)
self.assertIn("\x1b[3;1H", out)
def test_game_data_names_the_folder_it_goes_in(self):
entry = {"dest": "jazz2/Source/Anims.j2a", "required": True, "category": "game_data",
"system": "jazz-jackrabbit-2"}
bios = Path("/sdcard/RetroArch/system")
lines = install._omission_lines(1, [entry], bios)
said = " ".join(lines)
self.assertIn(f"into {bios / 'jazz2' / 'Source'}{os.sep}", said)
# Defined on its own line, never spliced into the sentence naming
# the file.
self.assertIn("files a game or a game engine reads", said)
self.assertEqual([line for line in lines if "game engine reads" in line],
[" Game data: files a game or a game engine reads, of no use to "
"the other cores."])
self.assertNotIn("Needed to start an emulator", said)
class WhatToActOnStaysOnTheScreen(unittest.TestCase):
"""A failure, a file an emulator needs that the collection lacks, a
remedy to choose: on the screen by default, never only on Details
(review of 2026-11-10)."""
def setUp(self):
patcher = mock.patch.object(install, "_mounted_cards", return_value=[])
patcher.start()
self.addCleanup(patcher.stop)
def text(self, state: install.TuiState) -> str:
return " ".join(" ".join(install.tui_view(state, 80, 24)).split())
def test_a_failed_file_is_named_on_the_result_and_after_exit(self):
state = golden_states_result()
self.assertIn("failed: scph5500.bin (HTTP 404)", self.text(state))
press(state, "enter")
self.assertIn("failed: scph5500.bin (HTTP 404)", "\n".join(install.tui_farewell(state)))
def needs(self, state: install.TuiState) -> install.TuiState:
state.manifest = {**MANIFEST, "omitted_files": [
{"dest": "lost.bin", "system": "sony-playstation", "required": True},
{"dest": "spare.bin", "system": "sony-playstation", "required": False}]}
return state
def test_a_file_an_emulator_needs_is_counted_on_the_plan(self):
state = self.needs(checked_state())
said = "1 file an emulator needs is not available here (Details names it)."
self.assertIn(said, self.text(state))
press(state, "d")
self.assertIn("lost.bin", self.text(state))
# With --verbose the names are on the plan, and the count not again.
state = self.needs(checked_state())
state.passthrough = [("--verbose", None)]
self.assertNotIn(said, self.text(state))
self.assertIn("lost.bin", self.text(state))
def test_a_file_an_emulator_needs_is_counted_on_the_result(self):
state = self.needs(result_states()["done"])
self.assertIn("1 file an emulator needs is not available here (Details names it).",
self.text(state))
def test_the_save_folder_remedy_is_on_the_result(self):
state = result_states()["done"]
state.manifest = {**MANIFEST, "save_directory": {"folder": "saves", "by_core": True}}
state.summary["skipped"] = [{"reason": "no_save_directory", "files": 2}]
text = self.text(state)
self.assertIn("2 files read from RetroArch's save directory left out. "
f"{install.TUI_SAVE_REMEDY}", text)
self.assertNotIn("Its place is not known.", text)
press(state, "o")
self.assertIn("Its place is not known.", self.text(state))
def test_the_save_folder_remedy_is_on_the_plan(self):
state = checked_state()
state.manifest = {**MANIFEST, "save_directory": {"folder": "saves", "by_core": True}}
state.check_summary = {"skipped": [{"reason": "no_save_directory", "files": 2}]}
self.assertIn("Choose it in Change, Save folder (--save-dir).", self.text(state))
def test_files_that_could_not_be_read_are_counted_where_no_row_says_so(self):
unread = [{"event": "unreadable", "platform": "retroarch", "folder": "/media/OLD",
"path": "/media/OLD/scph5501.bin", "member": "",
"reason": "Permission denied"}]
state = checked_state()
state.unreadable = list(unread)
# The plan's row names them: the count waits on Details.
self.assertIn("Show the files that could not be read", self.text(state))
# Everything in place: no row, the count on the plan.
done = checked_state()
done.check = {**CHECK, "present": 5, "missing": 0, "wrong_hash": 0,
"bytes_needed": 0, "not_installable": 0}
done.unreadable = list(unread)
self.assertNotIn("unreadable", [row.action for row in install.tui_rows(done)])
self.assertIn("1 file in OLD could not be read.", self.text(done))
def test_another_drive_to_add_is_said_on_the_plan(self):
state = checked_state()
state.scanned = [{"event": "scanned", "folder": "E:\\", "files": 200000,
"truncated": True, "other_drives": ["E:\\D"]}]
text = self.text(state)
self.assertIn("E:\\D is another drive: add it to copy from it too.", text)
self.assertNotIn("Read the first", text)
class DeviceAndEmulatorScreens(unittest.TestCase):
"""Device chooses --target and --every-board, Emulators --emulator, and
Change keeps every option one level below the plan, grouped by intent."""
def setUp(self):
patcher = mock.patch.object(install, "_mounted_cards", return_value=[])
patcher.start()
self.addCleanup(patcher.stop)
def text(self, state: install.TuiState, cols: int = 80, rows: int = 24) -> str:
return "\n".join(str(line) for line in install.tui_view(state, cols, rows))
def focus(self, state: install.TuiState, action: str, value: object = None) -> None:
rows = install.tui_rows(state)
state.focus[state.screen] = next(
index for index, row in enumerate(rows)
if row.action == action and (value is None or row.value == value))
def test_change_groups_every_option_under_headings_focus_skips(self):
state = checked_state()
press(state, "o")
rows = install.tui_rows(state)
headings = [row.label for row in rows if row.action == "heading"]
self.assertEqual(headings, list(install.TUI_CHANGE_GROUPS))
self.assertNotEqual(rows[state.focus["options"]].action, "heading")
flags = {row.right for row in rows if row.action != "heading"}
for flag in ("--region", "--core", "--emulator", "--no-game-data", "--dest", "--from",
"--from-pack", "--target", "--installed-cores", "--jobs", "--offline",
"--dry-run"):
self.assertIn(flag, flags)
# Down and Up never stop on a heading, Home neither.
for key in ("down",) * len(rows) + ("up",) * len(rows) + ("home", "end", "home"):
press(state, key)
self.assertNotEqual(install.tui_rows(state)[state.focus["options"]].action,
"heading", key)
# Up on the first row stays: the list does not wrap past its heading.
press(state, "home", "up")
self.assertEqual(state.focus["options"], 1)
# The plan's row and bar name the screen.
plan = checked_state()
self.assertIn("Change", [row.label for row in install.tui_rows(plan)])
self.assertIn("Y/o Change", self.text(plan))
def test_a_tap_on_a_heading_does_nothing(self):
state = checked_state()
press(state, "o")
before = dict(state.focus)
rows = install.tui_rows(state)
index = next(i for i, row in enumerate(rows) if row.action == "heading")
state.cols, state.rows = 80, 24
state.hits = install.tui_hits(state, install.tui_view(state, 80, 24))
number = next(target[0] for target in state.hits.targets
if target[3][:2] == ("row", index))
state.now = state.hits.shown + 1
install.tui_mouse(state, install.TuiMouse(0, 3, number + 1, False))
self.assertEqual(install.tui_mouse(state, install.TuiMouse(0, 3, number + 1, True)), [])
self.assertEqual(state.focus, before)
def test_device_lists_the_card_board_first_and_chosen(self):
state = device_state()
self.assertEqual(state.screen, "device")
rows = install.tui_rows(state)
self.assertEqual([row.label for row in rows],
["(x) h700", "( ) bcm2711", "( ) x86_64", "( ) Every board"])
self.assertEqual(rows[0].right, "named by the card")
self.assertEqual(rows[1].right, "rpi4")
self.assertEqual(state.focus["device"], 0)
# Chosen as it is: nothing to say on the command line.
press(state, "enter")
self.assertEqual(state.screen, "options")
self.assertEqual([flag for flag in install.tui_flags(state)
if flag[0] in ("--target", "--every-board")], [])
self.assertIn("Device: h700, named by the card", self.text(state))
def test_on_the_device_itself_it_says_this_device(self):
state = checked_state()
state.board_seen = ("retroarch", state.dest, "bcm2711", True, True)
state.stack.append("options")
self.assertIn("Device: bcm2711, this device", self.text(state))
def test_the_board_event_is_kept_across_checks(self):
state = checked_state()
state.run, state.running = "check", True
install.tui_receive(state, ("event", state.run_id, {
"event": "board", "platform": "retroarch", "board": "h700", "applied": True,
"message": "Board h700 found on the card (--every-board installs all boards)"}))
with mock.patch.object(install, "detect_board", return_value=None):
self.assertEqual(install._board_seen(state)[:2], ("h700", True))
install._start_run(state, "check")
self.assertEqual(install._board_seen(state)[:2], ("h700", True))
def test_another_board_and_every_board_set_their_flag(self):
state = device_state()
self.focus(state, "board", "bcm2711")
press(state, "enter")
self.assertIn(("--target", "bcm2711"), install.tui_flags(state))
self.assertIn("--target=bcm2711", install.tui_argv(state, "install", "py", "i.py"))
self.assertIn("Device: bcm2711", self.text(state))
# Back on the plan, counted again for the board.
self.assertEqual(press(state, "esc"), [("run", "check")])
state = device_state()
self.focus(state, "board", "")
press(state, "enter")
self.assertEqual([flag for flag in install.tui_flags(state)
if flag[0] in ("--target", "--every-board")],
[("--every-board", None)])
self.assertIn("Device: every board", self.text(state))
def test_with_no_board_read_every_board_is_the_choice(self):
state = device_state(board="")
self.assertEqual(install.tui_rows(state)[-1].label, "(x) Every board")
self.assertEqual(state.focus["device"], 3)
self.assertEqual([flag for flag in install.tui_flags(state)
if flag[0] in ("--target", "--every-board")], [])
# Chosen, it is said: a card put in the reader later names none.
press(state, "enter")
self.assertEqual([flag for flag in install.tui_flags(state)
if flag[0] in ("--target", "--every-board")],
[("--every-board", None)])
def test_a_board_list_that_cannot_be_read_is_said(self):
state = checked_state()
state.stack.append("options")
self.focus(state, "device")
press(state, "enter")
self.assertIn("Reading the board list...", self.text(state))
install.tui_receive(state, ("targets", "retroarch", None,
"The board list could not be read."))
self.assertIn("The board list could not be read.", self.text(state))
self.assertEqual(press(state, "esc"), [])
self.assertEqual(state.screen, "options")
def test_the_command_line_choice_is_the_one_shown(self):
args = _args(platform="retroarch", dest=SYSTEM_DIR, target="bcm2711",
emulator=["mesen"])
state, _effects = install.tui_start(args, "linux", detect=False)
self.assertEqual((state.target, state.emulators), ("bcm2711", ["mesen"]))
self.assertNotIn("--target", [flag for flag, _value in state.passthrough])
flags = install.tui_flags(state)
self.assertIn(("--target", "bcm2711"), flags)
self.assertIn(("--emulator", "mesen"), flags)
def test_emulators_ticked_are_the_emulator_flags(self):
state = checked_state()
state.stack.append("options")
self.focus(state, "emulators")
press(state, "enter")
self.assertEqual(state.screen, "emulators")
rows = install.tui_rows(state)
self.assertEqual([row.label for row in rows if row.action == "emulator"],
["[ ] mesen", "[ ] pcsx_rearmed"])
self.assertEqual(rows[state.focus["emulators"]].value, "mesen")
press(state, " ")
self.assertEqual(state.emulators, ["mesen"])
self.assertIn(("--emulator", "mesen"), install.tui_flags(state))
press(state, "n")
self.assertEqual(state.emulators, [])
press(state, " ", "esc")
self.assertEqual(state.screen, "options")
self.assertIn("Emulators: mesen", self.text(state))
def test_without_the_internet_sets_offline_for_the_runs(self):
state = checked_state()
state.stack.append("options")
self.focus(state, "offline")
with mock.patch.dict(os.environ, {}, clear=False):
os.environ.pop(install.OFFLINE_VARIABLE, None)
self.assertIn("Without the internet: no", self.text(state))
self.assertEqual(press(state, "enter"), [("offline", True)])
install.set_offline(True)
self.assertIn("Without the internet: yes", self.text(state))
self.assertIn(("--offline", None), install.tui_flags(state))
self.assertEqual(press(state, "left"), [("offline", False)])
install.set_offline(False)
self.assertNotIn(("--offline", None), install.tui_flags(state))
def test_from_a_pack_opens_the_browser_on_zips_and_reads_the_pack(self):
root = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, root, True)
(root / "Downloads").mkdir()
pack = root / "Downloads" / "RetroArch_BIOS_Pack.zip"
pack.write_bytes(b"PK")
(root / "Downloads" / "notes.txt").write_text("x")
state = checked_state()
state.home = root
state.stack.append("options")
self.focus(state, "pack")
press(state, "enter")
self.assertEqual((state.screen, state.browse_for), ("browse", "pack"))
rows = install.tui_rows(state)
self.assertNotIn("use", [row.action for row in rows])
self.assertEqual([row.label for row in rows if row.action == "zip"],
["RetroArch_BIOS_Pack.zip"])
self.focus(state, "zip")
self.assertIn("A/Enter Use this pack", self.text(state))
self.assertEqual(press(state, "enter"), [("pack", pack)])
# Refused: said, the browser stays.
install.tui_receive(state, ("pack_opened", pack, None, "Not a pack."))
self.assertEqual(state.screen, "browse")
self.assertIn("Not a pack.", self.text(state))
opened = mock.Mock()
effects = install.tui_receive(state, ("pack_opened", pack, opened, ""))
self.assertEqual(effects, [("use_pack", opened), ("fetch", "retroarch")])
self.assertEqual(state.packs, [pack])
self.assertIn(("--from-pack", str(pack)), install.tui_flags(state))
def test_open_tui_pack_refuses_another_platforms_pack(self):
root = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, root, True)
pack = root / "Batocera_BIOS_Pack.zip"
with zipfile.ZipFile(pack, "w") as archive:
archive.writestr("manifest.json", json.dumps({"platform": "batocera",
"files": []}))
previous = install.LOCAL.pack
opened, problem = install.open_tui_pack(pack, "retroarch")
self.assertIs(install.LOCAL.pack, previous)
self.assertIsNone(opened)
self.assertTrue(problem)
class DeviceAndEmulatorReview(unittest.TestCase):
"""The review of 2026-11-11: each finding, held."""
def setUp(self):
patcher = mock.patch.object(install, "_mounted_cards", return_value=[])
patcher.start()
self.addCleanup(patcher.stop)
@staticmethod
def focus(state: install.TuiState, action: str, value: object = None) -> None:
rows = install.tui_rows(state)
state.focus[state.screen] = next(
index for index, row in enumerate(rows)
if row.action == action and (value is None or row.value == value))
def text(self, state: install.TuiState) -> str:
return "\n".join(str(line) for line in install.tui_view(state, 80, 24))
def test_every_board_is_said_whatever_the_run_started_with(self):
for start in ({"target": "bcm2711"}, {"every_board": True}, {}):
with self.subTest(start=start):
state = device_state(board="")
state.target = start.get("target", "")
state.every_board = start.get("every_board", False)
self.focus(state, "board", "")
press(state, "enter")
self.assertEqual([flag for flag in install.tui_flags(state)
if flag[0] in ("--target", "--every-board")],
[("--every-board", None)])
# The board the run reads itself clears both.
state = device_state()
state.every_board = True
self.focus(state, "board", "h700")
press(state, "enter")
self.assertEqual((state.target, state.every_board), ("", False))
def test_a_board_list_that_failed_is_fetched_again(self):
state = checked_state()
state.stack.append("options")
self.focus(state, "device")
self.assertEqual(press(state, "enter"), [("targets", "retroarch")])
install.tui_receive(state, ("targets", "retroarch", None,
"The board list could not be read."))
self.assertIn("The board list could not be read.", self.text(state))
press(state, "esc")
self.assertEqual(press(state, "enter"), [("targets", "retroarch")])
self.assertIn("Reading the board list...", self.text(state))
def test_a_pack_is_read_only_once_the_screen_takes_it(self):
state = checked_state()
state.stack += ["options", "browse"]
state.browse_for = "pack"
pack = mock.Mock()
effects = install.tui_receive(state, ("pack_opened", Path("p.zip"), pack, ""))
self.assertEqual(effects[0], ("use_pack", pack))
# Left before it opened: closed, never read.
state = checked_state()
effects = install.tui_receive(state, ("pack_opened", Path("p.zip"), pack, ""))
self.assertEqual(effects, [("close_pack", pack)])
self.assertEqual(state.packs, [])
def test_open_tui_pack_leaves_the_run_s_pack_alone(self):
root = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, root, True)
pack = root / "RetroArch_BIOS_Pack.zip"
with zipfile.ZipFile(pack, "w") as archive:
archive.writestr("manifest.json", json.dumps({
"platform": "retroarch", "files": [
{"dest": "a.bin", "path": "a.bin", "sha1": "0" * 40, "size": 1}]}))
archive.writestr("a.bin", b"a")
previous = install.LOCAL.pack
opened, problem = install.open_tui_pack(pack, "retroarch")
self.addCleanup(lambda: opened is not None and opened.close())
self.assertEqual(problem, "", problem)
self.assertIsNotNone(opened)
self.assertIs(install.LOCAL.pack, previous)
def test_a_zip_that_is_no_pack_is_closed(self):
root = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, root, True)
notpack = root / "photos.zip"
with zipfile.ZipFile(notpack, "w") as archive:
archive.writestr("a.jpg", b"x")
opened = []
real = zipfile.ZipFile
def tracked(*args, **kwargs):
archive = real(*args, **kwargs)
opened.append(archive)
return archive
with mock.patch.object(install.zipfile, "ZipFile", side_effect=tracked), self.assertRaises(ValueError):
install.PackSource([notpack])
self.assertTrue(opened)
self.assertTrue(all(archive.fp is None for archive in opened))
def test_another_setup_drops_the_board_and_emulators(self):
state = checked_state()
state.target, state.every_board, state.emulators = "bcm2711", False, ["mesen"]
install._set_platform(state, "batocera")
self.assertEqual((state.target, state.every_board, state.emulators),
("", False, []))
state = checked_state()
state.target, state.emulators = "bcm2711", ["mesen"]
install._set_platform(state, "retroarch")
self.assertEqual((state.target, state.emulators), ("bcm2711", ["mesen"]))
def test_names_the_new_list_lacks_are_left_out_and_said(self):
state = checked_state()
state.emulators, state.target = ["mesen", "gone_core"], "nowhere"
state.targets, state.targets_for = dict(TARGETS), "retroarch"
install._known_choice(state, "retroarch", MANIFEST)
self.assertEqual((state.emulators, state.target), (["mesen"], ""))
self.assertEqual(state.status, "Left out, not in this list: --emulator gone_core, "
"--target nowhere.")
def test_page_up_and_home_never_rest_on_a_heading(self):
state = checked_state()
press(state, "o")
rows = install.tui_rows(state)
for start in (1, 6, len(rows) - 1):
for key in ("pgup", "home"):
with self.subTest(start=start, key=key):
state.focus["options"] = start
press(state, key)
self.assertEqual(state.focus["options"], 1)
def test_offline_is_refused_for_a_target_with_no_board_list_held(self):
state = checked_state()
state.target = "bcm2711"
state.stack.append("options")
self.focus(state, "offline")
with mock.patch.dict(os.environ, {}, clear=False):
os.environ.pop(install.OFFLINE_VARIABLE, None)
self.assertEqual(press(state, "enter"), [])
self.assertIn("Open Device once first", self.text(state))
state.targets, state.targets_for = dict(TARGETS), "retroarch"
self.assertEqual(press(state, "enter"), [("offline", True)])
def test_the_board_list_is_fetched_once_with_the_list_s_timeout(self):
inbox: queue.Queue = queue.Queue()
with mock.patch.object(install, "_fetch_json", return_value={}) as fetched, \
mock.patch.object(install, "held_targets", return_value=None):
install._tui_fetch_targets("retroarch", inbox)
self.assertEqual(fetched.call_args.kwargs["attempts"], 1)
self.assertEqual(fetched.call_args.kwargs["timeout"], install.TUI_FETCH_TIMEOUT)
self.assertEqual(inbox.get_nowait(), ("targets", "retroarch", {}, ""))
def test_a_board_list_refused_is_said_in_the_screen_s_words(self):
"""The screen showed the terminal line, "Error:" prefix and urllib
text included: "...: Error: failed to fetch targets for batocera:
HTTP Error 500: Internal Server Error"."""
inbox: queue.Queue = queue.Queue()
refused = install.urllib.error.HTTPError("u", 500, "Internal Server Error", {}, None)
with mock.patch.object(install, "_fetch_json", side_effect=refused), \
mock.patch.object(install, "held_targets", return_value=None), \
contextlib.redirect_stderr(io.StringIO()) as err:
install._tui_fetch_targets("batocera", inbox)
self.assertEqual(inbox.get_nowait(), (
"targets", "batocera", None,
"The board list could not be read: the server answered HTTP 500."))
self.assertEqual(err.getvalue(), "")
if __name__ == "__main__":
unittest.main()
+565
View File
@@ -0,0 +1,565 @@
"""The full screen's model: how it moves from screen to screen, its widgets, the
warnings of a plan and the text that fits."""
from __future__ import annotations
import tests
import os
import re
import shutil
import tempfile
import unittest
from pathlib import Path
from unittest import mock
import install
from tests.netguard import module_guard
from tests.tuisupport import (
_args, CHECK, checked_state, FILES, fresh_state, HOME, Key, listed, MANIFEST, option_focus,
PLAN, press, REPO_ROOT, SYSTEM_DIR,
)
# No connection off the loopback and no card of the host reaches a test,
# in this process or one it starts: the module fails at its end when one is tried.
setUpModule, tearDownModule = module_guard("test_tui_flow")
class Flow(unittest.TestCase):
"""update() on keys and events: what each choice starts and passes on."""
def test_three_presses_install_everything(self):
state = checked_state()
self.assertEqual(state.screen, "plan")
self.assertEqual(press(state, "enter"), [("run", "install")])
self.assertEqual(state.screen, "installing")
argv = install.tui_argv(state, "install", "py", "install.py")
self.assertEqual(argv, ["py", "install.py", "--platform=retroarch",
f"--dest={SYSTEM_DIR}", "--events", "--yes"])
for event in ({"event": "download", "platform": "retroarch", "files": 4,
"bytes": 1064964},
{"event": "downloaded", "dest": "gba_bios.bin", "ok": True, "reason": "",
"size": 16384, "files_done": 1, "files_total": 4,
"bytes_done": 16384, "bytes_total": 1064964},
{"event": "summary", "mode": "install", "installed": 4, "up_to_date": 1,
"pending": 0, "failed": [], "skipped": [], "left_out": [],
"kept": [], "interrupted": False}):
install.tui_receive(state, ("event", state.run_id, event))
install.tui_receive(state, ("ended", state.run_id, 0, []))
self.assertEqual(state.screen, "result")
press(state, "enter")
self.assertEqual(state.exit_code, 0)
def test_every_run_reads_the_folders_given_with_from(self):
"""--tui --from OLD: the check and the install both copy from OLD,
each folder named once."""
args = _args(**{"from": [Path("old-card"), Path("backup.zip")],
"from_pack": [Path("pack.zip")]})
with mock.patch.object(install, "_mounted_cards", return_value=[]), \
mock.patch.object(install, "detect_platforms", return_value=[]), \
mock.patch.object(install, "detect_frontends", return_value=[]):
started, _effects = install.tui_start(args, "linux")
state = checked_state()
state.passthrough = started.passthrough
state.from_folders = started.from_folders
state.packs = started.packs
for run in ("check", "install"):
argv = install.tui_argv(state, run, "py", "i.py")
for folder in ("old-card", "backup.zip"):
self.assertEqual(argv.count(f"--from={Path(folder).absolute()}"), 1, argv)
self.assertIn(f"--from-pack={Path('pack.zip').absolute()}", argv)
def test_the_check_runs_with_the_command_line_choices(self):
state = fresh_state()
state.passthrough = [("--target", "switch")]
state.cli_systems = ["psx"]
state.regions = ["north-america"]
state.platform, state.dest = "retroarch", SYSTEM_DIR
state.manifest, state.manifest_for = MANIFEST, "retroarch"
self.assertEqual(install._start_check(state), [("run", "check")])
self.assertEqual(install.tui_argv(state, "check", "py", "i.py")[4:], [
"--target=switch", "--system=psx", "--region=north-america",
"--check", "--events"])
def test_one_system_goes_through_the_dry_run(self):
state = checked_state()
press(state, "down", "enter")
self.assertEqual(state.screen, "systems")
self.assertEqual(state.ticked, {"nintendo-gba", "sony-playstation"})
self.assertEqual(install.tui_rows(state)[state.focus["systems"]].action, "system")
press(state, "n")
self.assertEqual(state.ticked, set())
focus = next(i for i, row in enumerate(install.tui_rows(state))
if row.value == "nintendo-gba")
state.focus["systems"] = focus
# A ticks the system in focus, B goes back to the plan, and Install
# there counts the choice first.
self.assertEqual(press(state, "enter", "esc"), [])
self.assertEqual(state.ticked, {"nintendo-gba"})
self.assertEqual(state.screen, "plan")
self.assertEqual(press(state, "enter"), [("run", "confirm")])
self.assertEqual(state.screen, "confirm")
self.assertIn("--system=nintendo-gba", install.tui_argv(state, "confirm", "py", "i.py"))
self.assertIn("--dry-run", install.tui_argv(state, "confirm", "py", "i.py"))
dry = {**CHECK, "files": 1, "present": 0, "missing": 1, "wrong_hash": 0,
"bytes_needed": 16384}
install.tui_receive(state, ("event", state.run_id, dry))
install.tui_receive(state, ("ended", state.run_id, 0, []))
self.assertEqual(state.screen, "confirm")
self.assertEqual(press(state, "enter"), [("run", "install")])
argv = install.tui_argv(state, "install", "py", "i.py")
self.assertEqual(argv[4:], ["--system=nintendo-gba", "--events", "--yes"])
def test_a_choice_that_changes_nothing_skips_the_confirmation(self):
state = checked_state()
state.jobs = 4
self.assertEqual(press(state, "enter"), [("run", "confirm")])
install.tui_receive(state, ("event", state.run_id, dict(CHECK)))
effects = install.tui_receive(state, ("ended", state.run_id, 0, []))
self.assertEqual(effects, [("run", "install")])
self.assertEqual(state.screen, "installing")
def test_options_set_the_flags_they_name(self):
state = checked_state()
press(state, "o")
self.assertEqual(state.screen, "options")
rows = install.tui_rows(state)
# Grouped by what each decides, a heading above each group.
self.assertEqual([row.right or row.label for row in rows], [
"What to install", "--region", "--core", "--emulator", "--no-game-data",
"Where", "--dest", "--from", "--from-pack",
"For which device", "--target", "--installed-cores",
"How", "--offline", "--jobs", "See", "--dry-run", "Show the command line"])
press(state, "enter")
self.assertEqual(state.screen, "regions")
# Ticked in the order of preference, then moved up.
regions = [row.value for row in install.tui_rows(state) if row.action == "region"]
self.assertEqual(regions, ["japan", "north-america"])
press(state, "enter", "down", "enter")
self.assertEqual(state.regions, ["japan", "north-america"])
press(state, "left")
self.assertEqual(state.regions, ["north-america", "japan"])
# The rank moves, the row stays where it is, under the focus.
self.assertEqual(state.focus["regions"], 1)
self.assertEqual([row.label for row in install.tui_rows(state)],
["[2] Japan", "[1] North America", "None", "Done"])
press(state, "shift-down")
self.assertEqual(state.regions, ["japan", "north-america"])
# Down passes the headings: Game data, Installed cores only, then
# Parallel downloads.
press(state, "esc", "down", "down", "down", "enter", *["down"] * 5, "right",
"down", "down", "right", "right")
self.assertTrue(state.no_game_data)
self.assertTrue(state.installed_only)
self.assertEqual(state.jobs, 10)
argv = install.tui_argv(state, "install", "py", "i.py")
self.assertEqual(argv[4:], ["--region=japan,north-america", "--no-game-data",
"--installed-cores", "--jobs=10", "--events", "--yes"])
self.assertIn("--region japan,north-america --no-game-data", install.tui_command(state))
def test_cores_checklist(self):
state = checked_state()
press(state, "o")
option_focus(state, "cores")
press(state, "enter")
self.assertEqual(state.screen, "cores")
self.assertEqual([row.value for row in install.tui_rows(state)
if row.action == "core"], ["mesen", "pcsx_rearmed"])
self.assertEqual(install.tui_rows(state)[state.focus["cores"]].value, "mesen")
# Every core ticked while none narrows the run: one untick keeps
# the others, ticked back it is every core again.
press(state, " ")
self.assertEqual(state.cores, ["pcsx_rearmed"])
press(state, "right")
self.assertEqual(state.cores, [])
press(state, "/", "p", "c")
self.assertEqual([row.value for row in install.tui_rows(state)
if row.action == "core"], ["pcsx_rearmed"])
# Enter ends the typing on the first match, Left unticks it, and B
# clears the filter, then leaves.
press(state, "enter", "left", "esc", "esc")
self.assertEqual(state.screen, "options")
self.assertEqual(install.tui_flags(state), [("--core", "mesen")])
def test_preview_is_a_dry_run(self):
state = checked_state()
press(state, "o")
option_focus(state, "preview")
self.assertEqual(press(state, "enter"), [("run", "preview")])
self.assertEqual(install.tui_argv(state, "preview", "py", "i.py")[-2:],
["--dry-run", "--events"])
for event in [*FILES, CHECK, PLAN]:
install.tui_receive(state, ("event", state.run_id, event))
install.tui_receive(state, ("ended", state.run_id, 0, []))
text = "\n".join(install.tui_view(state, 80, 24))
self.assertIn("4 files to download, 1.0 MB. Nothing is written.", text)
self.assertIn("wrong copy", text)
press(state, "esc")
self.assertEqual(state.screen, "options")
def test_back_and_quit(self):
state = fresh_state()
press(state, "esc")
self.assertEqual(state.screen, "quit")
press(state, "esc")
self.assertEqual(state.screen, "setup")
press(state, "esc", "enter")
self.assertEqual(state.exit_code, install.QUIT_CODE)
state = checked_state()
self.assertEqual(press(state, "q"), [])
self.assertEqual(state.exit_code, install.QUIT_CODE)
def test_ctrl_c_stops_an_install_once_then_kills(self):
state = checked_state()
press(state, "enter")
self.assertEqual(press(state, "ctrl-c"), [("stop",)])
self.assertTrue(state.stopping)
self.assertEqual(press(state, "ctrl-c"), [("kill",)])
summary = {"event": "summary", "mode": "install", "installed": 1, "up_to_date": 1,
"pending": 3, "failed": [], "skipped": [], "left_out": [], "kept": [],
"interrupted": True}
install.tui_receive(state, ("event", state.run_id,
{"event": "download", "platform": "retroarch",
"files": 4, "bytes": 1064964}))
install.tui_receive(state, ("event", state.run_id, summary))
install.tui_receive(state, ("ended", state.run_id, 130, []))
title, lines = install.tui_outcome(state)
self.assertEqual(title, "Stopped")
self.assertEqual(lines[0], "Stopped: 1 of 4 installed, run again to finish.")
press(state, "enter")
self.assertEqual(state.exit_code, 130)
def test_back_from_the_check_stops_it(self):
state = fresh_state()
with mock.patch.object(install.Path, "exists", return_value=True):
press(state, "enter")
install.tui_receive(state, ("manifest", "retroarch", MANIFEST))
self.assertTrue(state.running)
self.assertEqual(press(state, "esc"), [("kill",)])
self.assertEqual(state.screen, "setup")
install.tui_receive(state, ("ended", state.run_id - 1, 1, []))
self.assertEqual(state.screen, "setup")
def test_ctrl_c_elsewhere_ends_at_once(self):
state = fresh_state()
self.assertEqual(press(state, "ctrl-c"), [])
self.assertEqual(state.exit_code, 130)
state = checked_state()
state.running = True
self.assertEqual(press(state, "ctrl-d"), [("kill",)])
def test_the_folder_path(self):
state = fresh_state()
press(state, "down", "down", "enter")
self.assertEqual(state.screen, "platforms")
self.assertEqual(install.tui_rows(state)[state.focus["platforms"]].value, "retroarch")
press(state, "/", "b", "a", "t", "o")
self.assertEqual([row.value for row in install.tui_rows(state)][1:], ["batocera"])
# the one match is chosen with the first Enter.
press(state, "enter")
self.assertEqual(state.screen, "folder")
self.assertEqual(state.platform, "batocera")
state.focus["folder"] = 2
press(state, "enter")
self.assertEqual(state.screen, "path")
state.path_text = ""
press(state, "paste")
install.tui_update(state, Key("paste", '"~/my bios"'))
# Two missing levels are asked, Choose another folder in focus.
with mock.patch.object(install, "missing_folder",
return_value=install.MissingFolder(HOME, 2, "ask")):
press(state, "enter")
self.assertEqual(state.screen, "create")
self.assertEqual(state.dest, Path(os.path.expanduser("~/my bios")))
press(state, "enter")
self.assertEqual(state.screen, "folder")
def test_typed_paths(self):
with mock.patch.dict(os.environ, {"CARD": "/media/sd"}):
self.assertEqual(install.typed_path(' "$CARD/Bios" '), Path("/media/sd/Bios"))
self.assertEqual(install.typed_path("'C:\\RetroBat\\bios'"), Path("C:\\RetroBat\\bios"))
self.assertIsNone(install.typed_path('""'))
def test_the_browser_lists_folders_and_goes_up(self):
root = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, root, True)
for name in ("system", ".config", "Bios"):
(root / name).mkdir()
(root / "file.bin").write_bytes(b"")
state = fresh_state()
state.platform = "retroarch"
state.stack = ["folder"]
state.folder_default = root / "system"
with mock.patch.object(install, "_mounted_cards", return_value=[]):
press(state, "down", "enter")
self.assertEqual(state.screen, "browse")
self.assertEqual(state.browse_dir, root / "system")
self.assertEqual([row.label for row in install.tui_rows(state)],
["Use this folder", ".."])
press(state, "down", "enter")
self.assertEqual(state.browse_dir, root)
labels = [row.label for row in install.tui_rows(state)]
self.assertEqual(labels, ["Use this folder", "..", "Bios/", "system/", ".config/"])
self.assertEqual(install.tui_rows(state)[state.focus["browse"]].label, "system/")
effects = press(state, "home", "enter")
self.assertEqual(effects, [("fetch", "retroarch")])
self.assertEqual(state.dest, root)
def test_a_holds_no_bios_folder_root_never_takes_a(self):
"""With no usual folder the browser opens at HOME, on Use this
folder: A five times installed the BIOS files into ~. At HOME or a
drive's root, A goes into the first folder instead."""
home = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, home, True)
(home / "Games").mkdir()
state = install.TuiState(os_type="linux", home=home)
state.platform = "retroarch"
state.stack = ["folder"]
state.folder_default = None
with mock.patch.object(install, "_mounted_cards", return_value=[]):
install._browse_to(state, home)
self.assertEqual(state.browse_rows[state.focus["browse"]].label, "Games/")
install._browse_to(state, home / "Games")
self.assertEqual(state.browse_rows[state.focus["browse"]].label,
"Use this folder")
install._browse_to(state, Path(home.anchor))
self.assertNotEqual(state.browse_rows[state.focus["browse"]].action, "use")
def test_cards_are_listed_first(self):
card = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, card, True)
(card / ".system").mkdir()
(card / ".system" / "version.txt").write_text("NextUI-20250101\n")
with mock.patch.object(install, "_mounted_cards", return_value=[card]):
rows, error = install._browse_rows(REPO_ROOT / "tests")
self.assertEqual(error, "")
self.assertEqual(rows[2].label, f"{card} (NextUI card)")
def test_a_mounted_card_is_a_setup_of_its_own(self):
card = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, card, True)
(card / ".system").mkdir()
(card / ".system" / "version.txt").write_text("MinUI-20250101\n")
with mock.patch.object(install, "_mounted_cards", return_value=[card]), \
mock.patch.object(install, "detect_platforms", return_value=[]), \
mock.patch.object(install, "detect_frontends", return_value=[]):
state, effects = install.tui_start(_args(), "linux")
# The one setup found: its plan first, the list one Back away.
self.assertEqual((state.screen, effects), ("checking", [("fetch", "minui")]))
self.assertEqual(listed(state).screen, "setup")
label = f"MinUI SD card ({card.name})"
self.assertEqual(state.setups, [("minui", card, label)])
self.assertEqual([row.label for row in install.tui_rows(state)],
[label, "Another setup or folder"])
def test_an_error_offers_another_try(self):
state = fresh_state()
with mock.patch.object(install.Path, "exists", return_value=True):
press(state, "enter")
install.tui_receive(state, ("manifest_failed", "retroarch", "No connection",
[" Could not fetch the file list for retroarch", ""], 1))
self.assertIn("RetroBIOS: No connection", install.tui_view(state, 80, 24)[0])
self.assertEqual(state.screen, "error")
self.assertEqual([row.action for row in install.tui_rows(state)],
["retry", "elsewhere", "quit"])
self.assertEqual(press(state, "enter"), [("fetch", "retroarch")])
install.tui_receive(state, ("manifest_failed", "retroarch", "No connection", ["no"], 1))
press(state, "down", "down", "enter")
self.assertEqual(state.exit_code, 1)
def test_a_check_that_writes_no_check_event_is_an_error(self):
state = fresh_state()
state.platform, state.dest = "retroarch", SYSTEM_DIR
state.manifest, state.manifest_for = MANIFEST, "retroarch"
install._start_check(state)
install.tui_receive(state, ("ended", state.run_id, 1,
["Error: /x is inside a NextUI card."]))
self.assertEqual(state.screen, "error")
self.assertEqual(state.error, ["Error: /x is inside a NextUI card."])
def test_events_of_an_abandoned_run_are_ignored(self):
state = checked_state()
press(state, "o")
option_focus(state, "preview")
press(state, "enter")
old = state.run_id
self.assertEqual(press(state, "esc"), [("kill",)])
install.tui_receive(state, ("event", old, dict(CHECK)))
install.tui_receive(state, ("ended", old, 0, []))
self.assertIsNone(state.dry)
self.assertEqual(state.screen, "options")
def test_help_and_a_small_window(self):
state = fresh_state()
press(state, "?")
self.assertTrue(state.help)
self.assertIn("Any key closes", install.tui_view(state, 80, 24)[-1])
press(state, "down")
self.assertFalse(state.help)
self.assertEqual(state.focus.get("setup", 0), 0)
state.cols, state.rows = 30, 10
press(state, "enter")
self.assertEqual(state.screen, "setup")
lines = install.tui_view(state, 30, 10)
self.assertEqual([line.strip() for line in lines if line.strip()],
["Make the window larger:", "40x12 or more, now 30x10"])
self.assertEqual(len(install.tui_view(state, 39, 1)), 1)
self.assertEqual(install.tui_view(state, 30, 0), [])
class PlanWarnings(unittest.TestCase):
def test_a_folder_that_cannot_take_the_files_says_so_first(self):
state = checked_state({"free": 1024, "writable": False, "cores": []})
text = " ".join(install.tui_view(state, 120, 40))
self.assertIn("Not enough free space: 1.0 MB needed.", text)
self.assertIn("This folder cannot be written to: choose another one.", text)
# sudo changes the home folder: the advice names this one.
self.assertIn("Or run it as root, this folder named: sudo python3 install.py "
f"--platform retroarch --dest {SYSTEM_DIR}",
" ".join(text.replace(" \\", "").split()))
rows = install.tui_rows(state)
self.assertEqual([row.action for row in rows[:2]], ["folder", "install"])
self.assertEqual(state.focus.get("plan", 0), 0)
self.assertEqual(press(state, "enter"), [])
self.assertEqual(state.screen, "folder")
self.assertNotIn("--installed-cores", [row.right for row in install._option_rows(state)])
class Widgets(unittest.TestCase):
def systems_state(self, count: int) -> install.TuiState:
state = checked_state()
state.systems = [{"event": "system", "system": f"system-{n:03d}", "name": f"s{n}",
"files": 1, "present": 0, "missing": 1, "wrong_hash": 0,
"bytes_needed": 10} for n in range(count)]
state.ticked = {row["system"] for row in state.systems}
state.stack.append("systems")
return state
def test_a_long_list_scrolls_and_says_where(self):
state = self.systems_state(112)
press(state, "end")
lines = install.tui_view(state, 40, 15)
self.assertIn("> Done", "\n".join(lines))
self.assertIn("[x] system-111", "\n".join(lines))
# The Filter, All, None and Done rows are not counted among the systems.
self.assertTrue(any(re.fullmatch(r" \d+-112 of 112", line) for line in lines), lines)
press(state, "pgup")
self.assertLess(state.focus["systems"], 114)
press(state, "home")
self.assertEqual(state.focus["systems"], 0)
def test_up_wraps_only_in_short_menus(self):
state = fresh_state()
press(state, "up")
self.assertEqual(state.focus["setup"], 2)
state = fresh_state()
state.stack = ["setup", "platforms"]
press(state, "up")
self.assertEqual(state.focus["platforms"], 0)
# A list of ticks wraps at any length: None and Done, at its end,
# are a few presses up from its first item.
state = self.systems_state(20)
state.focus["systems"] = 0
press(state, "up")
self.assertEqual(install.tui_rows(state)[state.focus["systems"]].action, "done")
def test_filter_ignores_case_and_accents(self):
state = self.systems_state(3)
state.systems.append({"system": "sega-genesis", "name": "Mégadrive", "files": 1,
"present": 0, "missing": 1, "wrong_hash": 0,
"bytes_needed": 3})
press(state, "/", "M", "E", "G")
self.assertEqual([row.value for row in install.tui_rows(state)
if row.action == "system"], ["sega-genesis"])
press(state, "esc")
self.assertEqual(state.filters["systems"], "")
self.assertEqual(state.screen, "systems")
press(state, "/", "z", "z", "enter")
self.assertIn("No system matches 'zz'.", "\n".join(install.tui_view(state, 80, 24)))
# Esc clears a kept filter first, and goes back only then.
press(state, "esc")
self.assertEqual((state.screen, state.filters["systems"]), ("systems", ""))
press(state, "esc")
self.assertEqual(state.screen, "plan")
def test_all_and_none(self):
state = self.systems_state(5)
press(state, "n")
self.assertEqual(state.ticked, set())
press(state, "a")
self.assertEqual(len(state.ticked), 5)
state.focus["systems"] = next(i for i, row in enumerate(install.tui_rows(state))
if row.action == "none")
# X on None does nothing: only A, an explicit choice, unticks all.
press(state, " ")
self.assertEqual(len(state.ticked), 5)
press(state, "enter")
self.assertEqual(state.ticked, set())
def test_running_total_counts_each_file_once(self):
state = checked_state()
state.stack.append("systems")
state.files.append({"event": "file", "dest": "shared.bin", "size": 1024 * 1024,
"systems": ["nintendo-gba", "sony-playstation"],
"state": "missing"})
footer = install.tui_view(state, 80, 24)[-2]
self.assertEqual(footer.strip(), "2 of 3 systems: 5 files, 2.0 MB")
state.ticked = {"nintendo-gba"}
footer = install.tui_view(state, 80, 24)[-2]
self.assertEqual(footer.strip(), "1 of 3 systems: 2 files, 1.0 MB")
class TextThatFits(unittest.TestCase):
"""A pack's name cut in a
command, folder lines at two indents, the 40x12 plan dropping the
version note, and the --from plan without its kinds."""
def test_a_pack_path_keeps_its_name_whole(self):
pack = "/home/user/Downloads/RetroArch_BIOS_Pack.zip"
text = ("curl -fsSL https://abdess.github.io/retrobios/i | sh -s -- --platform "
f"retroarch --dest /media/moi/ONION/BIOS --from-pack {pack} --offline")
for width in (38, 50, 78):
with self.subTest(width=width), \
mock.patch.dict(os.environ, {"RETROBIOS_BOOTSTRAP": "sh"}):
lines = install._command_wrap(text, width)
joined = " ".join(lines)
self.assertIn("RetroArch_BIOS_Pack.zip", joined)
self.assertNotRegex(joined, r"\.\.\.[^/ ]*Pack\.zip")
for line in lines:
self.assertLessEqual(install.cell_width(line), width, line)
def test_a_folder_on_its_own_line_keeps_one_indent(self):
base = "/home/me/very/long/folder/names/for/an/android/storage/RetroArch"
items = [f"BIOS folder: {base}/system",
"1 file read from RetroArch's save directory goes to a folder per core:",
f" {base}/saves"]
for width in (38, 70, 78):
for whole in (False, True):
with self.subTest(width=width, whole=whole):
lines = [str(line) for line in install._text_lines(items, width, whole)]
folders = [line for line in lines if "/" in line
and not line.startswith("BIOS folder:")]
self.assertTrue(folders)
for line in folders:
self.assertEqual(len(line) - len(line.lstrip(" ")), 2, lines)
def test_the_40x12_plan_keeps_the_version_note(self):
state = checked_state()
state.dest = Path("/home/moi/retroarch_system/tmp/tui_audit15/rb2/bios")
install.tui_receive(state, ("event", state.run_id, {
"event": "version", "platform": "retroarch", "list_version": "1.22.2",
"installed_version": "1.21.0",
"message": "This list was built for RetroArch 1.22.2, this machine runs 1.21.0. "
"Some files may differ from what this version reads."}))
state.run = "check"
narrow = " ".join(" ".join(str(line).split())
for line in install.tui_view(state, 40, 12))
self.assertIn("List for RetroArch 1.22.2, this is 1.21.0.", narrow)
self.assertIn("BIOS folder:", narrow)
wide = " ".join(" ".join(str(line).split()) for line in install.tui_view(state, 80, 24))
self.assertIn("This list was built for RetroArch 1.22.2, this machine runs 1.21.0.", wide)
if __name__ == "__main__":
unittest.main()
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+985
View File
@@ -0,0 +1,985 @@
"""The terminal and its input: when the screen can open, the keys, the pad
routes, Windows without the POSIX modules, terminals the screen cannot draw,
the idle exit and the terminal given back after a crash."""
from __future__ import annotations
import tests
import contextlib
import errno
import fcntl
import io
import os
import re
import shutil
import struct
import sys
import tempfile
import termios
import time
import types
import unittest
from pathlib import Path
from unittest import mock
import install
from tests.netguard import module_guard
from tests.tuisupport import (
_args, CHECK, checked_state, FILES, fresh_state, GOLDEN, golden_states, install_run, Key, press,
REPO_ROOT, ROUTES, SIZES, SYSTEM_DIR, _terminfo_entry, _terminfo_folder, WindowsOs,
)
# No connection off the loopback and no card of the host reaches a test,
# in this process or one it starts: the module fails at its end when one is tried.
setUpModule, tearDownModule = module_guard("test_tui_terminal")
try:
from hypothesis import given, settings
from hypothesis import strategies as st
except ImportError:
given = None
def keys(*names: str) -> list:
return [Key("char", name[5:]) if name.startswith("char:") else Key(name) for name in names]
class KeyDecoding(unittest.TestCase):
def feed(self, *chunks: str, flush: bool = True) -> list:
decoder = install.KeyDecoder()
found = []
for chunk in chunks:
found += decoder.feed(chunk)
if flush:
found += decoder.flush()
return found
def test_every_key_of_the_table(self):
table = {
"\x1b[A": "up", "\x1b[B": "down", "\x1b[C": "right", "\x1b[D": "left",
"\x1bOA": "up", "\x1bOB": "down", "\x1bOC": "right", "\x1bOD": "left",
"\x1b[5~": "pgup", "\x1b[6~": "pgdn", "\x1b[H": "home", "\x1b[F": "end",
"\x1b[1~": "home", "\x1b[4~": "end", "\x1b[7~": "home", "\x1b[8~": "end",
"\x1bOH": "home", "\x1bOF": "end", "\x1bOP": "f1", "\x1b[11~": "f1",
"\x1b[1;2A": "shift-up", "\x1b[1;2B": "shift-down", "\x1b[3~": "delete",
"\r": "enter", "\n": "enter", "\x1bOM": "enter", "\x7f": "backspace",
"\x08": "backspace", "\t": "tab", "\x03": "ctrl-c", "\x04": "ctrl-d",
"\x1b": "esc",
}
for sequence, name in table.items():
with self.subTest(sequence=sequence):
self.assertEqual(self.feed(sequence), [Key(name)])
def test_text_keys(self):
self.assertEqual(self.feed("q /?jké"), keys("char:q", "char: ", "char:/", "char:?",
"char:j", "char:k", "char:é"))
def test_two_arrows_in_one_read_are_two_moves(self):
self.assertEqual(self.feed("\x1b[B\x1b[B"), keys("down", "down"))
def test_a_sequence_split_across_reads_is_one_key(self):
for cut in range(1, 4):
with self.subTest(cut=cut):
sequence = "\x1b[5~"
self.assertEqual(self.feed(sequence[:cut], sequence[cut:]), keys("pgup"))
def test_esc_waits_for_the_rest_then_stands_alone(self):
decoder = install.KeyDecoder()
self.assertEqual(decoder.feed("\x1b"), [])
self.assertTrue(decoder.waiting)
self.assertEqual(decoder.flush(), keys("esc"))
self.assertFalse(decoder.waiting)
def test_esc_then_a_letter(self):
self.assertEqual(self.feed("\x1bq"), keys("esc", "char:q"))
self.assertEqual(self.feed("\x1b\x1b[A"), keys("esc", "up"))
def test_unknown_sequences_are_dropped_not_typed(self):
for sequence in ("\x1b[25~", "\x1b[1;5A", "\x1b[M !!", "\x1b[<0;10;5M", "\x1b[?1;2c",
"\x1bOZ"):
with self.subTest(sequence=sequence):
# A mouse report is a report (MouseReports), never typed.
self.assertEqual([key for key in self.feed(sequence + "x")
if key.name != "mouse"], keys("char:x"))
def test_an_incomplete_sequence_is_dropped_at_the_timeout(self):
self.assertEqual(self.feed("\x1b[1"), [])
def test_a_paste_is_one_piece_without_its_newlines(self):
self.assertEqual(self.feed("\x1b[200~/media/sd\ncard\r\n\x1b[201~"),
[Key("paste", "/media/sdcard")])
self.assertEqual(self.feed("\x1b[200~/a/b\x1b[2", "01~\r"),
[Key("paste", "/a/b"), Key("enter")])
def test_controls_nobody_bound_are_ignored(self):
self.assertEqual(self.feed("\x00\x1cx"), keys("char:x"))
# Ctrl-Z is a key once ISIG is off: the run stops on it, as on SIGTSTP.
self.assertEqual(self.feed("\x1a"), [Key("ctrl-z")])
def test_windows_scan_codes(self):
for prefix in ("\x00", "\xe0"):
for code, name in (("H", "up"), ("P", "down"), ("K", "left"), ("M", "right"),
("I", "pgup"), ("Q", "pgdn"), ("G", "home"), ("O", "end"),
(";", "f1")):
with self.subTest(prefix=prefix, code=code):
pending = iter([code])
self.assertEqual(install.decode_windows_key(prefix, pending.__next__),
Key(name))
unread = iter(())
for char, name in (("\r", "enter"), ("\x1b", "esc"), ("\x08", "backspace"),
("\x03", "ctrl-c"), ("\t", "tab")):
self.assertEqual(install.decode_windows_key(char, unread.__next__), Key(name))
self.assertEqual(install.decode_windows_key("a", unread.__next__), Key("char", "a"))
self.assertIsNone(install.decode_windows_key("\xe0", iter(["\x86"]).__next__))
@unittest.skipUnless(given, "the decoder fuzz needs hypothesis")
def test_any_input_decodes_the_same_however_it_is_split(self):
alphabet = st.sampled_from(["\x1b", "[", "O", "A", "B", "5", "~", "1", ";", "2",
"200~", "201~", "\r", "x", "M", "\x03", "<", " "])
@settings(max_examples=400, deadline=None)
@given(st.lists(alphabet, max_size=30), st.data())
def check(parts, data):
text = "".join(parts)
whole = self.feed(text)
cuts = sorted(data.draw(st.lists(st.integers(0, len(text)), max_size=5)))
chunks = [text[a:b] for a, b in zip([0, *cuts], [*cuts, len(text)])]
self.assertEqual(self.feed(*chunks), whole)
for key in whole:
if key.name == "char":
self.assertNotEqual(key.text, "\x1b")
check()
class TextWidth(unittest.TestCase):
def test_wide_and_combining_characters(self):
self.assertEqual(install.cell_width("PlayStation"), 11)
self.assertEqual(install.cell_width("ファミコン"), 10)
self.assertEqual(install.cell_width("e\u0301"), 1)
def test_fit_never_cuts_a_character(self):
self.assertEqual(install.fit("ファミコン", 5), "ファ")
self.assertEqual(install.cell_width(install.fit("aファ", 2)), 1)
def test_middle_keeps_both_ends(self):
path = "/run/media/user/SDCARD/Bios/PS"
cut = install.middle(path, 20)
self.assertEqual(install.cell_width(cut), 20)
self.assertTrue(cut.startswith("/run/med"))
self.assertTrue(cut.endswith("Bios/PS"))
self.assertIn("...", cut)
self.assertEqual(install.middle("short", 20), "short")
class StartConditions(unittest.TestCase):
class _Tty(io.StringIO):
def __init__(self, fd: int) -> None:
super().__init__()
self.fd = fd
def isatty(self) -> bool:
return True
def fileno(self) -> int:
return self.fd
def setUp(self):
self.master, self.slave = os.openpty()
self.addCleanup(os.close, self.master)
self.addCleanup(os.close, self.slave)
self.size(80, 24)
self.tty = self._Tty(self.slave)
def size(self, cols: int, rows: int) -> None:
fcntl.ioctl(self.slave, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))
def blocker(self, env=None, **given) -> str:
return install.tui_blocker(_args(**given), self.tty, self.tty,
{"TERM": "xterm"} if env is None else env)
def test_an_install_at_a_terminal_opens_it(self):
self.assertEqual(self.blocker(), "")
self.assertEqual(self.blocker(platform="retroarch", system=["x"], region=["us"]), "")
def test_flags_that_keep_the_line_questions(self):
for flag in ("check", "dry_run", "list_platforms", "list_targets", "list_systems",
"list_cores", "list_emulators", "events", "quiet", "no_input", "yes"):
with self.subTest(flag=flag):
self.assertIn("runs without questions", self.blocker(**{flag: True}))
self.assertIn("--restore", self.blocker(restore=Path("x")))
def test_dumb_or_missing_term(self):
self.assertIn("TERM", self.blocker(env={"TERM": "dumb"}))
self.assertIn("TERM", self.blocker(env={}))
def test_not_a_terminal(self):
args = _args()
self.assertIn("input", install.tui_blocker(args, io.StringIO(), self.tty,
{"TERM": "xterm"}))
self.assertIn("output", install.tui_blocker(args, self.tty, io.StringIO(),
{"TERM": "xterm"}))
def test_too_small_and_unsized(self):
self.size(39, 30)
self.assertIn("39x30", self.blocker())
# script(1) fed from a pipe never sizes its terminal.
self.size(0, 0)
self.assertIn("0x0", self.blocker())
def test_a_windows_console_without_escape_sequences(self):
# Legacy conhost, PowerShell ISE: no virtual terminal, the questions run.
with mock.patch.dict(sys.modules, {"msvcrt": mock.Mock()}), \
mock.patch.object(install.os, "name", "nt"), \
mock.patch.object(install, "_enable_ansi", return_value=False):
self.assertIn("escape sequences", self.blocker(env={}))
with mock.patch.dict(sys.modules, {"msvcrt": mock.Mock()}), \
mock.patch.object(install.os, "name", "nt"), \
mock.patch.object(install, "_enable_ansi", return_value=True):
self.assertEqual(self.blocker(env={}), "")
def test_plain_mode(self):
self.assertTrue(install.plain_requested(_args(plain=True), {}))
self.assertTrue(install.plain_requested(_args(), {"RETROBIOS_PLAIN": "1"}))
self.assertTrue(install.plain_requested(_args(), {"ACCESSIBLE": "1"}))
self.assertFalse(install.plain_requested(_args(), {"ACCESSIBLE": "0",
"RETROBIOS_PLAIN": ""}))
def test_tui_refused_with_a_reason(self):
for extra, message in ((["--check"], "--check runs without questions"),
(["--plain"], "two different interfaces"),
([], "not a terminal")):
with self.subTest(extra=extra):
proc = install_run("--tui", *extra)
self.assertEqual(proc.returncode, 2)
self.assertIn(message, proc.stderr)
self.assertNotIn("\x1b", proc.stdout + proc.stderr)
def _bar_keys(line: str) -> set:
"""The key each entry of a hint bar names: its first word."""
return {part.split(" ", 1)[0] for part in line.strip().split(" ") if part}
# The keys each route has, as the bar may name them. "Any" opens "Any key
# closes this help", <> and ^v are the narrow forms of Left/Right, Up/Down.
ROUTE_KEYS = {
"keys": {"Enter", "Esc", "Space", "o", "?", "/", "Ctrl-C", "Ctrl-U", "PgUp/PgDn"},
"gptokeyb": {"A", "B", "X", "Y", "Select+Start", "L1/R1"},
"gptokeyb_muxterm": {"A", "B", "X", "Y", "Select+Start", "D-pad"},
"evmapy": {"A", "B", "X", "Y", "L1/R1"},
"muxterm": {"Start", "B", "Y", "Menu", "Select", "D-pad"},
"miyoo": {"A", "Start", "R2", "L2", "L1/R1"},
}
EVERY_ROUTE_HAS = {"Left/Right", "Up/Down", "<>", "^v", "Any"}
class PadRoutes(unittest.TestCase):
"""The bar names the buttons the launcher maps, and a desktop's keys."""
def test_the_route_from_the_environment(self):
route = install.tui_pad_route
for value in install.TUI_PAD_ROUTES:
self.assertEqual(route("linux", {"RETROBIOS_PAD": value, "DISPLAY": ":0"}), value)
self.assertEqual(route("linux", {"RETROBIOS_PAD": " MiYoo "}), "miyoo")
self.assertEqual(route("linux", {"RETROBIOS_PAD": "dualshock"}), "both")
for os_type in ("windows", "darwin", "wsl"):
self.assertEqual(route(os_type, {}), "keys", os_type)
for env in ({"DISPLAY": ":0", "TERM": "xterm-256color"}, {"WAYLAND_DISPLAY": "w-0"},
{"SSH_CONNECTION": "10.0.0.2 5 10.0.0.3 22"}, {"SSH_TTY": "/dev/pts/1"}):
self.assertEqual(route("linux", env), "keys", env)
# SteamOS game mode and anything Steam starts: Steam Input may be
# all there is. A console with nothing named, or Android: unknown.
for os_type, env in (("linux", {"SteamGamepadUI": "1", "DISPLAY": ":0"}),
("linux", {"GAMESCOPE_WAYLAND_DISPLAY": "gamescope-0",
"WAYLAND_DISPLAY": "w-0"}),
("windows", {"SteamGameId": "123"}),
("linux", {"SteamDeck": "1", "DISPLAY": ":0"}),
("linux", {"TERM": "linux", "SSH_TTY": "/dev/pts/0"}),
("linux", {"TERM": "linux"}), ("linux", {}),
("android", {"DISPLAY": ":0"})):
self.assertEqual(route(os_type, env), "both", env)
def test_the_launchers_values_are_the_routes(self):
tui = (REPO_ROOT / "ports" / "shared" / "tui.txt").read_text(encoding="utf-8")
named = set(re.findall(r'RB_PAD="(\w+)"', tui))
for launcher in REPO_ROOT.glob("ports/*/*.sh"):
named |= set(re.findall(r'RB_PAD="(\w+)"', launcher.read_text(encoding="utf-8")))
self.assertLessEqual(named, set(install.TUI_PAD_ROUTES))
self.assertEqual(set(ROUTES) - {"keys"}, set(install.TUI_PAD_ROUTES))
def test_the_plan_bar_of_each_route(self):
expected = {
"both": "A/Enter Install B/Esc Back Y/o Change ? Help",
"keys": "Enter Install Esc Back o Change ? Help",
"gptokeyb": "A Install B Back Y Change",
"evmapy": "A Install B Back Y Change",
"muxterm": "Start Install B Back",
"miyoo": "A Install R2 Back L2 Change",
}
for route, bar in expected.items():
with self.subTest(route=route):
state = checked_state()
state.pad = route
self.assertEqual(install.tui_view(state, 80, 24)[-1].strip(), bar)
def test_no_bar_names_a_key_its_route_lacks(self):
for route, have in ROUTE_KEYS.items():
for name, state in golden_states().items():
state.pad = route
for cols, rows in SIZES:
with self.subTest(route=route, screen=name, size=f"{cols}x{rows}"):
state.cols, state.rows = cols, rows
bar = install.tui_view(state, cols, rows)[-1]
self.assertLessEqual(_bar_keys(bar) - EVERY_ROUTE_HAS, have, bar)
def test_the_install_says_what_stops_it_there(self):
expected = {
"both": "B, Ctrl-C or Select+Start stops.", "keys": "Esc or Ctrl-C stops.",
"gptokeyb": "B or Select+Start stops.", "evmapy": "B stops.",
"muxterm": "B stops.", "miyoo": "R2 stops.",
}
for route, words in expected.items():
with self.subTest(route=route):
state = golden_states()["installing"]
state.pad = route
text = "\n".join(install.tui_view(state, 80, 24))
self.assertIn(f"{words} What is done stays done.", text)
state.stopping = True
again = {"both": "B or Ctrl-C", "keys": "Esc or Ctrl-C", "miyoo": "R2"}
self.assertIn(f"Press {again.get(route, 'B')} again to stop now.",
" ".join(" ".join(install.tui_view(state, 80, 24)).split()))
def test_the_help_lists_the_buttons_and_the_keys(self):
def help_text(route: str, screen: str = "plan") -> str:
state = golden_states()[screen]
state.pad, state.help = route, True
return "\n".join(line.rstrip() for line in install.tui_view(state, 80, 24))
gptk = help_text("gptokeyb")
for words in ("D-pad, Up/Down", "A, Start, Enter", "B, Select, Esc", "Y, Tab, o",
"Select, then Start", "Quit at once", "q, Ctrl-C"):
self.assertIn(words, gptk)
self.assertNotIn("Select+Start", help_text("evmapy"))
keys = help_text("keys")
for words in ("Enter", "Esc, Backspace", "o, Tab"):
self.assertIn(words, keys)
for button in ("A/Enter", "B/Esc", "L1", "Start", "Y,"):
self.assertNotIn(button, keys)
muxterm = help_text("muxterm")
for words in ("Start, Enter", "B, Esc, Backspace", "Keyboard on or off",
"Close the terminal"):
self.assertIn(words, muxterm)
self.assertNotIn("Select+Start", muxterm)
# gptokeyb2 owns the pad inside muxterm, which keeps PgUp and PgDn
# for its scrollback: the gptokeyb buttons, Left and Right to page.
in_muxterm = help_text("gptokeyb_muxterm", "preview")
for words in ("A, Start, Enter", "Select, then Start"):
self.assertIn(words, in_muxterm)
self.assertNotIn("L1/R1", in_muxterm)
self.assertIn("L1/R1", help_text("gptokeyb", "preview"))
# muxterm keeps PgUp and PgDn for its scrollback, and L1 and R1
# send nothing: the D-pad's Left and Right page there instead.
for screen in ("systems", "result", "plan"):
with self.subTest(screen=screen):
text = help_text("muxterm", screen)
for words in ("L1", "R1", "PgUp", "PgDn"):
self.assertNotIn(words, text)
self.assertIn("D-pad Left/Right Page", help_text("muxterm", "result"))
miyoo = help_text("miyoo", "systems")
for words in ("Start, Enter", "A, Space, Right/Left", "R2, Esc, Backspace",
"L2, Tab, o", "Sends no key here"):
self.assertIn(words, miyoo)
# The both-names form is the one it was.
self.assertEqual(help_text("both"), (GOLDEN / "help-80x24.txt").read_text().rstrip("\n"))
def test_a_miyoo_a_chooses_and_ticks(self):
"""A is Space on a Miyoo: it chooses where Enter does, ticks where X
would, and L1 and R1 (E and T) page."""
state = checked_state()
state.pad = "miyoo"
self.assertEqual(press(state, " "), [("run", "install")])
state = checked_state()
state.pad = "miyoo"
state.stack.append("systems")
rows = install.tui_rows(state)
first = next(i for i, row in enumerate(rows) if row.action == "system")
state.focus["systems"] = first
before = set(state.ticked)
press(state, " ")
self.assertNotEqual(state.ticked, before)
state.focus["systems"] = next(i for i, row in enumerate(rows) if row.action == "all")
press(state, " ")
self.assertEqual(state.ticked, {row["system"] for row in state.systems})
state.focus["systems"] = first
press(state, "t")
self.assertGreater(state.focus["systems"], first)
press(state, "e")
self.assertEqual(state.focus["systems"], 0)
# In a text field the letters are letters.
state.editing = "systems"
press(state, "t")
self.assertEqual(state.filters["systems"], "t")
def test_space_stays_x_on_the_other_routes(self):
for route in ("both", "keys", "gptokeyb", "evmapy", "muxterm"):
with self.subTest(route=route):
state = checked_state()
state.pad = route
self.assertEqual(press(state, " "), [("run", "confirm")])
class ControlCharacters(unittest.TestCase):
"""Names from the file list, the folders on disk and the installer's own
words reach the screen: an escape sequence among them would drive the
terminal (clear it, or set the clipboard with OSC 52)."""
HOSTILE = "a\x1b[2Jb\x1b]52;c;x\x07c\rd\ne\x7ff\x9bg\x85h"
def test_the_cleaning(self):
self.assertEqual(install.screen_text(self.HOSTILE), "a?[2Jb?]52;c;x?c?d?e?f?g?h")
self.assertEqual(install.screen_text("ファミコン é"), "ファミコン é")
def assertClean(self, lines) -> None:
for line in lines:
self.assertIsNone(re.search(r"[\x00-\x1f\x7f-\x9f]", line), repr(line))
def test_a_file_name_in_the_preview(self):
state = checked_state()
state.stack += ["options", "preview"]
state.dry = dict(CHECK)
state.dry_files = [{**FILES[0], "dest": "\x1b[2Jevil.bin"}]
lines = install.tui_view(state, 80, 24)
self.assertClean(lines)
self.assertIn("?[2Jevil.bin", "\n".join(lines))
def test_a_folder_name_in_the_browser(self):
root = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, root, True)
(root / "x\x1b]52;c;x\x07").mkdir()
state = fresh_state()
state.platform, state.stack = "retroarch", ["folder", "browse"]
with mock.patch.object(install, "_mounted_cards", return_value=[]):
install._browse_to(state, root)
lines = install.tui_view(state, 80, 24)
self.assertClean(lines)
self.assertIn("x?]52;c;x?/", "\n".join(lines))
def test_the_child_tail_on_the_error_screen(self):
state = fresh_state()
state.stack, state.run = ["setup", "error"], "check"
state.error = ["\x1b[31mError\x1b[0m: \x07bad\r"]
self.assertClean(install.tui_view(state, 40, 15))
def test_the_renderer_guards_whatever_reaches_it(self):
out = io.StringIO()
terminal = install._TuiTerminal.__new__(install._TuiTerminal)
terminal.stdout, terminal.encoding = out, "utf-8"
terminal.frame = [("", "")] * 3
terminal.draw(["x", "\x1b]52;c;x\x07", "z"], 40)
self.assertNotIn("\x1b]", out.getvalue())
self.assertNotIn("\x07", out.getvalue())
def test_the_farewell_is_clean(self):
state = checked_state()
state.dest = Path("/media/\x1b[2J")
state.stack.append("result")
state.code = 0
state.summary = {"installed": 1, "failed": [{"dest": "\x1b]0;t\x07x", "reason": "\x1b"}]}
self.assertClean(install.tui_farewell(state))
class CleanupSurvivesABrokenTerminal(unittest.TestCase):
"""A write that fails (EIO when the window closed, EPIPE) on the way out
left the terminal raw and the handlers installed."""
class Tty(io.StringIO):
broken = False
def __init__(self, fd: int) -> None:
super().__init__()
self.fd = fd
def isatty(self) -> bool:
return True
def fileno(self) -> int:
return self.fd
def write(self, text: str) -> int:
if CleanupSurvivesABrokenTerminal.Tty.broken:
raise OSError(5, "Input/output error")
return super().write(text)
def test_termios_and_handlers_come_back(self):
import signal
master, slave = os.openpty()
self.addCleanup(os.close, master)
self.addCleanup(os.close, slave)
fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", 24, 80, 0, 0))
before = termios.tcgetattr(slave)
handlers = {n: signal.getsignal(n) for n in (signal.SIGINT, signal.SIGTERM,
signal.SIGHUP)}
# Keys come in on the terminal itself, the screen goes out on a
# descriptor of its own, as fd 0 and fd 1 are.
tty, screen_fd = self.Tty(slave), os.dup(slave)
self.addCleanup(os.close, screen_fd)
out = self.Tty(screen_fd)
real_draw = install._TuiTerminal.draw
def breaking_draw(terminal, lines, cols):
terminal.frame = []
real_draw(terminal, lines, cols)
CleanupSurvivesABrokenTerminal.Tty.broken = True
self.addCleanup(setattr, CleanupSurvivesABrokenTerminal.Tty, "broken", False)
work = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, work, True)
with mock.patch.object(install._TuiTerminal, "draw", breaking_draw), \
mock.patch.object(install.tempfile, "mkdtemp", return_value=str(work)), \
mock.patch.object(install, "tui_start", return_value=(fresh_state(), [])), \
mock.patch.object(install, "open_list_and_pack"), \
mock.patch.object(install, "detect_os", return_value="linux"), \
mock.patch.object(sys, "stdin", tty), mock.patch.object(sys, "stdout", out), \
mock.patch.object(sys, "stderr", out):
code = install.run_tui(_args())
self.assertIs(sys.stdout, out)
# A window that answers EIO is a closed window: its signal's code,
# not a crash.
self.assertEqual(code, 129)
# The farewell found no terminal: what still flushes at exit goes to
# the null device, and the exit code stays the one returned.
self.assertEqual(os.fstat(screen_fd).st_rdev, os.stat(os.devnull).st_rdev)
# No crash log is kept, and nothing else of the run.
self.assertFalse(work.exists())
self.assertEqual(termios.tcgetattr(slave), before)
for number, handler in handlers.items():
self.assertEqual(signal.getsignal(number), handler)
class IdleExit(unittest.TestCase):
def test_the_variable(self):
for value, seconds in (("30", 30.0), (" 2.5 ", 2.5), ("", None), ("0", None),
("-4", None), ("soon", None), ("inf", None), ("nan", None)):
with self.subTest(value=value):
self.assertEqual(install.tui_idle_exit({install.TUI_IDLE_ENV: value}),
seconds)
self.assertIsNone(install.tui_idle_exit({}))
def test_the_farewell(self):
state = fresh_state()
state.idle_closed, state.exit_code = True, 0
self.assertEqual(install.tui_farewell(state),
["RetroBIOS: No button pressed, closing."])
def test_an_error_screen_closes_with_its_code(self):
"""Closed idle on "No internet: offline mode", the launcher read 0
and showed nothing."""
state = fresh_state()
state.stack = ["setup", "checking"]
install._fail(state, ["Give the file list with --manifest FILE."], 1)
state.error_title = "No internet: offline mode"
self.assertEqual(self.idle_close(state), 1)
self.assertEqual(install.tui_farewell(state), [
"RetroBIOS: No button pressed, closing.",
"RetroBIOS: No internet: offline mode",
"Give the file list with --manifest FILE."])
def test_a_result_closes_with_the_install_code(self):
state = fresh_state()
state.stack = ["setup", "result"]
state.code = 2
state.summary = {"event": "summary", "mode": "install", "installed": 1,
"up_to_date": 0, "pending": 0,
"failed": [{"dest": "a.bin", "reason": "disk full"}],
"skipped": [], "left_out": [], "kept": [], "interrupted": False}
state.dest = SYSTEM_DIR
self.assertEqual(self.idle_close(state), 2)
farewell = install.tui_farewell(state)
self.assertEqual(farewell[:2], ["RetroBIOS: No button pressed, closing.",
"RetroBIOS: Finished with errors"])
def test_any_other_screen_closes_as_a_quit(self):
"""0 read as "everything asked for is installed" with nothing done."""
state = fresh_state()
state.stack = ["setup"]
self.assertEqual(self.idle_close(state), install.QUIT_CODE)
def idle_close(self, state: install.TuiState) -> int:
"""run_tui on state, no key ever pressed, closed by the idle timer."""
class Quiet(Crash.FakeTerminal):
def keys(self, timeout):
time.sleep(0.01)
return []
out = io.StringIO()
work = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, work, True)
with mock.patch.object(install, "_TuiTerminal", Quiet), \
mock.patch.object(install.tempfile, "mkdtemp", return_value=str(work)), \
mock.patch.object(install, "tui_start", return_value=(state, [])), \
mock.patch.object(install, "open_list_and_pack"), \
mock.patch.object(install, "detect_os", return_value="linux"), \
mock.patch.dict(os.environ, {install.TUI_IDLE_ENV: "0.05"}), \
mock.patch.object(sys, "stdout", out), mock.patch.object(sys, "stderr", out):
code = install.run_tui(_args())
self.assertTrue(state.idle_closed)
self.assertIn("No button pressed, closing.", out.getvalue())
return code
class AReadErrorIsNotAClosedWindow(unittest.TestCase):
"""Any EIO read as the window closing: a failing SD card answers EIO
too, and that run ended 129, no error.log, no launcher message."""
def test_eio_counts_only_once_the_terminal_hung_up(self):
import pty
master, slave = pty.openpty()
try:
with open(os.dup(slave), "w", encoding="utf-8") as screen:
terminal = mock.Mock(fd=slave, stdout=screen)
card = OSError(errno.EIO, "Input/output error", "/media/card/bios/x.bin")
self.assertFalse(install._closed_terminal(card, terminal))
self.assertFalse(install._closed_terminal(
OSError(errno.ENOENT, "No such file"), terminal))
os.close(master)
master = -1
self.assertTrue(install._closed_terminal(card, terminal))
self.assertTrue(install._closed_terminal(termios.error(errno.EIO, "gone"),
terminal))
finally:
os.close(slave)
if master >= 0:
os.close(master)
class Crash(unittest.TestCase):
"""An unexpected error ends on one sentence and a log, never a traceback."""
class FakeTerminal:
left = False
def __init__(self, *_streams) -> None:
self.frame = []
def enter(self) -> None:
pass
def leave(self) -> None:
Crash.FakeTerminal.left = True
def size(self) -> tuple:
return 80, 24
def draw(self, lines, cols) -> None:
pass
def set_mouse(self, on: bool) -> None:
pass
def keys(self, timeout):
raise RuntimeError("a defect")
def test_the_terminal_is_restored_and_one_line_printed(self):
args = _args()
out, err = io.StringIO(), io.StringIO()
with mock.patch.object(install, "_TuiTerminal", self.FakeTerminal), \
mock.patch.object(install, "tui_start", return_value=(fresh_state(), [])), \
mock.patch.object(install, "open_list_and_pack"), \
mock.patch.object(install, "detect_os", return_value="linux"), \
mock.patch.object(sys, "stdout", out), mock.patch.object(sys, "stderr", err):
code = install.run_tui(args)
self.assertEqual(code, 1)
self.assertTrue(self.FakeTerminal.left)
lines = err.getvalue().splitlines()
self.assertEqual(len(lines), 1, lines)
self.assertIn("stopped on an unexpected error", lines[0])
log = Path(lines[0].rsplit(" ", 1)[-1].rstrip("."))
self.addCleanup(shutil.rmtree, log.parent, True)
self.assertIn("RuntimeError: a defect", log.read_text())
self.assertNotIn("Traceback", err.getvalue() + out.getvalue())
# POSIX modules a Windows Python does not have: importing one raises there.
POSIX_ONLY = ("termios", "tty", "pty", "fcntl", "select", "resource", "pwd", "grp")
# The signal names a Windows Python defines.
WINDOWS_SIGNALS = ("SIGABRT", "SIGBREAK", "SIGFPE", "SIGILL", "SIGINT", "SIGSEGV",
"SIGTERM")
class SimulatedWindows:
"""os.name "nt", the POSIX modules unimportable, the signal module cut
down to the names Windows has, and msvcrt reading the given keys."""
def __init__(self, keys: str = "") -> None:
self.keys = list(keys)
self.handlers: dict[int, object] = {}
self.locked: list[int] = []
self.msvcrt = types.SimpleNamespace(
kbhit=lambda: bool(self.keys), getwch=lambda: self.keys.pop(0),
locking=lambda fd, mode, size: self.locked.append(fd), LK_NBLCK=2)
self.signal = types.ModuleType("signal")
for number, name in enumerate(WINDOWS_SIGNALS, start=100):
setattr(self.signal, name, number)
self.signal.SIG_DFL, self.signal.SIG_IGN = 0, 1
self.signal.CTRL_C_EVENT, self.signal.CTRL_BREAK_EVENT = 0, 1
self.signal.signal = self._install
self.signal.getsignal = lambda number: self.handlers.get(number, 0)
self.stack = contextlib.ExitStack()
def _install(self, number: int, handler: object) -> object:
if number not in {getattr(self.signal, name) for name in WINDOWS_SIGNALS}:
raise ValueError(f"invalid signal value {number}")
previous = self.handlers.get(number, 0)
self.handlers[number] = handler
return previous
def __enter__(self) -> SimulatedWindows:
self.stack.enter_context(mock.patch.dict(
sys.modules, {**{name: None for name in POSIX_ONLY}, "msvcrt": self.msvcrt}))
# install.py alone sees "nt": pathlib here keeps making PosixPaths.
self.stack.enter_context(mock.patch.object(install, "os", WindowsOs()))
self.stack.enter_context(mock.patch.object(install, "signal", self.signal))
return self
def __exit__(self, *exc: object) -> None:
self.stack.close()
class WindowsHasNoPosixModules(unittest.TestCase):
"""_terminal_gone imported termios unguarded: on Windows a closed console
raised ModuleNotFoundError inside run_tui's except block, a traceback
instead of an exit code. Every path the interface takes on Windows runs
here with the POSIX modules gone."""
class Console(io.StringIO):
broken = False
def fileno(self) -> int:
return 0
def isatty(self) -> bool:
return True
def write(self, text: str) -> int:
if self.broken:
raise OSError(errno.EPIPE, "The pipe is being closed")
return super().write(text)
def test_the_simulation_refuses_posix_imports(self):
with SimulatedWindows():
for name in POSIX_ONLY:
with self.subTest(module=name), self.assertRaises(ImportError):
__import__(name)
self.assertFalse(hasattr(install.signal, "SIGTSTP"))
def test_a_closed_console_is_a_closed_terminal(self):
console = self.Console()
with SimulatedWindows():
terminal = install._TuiTerminal(console, console)
self.assertTrue(install._closed_terminal(
OSError(errno.EPIPE, "The pipe is being closed"), terminal))
self.assertFalse(install._closed_terminal(
OSError(errno.ENOENT, "No such file"), terminal))
def test_keys_enter_leave_and_cleanup(self):
console = self.Console()
with SimulatedWindows("a\xe0H") as windows:
terminal = install._TuiTerminal(console, console)
terminal.enter()
self.assertEqual([(key.name, key.text) for key in terminal.keys(0.05)],
[("char", "a"), ("up", "")])
handlers = {windows.signal.SIGINT: windows.signal.SIG_DFL}
self.assertEqual(install._tui_cleanup(terminal, [], handlers, fresh_state()), [])
self.assertIn(install._SCREEN_OFF, console.getvalue())
def test_a_child_is_interrupted_through_the_console(self):
run = install._EngineRun.__new__(install._EngineRun)
run.proc = mock.Mock(**{"poll.return_value": None})
with SimulatedWindows(), mock.patch.object(install.os, "kill") as kill:
run.interrupt(from_key=False)
kill.assert_not_called()
run.proc.send_signal.assert_not_called()
run.interrupt(from_key=True)
kill.assert_called_once_with(0, install.signal.CTRL_C_EVENT)
def test_work_folder_owner_and_partial_lock(self):
work = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, work, True)
(work / install.TUI_OWNER).write_text(str(os.getpid()), encoding="utf-8")
with SimulatedWindows() as windows:
self.assertIsNone(install._owner_alive(work))
handle = install._claim_partial(work / "x.bin.part")
self.assertIsNotNone(handle)
handle.close()
self.assertEqual(len(windows.locked), 1)
def test_run_tui_ends_on_the_closed_console_code(self):
console = self.Console()
real_draw = install._TuiTerminal.draw
def breaking_draw(terminal, lines, cols):
console.broken = True
real_draw(terminal, lines, cols)
work = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, work, True)
with SimulatedWindows() as windows, \
mock.patch.object(install._TuiTerminal, "draw", breaking_draw), \
mock.patch.object(install, "_drop_closed_terminal"), \
mock.patch.object(install.tempfile, "mkdtemp", return_value=str(work)), \
mock.patch.object(install, "tui_start", return_value=(fresh_state(), [])), \
mock.patch.object(install, "open_list_and_pack"), \
mock.patch.object(install, "detect_os", return_value="windows"), \
mock.patch.object(sys, "stdin", console), \
mock.patch.object(sys, "stdout", console), \
mock.patch.object(sys, "stderr", console):
code = install.run_tui(_args())
# SIGHUP does not exist there: the closed window's code is 129.
self.assertEqual(code, 129)
self.assertFalse((work / "error.log").exists())
self.assertTrue(all(handler == 0 for handler in windows.handlers.values()),
windows.handlers)
class TerminalsTheScreenCannotDraw(unittest.TestCase):
"""The screen writes CSI sequences: a terminal whose description moves
the cursor otherwise, or not at all, gets the line questions."""
def setUp(self):
self.master, self.slave = os.openpty()
self.addCleanup(os.close, self.master)
self.addCleanup(os.close, self.slave)
fcntl.ioctl(self.slave, termios.TIOCSWINSZ, struct.pack("HHHH", 24, 80, 0, 0))
self.tty = StartConditions._Tty(self.slave)
self.env = {"TERMINFO": str(_terminfo_folder(self))}
def blocker(self, term: str) -> str:
return install.tui_blocker(_args(), self.tty, self.tty, {**self.env, "TERM": term})
def test_the_cursor_address_is_read(self):
self.assertEqual(install.terminal_cursor_address("rbtest-ansi", self.env),
"\x1b[%i%p1%d;%p2%dH")
self.assertEqual(install.terminal_cursor_address("rbtest-ansi2", self.env),
"\x1b[%i%p1%d;%p2%dH")
self.assertEqual(install.terminal_cursor_address("rbtest-glass", self.env), "")
self.assertIsNone(install.terminal_cursor_address("rbtest-none", self.env))
def test_ansi_opens_and_the_others_say_why(self):
self.assertEqual(self.blocker("rbtest-ansi"), "")
self.assertEqual(self.blocker("rbtest-ansi2"), "")
self.assertEqual(self.blocker("rbtest-glass"),
"TERM=rbtest-glass cannot move the cursor")
self.assertIn("escape sequences", self.blocker("rbtest-vt52"))
def test_no_description_is_no_refusal(self):
"""Android and most handheld images carry no terminfo: the screen
draws there as before."""
self.assertEqual(self.blocker("rbtest-none"), "")
self.assertEqual(self.blocker("../r/rbtest-glass"), "")
def test_the_folders_are_searched_in_order(self):
home = Path(self.env["TERMINFO"])
(home / ".terminfo" / "r").mkdir(parents=True)
(home / ".terminfo" / "r" / "rbtest-ansi").write_bytes(
_terminfo_entry("rbtest-ansi", None))
# $TERMINFO first, then ~/.terminfo, then $TERMINFO_DIRS.
self.assertTrue(install.terminal_cursor_address(
"rbtest-ansi", {**self.env, "HOME": str(home)}))
self.assertEqual(install.terminal_cursor_address(
"rbtest-ansi", {"HOME": str(home), "TERMINFO_DIRS": self.env["TERMINFO"]}), "")
# macOS files a terminal under the hex of its first letter.
(home / "72").mkdir()
(home / "72" / "rbtest-hex").write_bytes(_terminfo_entry("rbtest-hex", None))
self.assertEqual(install.terminal_cursor_address(
"rbtest-hex", {"TERMINFO_DIRS": str(home)}), "")
def test_the_line_questions_draw_no_escape_there_either(self):
"""The progress line redraws with CSI and paints with SGR: on a VT52
both print as text, as on TERM=dumb."""
for term, live in (("rbtest-ansi", True), ("rbtest-vt52", False),
("rbtest-glass", False)):
with self.subTest(term=term), mock.patch.dict(
os.environ, {**self.env, "TERM": term}), \
mock.patch.object(install, "_enable_ansi", return_value=True):
os.environ.pop("NO_COLOR", None)
shown = install.Terminal(self.tty)
self.assertEqual((shown.live, shown.colour), (live, live))
self.assertEqual(shown.ok("ok") == "ok", not live)
def test_the_colours_are_read(self):
self.assertEqual(install.terminal_colours("rbtest-ansi", self.env), 8)
self.assertEqual(install.terminal_colours("rbtest-ansi2", self.env), 256)
self.assertEqual(install.terminal_colours("rbtest-two", self.env), 2)
self.assertEqual(install.terminal_colours("rbtest-mono", self.env), 0)
self.assertIsNone(install.terminal_colours("rbtest-none", self.env))
for data in (b"", b"\x00" * 12, _terminfo_entry("x", None, colours=8)[:40]):
with self.subTest(data=data):
self.assertIsNone(install.terminfo_number(data, install._TERMINFO_COLORS))
def test_fewer_than_8_colours_draw_the_line_live_and_plain(self):
"""A vt100 moves the cursor the ANSI way and has no colour: the
progress line still redraws, its words unpainted."""
for term, colour in (("rbtest-ansi", True), ("rbtest-ansi2", True),
("rbtest-two", False), ("rbtest-mono", False),
("rbtest-none", True)):
with self.subTest(term=term), mock.patch.dict(
os.environ, {**self.env, "TERM": term}), \
mock.patch.object(install, "_enable_ansi", return_value=True):
os.environ.pop("NO_COLOR", None)
shown = install.Terminal(self.tty)
self.assertEqual((shown.live, shown.colour), (True, colour))
self.assertEqual(shown.status("1 failed") != "1 failed", colour)
def test_the_screen_draws_without_colour_for_each_reason(self):
"""NO_COLOR, TERM dumb or unset, fewer than 8 colours, an output no
terminal: each turns the colour off, and says which."""
for env, said in (({"TERM": "rbtest-ansi"}, ""),
({"TERM": "rbtest-none"}, ""),
({"TERM": "rbtest-ansi", "NO_COLOR": "1"}, "NO_COLOR is set"),
({"TERM": "rbtest-ansi", "NO_COLOR": ""}, ""),
({"TERM": "dumb"}, "TERM is dumb or not set"),
({}, "TERM is dumb or not set"),
({"TERM": "rbtest-two"},
"TERM=rbtest-two names 2 colours, fewer than 8"),
({"TERM": "rbtest-mono"},
"TERM=rbtest-mono names 0 colours, fewer than 8")):
with self.subTest(env=env):
self.assertEqual(install.colour_blocker({**self.env, **env}, self.tty), said)
self.assertEqual(install.colour_blocker({**self.env, "TERM": "rbtest-ansi"},
io.StringIO()),
"the output is not a terminal")
with mock.patch.dict(os.environ, {**self.env, "TERM": "rbtest-mono"}), \
mock.patch.object(install, "_enable_ansi", return_value=True):
self.assertFalse(install._TuiTerminal(self.tty, self.tty).colour)
os.environ["TERM"] = "rbtest-ansi"
os.environ.pop("NO_COLOR", None)
self.assertTrue(install._TuiTerminal(self.tty, self.tty).colour)
def test_an_unset_term_is_a_dumb_one(self):
with mock.patch.dict(os.environ, {"FORCE_COLOR": ""}), \
mock.patch.object(install, "_enable_ansi", return_value=True):
for name in ("TERM", "NO_COLOR"):
os.environ.pop(name, None)
shown = install.Terminal(self.tty)
self.assertEqual((shown.live, shown.colour), (False, False))
with mock.patch.object(install.os, "name", "nt"):
self.assertTrue(install.Terminal(self.tty).live)
def test_a_damaged_description_is_no_description(self):
for data in (b"", b"\x1a\x01", b"\x00" * 12, _terminfo_entry("x", "\x1b[H")[:-1]):
with self.subTest(data=data):
self.assertIsNone(install.terminfo_string(data, install._TERMINFO_CUP))
if __name__ == "__main__":
unittest.main()
+949
View File
@@ -0,0 +1,949 @@
"""The screens as drawn, held against the golden text in tests/fixtures/tui/."""
from __future__ import annotations
import tests
import argparse
import contextlib
import io
import os
import re
import unittest
from pathlib import Path
from unittest import mock
import install
from tests.netguard import module_guard
from tests.tuisupport import (
_args, BACKUPS, backups_state, CHECK, checked_state, FILES, fresh_state, GOLDEN, golden_states,
golden_states_result, HOME, in_full, Key, MANIFEST, more_state, pack_event, pack_plan_state,
PLAN, planned, press, record_setup, record_state, removal_done_state, REMOVAL_PLAN,
removal_state, REPO_ROOT, result_states, ROUTES, screen_text, SIZES, SYSTEM_DIR, SYSTEMS,
)
# No connection off the loopback and no card of the host reaches a test,
# in this process or one it starts: the module fails at its end when one is tried.
setUpModule, tearDownModule = module_guard("test_tui_views")
class RecordedPlan(unittest.TestCase):
"""The plan of a folder with an install record: opened on the one setup
found, on the recorded choice, one press from installing it again."""
def row(self, state: install.TuiState, action: str) -> install.TuiRow:
return next(row for row in install.tui_rows(state) if row.action == action)
def test_a_part_of_the_record_that_cannot_apply_is_left_out_as_line_mode_does(self):
"""Each region tested alone, as line mode keeps them, and the systems
and emulators the list no longer names left out and said."""
for choice, kept, said in (
(["--region", "us", "--region", "zz"], ["--region", "us"],
"--region (a region this installer does not know)"),
(["--system", "nintendo-gba", "--system", "zz-gone"],
["--system", "nintendo-gba"], "--system (zz-gone no longer on the list)"),
(["--emulator", "nosuch"], [], "--emulator (nosuch no longer on the list)")):
with self.subTest(choice=choice):
state = record_state(record_setup(choice))
self.assertEqual(state.status, f"Left out of the recorded choice: {said}.")
self.assertEqual(state.record["choice"], kept)
self.assertEqual(record_state(record_setup(
["--region", "us", "--region", "zz"])).regions, ["north-america"])
def test_a_recorded_region_is_the_same_choice_on_screen(self):
"""The screen spells regions as the manifests do and joins them: the
record's own words are still its choice, in their order."""
state = record_state(record_setup(["--region", "us", "--region", "jp"]))
self.assertTrue(install.tui_record_kept(state))
self.assertNotEqual(install._record_key([("--region", "us,jp")]),
install._record_key([("--region", "jp,us")]))
def test_opens_on_the_plan_of_the_one_setup_found(self):
state = record_state()
self.assertTrue(state.opened_on_plan)
self.assertEqual(state.stack, ["setup", "plan"])
self.assertEqual(install.tui_rows(state)[0].action, "install")
press(state, "end", "up", "up", "up", "up")
self.assertEqual(install.tui_rows(state)[state.focus["plan"]].label, "Change where")
press(state, "enter")
self.assertEqual(state.screen, "setup")
def test_the_notes_of_the_setups_screen_are_on_the_plan(self):
"""Opened on the plan, the ES-DE note and the setup's label, which
only the setups screen showed, were never seen."""
setups = fresh_state().setups[:1]
with mock.patch.object(install, "found_setups", return_value=(setups, set())), \
mock.patch.object(install, "detect_frontends", return_value=["esde"]), \
mock.patch.object(install, "_mounted_cards", return_value=[]), \
mock.patch.object(install, "_DETECTION_REFUSED", []), \
mock.patch.object(install.Path, "exists", return_value=True):
state, _effects = install.tui_start(_args(), "linux")
self.assertTrue(state.opened_on_plan)
install.tui_receive(state, ("manifest", "retroarch", MANIFEST))
for event in [*FILES, *SYSTEMS, CHECK, PLAN]:
install.tui_receive(state, ("event", state.run_id, event))
with mock.patch.object(install, "_tui_folder_facts", return_value={
"free": 50 * 1024 ** 3, "writable": True}):
install.tui_receive(state, ("ended", state.run_id, 1, []))
state.pad = "both"
plan = screen_text(install.tui_view(state, 80, 24))
self.assertIn("1 note on this machine: Details.", plan)
self.assertNotIn(install.TUI_ESDE_NOTE, plan)
# The plan's budget, plus the note line (6 words) and Change where (2).
self.assertLessEqual(screen_words(install.tui_view(state, 80, 24)),
SCREEN_WORDS["plan"][2] + 8)
state.focus["plan"] = [row.action for row in install.tui_rows(state)].index("details")
press(state, "enter")
details = screen_text(install.tui_view(state, 120, 40))
self.assertIn(screen_text([install.TUI_ESDE_NOTE]), details)
self.assertIn("Found here: RetroArch.", details)
def test_several_setups_open_the_list(self):
with mock.patch.object(install, "found_setups", return_value=(
fresh_state().setups, set())), \
mock.patch.object(install, "detect_frontends", return_value=[]), \
mock.patch.object(install, "_mounted_cards", return_value=[]), \
mock.patch.object(install, "_DETECTION_REFUSED", []):
state, effects = install.tui_start(_args(), "linux")
self.assertEqual((state.screen, effects, state.opened_on_plan), ("setup", [], False))
def test_one_press_installs_the_recorded_choice(self):
state = record_state()
self.assertEqual(self.row(state, "record").label, "Same choice as on 3 Nov: yes")
self.assertIn("For nintendo-gba.", screen_text(
install.tui_view(state, 80, 24)))
self.assertEqual(press(state, "enter"), [("run", "install")])
argv = install.tui_argv(state, "install", "py", "install.py")
self.assertIn("--system=nintendo-gba", argv)
self.assertNotIn("--all-files", argv)
def test_no_takes_the_whole_list_and_yes_brings_it_back(self):
state = record_state()
state.focus["plan"] = install.tui_rows(state).index(self.row(state, "record"))
with mock.patch.object(install, "games_probe", return_value=None):
effects = press(state, "enter")
self.assertEqual(effects, [("run", "check")])
flags = install.tui_flags(state)
self.assertIn(("--all-files", None), flags)
self.assertFalse([flag for flag in flags if flag[0] == "--system"])
self.assertFalse(install.tui_record_kept(state))
for event in [*FILES, *SYSTEMS, CHECK, PLAN]:
install.tui_receive(state, ("event", state.run_id, event))
with mock.patch.object(install, "_tui_folder_facts", return_value={
"free": 50 * 1024 ** 3, "writable": True}):
install.tui_receive(state, ("ended", state.run_id, 1, []))
self.assertEqual(self.row(state, "record").label, "Same choice as on 3 Nov: no")
self.assertEqual(install.tui_rows(state)[state.focus["plan"]].action, "record")
self.assertEqual(press(state, "enter"), [("run", "check")])
self.assertIn(("--system", "nintendo-gba"), install.tui_flags(state))
self.assertTrue(install.tui_record_kept(state))
def test_the_command_line_choice_wins(self):
with mock.patch.object(install, "setup_record",
return_value=(record_setup(), SYSTEM_DIR, "")), \
mock.patch.object(install.Path, "exists", return_value=True):
state, _effects = install.tui_start(
_args(platform="retroarch", dest=str(SYSTEM_DIR), system=["sony-playstation"]),
"linux", detect=False)
self.assertEqual(install._tui_system_flags(state), [("--system", "sony-playstation")])
self.assertFalse(install.tui_record_kept(state))
self.assertEqual(install._record_rows(state), [])
def test_a_record_that_cannot_be_read_is_said_once(self):
problem = "The install record /x/system.install.json is damaged"
install._RECORD_SAID.discard("/x/system.install.json")
with mock.patch.object(install, "setup_record",
return_value=(None, Path("/x/system.install.json"), problem)), \
mock.patch.object(install.Path, "exists", return_value=True):
state, _effects = install.tui_start(
_args(platform="retroarch", dest=str(SYSTEM_DIR)), "linux", detect=False)
self.assertEqual(str(state.status), f"{problem}, so it is ignored.")
state.status, state.record_for = "", None
install._tui_record_load(state)
self.assertEqual(state.status, "")
self.assertIsNone(state.record)
self.assertNotIn("--all-files", str(install.tui_flags(state)))
def test_the_install_row_says_the_size_the_headline_says(self):
"""14930 files to download, 6.8 GB stood above Install 6.6 GB: the
data files counted in one, the copies in the other."""
big = 2 * 1024 ** 3
state = checked_state()
state.files[0] = {**state.files[0], "size": big}
state.check = planned({**state.check, "bytes_needed": state.check["bytes_needed"] + big,
"data_missing": 3, "data_bytes": 300 * 1024 ** 2})
headline = str(install._plan_lines(state.check, state.dest, state)[0])
size = headline.rsplit(", ", 1)[1]
self.assertEqual(install.tui_rows(state)[0].label, f"Install {size}")
class Views(unittest.TestCase):
"""Every screen as text, at the sizes a handheld and a desktop show."""
def setUp(self):
# The card screen lists the cards mounted here: none, on every machine.
patcher = mock.patch.object(install, "_mounted_cards", return_value=[])
patcher.start()
self.addCleanup(patcher.stop)
def test_goldens(self):
update = os.environ.get("RETROBIOS_UPDATE_GOLDENS") == "1"
GOLDEN.mkdir(parents=True, exist_ok=True)
for name, state in golden_states().items():
for cols, rows in SIZES:
with self.subTest(screen=name, size=f"{cols}x{rows}"):
state.cols, state.rows = cols, rows
lines = install.tui_view(state, cols, rows)
self.assertEqual(len(lines), rows)
for line in lines:
# A path or a command kept whole folds in the terminal.
if line.style != "long":
self.assertLessEqual(install.cell_width(line), cols, line)
self.assertTrue(all(ord(c) < 128 or c in "ファミコン" for c in line),
line)
self.assertLess(install.cell_width(lines[-1]), cols)
text = "\n".join(line.rstrip() for line in lines) + "\n"
path = GOLDEN / f"{name}-{cols}x{rows}.txt"
if update:
path.write_text(text, encoding="utf-8")
self.assertEqual(text, path.read_text(encoding="utf-8"))
def test_goldens_per_route(self):
"""Each input route at the handheld sizes and 80x24, kept only where a
screen reads differently from the both-names form."""
update = os.environ.get("RETROBIOS_UPDATE_GOLDENS") == "1"
for route in ROUTES:
sections = []
for name, state in golden_states().items():
state.pad = route
for cols, rows in SIZES[:3]:
with self.subTest(route=route, screen=name, size=f"{cols}x{rows}"):
state.cols, state.rows = cols, rows
lines = install.tui_view(state, cols, rows)
for line in lines:
if line.style != "long":
self.assertLessEqual(install.cell_width(line), cols, line)
self.assertLess(install.cell_width(lines[-1]), cols)
text = "\n".join(line.rstrip() for line in lines) + "\n"
both = (GOLDEN / f"{name}-{cols}x{rows}.txt").read_text(encoding="utf-8")
if text != both:
sections.append(f"=== {name} {cols}x{rows}\n{text}")
path = GOLDEN / f"route-{route}.txt"
if update:
path.write_text("".join(sections), encoding="utf-8")
with self.subTest(route=route):
self.assertEqual("".join(sections), path.read_text(encoding="utf-8"))
def test_colour_goldens(self):
"""Every screen as the terminal gets it with colour, the escape
codes kept (ESC written ^[), one file per size."""
update = os.environ.get("RETROBIOS_UPDATE_GOLDENS") == "1"
for cols, rows in SIZES:
sections = []
for name, state in golden_states().items():
state.cols, state.rows = cols, rows
painted = [install.tui_paint(str(line), line.style, True)
for line in install.tui_view(state, cols, rows)]
sections.append(f"=== {name}\n" + "\n".join(painted).replace("\x1b", "^[")
+ "\n")
path = GOLDEN / f"colour-{cols}x{rows}.txt"
if update:
path.write_text("".join(sections), encoding="utf-8")
with self.subTest(size=f"{cols}x{rows}"):
self.assertEqual("".join(sections), path.read_text(encoding="utf-8"))
def test_colour_adds_codes_and_never_text(self):
"""With colour off a line is drawn as before, its style alone, and
with colour on, stripped of its codes, it is the same text: the
golden screen, character for character."""
for cols, rows in SIZES:
colour = (GOLDEN / f"colour-{cols}x{rows}.txt").read_text(encoding="utf-8")
screens = dict(re.findall(r"=== (\S+)\n(.*?)(?=\n=== |\n\Z)", colour, re.S))
for name, state in golden_states().items():
with self.subTest(screen=name, size=f"{cols}x{rows}"):
state.cols, state.rows = cols, rows
lines = install.tui_view(state, cols, rows)
for line in lines:
# The bar's key names faint, its actions not:
# the rest as before.
self.assertEqual(install.tui_paint(str(line), line.style, False),
install.painted(line, install._bar_spans(
line, "strong")) if line.style == "hint"
else install._STYLES.get(line.style, "") + line)
stripped = [install.unpainted(painted.replace("^[", "\x1b")).rstrip()
for painted in screens[name].split("\n")]
golden = (GOLDEN / f"{name}-{cols}x{rows}.txt").read_text(encoding="utf-8")
self.assertEqual("\n".join(stripped) + "\n", golden)
def test_each_role_paints_a_status_word_on_the_result_screens(self):
"""Done, a part done, files left offline, a stop: between them the
result screens use every role, each on a word that says it."""
# The failed files are listed on the result's Details.
told = result_states()["partial"]
told.stack.append("details")
drawn = "\n".join(install.tui_paint(str(line), line.style, True)
for state in [*result_states().values(), told]
for line in install.tui_view(state, 80, 24))
for role, word in (("accent", "RetroBIOS"), ("strong+success", "4 files installed"),
("strong+success", "Done"), ("failure", "1 failed"),
("failure", "failed:"), ("strong+warning", "3 not fetched"),
("strong+warning", "Stopped"),
("strong", "/home/user/.config/retroarch/system")):
with self.subTest(role=role, word=word):
self.assertIn(install._sgr(role) + word, drawn)
# "2 of 4 installed" is no count of files installed.
self.assertNotIn(install._sgr("strong+success") + "4 installed", drawn)
def test_the_status_words_take_their_role_and_a_zero_none(self):
spans = install.status_spans("1 in place, 0 missing, 3 missing, 1 wrong copy, 2 failed")
self.assertEqual([("1 in place", "success"), ("3 missing", "warning"),
("1 wrong copy", "warning"), ("2 failed", "failure")],
[("1 in place, 0 missing, 3 missing, 1 wrong copy, 2 failed"[a:b], r)
for a, b, r in spans])
self.assertEqual(install.status_spans("0 wrong copies, 0 missing"), [])
self.assertEqual(install.status_spans("python3 install.py --platform retroarch"), [])
def test_the_bar_paints_a_key_only(self):
"""The first entry's key in the accent, never a word: "Writing to the
card..." and "Any key closes this help" name no key."""
for text in (" Writing to the card...", " Any key closes this help"):
self.assertEqual(install.tui_paint(text, "hint", True), text)
painted = install.tui_paint(" A/Enter Exit B/Esc Back", "hint", True)
# The actions plain, the other keys faint.
self.assertEqual(painted, " " + install._sgr("accent") + "A/Enter\x1b[0m Exit "
+ install._sgr("muted") + "B/Esc\x1b[0m Back")
def test_the_hint_bar_names_the_primary_action_first(self):
for name, state in golden_states().items():
with self.subTest(screen=name):
hint = install.tui_view(state, 40, 15)[-1].strip()
# Checking has no A: Back comes first, Quit never in the
# cell the screen before had Continue in.
self.assertTrue(hint.startswith(("A/Enter", "A ", "Enter", "Ctrl-C", "Any key",
"B/Esc Stop", "B Stop")
+ (("B ",) if name == "checking" else ())),
hint)
def test_focus_is_marked_without_colour(self):
lines = install.tui_view(fresh_state(), 80, 24)
focused = [line for line in lines if getattr(line, "style", "") == "focus"]
self.assertEqual(len(focused), 1)
self.assertTrue(focused[0].lstrip().startswith("> RetroArch"))
class Rendering(unittest.TestCase):
def test_only_changed_lines_are_written(self):
out = io.StringIO()
terminal = install._TuiTerminal.__new__(install._TuiTerminal)
terminal.stdout, terminal.encoding, terminal.frame = out, "ascii", []
state = fresh_state()
terminal.draw(install.tui_view(state, 40, 12), 40)
first = out.getvalue()
self.assertTrue(first.startswith("\x1b[H\x1b[2J"))
press(state, "down")
out.seek(0)
out.truncate()
terminal.draw(install.tui_view(state, 40, 12), 40)
changed = out.getvalue()
self.assertEqual(changed.count("\x1b[7m"), 1)
before = install.tui_view(fresh_state(), 40, 12)
after = install.tui_view(state, 40, 12)
moved = [f"\x1b[{i + 1};1H" for i, (a, b) in enumerate(zip(before, after)) if a != b]
self.assertEqual(changed.count(";1H"), len(moved))
for move in moved:
self.assertIn(move, changed)
def test_text_the_terminal_cannot_encode_is_replaced(self):
out = io.StringIO()
terminal = install._TuiTerminal.__new__(install._TuiTerminal)
terminal.stdout, terminal.encoding, terminal.frame = out, "ascii", []
terminal.write("ファ")
self.assertEqual(out.getvalue(), "??")
class TheSectionStandsApart(unittest.TestCase):
def test_no_name_of_the_installer_is_defined_again(self):
"""_run and _system_label were defined twice: the later one won, and
the installer's listing called the interface's. The interface is
modules of installer/ now, joined into one namespace with the rest,
so no name is defined twice anywhere in the file."""
import ast
source = (REPO_ROOT / "install.py").read_text(encoding="utf-8")
seen: dict = {}
for node in ast.parse(source).body:
names = [node.name] if isinstance(node, (ast.FunctionDef, ast.ClassDef)) else [
target.id for target in getattr(node, "targets", [])
if isinstance(target, ast.Name)]
for name in names:
seen.setdefault(name, []).append(node.lineno)
twice = {name: lines for name, lines in seen.items()
if len(lines) > 1}
self.assertEqual(twice, {})
class SmallFixes(unittest.TestCase):
def test_a_system_name_is_said_once_with_a_pack(self):
""""Onion gets the RetroArch file list" was
printed by the pack check, then again where the platform is read."""
pack = mock.Mock(files=[Path("RetroArch_BIOS_Pack.zip")])
pack.name = "RetroArch_BIOS_Pack.zip"
pack.platforms.return_value = ["retroarch"]
args = argparse.Namespace(manifest=None, from_pack=Path("p.zip"), platform="onion",
**{"from": None})
with mock.patch.object(install, "PackSource", return_value=pack), \
contextlib.redirect_stdout(io.StringIO()) as out:
install._open_local_sources(args)
self.assertNotIn("Onion gets", out.getvalue())
install.LOCAL.reset()
def test_a_command_line_region_the_list_lacks(self):
state = checked_state()
state.cli_regions = ["europe"]
state.regions = list(state.cli_regions)
state.stack += ["options", "regions"]
self.assertEqual([row.value for row in install.tui_rows(state)
if row.action == "region"], ["europe", "japan", "north-america"])
press(state, "enter")
self.assertEqual(state.regions, [])
self.assertIn("europe", [row.value for row in install.tui_rows(state)])
press(state, "enter")
self.assertEqual(state.regions, ["europe"])
def test_stay_after_esc_on_a_direct_check_checks_again(self):
state = fresh_state()
state.stack = []
state.manifest, state.manifest_for = MANIFEST, "retroarch"
install._choose(state, "retroarch", Path(REPO_ROOT))
self.assertEqual(state.screen, "checking")
self.assertEqual(press(state, "esc"), [("kill",)])
self.assertEqual(state.screen, "quit")
self.assertEqual(press(state, "down", "enter"), [("run", "check")])
self.assertEqual((state.stack, state.running), (["checking"], True))
press(state, "esc")
self.assertEqual(press(state, "esc"), [("run", "check")])
def test_speed_ignores_a_resumed_partial(self):
state = checked_state()
press(state, "enter")
mega = 1024 * 1024
state.now = 9.0
install.tui_receive(state, ("event", state.run_id, {
"event": "download", "platform": "retroarch", "files": 2, "bytes": 1000 * mega}))
# The first event carries the 500 MB already on disk.
for when, done in ((10.0, 500 * mega), (11.0, 501 * mega), (12.0, 502 * mega)):
state.now = when
install.tui_receive(state, ("event", state.run_id, {
"event": "progress", "files_done": 0, "files_total": 2,
"bytes_done": done, "bytes_total": 1000 * mega}))
# The partial copy resumed is counted local by the engine.
install.tui_receive(state, ("event", state.run_id, {
"event": "transfer", "bytes_local": 500 * mega,
"bytes_network": done - 500 * mega}))
text = "\n".join(install.tui_view(state, 80, 24))
self.assertIn("1.0 MB/s, 8:18 left", text)
def test_numbers_from_before_the_options_say_so(self):
state = checked_state()
state.stack.append("systems")
self.assertNotIn("before the options", "\n".join(install.tui_view(state, 80, 24)))
state.regions = ["japan"]
footer = "\n".join(install.tui_view(state, 80, 24)[-3:])
self.assertIn("before the options", footer)
def test_a_cores_folder_implies_the_installed_cores(self):
state = checked_state()
state.passthrough = [("--cores-dir", "/opt/cores")]
state.installed_only = True
state.stack.append("options")
row = next(r for r in install.tui_rows(state) if r.action == "installed")
self.assertEqual(row.label, "Installed cores only: yes, implied by --cores-dir")
state.focus["options"] = install.tui_rows(state).index(row)
press(state, "enter", "left")
self.assertTrue(state.installed_only)
self.assertNotIn("--installed-cores", [f for f, _v in install.tui_flags(state)])
@in_full
def test_the_end_of_a_wrapped_pager_is_reachable(self):
state = checked_state()
state.stack.append("result")
state.code, state.summary = 0, {"installed": 3}
state.dest = Path("/media/" + "long-folder-name/" * 8)
state.cols, state.rows = 40, 12
press(state, "end")
lines = install.tui_view(state, 40, 12)
self.assertIn("python3 install.py", "\n".join(lines))
top = state.focus["result"]
press(state, "up")
self.assertEqual(state.focus["result"], top - 1)
def test_end_then_up_in_a_pager(self):
state = checked_state()
state.stack += ["options", "preview"]
state.dry, state.dry_files = dict(CHECK), list(FILES) * 10
state.cols, state.rows = 40, 15
press(state, "end")
last = install.tui_view(state, 40, 15)
press(state, "up")
self.assertNotEqual(install.tui_view(state, 40, 15), last)
def test_a_paste_slower_than_the_escape_wait_stays_one_piece(self):
decoder = install.KeyDecoder()
self.assertEqual(decoder.feed("\x1b[200~/media/"), [])
self.assertEqual(decoder.flush(), [])
self.assertTrue(decoder.waiting)
self.assertEqual(decoder.feed("sd\x1b[201~"), [Key("paste", "/media/sd")])
def test_values_cannot_be_read_as_options(self):
state = checked_state()
state.dest = Path("-rf")
state.cores = ["-x"]
argv = install.tui_argv(state, "install", "py", "i.py")
self.assertIn("--dest=-rf", argv)
self.assertIn("--core=-x", argv)
self.assertIn("--platform=retroarch", argv)
def test_the_second_ctrl_c_is_announced_and_the_result_stays_honest(self):
state = checked_state()
press(state, "enter")
install.tui_receive(state, ("event", state.run_id, {
"event": "download", "platform": "retroarch", "files": 4, "bytes": 100}))
install.tui_receive(state, ("event", state.run_id, {
"event": "downloaded", "dest": "a.bin", "ok": True, "reason": "", "size": 1,
"files_done": 1, "files_total": 4, "bytes_done": 1, "bytes_total": 100}))
press(state, "ctrl-c")
self.assertIn("Press B or Ctrl-C again to stop now.",
" ".join(install.tui_view(state, 120, 40)))
self.assertEqual(press(state, "ctrl-c"), [("kill",)])
install.tui_receive(state, ("ended", state.run_id, -9, []))
title, lines = install.tui_outcome(state)
self.assertEqual((title, state.code), ("Stopped", 130))
self.assertEqual(lines[0], "Stopped: 1 of 4 installed, run again to finish.")
def test_systems_show_the_platform_names(self):
state = checked_state()
state.systems.append({"event": "system", "system": "sega-saturn",
"name": "Sega - Saturn", "files": 1, "present": 0,
"missing": 1, "wrong_hash": 0, "bytes_needed": 5})
state.ticked.add("sega-saturn")
state.stack.append("systems")
wide = "\n".join(install.tui_view(state, 120, 40))
self.assertIn("[x] Sega - Saturn", wide)
self.assertIn("sega-saturn", wide)
narrow = "\n".join(install.tui_view(state, 40, 15))
self.assertIn("[x] Sega - Saturn", narrow)
self.assertNotIn("sega-saturn", narrow)
press(state, "/", "s", "a", "t", "u")
self.assertEqual([row.value for row in install.tui_rows(state)
if row.action == "system"], ["sega-saturn"])
# The most words each screen may show by default, one count per size of
# SIZES (owner, 2026-11-09: a beginner lost the important line in text). A
# path is no word. The plan, Confirm and the result say what happens, where
# and what next, and their counts, notes and commands wait on Details. A list
# shows more rows on a taller window. A change that adds words to a screen
# raises its numbers here and says why: the result names its failed files
# (review of 2026-11-10), what the user acts on.
SCREEN_WORDS = {
"setup": (29, 36, 34, 34), "platforms": (23, 27, 89, 225), "folder": (27, 27, 25, 25),
"folder-card": (52, 52, 50, 50), "browse": (17, 17, 15, 15), "path": (23, 23, 25, 25),
"create": (23, 23, 21, 21), "checking": (18, 18, 17, 17), "plan": (32, 32, 32, 32),
"plan-in-place": (23, 23, 20, 20), "systems": (36, 37, 36, 36),
"regions": (45, 44, 42, 42), "cores": (47, 47, 45, 45),
"preview": (29, 29, 28, 28), "command": (22, 22, 16, 16), "confirm": (22, 22, 20, 20),
"installing": (32, 32, 31, 31), "result": (33, 33, 31, 31), "error": (37, 34, 32, 31),
"quit": (14, 14, 12, 12), "help": (24, 26, 26, 26), "plan-games": (36, 47, 55, 55),
"games": (36, 45, 44, 44), "plan-details": (30, 30, 29, 29),
"result-details": (30, 30, 19, 19),
# The plan's words, plus the recorded choice by name, its row (the one
# press back to the whole list) and Change where (back to the setups,
# the plan having opened on the one found), and More, the record being
# what a removal reads.
"plan-record": (38, 42, 43, 43),
# Change holds every option one level below the plan (design 4.4): the
# rows for Emulators, a pack, the device and the internet, and the five
# headings that group them, the intro sentence they replace dropped.
"change": (32, 42, 72, 72),
# Change with an expert row: one BIOS per console and region on a list
# that records its slots, or the standalone build of the emulator chosen.
"change-slot": (34, 44, 78, 78), "change-standalone": (32, 42, 76, 76),
# A list of boards and one of emulators, each with the line that says
# what the choice does and the gloss of "board".
"device": (35, 35, 33, 33), "emulators": (29, 29, 27, 27),
# Every plan names More (one word, counted in the plan budgets above):
# a pack can always be made. More's four rows where the folder has a
# record or a backup, then Make a pack (three words), Remove files with each system the record holds and its
# size and the row for the misplaced copies (two words), the removal plan (what goes, the space freed, the folder, what
# stays and why), its confirm and result, and the backups newest first.
"more": (20, 20, 18, 18), "remove": (33, 33, 31, 31), "removal": (34, 34, 32, 32),
"removal-confirm": (18, 18, 16, 16), "removal-done": (18, 18, 16, 16),
"backups": (24, 24, 22, 22),
# Make a pack: what goes in, its size and setup, where it goes, how it
# is written (one ZIP, or the parts and why), then the result.
"pack-plan": (27, 27, 24, 24), "pack-plan-parts": (39, 39, 35, 35),
"pack-done": (29, 29, 25, 25),
}
def screen_words(lines: list) -> int:
"""Words of a drawn screen, its title and bar included, a path left out."""
return sum(1 for line in lines for token in str(line).split()
if re.search(r"[A-Za-z0-9]", token) and "/" not in token)
class MoreScreens(unittest.TestCase):
"""More: removal, the backups, putting one back and deleting one, each
a child run with its own options and none of the plan's."""
def setUp(self):
patcher = mock.patch.object(install, "_mounted_cards", return_value=[])
patcher.start()
self.addCleanup(patcher.stop)
def test_a_plan_names_more_where_it_has_something_to_act_on(self):
self.assertEqual([row.action for row in install.tui_rows(more_state())][-2:],
["more", "quit"])
done = golden_states()["plan-in-place"]
self.assertEqual(install.tui_rows(done)[-1].action, "more")
self.assertEqual([row.action for row in install.tui_rows(more_state("more"))],
["remove", "backups", "putback", "dropbackup", "packmake"])
def test_the_removal_plan_asks_its_own_child(self):
state = removal_state()
state.regions = ["japan"]
argv = install.tui_argv(state, "removal_plan", "python", "install.py")
self.assertEqual(argv[-4:], ["--remove", "--system=sony-playstation", "--dry-run",
"--events"])
self.assertNotIn("--region=japan", argv)
self.assertIn(f"--dest={SYSTEM_DIR}", argv)
self.assertEqual(state.screen, "removal")
self.assertEqual(install.tui_rows(state)[0].label, "Remove 512.0 KB")
def test_everything_removes_with_no_system(self):
state = removal_state(system=False)
argv = install.tui_argv(state, "removal_plan", "python", "install.py")
self.assertEqual(argv[-3:], ["--remove", "--dry-run", "--events"])
def test_the_misplaced_copies_are_deleted_never_moved_to_a_backup(self):
state = more_state("more", "remove")
actions = [row.action for row in install.tui_rows(state)]
state.focus["remove"] = actions.index("rmmisplaced")
self.assertEqual(install.tui_update(state, Key("enter")), [("run", "removal_plan")])
argv = install.tui_argv(state, "removal_plan", "python", "install.py")
self.assertEqual(argv[-4:], ["--remove", "--misplaced", "--dry-run", "--events"])
install.tui_receive(state, ("event", state.run_id, REMOVAL_PLAN))
install.tui_receive(state, ("ended", state.run_id, 0, []))
state.removal_backup = True
self.assertNotIn("rmbackup", [row.action for row in install.tui_rows(state)])
self.assertIn("in the wrong place go", screen_text(install.tui_view(state, 80, 24)))
state.focus["removal"] = 0
press(state, "enter")
self.assertIn("The files where the cores read them stay.",
screen_text(install.tui_view(state, 80, 24)))
press(state, "enter")
argv = install.tui_argv(state, "remove", "python", "install.py")
self.assertEqual(argv[-4:], ["--remove", "--misplaced", "--events", "--yes"])
def test_a_backup_is_one_row_away_and_the_removal_says_so(self):
state = removal_state()
state.focus["removal"] = 1
press(state, "enter")
self.assertTrue(state.removal_backup)
self.assertEqual(install.tui_rows(state)[0].label, "Move 512.0 KB to a backup")
state.focus["removal"] = 0
press(state, "enter")
self.assertEqual(state.screen, "actconfirm")
effects = press(state, "enter")
self.assertEqual(effects, [("run", "remove")])
argv = install.tui_argv(state, "remove", "python", "install.py")
self.assertEqual(argv[-4:], ["--system=sony-playstation", "--backup", "--events",
"--yes"])
def test_close_ends_with_the_removal_s_code_and_back_counts_again(self):
state = removal_done_state()
self.assertEqual(state.screen, "actdone")
self.assertIn("Removed 2 files, 512.0 KB freed.",
screen_text(install.tui_view(state, 80, 24)))
press(state, "enter")
self.assertEqual(state.exit_code, 0)
state = removal_done_state()
with mock.patch.object(install, "setup_record", return_value=(None, None, "")):
effects = press(state, "esc")
self.assertEqual(effects, [("run", "check")])
self.assertEqual(state.screen, "checking")
# The record is read again: the removal changed it.
self.assertIsNone(state.record)
def test_a_failure_is_said_and_ends_on_one(self):
state = removal_state()
press(state, "enter", "enter")
install.tui_receive(state, ("event", state.run_id, {
"event": "removed", "platform": "retroarch", "dest": "scph5500.bin",
"size": 524288, "ok": False, "reason": "Permission denied", "moved_to": ""}))
install.tui_receive(state, ("ended", state.run_id, 1, []))
self.assertIn("1 file failed.", screen_text(install.tui_view(state, 80, 24)))
press(state, "enter")
self.assertEqual(state.exit_code, 1)
def test_a_put_back_says_why_it_is_not_done_and_where_files_were_kept(self):
folder = str(BACKUPS[0]["folder"])
state = backups_state("putback")
press(state, "enter", "enter")
install.tui_receive(state, ("event", state.run_id, {
"event": "restored", "folder": folder, "path": "/bios/scph5500.bin",
"size": 524288, "ok": True, "reason": ""}))
install.tui_receive(state, ("event", state.run_id, {
"event": "restore", "folder": folder, "status": "not_done", "files": 1,
"bytes": 524288, "kept": [{"folder": "/kept/20261122-101010", "files": 1,
"bytes": 4}],
"problem": "it is for /bios, which does not hold the files put back",
"message": ""}))
install.tui_receive(state, ("ended", state.run_id, 1, []))
text = screen_text(install.tui_view(state, 100, 30))
self.assertIn("Put back 1 file, 512.0 KB.", text)
self.assertIn("Kept 1 file that were in their place (4 B) in /kept/20261122-101010",
text)
self.assertIn("The install record could not be updated (it is for /bios", text)
def test_put_back_and_delete_name_the_backup_alone(self):
folder = BACKUPS[0]["folder"]
for purpose, run, argv in (
("putback", "restore", [f"--restore={folder}", "--events"]),
("dropbackup", "delete_backup",
[f"--delete-backup={folder}", "--events", "--yes"])):
with self.subTest(purpose=purpose):
state = backups_state(purpose)
press(state, "enter")
self.assertEqual(state.screen, "actconfirm")
self.assertEqual(press(state, "enter"), [("run", run)])
self.assertEqual(install.tui_argv(state, run, "python", "install.py"),
["python", "install.py", *argv])
def test_a_backup_looked_at_offers_both(self):
state = backups_state()
press(state, "down", "enter")
self.assertEqual(state.screen, "backup")
self.assertEqual(state.backup_chosen["date"], BACKUPS[1]["date"])
self.assertEqual([row.action for row in install.tui_rows(state)],
["bkrestore", "bkdelete", "back"])
argv = install.tui_argv(state, "backups", "python", "install.py")
self.assertEqual(argv[-2:], ["--backups", "--events"])
def test_without_a_record_nothing_is_offered_to_remove(self):
state = checked_state()
state.record = None
state.stack += ["more", "remove"]
self.assertEqual([row.action for row in install.tui_rows(state)], ["back"])
self.assertIn("No install record here", screen_text(install.tui_view(state, 80, 24)))
def test_the_files_and_what_stays_are_on_details(self):
state = removal_state()
state.focus["removal"] = [row.action for row in install.tui_rows(state)].index(
"details")
press(state, "enter")
text = screen_text(install.tui_view(state, 80, 24))
self.assertIn("pcsx/extra.bin", text)
self.assertIn("scph5501.bin: changed since it was installed", text)
class PackScreens(unittest.TestCase):
"""More, Make a pack: a dry run says what goes in, the run makes it,
each a child given the plan's choice and none of the folder's options."""
def setUp(self):
patcher = mock.patch.object(install, "_mounted_cards", return_value=[])
patcher.start()
self.addCleanup(patcher.stop)
def test_more_is_on_every_plan_with_make_a_pack(self):
state = checked_state()
self.assertEqual([row.action for row in install.tui_rows(state)][-2:],
["more", "quit"])
state.stack.append("more")
self.assertEqual([row.action for row in install.tui_rows(state)], ["packmake"])
self.assertEqual([row.action for row in install.tui_rows(more_state("more"))][-1],
"packmake")
def test_the_dry_run_takes_the_choice_and_not_the_folder(self):
state = pack_plan_state()
state.regions = ["japan"]
state.passthrough = [("--save-dir", "/saves")]
argv = install.tui_argv(state, "pack_plan", "python", "install.py")
self.assertIn("--region=japan", argv)
self.assertFalse([arg for arg in argv if arg.startswith(("--dest", "--save-dir"))])
# No Downloads folder here: the home folder.
self.assertEqual(argv[-3:], [f"--pack={HOME}{os.sep}", "--dry-run", "--events"])
with mock.patch.object(install, "_is_dir", return_value=True):
self.assertEqual(install.tui_pack_dir(state), HOME / "Downloads")
self.assertEqual([row.action for row in install.tui_rows(state)],
["packgo", "packwhere"])
def test_make_the_pack_runs_it_and_close_ends_on_its_code(self):
state = pack_plan_state()
self.assertEqual(install.tui_update(state, Key("enter")), [("run", "pack")])
self.assertEqual(install.tui_argv(state, "pack", "python", "install.py")[-2:],
["--events", "--yes"])
self.assertIn("Making the pack...", screen_text(install.tui_view(state, 80, 24)))
install.tui_receive(state, ("event", state.run_id, pack_event("written", size=900)))
install.tui_receive(state, ("ended", state.run_id, 0, []))
self.assertIn("Pack made: 4 files, 900 B.", screen_text(install.tui_view(state, 80, 24)))
install.tui_update(state, Key("enter"))
self.assertEqual(state.exit_code, 0)
def test_a_pack_not_made_says_so_and_back_returns_to_more(self):
state = pack_plan_state()
install.tui_update(state, Key("enter"))
failed = {**pack_event("failed"), "parts": [],
"message": "1 file could not be had: no pack was written."}
install.tui_receive(state, ("event", state.run_id, failed))
install.tui_receive(state, ("ended", state.run_id, 1, []))
text = screen_text(install.tui_view(state, 80, 24))
self.assertIn("No pack was made.", text)
self.assertIn("1 file could not be had", text)
install.tui_update(state, Key("esc"))
self.assertEqual(state.screen, "more")
def test_change_where_browses_and_reads_the_plan_again(self):
state = pack_plan_state()
state.focus["packplan"] = 1
with mock.patch.object(install, "_browse_rows", return_value=(
[install.TuiRow("use", "Use this folder")], "")):
install.tui_update(state, Key("enter"))
self.assertEqual((state.screen, state.browse_for), ("browse", "packto"))
state.browse_dir = Path("/media/card")
self.assertEqual(install.tui_update(state, Key("enter")), [("run", "pack_plan")])
self.assertEqual(state.screen, "packplan")
self.assertEqual(install.tui_argv(state, "pack_plan", "python", "install.py")[-3],
f"--pack={Path('/media/card')}{os.sep}")
def test_a_dry_run_that_ends_without_its_event_is_an_error(self):
state = checked_state()
state.stack += ["more"]
state.focus["more"] = 0
install.tui_update(state, Key("enter"))
install.tui_receive(state, ("ended", state.run_id, 2, ["install.py: error: no"]))
self.assertEqual(state.screen, "error")
class ScreenWordBudgets(unittest.TestCase):
def setUp(self):
patcher = mock.patch.object(install, "_mounted_cards", return_value=[])
patcher.start()
self.addCleanup(patcher.stop)
def test_every_screen_keeps_to_its_budget(self):
states = golden_states()
self.assertEqual(sorted(states), sorted(SCREEN_WORDS),
"a screen without a word budget, or a budget without its screen")
for name, state in states.items():
for (cols, rows), budget in zip(SIZES, SCREEN_WORDS[name]):
with self.subTest(screen=name, size=f"{cols}x{rows}"):
state.cols, state.rows = cols, rows
words = screen_words(install.tui_view(state, cols, rows))
self.assertLessEqual(words, budget)
def test_the_default_path_says_what_where_and_next_first(self):
"""The plan opens on what it installs and where, the result on what
happened, where and the next step: nothing between them."""
plan = [str(line).strip() for line in install.tui_view(checked_state(), 80, 24)]
self.assertEqual(plan[2:4], ["4 files to download, 1.0 MB",
"BIOS folder: ~/.config/retroarch/system"])
self.assertEqual(plan[4], "")
done = result_states()["done"]
lines = [str(line).strip() for line in install.tui_view(done, 80, 24)]
self.assertEqual(lines[2:5], ["4 files installed. 1 file already in place.",
f"BIOS folder: {SYSTEM_DIR}",
"Next: start RetroArch and play."])
class DetailsScreen(unittest.TestCase):
"""What the plan, Confirm and the result leave out by default, one key
or one row away, and every line of --verbose in one place or the other."""
def setUp(self):
patcher = mock.patch.object(install, "_mounted_cards", return_value=[])
patcher.start()
self.addCleanup(patcher.stop)
def text(self, state: install.TuiState, cols: int = 80, rows: int = 24) -> str:
return "\n".join(str(line) for line in install.tui_view(state, cols, rows))
def test_d_opens_the_plans_details_and_b_comes_back(self):
state = checked_state()
self.assertNotIn("Free space", self.text(state))
press(state, "d")
self.assertEqual(state.screen, "details")
shown = self.text(state)
for line in ("1 in place, 3 missing, 1 wrong copy", "Free space: 50.0 GB",
"The 1 wrong copy is replaced"):
self.assertIn(line, shown)
press(state, "esc")
self.assertEqual(state.screen, "plan")
def test_a_controller_reaches_them_by_the_row(self):
state = checked_state()
rows = install.tui_rows(state)
state.focus["plan"] = [row.action for row in rows].index("details")
self.assertIn("A/Enter Show", self.text(state))
press(state, "enter")
self.assertEqual(state.screen, "details")
press(state, "enter")
self.assertEqual(state.screen, "plan")
def test_the_results_details_are_said_after_exit_once_opened(self):
state = golden_states_result()
self.assertIn("Y/o Details", self.text(state))
self.assertNotIn("Same choice without questions", "\n".join(install.tui_farewell(state)))
press(state, "o")
self.assertEqual(state.screen, "details")
self.assertIn("Same choice without questions:", self.text(state))
press(state, "esc")
self.assertEqual(state.screen, "result")
press(state, "enter")
farewell = "\n".join(install.tui_farewell(state))
self.assertIn("Same choice without questions:", farewell)
self.assertIn("failed: scph5500.bin (HTTP 404)", farewell)
def test_confirm_has_its_details_too(self):
state = golden_states()["confirm"]
self.assertNotIn("Free space", self.text(state))
press(state, "d")
self.assertEqual(state.screen, "details")
self.assertIn("Nothing is written before Install.", self.text(state))
self.assertIn("Free space: 50.0 GB", self.text(state))
def test_every_line_is_on_the_screen_or_its_details(self):
"""The screen and its Details together say what --verbose says on
the screen alone: no line is lost."""
for name in ("plan", "plan-games", "plan-in-place", "confirm", "result"):
with self.subTest(screen=name):
state = golden_states()[name]
whole = (install._plan_text(state) if state.screen == "plan"
else install._confirm_text(state) if state.screen == "confirm"
else install.tui_outcome(state)[1])
shown = install._shown(state, whole)
state.stack.append("details")
told = install.details_lines(state)
self.assertEqual(sorted(map(str, whole)),
sorted(map(str, [*shown, *[line for line in told
if install._is_detail(line)]])))
def test_verbose_draws_them_in_place_and_offers_no_row(self):
state = checked_state()
state.passthrough = [("--verbose", None)]
text = self.text(state)
self.assertIn("Free space: 50.0 GB", text)
self.assertNotIn("details", [row.action for row in install.tui_rows(state)])
def test_installing_lists_the_files_that_went_well_with_verbose(self):
state = golden_states()["installing"]
self.assertNotIn("gba_bios.bin", self.text(state))
self.assertIn("FAILED scph5500.bin (HTTP 404)", self.text(state))
state.passthrough = [("--verbose", None)]
self.assertIn("ok gba_bios.bin", self.text(state))
if __name__ == "__main__":
unittest.main()
+1473
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -69,7 +69,7 @@ Every module in `tests/`, by the area it guards.
| Packs and manifests | synthetic + real packs | `test_artifact_lock`, `test_atomic_artifacts`, `test_batocera_cores`, `test_core_data_trees`, `test_deterministic_zip`, `test_emulator_pack_counts`, `test_finalize_pack_names`, `test_large_file_cache`, `test_libretro_layout`, `test_manifest_entry`, `test_manifest_narrowings`, `test_minui_platform`, `test_no_game_data`, `test_pack_conformance_dirs`, `test_pack_core_extras`, `test_pack_counts`, `test_pack_destinations`, `test_pack_failures`, `test_pack_file_names`, `test_pack_grouping`, `test_pack_integrity`, `test_pack_member_identity`, `test_pack_readme`, `test_platform_inheritance`, `test_platform_keys`, `test_release_packs`, `test_required_only_archives`, `test_required_only_twins`, `test_save_root`, `test_split_extras`, `test_split_names`, `test_split_pack`, `test_system_pack_extras`, `test_system_pack_parity`, `test_torrentzip`, `test_which_pack` |
| Slots and regions | synthetic + profiles | `test_region`, `test_region_agnostic_scan`, `test_region_groups`, `test_region_held`, `test_region_platform_index`, `test_region_required_only`, `test_slot`, `test_slots`, `test_slots_shipped_file` |
| Hardware targets and systems | synthetic + target files | `test_amberelec_targets`, `test_emuelec_targets`, `test_extract_targets`, `test_lakka_targets`, `test_libretro_slugs`, `test_system_ids`, `test_system_selection`, `test_target_names`, `test_target_scrapers`, `test_target_systems`, `test_target_verify` |
| Installer and downloads | loopback server | `test_build_installer`, `test_check_release`, `test_download`, `test_install_app`, `test_install_bootstrap`, `test_install_config`, `test_install_cores`, `test_install_data_trees`, `test_install_detection`, `test_install_devices`, `test_install_downloads`, `test_install_events`, `test_install_experience`, `test_install_expert`, `test_install_filesystems`, `test_install_from`, `test_install_games`, `test_install_journeys`, `test_install_kept`, `test_install_offline`, `test_install_pack`, `test_install_pack_parity`, `test_install_platforms`, `test_install_removal`, `test_install_runs`, `test_install_selection`, `test_install_standalone`, `test_install_tui`, `test_pypi_package` |
| Installer and downloads | loopback server | `test_build_installer`, `test_check_release`, `test_download`, `test_install_app`, `test_install_bootstrap`, `test_install_config`, `test_install_cores`, `test_install_data_trees`, `test_install_detection`, `test_install_devices`, `test_install_downloads`, `test_install_events`, `test_install_experience`, `test_install_expert`, `test_install_filesystems`, `test_install_from`, `test_install_games`, `test_install_journeys`, `test_install_kept`, `test_install_offline`, `test_install_pack`, `test_install_pack_parity`, `test_install_platforms`, `test_install_removal`, `test_install_runs`, `test_install_selection`, `test_install_standalone`, `test_pypi_package`, `test_tui_card_counts`, `test_tui_card_setups`, `test_tui_card_space`, `test_tui_choices`, `test_tui_devices`, `test_tui_flow`, `test_tui_folders`, `test_tui_line_mode`, `test_tui_mouse`, `test_tui_packs`, `test_tui_pty`, `test_tui_screens`, `test_tui_terminal`, `test_tui_views` |
| Handheld launchers | a pty as the console, fake installer and firmware tools, stubbed PortMaster dialogs | `test_handheld_frontends`, `test_handheld_portmaster`, `test_handheld_scripts`, `test_port`, `test_site_handheld` |
| Running cores | parsers on fixed inputs, a libretro core built from C in the test when a compiler exists | `test_core_probe` |
| Measurement records | synthetic record files, the committed `measurements/` against HEAD, the **Proof** line naming the BIOS a core ran, and that no page shows a Tested block, a region outcome or a time per frame | `test_measurements` |