about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorfox <fox@fakecake.org>2026-07-04 09:16:15 +0300
committerfox <fox@fakecake.org>2026-07-04 09:16:15 +0300
commit73da29ebcff63c58d28eba51f5029eaf1fa17492 (patch)
tree434eea4a2b84ec872d103285999e7ff6d4039a18
parentbe5112e34098931aa72803cf9d06deadfdf7a0fd (diff)
parentc907a702922a22f7b01f54a401b90aff41dd213f (diff)
downloadfungus-launcher-73da29ebcff63c58d28eba51f5029eaf1fa17492.tar.gz
fungus-launcher-73da29ebcff63c58d28eba51f5029eaf1fa17492.tar.xz
Merge branch 'dev' into 'master'
add tests for run manager

See merge request git/fungus-launcher!36
-rw-r--r--.gitlab-ci.yml5
-rw-r--r--fungus-run.py4
-rw-r--r--fungus/run_manager.py2
-rw-r--r--scripts/check_meson_py_files.py60
-rw-r--r--tests/test_run_manager.py456
5 files changed, 524 insertions, 3 deletions
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index 891d0b9..7573c62 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -27,6 +27,11 @@ signals:
   script:
     - python scripts/check_handlers.py
 
+meson-modules:
+  extends: .ruff
+  script:
+    - python scripts/check_meson_py_files.py
+
 pyright:
   extends: .pyright
 
diff --git a/fungus-run.py b/fungus-run.py
index c5753d7..ab97922 100644
--- a/fungus-run.py
+++ b/fungus-run.py
@@ -27,12 +27,12 @@ def main() -> None:
     if args.verbose:
         set_level(logging.DEBUG)
 
-    from fungus.run_manager import handle_command, load_game_from_json
+    from fungus.run_manager import handle_command, load_game
 
     if not args.game:
         parser.error("no game provided. Use --game <gameid>.")
 
-    game = load_game_from_json(args.game)
+    game = load_game(args.game)
     if not game:
         parser.error(f'game "{args.game}" not found in games.json.')
 
diff --git a/fungus/run_manager.py b/fungus/run_manager.py
index 97dd790..00083bf 100644
--- a/fungus/run_manager.py
+++ b/fungus/run_manager.py
@@ -823,7 +823,7 @@ def handle_command(game: Game, cmd_override: str | None = None, igpu: bool = Fal
     sys.exit(0)
 
 
-def load_game_from_json(gameid):
+def load_game(gameid):
     """Load a ``Game`` object from the library by its gameid."""
     library = GameLibrary()
     if library.exists(gameid):
diff --git a/scripts/check_meson_py_files.py b/scripts/check_meson_py_files.py
new file mode 100644
index 0000000..06cb834
--- /dev/null
+++ b/scripts/check_meson_py_files.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python3
+"""Verify that all .py files in fungus/ are listed in fungus/meson.build."""
+
+import re
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+FUNGUS_DIR = ROOT / "fungus"
+MESON_BUILD = FUNGUS_DIR / "meson.build"
+
+
+def discover_py_files() -> set[str]:
+    """Return all .py files directly inside fungus/ (excluding __pycache__)."""
+    return {
+        f.name
+        for f in FUNGUS_DIR.iterdir()
+        if f.is_file() and f.suffix == ".py" and f.name != "__main__.py"
+    }
+
+
+def extract_listed_py_files() -> set[str]:
+    """Parse fungus/meson.build and extract quoted .py filenames."""
+    text = MESON_BUILD.read_text(encoding="utf-8")
+    # Match single-quoted strings ending with .py
+    return {
+        m.group(1)
+        for m in re.finditer(r"'([^']+\.py)'", text)
+    }
+
+
+def main() -> int:
+    discovered = discover_py_files()
+    listed = extract_listed_py_files()
+
+    missing_in_meson = discovered - listed
+    extra_in_meson = listed - discovered
+
+    status = 0
+    if missing_in_meson:
+        print("❌ .py files in fungus/ NOT listed in meson.build:")
+        for name in sorted(missing_in_meson):
+            print(f"   {name}")
+        status = 1
+
+    if extra_in_meson:
+        print("⚠️  .py files listed in meson.build but missing from fungus/:")
+        for name in sorted(extra_in_meson):
+            print(f"   {name}")
+        if not status:
+            status = 1  # warn is non-zero too
+
+    if not missing_in_meson and not extra_in_meson:
+        print("✅ All .py files in fungus/ are accounted for in meson.build.")
+
+    return status
+
+
+if __name__ == "__main__":
+    sys.exit(main())
diff --git a/tests/test_run_manager.py b/tests/test_run_manager.py
new file mode 100644
index 0000000..99d4b5b
--- /dev/null
+++ b/tests/test_run_manager.py
@@ -0,0 +1,456 @@
+"""Tests for fungus.run_manager — non-UI logic (bwrap args, env loading, path resolution)."""
+
+import os
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+@pytest.fixture()
+def mock_gtk():
+    """Provide minimal GTK/GLib mocks so run_manager can be imported."""
+    with patch("gi.require_version"):
+        mock_gtk = MagicMock()
+        mock_glib = MagicMock()
+        mock_glib.PRIORITY_LOW = -100
+        mock_glib.PRIORITY_DEFAULT = 0
+        mock_glib.IO_IN = 1
+        mock_glib.idle_add = MagicMock(return_value=1)
+        mock_glib.io_add_watch = MagicMock(return_value=1)
+        mock_glib.child_watch_add = MagicMock()
+        mock_glib.timeout_add_seconds = MagicMock(return_value=1)
+        mock_gtk.Window = MagicMock
+        mock_gtk.Application = MagicMock
+        mock_gtk.ApplicationWindow = MagicMock
+        mock_gtk.Application.main = MagicMock()
+        mock_gtk.main_quit = MagicMock()
+        mock_gtk.main = MagicMock()
+        with patch.dict("sys.modules", {"gi": MagicMock(), "gi.repository": MagicMock()}):
+            sys_modules = __import__("sys").modules
+            sys_modules["gi"].require_version = lambda *a: None
+            repo = MagicMock()
+            repo.Gtk = mock_gtk
+            repo.GLib = mock_glib
+            sys_modules["gi.repository"] = repo
+            yield mock_gtk, mock_glib
+
+
+@pytest.fixture()
+def game(tmp_path):
+    """Provide a minimal Game object for FungusRun tests."""
+    from fungus.game_model import Game
+
+    return Game(
+        gameid="umu-1234",
+        title="Test Game",
+        path=str(tmp_path / "game.sh"),
+        prefix=str(tmp_path / "prefix"),
+        launch_arguments="",
+        game_arguments="--verbose",
+        protonfix="umu-1234",
+        runner="GE-Proton9-11",
+        playtime=0,
+        hidden=False,
+        favorite=False,
+    )
+
+
+@pytest.fixture()
+def fungus_run(tmp_path, game, mock_gtk):
+    """Provide a FungusRun instance with mocked GTK and a real tmp prefix."""
+    from fungus.run_manager import FungusRun
+
+    # Create the game script so _resolve_command_path has something to find
+    game_path = Path(game.path)
+    game_path.write_text("#!/bin/bash\necho hello\n", encoding="utf-8")
+    game_path.chmod(0o755)
+
+    # Create prefix dirs so _resolve_command_path can search them
+    prefix = Path(game.prefix)
+    prefix.mkdir(parents=True, exist_ok=True)
+    (prefix / "drive_c" / "windows" / "system32").mkdir(parents=True, exist_ok=True)
+
+    # Mock ConfigManager so load_config doesn't touch real files
+    mock_cfg = MagicMock()
+    mock_cfg.get_bool.return_value = False
+    mock_cfg.get.return_value = ""
+
+    with patch("fungus.run_manager.ConfigManager", return_value=mock_cfg):
+        run = FungusRun(game, igpu=False)
+
+    # Replace the game object with one that has an absolute path so
+    # _resolve_command_path doesn't try filesystem lookups during init
+    run.game.path = str(game_path)
+
+    yield run
+
+
+@pytest.fixture()
+def env_file(tmp_path):
+    """Write a sample environment file and return its path."""
+    env_path = tmp_path / "env.txt"
+    env_path.write_text(
+        "FOO=bar\nBAZ=qux\n",
+        encoding="utf-8",
+    )
+    return env_path
+
+
+# ---------------------------------------------------------------------------
+# Test _flatten_bwrap_args
+# ---------------------------------------------------------------------------
+
+
+class TestFlattenBwrapArgs:
+    def test_single_entry(self, mock_gtk):
+        from fungus.run_manager import FungusRun
+
+        result = FungusRun._flatten_bwrap_args([("--ro-bind", "/usr", "/usr")])
+        assert result == ["--ro-bind", "/usr", "/usr"]
+
+    def test_multiple_entries(self, mock_gtk):
+        from fungus.run_manager import FungusRun
+
+        entries = [
+            ("--ro-bind", "/usr", "/usr"),
+            ("--proc", "/proc"),
+            ("--bind", "/tmp", "/tmp"),
+        ]
+        result = FungusRun._flatten_bwrap_args(entries)
+        assert result == ["--ro-bind", "/usr", "/usr", "--proc", "/proc", "--bind", "/tmp", "/tmp"]
+
+    def test_empty_list(self, mock_gtk):
+        from fungus.run_manager import FungusRun
+
+        result = FungusRun._flatten_bwrap_args([])
+        assert result == []
+
+    def test_preserves_order(self, mock_gtk):
+        from fungus.run_manager import FungusRun
+
+        entries = [("--bind", "a", "a"), ("--ro-bind", "b", "b")]
+        result = FungusRun._flatten_bwrap_args(entries)
+        assert result[0] == "--bind"
+        assert result[3] == "--ro-bind"
+
+
+# ---------------------------------------------------------------------------
+# Test _resolve_command_path
+# ---------------------------------------------------------------------------
+
+
+class TestResolveCommandPath:
+    def test_absolute_existing_path_unchanged(self, fungus_run, tmp_path):
+        """If game.path is already absolute and exists, it is left alone."""
+        script = tmp_path / "game.sh"
+        script.write_text("#!/bin/bash", encoding="utf-8")
+        script.chmod(0o755)
+        fungus_run.game.path = str(script)
+        fungus_run._resolve_command_path()
+        assert fungus_run.game.path == str(script)
+
+    def test_simple_command_name_not_found(self, fungus_run):
+        """If the path is a bare name and not found in prefix system dirs, it stays unchanged."""
+        fungus_run.game.path = "winecfg"
+        fungus_run.game.prefix = str(fungus_run.game.prefix)  # ensure it's a string
+        fungus_run._resolve_command_path()
+        # Path should remain as-is since it's not absolute and not found
+        assert fungus_run.game.path == "winecfg"
+
+    def test_simple_command_found_in_system32(self, tmp_path, mock_gtk):
+        """If a bare command name exists in drive_c/windows/system32, path is resolved."""
+        from fungus.game_model import Game
+        from fungus.run_manager import FungusRun
+
+        prefix = tmp_path / "prefix"
+        system32 = prefix / "drive_c" / "windows" / "system32"
+        system32.mkdir(parents=True)
+        cmd = system32 / "winecfg"
+        cmd.write_text("#!/bin/bash", encoding="utf-8")
+
+        game = Game(
+            gameid="umu-9999",
+            title="Test",
+            path="winecfg",
+            prefix=str(prefix),
+            runner="GE-Proton9-11",
+        )
+
+        mock_cfg = MagicMock()
+        mock_cfg.get_bool.return_value = False
+        mock_cfg.get.return_value = ""
+
+        with patch("fungus.run_manager.ConfigManager", return_value=mock_cfg):
+            run = FungusRun(game)
+
+        run._resolve_command_path()
+        assert run.game.path == str(cmd)
+
+    def test_simple_command_found_as_exe_in_windows_dir(self, tmp_path, mock_gtk):
+        """If 'winecfg' doesn't exist but 'winecfg.exe' does in drive_c/windows, use that."""
+        from fungus.game_model import Game
+        from fungus.run_manager import FungusRun
+
+        prefix = tmp_path / "prefix"
+        windows_dir = prefix / "drive_c" / "windows"
+        windows_dir.mkdir(parents=True)
+        cmd = windows_dir / "winecfg.exe"
+        cmd.write_text("#!/bin/bash", encoding="utf-8")
+
+        game = Game(
+            gameid="umu-9998",
+            title="Test",
+            path="winecfg",
+            prefix=str(prefix),
+            runner="GE-Proton9-11",
+        )
+
+        mock_cfg = MagicMock()
+        mock_cfg.get_bool.return_value = False
+        mock_cfg.get.return_value = ""
+
+        with patch("fungus.run_manager.ConfigManager", return_value=mock_cfg):
+            run = FungusRun(game)
+
+        run._resolve_command_path()
+        assert run.game.path == str(cmd)
+
+    def test_no_prefix_empty_path(self, fungus_run):
+        """If game.prefix is empty, path resolution is a no-op."""
+        fungus_run.game.path = "something"
+        fungus_run.game.prefix = ""
+        fungus_run._resolve_command_path()
+        assert fungus_run.game.path == "something"
+
+
+# ---------------------------------------------------------------------------
+# Test load_env_from_file
+# ---------------------------------------------------------------------------
+
+
+class TestLoadEnvFromFile:
+    def test_loads_valid_env_file(self, fungus_run, env_file):
+        result = fungus_run.load_env_from_file(str(env_file))
+        assert result == {"FOO": "bar", "BAZ": "qux"}
+
+    def test_returns_empty_dict_for_missing_file(self, fungus_run, tmp_path):
+        result = fungus_run.load_env_file = fungus_run.load_env_from_file
+        result(tmp_path / "nonexistent.txt")
+        assert result(tmp_path / "nonexistent.txt") == {}
+
+    def test_ignores_empty_lines_and_comments(self, tmp_path, fungus_run):
+        env_path = tmp_path / "env.txt"
+        env_path.write_text(
+            "FOO=bar\n\n# comment\nBAZ=qux\n\n",
+            encoding="utf-8",
+        )
+        result = fungus_run.load_env_from_file(str(env_path))
+        assert result == {"FOO": "bar", "BAZ": "qux"}
+
+    def test_splits_on_first_equals_only(self, tmp_path, fungus_run):
+        """Values containing '=' should be preserved."""
+        env_path = tmp_path / "env.txt"
+        env_path.write_text("KEY=value=with=equals\n", encoding="utf-8")
+        result = fungus_run.load_env_from_file(str(env_path))
+        assert result == {"KEY": "value=with=equals"}
+
+    def test_sets_os_environ(self, tmp_path, fungus_run):
+        env_path = tmp_path / "env.txt"
+        env_path.write_text("TEST_VAR=hello\n", encoding="utf-8")
+        fungus_run.load_env_from_file(str(env_path))
+        assert os.environ.get("TEST_VAR") == "hello"
+
+
+# ---------------------------------------------------------------------------
+# Test build_bwrap_command
+# ---------------------------------------------------------------------------
+
+
+class TestBuildBwrapCommand:
+    def test_basic_command_structure(self, fungus_run):
+        """The bwrap command should start with 'bwrap' and include required flags."""
+        bwrap_args, _, _ = fungus_run.build_bwrap_command(
+            fungus_run.game, [], None,
+        )
+        assert bwrap_args[0] == "bwrap"
+        assert "--die-with-parent" in bwrap_args
+        assert "--unshare-user" in bwrap_args
+        assert "--unshare-cgroup" in bwrap_args
+        assert "--unshare-pid" in bwrap_args
+        assert "--unshare-uts" in bwrap_args
+        assert "--unshare-net" in bwrap_args
+        assert "--new-session" in bwrap_args
+
+    def test_umu_env_vars_set(self, fungus_run):
+        """GAMEID, WINEPREFIX, PROTONPATH should be in sandbox_env."""
+        _, sandbox_env, _ = fungus_run.build_bwrap_command(
+            fungus_run.game, [], None,
+        )
+        assert sandbox_env["GAMEID"] == "umu-1234"
+        assert sandbox_env["WINEPREFIX"] == fungus_run.game.prefix
+        assert sandbox_env["PROTONPATH"] == "GE-Proton9-11"
+
+    def test_inner_command_contains_umu_run_and_game_path(self, fungus_run):
+        from fungus.constants import umu_run
+
+        _, _, inner_cmd = fungus_run.build_bwrap_command(
+            fungus_run.game, [], None,
+        )
+        assert inner_cmd[0] == umu_run
+        assert inner_cmd[1] == fungus_run.game.path
+
+    def test_game_arguments_appended(self, fungus_run):
+        """game_arguments should be appended to the inner command."""
+        _, _, inner_cmd = fungus_run.build_bwrap_command(
+            fungus_run.game, [], None,
+        )
+        # --verbose is the game_arguments
+        assert "--verbose" in inner_cmd
+
+    def test_game_dirs_bind_mounted(self, tmp_path, fungus_run):
+        """Each game directory should be bind-mounted."""
+        game_dir = str(tmp_path / "games")
+        Path(game_dir).mkdir()
+        bwrap_args, _, _ = fungus_run.build_bwrap_command(
+            fungus_run.game, [game_dir], None,
+        )
+        assert "--bind" in bwrap_args
+        # Find the index of the bind mount for game_dir
+        bind_idx = bwrap_args.index("--bind")
+        assert bwrap_args[bind_idx + 1] == game_dir
+        assert bwrap_args[bind_idx + 2] == game_dir
+
+    def test_env_from_file_merged(self, tmp_path, fungus_run, env_file):
+        """Environment variables from file should be in sandbox_env."""
+        env_data = fungus_run.load_env_from_file(str(env_file))
+        _, sandbox_env, _ = fungus_run.build_bwrap_command(
+            fungus_run.game, [], env_data,
+        )
+        assert sandbox_env["FOO"] == "bar"
+        assert sandbox_env["BAZ"] == "qux"
+
+    def test_ro_bind_entries_present(self, fungus_run):
+        """Read-only system binds should be present."""
+        bwrap_args, _, _ = fungus_run.build_bwrap_command(
+            fungus_run.game, [], None,
+        )
+        # Check that --ro-bind /usr /usr is present
+        assert "--ro-bind" in bwrap_args
+        usr_idx = bwrap_args.index("--ro-bind")
+        assert bwrap_args[usr_idx + 1] == "/usr"
+        assert bwrap_args[usr_idx + 2] == "/usr"
+
+    def test_sandbox_env_keys_from_os_environ(self, fungus_run):
+        """SANDBOX_ENV_KEYS values should be pulled from os.environ."""
+        os.environ["DRI_PRIME"] = "1"
+        try:
+            _, sandbox_env, _ = fungus_run.build_bwrap_command(
+                fungus_run.game, [], None,
+            )
+            assert sandbox_env["DRI_PRIME"] == "1"
+        finally:
+            del os.environ["DRI_PRIME"]
+
+    def test_config_files_bind_mounted(self, tmp_path, fungus_run, tmp_config_dir):
+        """Config files that exist should be ro-bind mounted."""
+        config_dir = tmp_config_dir / "fungus-launcher"
+        config_dir.mkdir(parents=True, exist_ok=True)
+        (config_dir / "games.json").write_text("{}", encoding="utf-8")
+
+        bwrap_args, _, _ = fungus_run.build_bwrap_command(
+            fungus_run.game, [], None,
+        )
+        games_json_path = str(config_dir / "games.json")
+        assert "--ro-bind" in bwrap_args
+        # Check that the games.json path is bind-mounted
+        found = False
+        for i, arg in enumerate(bwrap_args):
+            if arg == "--ro-bind" and i + 2 < len(bwrap_args):
+                if bwrap_args[i + 1] == games_json_path:
+                    found = True
+                    break
+        assert found, f"games.json not ro-bind mounted. bwrap_args: {bwrap_args}"
+
+
+# ---------------------------------------------------------------------------
+# Test load_config
+# ---------------------------------------------------------------------------
+
+
+class TestLoadConfig:
+    def test_default_discrete_gpu_false(self, fungus_run):
+        assert fungus_run.discrete_gpu is False
+
+    def test_default_game_directories_empty(self, fungus_run):
+        assert fungus_run.game_directories == ""
+
+    def test_discrete_gpu_from_config(self, tmp_path, game, mock_gtk):
+        """discrete-gpu=True in config should be reflected."""
+        from fungus.run_manager import FungusRun
+
+        cfg_dir = tmp_path / "config"
+        cfg_dir.mkdir(parents=True, exist_ok=True)
+        cfg_file = cfg_dir / "config.ini"
+        cfg_file.write_text(
+            "[settings]\ndiscrete-gpu = true\n",
+            encoding="utf-8",
+        )
+
+        mock_cfg = MagicMock()
+        mock_cfg.get_bool.return_value = True
+        mock_cfg.get.return_value = ""
+
+        with patch("fungus.run_manager.ConfigManager", return_value=mock_cfg):
+            run = FungusRun(game)
+
+        assert run.discrete_gpu is True
+
+    def test_game_directories_from_config(self, tmp_path, game, mock_gtk):
+        """game-directories from config should be reflected."""
+        from fungus.run_manager import FungusRun
+
+        mock_cfg = MagicMock()
+        mock_cfg.get_bool.return_value = False
+        mock_cfg.get.return_value = "/home/user/Games"
+
+        with patch("fungus.run_manager.ConfigManager", return_value=mock_cfg):
+            run = FungusRun(game)
+
+        assert run.game_directories == "/home/user/Games"
+
+
+# ---------------------------------------------------------------------------
+# Test class-level constants
+# ---------------------------------------------------------------------------
+
+
+class TestClassConstants:
+    def test_system_ro_binds_structure(self, mock_gtk):
+        """SYSTEM_RO_BINDS entries should be valid (flag, src, dst) tuples."""
+        from fungus.run_manager import FungusRun
+
+        for entry in FungusRun.SYSTEM_RO_BINDS:
+            assert len(entry) == 3
+            assert entry[0].startswith("--")
+
+    def test_system_binds_structure(self, mock_gtk):
+        """SYSTEM_BINDS entries should be valid tuples."""
+        from fungus.run_manager import FungusRun
+
+        for entry in FungusRun.SYSTEM_BINDS:
+            assert len(entry) >= 2
+            assert entry[0].startswith("--")
+
+    def test_sandbox_env_keys_defined(self, mock_gtk):
+        """SANDBOX_ENV_KEYS should be a non-empty tuple of strings."""
+        from fungus.run_manager import FungusRun
+
+        assert isinstance(FungusRun.SANDBOX_ENV_KEYS, tuple)
+        assert len(FungusRun.SANDBOX_ENV_KEYS) > 0
+        for key in FungusRun.SANDBOX_ENV_KEYS:
+            assert isinstance(key, str)