about summary refs log tree commit diff stats
path: root/tests/test_run_manager.py
blob: 8face5b1219600a66e5e474ca15b5871311f017c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
"""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)