diff options
| author | fox <fox@fakecake.org> | 2026-07-02 18:09:11 +0300 |
|---|---|---|
| committer | fox <fox@fakecake.org> | 2026-07-02 18:09:11 +0300 |
| commit | fefa317e1ca59c756b32f84b1e6280cc3b480902 (patch) | |
| tree | f37345ccd0c6b96032b06a1c8c4e3224e4a4c3d3 | |
| parent | 66b57b1db58439caaa155ff98be4a3c8ca72b037 (diff) | |
| parent | 802acc5b01d4d53284f6fb480f8922b8ee7d934c (diff) | |
| download | fungus-launcher-fefa317e1ca59c756b32f84b1e6280cc3b480902.tar.gz fungus-launcher-fefa317e1ca59c756b32f84b1e6280cc3b480902.tar.xz | |
Merge branch 'dev' into 'master'
Dev See merge request git/fungus-launcher!30
| -rw-r--r-- | .gitlab-ci.yml | 3 | ||||
| -rw-r--r-- | AGENTS.md | 2 | ||||
| -rw-r--r-- | fungus/__init__.py | 73 | ||||
| -rw-r--r-- | fungus/meson.build | 1 | ||||
| -rw-r--r-- | fungus/utils.py | 159 | ||||
| -rw-r--r-- | fungus/utils_pure.py | 143 | ||||
| -rw-r--r-- | pytest.ini | 3 | ||||
| -rw-r--r-- | tests/__init__.py | 0 | ||||
| -rw-r--r-- | tests/conftest.py | 73 | ||||
| -rw-r--r-- | tests/test_config_manager.py | 147 | ||||
| -rw-r--r-- | tests/test_game_model.py | 225 | ||||
| -rw-r--r-- | tests/test_path_manager.py | 84 | ||||
| -rw-r--r-- | tests/test_utils.py | 89 |
13 files changed, 842 insertions, 160 deletions
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index e2ae00c..891d0b9 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -30,6 +30,9 @@ signals: pyright: extends: .pyright +pytest: + extends: .pytest + build-43: extends: .build variables: diff --git a/AGENTS.md b/AGENTS.md index 4795e58..34afeaa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,2 +1,2 @@ -- after making any changes to Python code, invoke `ruff check .` and `pyright .`; +- after making any changes to Python code, invoke `ruff check .` and `pyright .` and unit tests `pytest`; - when adding or removing .py files consider updating `meson.build` in the directory if required; diff --git a/fungus/__init__.py b/fungus/__init__.py index 0c09fbd..e64600d 100644 --- a/fungus/__init__.py +++ b/fungus/__init__.py @@ -1,3 +1,4 @@ +# pyright: reportUnsupportedDunderAll=false """Fungus Launcher — a game library manager for Linux/Wine.""" __all__ = [ @@ -26,23 +27,55 @@ __all__ = [ __version__ = "0.1.0" -from fungus.app import FungusApp -from fungus.config_manager import ConfigManager -from fungus.constants import ( - fungus_version, - app_dir, - backup_dir, - config_file_dir, - desktop_dir, - envar_dir, - fungus_launcher_dir, - fungus_png, - fungus_run, - icons_dir, -) -from fungus.dialogs import SandboxWarningDialog -from fungus.game_model import Game, load_games_json, save_games_json, update_game_field -from fungus.main_window import Main -from fungus.path_manager import PathManager -from fungus.settings_dialog import SettingsDialog -from fungus.utils import format_title +# Lazy imports — avoids loading GTK/GI dependencies when only +# pure modules (e.g. game_model, config_manager) are needed. + +def __getattr__(name): + """Lazy-load symbols on first access.""" + _modules = { + "FungusApp": "fungus.app", + "ConfigManager": "fungus.config_manager", + "Game": "fungus.game_model", + "Main": "fungus.main_window", + "PathManager": "fungus.path_manager", + "SandboxWarningDialog": "fungus.dialogs", + "SettingsDialog": "fungus.settings_dialog", + "format_title": "fungus.utils_pure", + "load_games_json": "fungus.game_model", + "save_games_json": "fungus.game_model", + "update_game_field": "fungus.game_model", + } + if name in _modules: + import importlib + + mod = importlib.import_module(_modules[name]) + return getattr(mod, name.replace("_", "")) if name.startswith("_") else getattr(mod, name) + # Fall back to module-level constants + from fungus.constants import ( + app_dir, + backup_dir, + config_file_dir, + desktop_dir, + envar_dir, + fungus_launcher_dir, + fungus_png, + fungus_run, + icons_dir, + fungus_version, + ) + + _constants = { + "app_dir": app_dir, + "backup_dir": backup_dir, + "config_file_dir": config_file_dir, + "desktop_dir": desktop_dir, + "envar_dir": envar_dir, + "fungus_launcher_dir": fungus_launcher_dir, + "fungus_png": fungus_png, + "fungus_run": fungus_run, + "icons_dir": icons_dir, + "fungus_version": fungus_version, + } + if name in _constants: + return _constants[name] + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/fungus/meson.build b/fungus/meson.build index 9d3deb0..bcbbe2c 100644 --- a/fungus/meson.build +++ b/fungus/meson.build @@ -25,5 +25,6 @@ py.install_sources( 'settings_dialog.py', 'umu_manager.py', 'utils.py', + 'utils_pure.py', subdir: 'fungus', ) diff --git a/fungus/utils.py b/fungus/utils.py index 5ad2523..11813ec 100644 --- a/fungus/utils.py +++ b/fungus/utils.py @@ -1,64 +1,35 @@ #!/usr/bin/python3 +"""GTK-dependent utility functions. + +Pure utility functions live in ``fungus.utils_pure`` and are +re-exported here for backward compatibility. +""" + import os import re -import unicodedata -from pathlib import Path import gi + gi.require_version('Pango', '1.0') from gi.repository import Pango # type: ignore - -def format_title(title): - title = title.strip().lower() - title = re.sub(r"[^a-z0-9 ]+", "", title) - return re.sub(r"\s+", "-", title) - - -def is_valid_prefix_path(path: str) -> bool: - """Check whether *path* lies within the configured prefixes directory. - - Returns ``True`` only if the resolved path is the prefixes directory - itself or a descendant of it. - """ - from fungus.constants import prefixes_dir - - expanded = os.path.expanduser(path) - resolved = os.path.realpath(expanded) - safe_root = os.path.realpath(prefixes_dir) - - return resolved == safe_root or resolved.startswith(safe_root + os.sep) - - -def is_safe_prefix_path(path: str) -> bool: - """Check whether *path* is a safe target for recursive deletion. - - Returns ``True`` only if the resolved path lies within the fungus - user-data or user-config directories (``~/.local/share/fungus-launcher`` - or ``~/.config/fungus-launcher``), or is one of those directories - itself. - """ - from fungus.path_manager import PathManager - - expanded = os.path.expanduser(path) - resolved = os.path.realpath(expanded) - - safe_roots = [ - os.path.realpath(PathManager.user_data()), - os.path.realpath(PathManager.user_config()), - ] - - for root in safe_roots: - if resolved == root or resolved.startswith(root + os.sep): - return True - - return False - - +# Re-export pure utilities so existing imports from fungus.utils continue +# to work without breaking. +from fungus.utils_pure import ( # noqa: F401 + format_title, + has_proton_installed, + is_executable_in_whitelist, + is_safe_prefix_path, + is_valid_prefix_path, + _resolve_runner_to_directory, +) def _validate_text(entry): + """Remove non-Latin alphabetic characters from a GTK Entry widget.""" + import unicodedata + text = entry.get_text() for i, c in enumerate(text): if c.isalpha() and "LATIN" not in unicodedata.name(c, ""): @@ -68,50 +39,6 @@ def _validate_text(entry): break -def _resolve_runner_to_directory(runner): - """Resolve an old-style runner name to the actual directory on disk. - - If a matching directory exists in compatibilitytools.d, return it. - Otherwise fall back to the newest installed version of that family, - or None if nothing is available. - """ - from fungus.constants import share_dir - - compat_path = Path(share_dir) / "Steam/compatibilitytools.d" - if not compat_path.exists(): - return None - - # Direct directory names pass through unchanged - if (compat_path / runner).is_dir(): - return runner - - old_aliases = { - "Proton-GE Latest": "GE-Proton", - "GE-Proton Latest (default)": "GE-Proton", - "Proton-EM Latest": "Proton-EM", - "UMU-Proton Latest": None, # no directory equivalent - } - - family = old_aliases.get(runner) - if family is None: - return None # Linux-Native, Steam, or unknown — caller handles - - # Find matching directories in compatibilitytools.d - matches = [ - d for d in compat_path.iterdir() - if d.is_dir() and d.name.startswith(family) - ] - if not matches: - return None # user hasn't installed any version yet - - def sort_key(d): - parts = re.split(r'(\d+)', d.name.replace(family, '')) - return [int(p) if p.isdigit() else p for p in parts] - - matches.sort(key=sort_key, reverse=True) - return matches[0].name - - def populate_combobox_with_runners(combobox): """Populate a GTK ComboBoxText with available Proton/compatibility tool runners. @@ -151,52 +78,6 @@ def populate_combobox_with_runners(combobox): cell_renderer.set_property("max-width-chars", 20) -def has_proton_installed() -> bool: - """Check whether any proton/compatibility tool directories exist on disk.""" - from fungus.constants import share_dir - - compat_path = Path(share_dir) / "Steam/compatibilitytools.d" - if not compat_path.exists(): - return False - - for entry in compat_path.iterdir(): - if entry.is_dir() and entry.name not in ("LegacyRuntime",): - return True - return False - - -def is_executable_in_whitelist(exec_path: str, game_dirs: list[str]) -> bool: - """Check whether *exec_path* resides inside one of the whitelisted directories. - - The executable directory (or the file itself) must be a prefix of, or equal - to, at least one whitelisted directory. - - Returns ``True`` if *game_dirs* is empty (no whitelist configured) or if the - executable path falls within a whitelisted directory. - """ - if not game_dirs: - return True # no whitelist configured — allow everything - - exec_dir = os.path.realpath(os.path.dirname(os.path.abspath(exec_path))) - print(f"[sandbox-check] exec_path={exec_path!r}") - print(f"[sandbox-check] exec_dir={exec_dir!r}") - print(f"[sandbox-check] game_dirs={game_dirs!r}") - - for whitelisted in game_dirs: - wl_real = os.path.realpath(whitelisted) - match_exact = exec_dir == wl_real - match_prefix = exec_dir.startswith(wl_real + os.sep) - print(f"[sandbox-check] wl={whitelisted!r} -> realpath={wl_real!r}") - print(f"[sandbox-check] exact match: {match_exact}") - print(f"[sandbox-check] prefix match: {match_prefix}") - if match_exact or match_prefix: - print(f"[sandbox-check] => MATCH") - return True - - print(f"[sandbox-check] => NO MATCH") - return False - - def pick_folder(title: str, transient_for, current_folder: str | None = None) -> str | None: """Open a GTK folder picker and return the selected path (or ``None``). diff --git a/fungus/utils_pure.py b/fungus/utils_pure.py new file mode 100644 index 0000000..88c156e --- /dev/null +++ b/fungus/utils_pure.py @@ -0,0 +1,143 @@ +#!/usr/bin/python3 + +"""Pure utility functions — no GTK/GI dependencies. + +These can be imported and tested in isolation. +""" + +import os +import re +from pathlib import Path + + +def format_title(title): + """Normalize a title into a slug-like identifier. + + Lowercases, strips, removes non-alphanumeric characters (except spaces), + and collapses whitespace to single hyphens. + """ + title = title.strip().lower() + title = re.sub(r"[^a-z0-9 ]+", "", title) + return re.sub(r"\s+", "-", title) + + +def is_valid_prefix_path(path: str) -> bool: + """Check whether *path* lies within the configured prefixes directory. + + Returns ``True`` only if the resolved path is the prefixes directory + itself or a descendant of it. + """ + from fungus.constants import prefixes_dir + + expanded = os.path.expanduser(path) + resolved = os.path.realpath(expanded) + safe_root = os.path.realpath(prefixes_dir) + + return resolved == safe_root or resolved.startswith(safe_root + os.sep) + + +def is_safe_prefix_path(path: str) -> bool: + """Check whether *path* is a safe target for recursive deletion. + + Returns ``True`` only if the resolved path lies within the fungus + user-data or user-config directories (``~/.local/share/fungus-launcher`` + or ``~/.config/fungus-launcher``), or is one of those directories + itself. + """ + from fungus.path_manager import PathManager + + expanded = os.path.expanduser(path) + resolved = os.path.realpath(expanded) + + safe_roots = [ + os.path.realpath(PathManager.user_data()), + os.path.realpath(PathManager.user_config()), + ] + + for root in safe_roots: + if resolved == root or resolved.startswith(root + os.sep): + return True + + return False + + +def _resolve_runner_to_directory(runner): + """Resolve an old-style runner name to the actual directory on disk. + + If a matching directory exists in compatibilitytools.d, return it. + Otherwise fall back to the newest installed version of that family, + or None if nothing is available. + """ + from fungus.constants import share_dir + + compat_path = Path(share_dir) / "Steam/compatibilitytools.d" + if not compat_path.exists(): + return None + + # Direct directory names pass through unchanged + if (compat_path / runner).is_dir(): + return runner + + old_aliases = { + "Proton-GE Latest": "GE-Proton", + "GE-Proton Latest (default)": "GE-Proton", + "Proton-EM Latest": "Proton-EM", + "UMU-Proton Latest": None, # no directory equivalent + } + + family = old_aliases.get(runner) + if family is None: + return None # Linux-Native, Steam, or unknown — caller handles + + # Find matching directories in compatibilitytools.d + matches = [ + d for d in compat_path.iterdir() + if d.is_dir() and d.name.startswith(family) + ] + if not matches: + return None # user hasn't installed any version yet + + def sort_key(d): + parts = re.split(r'(\d+)', d.name.replace(family, '')) + return [int(p) if p.isdigit() else p for p in parts] + + matches.sort(key=sort_key, reverse=True) + return matches[0].name + + +def has_proton_installed() -> bool: + """Check whether any proton/compatibility tool directories exist on disk.""" + from fungus.constants import share_dir + + compat_path = Path(share_dir) / "Steam/compatibilitytools.d" + if not compat_path.exists(): + return False + + for entry in compat_path.iterdir(): + if entry.is_dir() and entry.name not in ("LegacyRuntime",): + return True + return False + + +def is_executable_in_whitelist(exec_path: str, game_dirs: list[str]) -> bool: + """Check whether *exec_path* resides inside one of the whitelisted directories. + + The executable directory (or the file itself) must be a prefix of, or equal + to, at least one whitelisted directory. + + Returns ``True`` if *game_dirs* is empty (no whitelist configured) or if the + executable path falls within a whitelisted directory. + """ + if not game_dirs: + return True # no whitelist configured — allow everything + + exec_dir = os.path.realpath(os.path.dirname(os.path.abspath(exec_path))) + + for whitelisted in game_dirs: + wl_real = os.path.realpath(whitelisted) + match_exact = exec_dir == wl_real + match_prefix = exec_dir.startswith(wl_real + os.sep) + if match_exact or match_prefix: + return True + + return False diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..4584de7 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +testpaths = tests +pythonpath = . diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/tests/__init__.py diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..7100715 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,73 @@ +"""Shared fixtures for the fungus-launcher test suite.""" + +import os +from unittest.mock import patch + +import pytest + + +@pytest.fixture() +def tmp_data_dir(tmp_path): + """Provide a temporary XDG_DATA_HOME directory.""" + with patch.dict(os.environ, {"XDG_DATA_HOME": str(tmp_path / "data")}): + yield tmp_path / "data" + + +@pytest.fixture() +def tmp_config_dir(tmp_path): + """Provide a temporary XDG_CONFIG_HOME directory.""" + with patch.dict(os.environ, {"XDG_CONFIG_HOME": str(tmp_path / "config")}): + yield tmp_path / "config" + + +@pytest.fixture() +def games_file(tmp_path): + """Provide a path to a temporary games.json file and clean it up.""" + path = tmp_path / "games.json" + yield path + if path.exists(): + path.unlink() + + +@pytest.fixture() +def sample_games(): + """Provide a list of sample Game objects.""" + from fungus.game_model import Game + + return [ + Game( + gameid="umu-1234", + title="Test Game Alpha", + path="/home/user/Games/alpha/game.sh", + prefix="/home/user/prefixes/umu-1234", + launch_arguments="", + game_arguments="--verbose", + protonfix="umu-1234", + runner="GE-Proton9-11", + playtime=3600, + hidden=False, + favorite=True, + ), + Game( + gameid="umu-5678", + title="Test Game Beta", + path="/home/user/Games/beta/beta.exe", + prefix="/home/user/prefixes/umu-5678", + launch_arguments="--options", + game_arguments="", + protonfix="umu-5678", + runner="Proton-EM-1.0", + playtime=7200, + hidden=True, + favorite=False, + ), + ] + + +@pytest.fixture() +def populated_games_file(games_file, sample_games): + """Write sample games to a JSON file and return the path.""" + from fungus.game_model import save_games_json + + save_games_json(str(games_file), sample_games) + return games_file diff --git a/tests/test_config_manager.py b/tests/test_config_manager.py new file mode 100644 index 0000000..6a52ff1 --- /dev/null +++ b/tests/test_config_manager.py @@ -0,0 +1,147 @@ +"""Tests for fungus.config_manager — ConfigManager INI wrapper.""" + + +import pytest + +from fungus.config_manager import ConfigManager + + +@pytest.fixture() +def config_path(tmp_config_dir): + """Return a path for the config.ini file and ensure clean state.""" + config_dir = tmp_config_dir / "fungus-launcher" + config_dir.mkdir(parents=True, exist_ok=True) + return config_dir / "config.ini" + + +@pytest.fixture() +def config_manager(config_path): + """Return a ConfigManager instance backed by a temporary file.""" + from fungus import config_manager as cm + + # Patch the module-level _config_path so it uses our temp file + original_path = cm._config_path + cm._config_path = config_path + + # Reset the instance to pick up the new path + instance = ConfigManager() + + yield instance + + # Restore original + cm._config_path = original_path + + +class TestConfigManagerDefaults: + def test_default_runner(self, config_manager): + assert config_manager.get("default-runner") == "GE-Proton" + + def test_default_discrete_gpu(self, config_manager): + assert config_manager.get("discrete-gpu") == "False" + + def test_default_show_hidden(self, config_manager): + assert config_manager.get("show-hidden") == "False" + + def test_default_game_directories(self, config_manager): + assert config_manager.get("game-directories") == "" + + +class TestConfigManagerGetSet: + def test_set_and_get(self, config_manager): + config_manager.set("default-runner", "Proton-9.0") + assert config_manager.get("default-runner") == "Proton-9.0" + + def test_get_nonexistent_key_returns_empty(self, config_manager): + assert config_manager.get("nonexistent-key") == "" + + def test_get_with_fallback(self, config_manager): + assert config_manager.get("nonexistent-key", "fallback") == "fallback" + + +class TestConfigManagerBool: + def test_true_values(self, config_manager): + for val in ("True", "true", "1", "Yes", "yes", "ON", "on"): + config_manager.set("discrete-gpu", val) + assert config_manager.get_bool("discrete-gpu") is True + + def test_false_values(self, config_manager): + for val in ("False", "false", "0", "No", "no", "OFF", "off"): + config_manager.set("discrete-gpu", val) + assert config_manager.get_bool("discrete-gpu") is False + + def test_default_false(self, config_manager): + assert config_manager.get_bool("nonexistent-key") is False + + def test_custom_fallback(self, config_manager): + assert config_manager.get_bool("nonexistent-key", fallback=True) is True + + +class TestConfigManagerSave: + def test_save_and_reload(self, config_manager, config_path): + config_manager.set("discrete-gpu", "True") + config_manager.set("game-directories", "/home/user/Games") + config_manager.save() + + # Reload from disk + fresh = ConfigManager() + assert fresh.get("discrete-gpu") == "True" + assert fresh.get("game-directories") == "/home/user/Games" + + def test_save_creates_directory(self, config_manager, tmp_config_dir): + config_dir = tmp_config_dir / "new-fungus" + from fungus import config_manager as cm + + original = cm._config_path + cm._config_path = config_dir / "config.ini" + + config_manager.save() + assert config_dir.exists() + assert cm._config_path.exists() + + cm._config_path = original + + def test_save_overwrites_existing(self, config_manager, config_path): + config_manager.set("default-runner", "GE-Proton9-11") + config_manager.save() + + config_manager.set("default-runner", "Proton-10") + config_manager.save() + + # Reload + fresh = ConfigManager() + assert fresh.get("default-runner") == "Proton-10" + + +class TestConfigManagerLegacy: + def test_legacy_key_value_format(self, config_path): + # Write a legacy-style config (no section header) + config_path.write_text( + 'default-runner = GE-Proton-GE-Latest\ndiscrete-gpu = true\n' + '; comment line\nshow-hidden = false\n' + ) + + from fungus import config_manager as cm + + original = cm._config_path + cm._config_path = config_path + mgr = ConfigManager() + + assert mgr.get("default-runner") == "GE-Proton-GE-Latest" + assert mgr.get_bool("discrete-gpu") is True + assert mgr.get("show-hidden") == "false" + + cm._config_path = original + + def test_legacy_ignores_unknown_keys(self, config_path): + config_path.write_text("unknown-key = something\ndefault-runner = TestRunner\n") + + from fungus import config_manager as cm + + original = cm._config_path + cm._config_path = config_path + mgr = ConfigManager() + + assert mgr.get("default-runner") == "TestRunner" + assert mgr.get("unknown-key") == "" # not in defaults + + cm._config_path = original diff --git a/tests/test_game_model.py b/tests/test_game_model.py new file mode 100644 index 0000000..321c879 --- /dev/null +++ b/tests/test_game_model.py @@ -0,0 +1,225 @@ +"""Tests for fungus.game_model — Game dataclass and JSON I/O helpers.""" + +import json +import os + +from fungus.game_model import ( + Game, + backup_games_file, + load_games_json, + save_games_json, + update_game_field, +) + + +# ── Game dataclass ────────────────────────────────────────────────────── + + +class TestGameDataclass: + def test_default_values(self): + game = Game() + assert game.gameid == "" + assert game.title == "" + assert game.path == "" + assert game.prefix == "" + assert game.launch_arguments == "" + assert game.game_arguments == "" + assert game.protonfix == "" + assert game.runner == "" + assert game.playtime == 0 + assert game.hidden is False + assert game.favorite is False + + def test_custom_values(self): + game = Game( + gameid="umu-42", + title="My Game", + path="/opt/games/mygame/run.sh", + prefix="/home/user/pfx", + game_arguments="-fullscreen", + runner="GE-Proton9-11", + playtime=1234, + hidden=False, + favorite=True, + ) + assert game.gameid == "umu-42" + assert game.title == "My Game" + assert game.playtime == 1234 + assert game.favorite is True + + def test_to_dict_roundtrip(self): + original = Game( + gameid="umu-99", + title="Round Trip", + path="/some/path", + prefix="/some/prefix", + launch_arguments="--opt", + game_arguments="-v", + protonfix="umu-99", + runner="GE-Proton10", + playtime=500, + hidden=True, + favorite=False, + ) + d = original.to_dict() + restored = Game.from_dict(d) + assert restored.gameid == original.gameid + assert restored.title == original.title + assert restored.path == original.path + assert restored.prefix == original.prefix + assert restored.launch_arguments == original.launch_arguments + assert restored.game_arguments == original.game_arguments + assert restored.protonfix == original.protonfix + assert restored.runner == original.runner + assert restored.playtime == original.playtime + assert restored.hidden == original.hidden + assert restored.favorite == original.favorite + + def test_from_dict_missing_keys_use_defaults(self): + game = Game.from_dict({}) + assert game.gameid == "" + assert game.title == "" + assert game.playtime == 0 + assert game.hidden is False + + def test_from_dict_partial(self): + game = Game.from_dict({"gameid": "umu-1", "title": "Partial"}) + assert game.gameid == "umu-1" + assert game.title == "Partial" + assert game.path == "" # default + assert game.favorite is False # default + + +# ── load_games_json ───────────────────────────────────────────────────── + + +class TestLoadGamesJson: + def test_load_from_valid_file(self, populated_games_file): + games = load_games_json(str(populated_games_file)) + assert len(games) == 2 + assert games[0].gameid == "umu-1234" + assert games[1].title == "Test Game Beta" + + def test_load_empty_file(self, games_file): + games_file.write_text("[]") + games = load_games_json(str(games_file)) + assert games == [] + + def test_load_nonexistent_file(self, games_file): + games_file.unlink(missing_ok=True) + games = load_games_json(str(games_file)) + assert games == [] + + def test_load_invalid_json(self, games_file): + games_file.write_text("{not valid json!!!") + games = load_games_json(str(games_file)) + assert games == [] + + +# ── save_games_json ───────────────────────────────────────────────────── + + +class TestSaveGamesJson: + def test_save_and_reload(self, games_file, sample_games): + save_games_json(str(games_file), sample_games, backup=False) + games = load_games_json(str(games_file)) + assert len(games) == 2 + assert games[0].gameid == "umu-1234" + assert games[1].favorite is False # should be preserved + + def test_save_with_deleted_gameid(self, games_file, sample_games): + save_games_json( + str(games_file), sample_games, deleted_gameid="umu-1234", backup=False + ) + games = load_games_json(str(games_file)) + assert len(games) == 1 + assert games[0].gameid == "umu-5678" + + def test_save_hidden_games_preserved(self, games_file, sample_games): + save_games_json(str(games_file), sample_games, backup=False) + games = load_games_json(str(games_file)) + hidden_games = [g for g in games if g.hidden] + assert len(hidden_games) == 1 + assert hidden_games[0].gameid == "umu-5678" + + def test_save_empty_list(self, games_file): + save_games_json(str(games_file), [], backup=False) + with open(games_file) as f: + data = json.load(f) + assert data == [] + + def test_backup_is_created(self, games_file, sample_games, tmp_path): + # Write initial file + save_games_json(str(games_file), sample_games, backup=False) + initial_mtime = os.path.getmtime(str(games_file)) + + # Now save again with backup + save_games_json(str(games_file), sample_games, backup=True) + assert os.path.getmtime(str(games_file)) > initial_mtime + + +# ── update_game_field ─────────────────────────────────────────────────── + + +class TestUpdateGameField: + def test_update_existing_game(self, populated_games_file): + update_game_field( + str(populated_games_file), "umu-1234", "favorite", True + ) + games = load_games_json(str(populated_games_file)) + game = next(g for g in games if g.gameid == "umu-1234") + assert game.favorite is True + + def test_update_nonexistent_gameid(self, populated_games_file): + # Should not raise; silently skips + update_game_field( + str(populated_games_file), "nonexistent", "title", "New Title" + ) + games = load_games_json(str(populated_games_file)) + assert all(g.title != "New Title" for g in games) + + def test_update_playtime(self, populated_games_file): + update_game_field( + str(populated_games_file), "umu-5678", "playtime", 9999 + ) + games = load_games_json(str(populated_games_file)) + game = next(g for g in games if g.gameid == "umu-5678") + assert game.playtime == 9999 + + +# ── backup_games_file ─────────────────────────────────────────────────── + + +class TestBackupGamesFile: + def test_creates_backup(self, games_file, tmp_config_dir, sample_games): + + # Write a games file + save_games_json(str(games_file), sample_games, backup=False) + + # Set backup dir + backup_dest = tmp_config_dir / "backups" + + backup_games_file(str(games_file), backup_dir=str(backup_dest)) + + backups = list(backup_dest.glob("games-data-*.json")) + assert len(backups) == 1 + + def test_prunes_old_backups(self, games_file, tmp_config_dir, sample_games): + backup_dest = tmp_config_dir / "backups" + backup_dest.mkdir(parents=True, exist_ok=True) + + # Create 22 fake old backups + for i in range(22): + ts = f"2025-01-01_00-00-{i:02d}" + (backup_dest / f"games-data-{ts}.json").write_text("[]") + + save_games_json(str(games_file), sample_games, backup=False) + backup_games_file(str(games_file), backup_dir=str(backup_dest)) + + backups = list(backup_dest.glob("games-data-*.json")) + assert len(backups) <= 20 + + def test_nonexistent_source_does_nothing(self, tmp_config_dir): + backup_dest = tmp_config_dir / "backups" + backup_games_file("/nonexistent/path.json", backup_dir=str(backup_dest)) + assert not backup_dest.exists() diff --git a/tests/test_path_manager.py b/tests/test_path_manager.py new file mode 100644 index 0000000..1069b09 --- /dev/null +++ b/tests/test_path_manager.py @@ -0,0 +1,84 @@ +"""Tests for fungus.path_manager — PathManager static methods.""" + +import os +from unittest.mock import patch + +from fungus.path_manager import PathManager + + +class TestUserConfig: + def test_default_fallback(self): + """When XDG_CONFIG_HOME is unset, falls back to ~/.config.""" + env = os.environ.copy() + env.pop("XDG_CONFIG_HOME", None) + with patch.dict(os.environ, env, clear=True): + result = PathManager.user_config() + assert "config" in result + assert result.endswith(".config") + + def test_custom_xdg_config_home(self): + with patch.dict(os.environ, {"XDG_CONFIG_HOME": "/tmp/myconfig"}): + result = PathManager.user_config("fungus-launcher") + assert result == "/tmp/myconfig/fungus-launcher" + + def test_joins_multiple_segments(self): + with patch.dict(os.environ, {"XDG_CONFIG_HOME": "/tmp/c"}): + result = PathManager.user_config("fungus-launcher", "sub", "dir") + assert result == "/tmp/c/fungus-launcher/sub/dir" + + +class TestUserData: + def test_default_fallback(self): + """When XDG_DATA_HOME is unset, falls back to ~/.local/share.""" + env = os.environ.copy() + env.pop("XDG_DATA_HOME", None) + with patch.dict(os.environ, env, clear=True): + result = PathManager.user_data() + assert "local/share" in result + + def test_custom_xdg_data_home(self): + with patch.dict(os.environ, {"XDG_DATA_HOME": "/tmp/mydata"}): + result = PathManager.user_data("Steam") + assert result == "/tmp/mydata/Steam" + + +class TestFindBinary: + def test_finds_existing_binary(self): + """Should find python3 which is on the PATH.""" + result = PathManager.find_binary("python3") + assert result != "" + + def test_nonexistent_binary(self): + with patch.dict(os.environ, {"PATH": "/nonexistent"}): + result = PathManager.find_binary("somebinary") + assert result == "" + + +class TestGetIcon: + def test_returns_fallback_when_not_found(self): + """When no icon exists, returns the last fallback path.""" + result = PathManager.get_icon("nonexistent-icon.png") + assert "nonexistent-icon.png" in result + + +class TestSystemData: + def test_searches_xdg_data_dirs(self): + """Should return the first existing path from XDG_DATA_DIRS.""" + with patch.dict( + os.environ, + {"XDG_DATA_DIRS": "/nonexistent1:/nonexistent2:/usr/share"}, + clear=True, + ): + result = PathManager.system_data("icons") + assert result == "/usr/share/icons" + + def test_returns_first_existing(self): + """Should return the first existing directory, not the last.""" + with patch.dict( + os.environ, + {"XDG_DATA_DIRS": "/usr/share:/usr/local/share"}, + clear=True, + ): + result = PathManager.system_data("applications") + # /usr/share/applications should exist + assert "applications" in result diff --git a/tests/test_utils.py b/tests/test_utils.py new file mode 100644 index 0000000..5c1b205 --- /dev/null +++ b/tests/test_utils.py @@ -0,0 +1,89 @@ +"""Tests for pure utility functions in fungus.utils_pure.""" + +from fungus.utils_pure import format_title, is_executable_in_whitelist + + +class TestFormatTitle: + def test_basic_title(self): + assert format_title("My Game") == "my-game" + + def test_removes_special_chars(self): + assert format_title("Game! @#$% Title") == "game-title" + + def test_lowercases(self): + assert format_title("UPPERCASE GAME") == "uppercase-game" + + def test_multiple_spaces_to_hyphens(self): + assert format_title("game with spaces") == "game-with-spaces" + + def test_empty_string(self): + assert format_title("") == "" + + def test_whitespace_only(self): + assert format_title(" ") == "" + + def test_leading_trailing_whitespace(self): + assert format_title(" My Game ") == "my-game" + + def test_numbers_preserved(self): + assert format_title("Game 2024") == "game-2024" + + def test_unicode_removal(self): + # Non-ASCII characters are stripped by the regex + result = format_title("Game café") + assert result == "game-caf" # é is removed, not normalized + + +class TestIsExecutableInWhitelist: + def test_empty_whitelist_allows_everything(self): + assert is_executable_in_whitelist("/some/path/game", []) is True + + def test_exact_dir_match(self): + game_dirs = ["/home/user/Games"] + assert is_executable_in_whitelist("/home/user/Games/game.exe", game_dirs) is True + + def test_subdir_match(self): + game_dirs = ["/home/user/Games"] + assert ( + is_executable_in_whitelist( + "/home/user/Games/subfolder/game.exe", game_dirs + ) + is True + ) + + def test_no_match_outside_whitelist(self): + game_dirs = ["/home/user/Games"] + assert ( + is_executable_in_whitelist("/opt/other/game.exe", game_dirs) is False + ) + + def test_multiple_whitelisted_dirs(self): + game_dirs = ["/home/user/Games", "/mnt/steam/steamapps"] + assert ( + is_executable_in_whitelist("/mnt/steam/steamapps/game.exe", game_dirs) + is True + ) + assert ( + is_executable_in_whitelist("/home/user/Games/another/game.exe", game_dirs) + is True + ) + assert ( + is_executable_in_whitelist("/tmp/hacker/game.exe", game_dirs) is False + ) + + def test_resolves_symlinks(self): + """Should use realpath to resolve symlinks before checking.""" + game_dirs = ["/home/user/Games"] + # Even with a symlink-like path, realpath normalization matters + # We can't easily create symlinks in tests, but we verify the + # function uses os.path.realpath internally. + assert is_executable_in_whitelist("/home/user/Games/game.exe", game_dirs) is True + + def test_prefix_match_prevents_escape(self): + """Game dirs starting with same prefix should not match.""" + game_dirs = ["/home/user/Games"] + # /home/user/GamesExtra should NOT match /home/user/Games + assert ( + is_executable_in_whitelist("/home/user/GamesExtra/game.exe", game_dirs) + is False + ) |
