"""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.game_launcher.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.game_launcher.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.game_launcher.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_global_env # --------------------------------------------------------------------------- class TestLoadGlobalEnv: def test_loads_envars_from_config(self, fungus_run): """load_global_env should return env vars stored in ConfigManager.""" result = fungus_run.load_global_env() assert result == {} # No envars configured in fixture def test_ignores_empty_lines(self, tmp_path, fungus_run): """Empty lines in the environment should be skipped.""" from fungus.config_manager import ConfigManager mock_cfg = MagicMock() mock_cfg.get_envars.return_value = ["FOO=bar", "", "BAZ=qux", ""] with patch.object(ConfigManager, "__new__", return_value=mock_cfg): result = fungus_run.load_global_env() assert result == {"FOO": "bar", "BAZ": "qux"} def test_splits_on_first_equals_only(self, tmp_path, fungus_run): """Values containing '=' should be preserved.""" from fungus.config_manager import ConfigManager mock_cfg = MagicMock() mock_cfg.get_envars.return_value = ["KEY=value=with=equals"] with patch.object(ConfigManager, "__new__", return_value=mock_cfg): result = fungus_run.load_global_env() assert result == {"KEY": "value=with=equals"} def test_ignores_malformed_lines(self, tmp_path, fungus_run): """Lines without '=' should be silently skipped.""" from fungus.config_manager import ConfigManager mock_cfg = MagicMock() mock_cfg.get_envars.return_value = ["FOO=bar", "malformed", "BAZ=qux"] with patch.object(ConfigManager, "__new__", return_value=mock_cfg): result = fungus_run.load_global_env() assert result == {"FOO": "bar", "BAZ": "qux"} def test_strips_whitespace(self, tmp_path, fungus_run): """Keys and values should be stripped of whitespace.""" from fungus.config_manager import ConfigManager mock_cfg = MagicMock() mock_cfg.get_envars.return_value = [" KEY = value "] with patch.object(ConfigManager, "__new__", return_value=mock_cfg): result = fungus_run.load_global_env() assert result == {"KEY": "value"} # --------------------------------------------------------------------------- # Test _build_per_game_env # --------------------------------------------------------------------------- class TestBuildPerGameEnv: def test_empty_environment(self, fungus_run): """An empty environment list should return an empty dict.""" fungus_run.game.environment = [] assert fungus_run._build_per_game_env() == {} def test_parses_env_vars(self, fungus_run): """Valid KEY=VALUE lines should be parsed.""" fungus_run.game.environment = ["WINEDLLOVERRIDES=winmm=n,b", "CUSTOM=val"] result = fungus_run._build_per_game_env() assert result == {"WINEDLLOVERRIDES": "winmm=n,b", "CUSTOM": "val"} def test_ignores_malformed_lines(self, fungus_run): """Lines without '=' should be silently skipped.""" fungus_run.game.environment = ["FOO=bar", "malformed", "BAZ=qux"] result = fungus_run._build_per_game_env() assert result == {"FOO": "bar", "BAZ": "qux"} def test_splits_on_first_equals_only(self, fungus_run): """Values containing '=' should be preserved.""" fungus_run.game.environment = ["KEY=value=with=equals"] result = fungus_run._build_per_game_env() assert result == {"KEY": "value=with=equals"} def test_strips_whitespace(self, fungus_run): """Keys and values should be stripped of whitespace.""" fungus_run.game.environment = [" KEY = value "] result = fungus_run._build_per_game_env() assert result == {"KEY": "value"} def test_duplicate_keys_later_wins(self, fungus_run): """If the same key appears twice, the later entry wins.""" fungus_run.game.environment = ["FOO=bar", "FOO=baz"] result = fungus_run._build_per_game_env() assert result == {"FOO": "baz"} # --------------------------------------------------------------------------- # 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_global_env_merged(self, fungus_run): """Environment variables from file should be in sandbox_env.""" env_data = {"FOO": "bar", "BAZ": "qux"} _, sandbox_env, _ = fungus_run.build_bwrap_command( fungus_run.game, [], env_data, ) assert sandbox_env["FOO"] == "bar" assert sandbox_env["BAZ"] == "qux" def test_per_game_env_overrides_file_env(self, fungus_run): """Per-game env should override global env for the same key.""" env_data = {"FOO": "bar", "BAZ": "qux"} per_game_data = {"FOO": "override", "CUSTOM": "val"} _, sandbox_env, _ = fungus_run.build_bwrap_command( fungus_run.game, [], env_data, per_game_data, ) assert sandbox_env["FOO"] == "override" assert sandbox_env["BAZ"] == "qux" assert sandbox_env["CUSTOM"] == "val" 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.game_launcher.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.game_launcher.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)