about summary refs log tree commit diff stats
path: root/tests/test_game_model.py
blob: 18a32f17f09ae750cf283267e831c0b1072769f5 (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
"""Tests for fungus.game_model — Game dataclass, GameLibrary, and migration."""

import json
import os


def _write_games_json(path, games):
    """Write a list of Game objects to a JSON file (test helper)."""
    with open(path, "w", encoding="utf-8") as f:
        json.dump([g.to_dict() for g in games], f, ensure_ascii=False, indent=4)

from fungus.game_model import (
    Game,
    GameLibrary,
    MigrationResult,
    load_games_json,
    migrate_to_per_game,
    needs_migration,
)


# ── 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 == []


# ── GameLibrary ─────────────────────────────────────────────────────────


class TestGameLibrary:
    def test_exists_true(self, sample_games_dir):
        library = GameLibrary(str(sample_games_dir))
        assert library.exists("umu-1234") is True

    def test_exists_false(self, sample_games_dir):
        library = GameLibrary(str(sample_games_dir))
        assert library.exists("nonexistent") is False

    def test_load_existing(self, sample_games_dir):
        library = GameLibrary(str(sample_games_dir))
        game = library.load("umu-1234")
        assert game is not None
        assert game.gameid == "umu-1234"
        assert game.title == "Test Game Alpha"
        assert game.playtime == 3600
        assert game.hidden is False
        assert game.favorite is True

    def test_load_nonexistent(self, sample_games_dir):
        library = GameLibrary(str(sample_games_dir))
        assert library.load("nonexistent") is None

    def test_load_all(self, sample_games_dir):
        library = GameLibrary(str(sample_games_dir))
        games = library.load_all()
        assert len(games) == 2
        ids = {g.gameid for g in games}
        assert ids == {"umu-1234", "umu-5678"}

    def test_load_all_empty_dir(self, tmp_path):
        library = GameLibrary(str(tmp_path))
        assert library.load_all() == []

    def test_save_roundtrip(self, tmp_path):
        library = GameLibrary(str(tmp_path))
        game = Game(
            gameid="umu-99",
            title="Saved Game",
            path="/some/path",
            prefix="/some/prefix",
            game_arguments="--verbose",
            runner="GE-Proton10",
            playtime=500,
            hidden=True,
            favorite=False,
        )
        library.save(game)
        loaded = library.load("umu-99")
        assert loaded is not None
        assert loaded.gameid == game.gameid
        assert loaded.title == game.title
        assert loaded.playtime == game.playtime
        assert loaded.hidden == game.hidden
        assert loaded.favorite == game.favorite

    def test_delete_existing(self, sample_games_dir):
        library = GameLibrary(str(sample_games_dir))
        assert library.delete("umu-1234") is True
        assert library.exists("umu-1234") is False
        # Other game still exists
        assert library.exists("umu-5678") is True

    def test_delete_nonexistent(self, sample_games_dir):
        library = GameLibrary(str(sample_games_dir))
        assert library.delete("nonexistent") is False

    def test_update_field_existing(self, sample_games_dir):
        library = GameLibrary(str(sample_games_dir))
        assert library.update_field("umu-1234", "favorite", False) is True
        game = library.load("umu-1234")
        assert game is not None
        assert game.favorite is False

    def test_update_field_nonexistent(self, sample_games_dir):
        library = GameLibrary(str(sample_games_dir))
        assert library.update_field("nonexistent", "title", "New") is False

    def test_add_new(self, tmp_path):
        library = GameLibrary(str(tmp_path))
        game = Game(gameid="umu-new", title="New Game", path="/new")
        assert library.add(game) is True
        assert library.exists("umu-new") is True

    def test_add_duplicate(self, sample_games_dir):
        library = GameLibrary(str(sample_games_dir))
        game = Game(gameid="umu-1234", title="Duplicate", path="/dup")
        assert library.add(game) is False
        # Original still intact
        original = library.load("umu-1234")
        assert original is not None
        assert original.title == "Test Game Alpha"

    def test_save_all(self, tmp_path):
        library = GameLibrary(str(tmp_path))
        games = [
            Game(gameid="a", title="A", path="/a"),
            Game(gameid="b", title="B", path="/b"),
        ]
        library.save_all(games)
        assert library.exists("a")
        assert library.exists("b")
        game_a = library.load("a")
        assert game_a is not None
        assert game_a.title == "A"
        game_b = library.load("b")
        assert game_b is not None
        assert game_b.title == "B"

    def test_atomic_write_crash_safety(self, tmp_path):
        """Verify writes use temp files (no partial .ini left on crash)."""
        library = GameLibrary(str(tmp_path))
        game = Game(gameid="umu-atomic", title="Atomic", path="/atomic")
        library.save(game)
        # No .tmp files left behind
        tmp_files = [f for f in os.listdir(tmp_path) if f.endswith(".ini.tmp")]
        assert tmp_files == []


class TestDuplicateDetection:
    def test_load_all_skips_duplicates(self, tmp_path):
        """If two files have the same gameid, first wins and a warning is logged."""
        library = GameLibrary(str(tmp_path))
        # Write first file normally
        game1 = Game(gameid="umu-dup", title="First", path="/first")
        library.save(game1)
        # Manually write a second file with a different name but same internal gameid
        (tmp_path / "other-name.ini").write_text(
            "[game]\n"
            "gameid = umu-dup\n"
            "title = Second\n"
            "path = /second\n"
            "hidden = false\n"
            "favorite = false\n"
        )
        # load_all returns only one (first alphabetically by filename)
        games = library.load_all()
        assert len(games) == 1
        # other-name.ini sorts before umu-dup.ini
        assert games[0].title == "Second"


# ── Migration ───────────────────────────────────────────────────────────


class TestMigrationResult:
    def test_defaults(self):
        result = MigrationResult()
        assert result.migrated == 0
        assert result.skipped_duplicate == 0
        assert result.skipped_error == 0
        assert result.errors == []


class TestNeedsMigration:
    def test_needs_migration_true(self, tmp_path):
        games_json = tmp_path / "games.json"
        games_json.write_text("[]")
        games_dir = tmp_path / "games"
        assert needs_migration(str(games_json), str(games_dir)) is True

    def test_needs_migration_false_dir_exists(self, tmp_path):
        games_json = tmp_path / "games.json"
        games_json.write_text("[]")
        games_dir = tmp_path / "games"
        games_dir.mkdir()
        assert needs_migration(str(games_json), str(games_dir)) is False

    def test_needs_migration_false_no_json(self, tmp_path):
        games_json = tmp_path / "games.json"
        games_dir = tmp_path / "games"
        assert needs_migration(str(games_json), str(games_dir)) is False


class TestMigrateToPerGame:
    def test_migrate_basic(self, tmp_path, sample_games):
        games_json = tmp_path / "games.json"
        games_dir = tmp_path / "games"
        # Write monolithic JSON
        _write_games_json(str(games_json), sample_games)
        assert games_json.exists()

        result = migrate_to_per_game(str(games_json), str(games_dir))

        assert result.migrated == 2
        assert result.skipped_duplicate == 0
        assert result.skipped_error == 0
        # Old file renamed
        assert (tmp_path / "games.json.migrated").exists()
        # New files created
        library = GameLibrary(str(games_dir))
        assert library.exists("umu-1234")
        assert library.exists("umu-5678")
        loaded = library.load("umu-1234")
        assert loaded is not None
        assert loaded.title == "Test Game Alpha"

    def test_migrate_empty_json(self, tmp_path):
        games_json = tmp_path / "games.json"
        games_json.write_text("[]")
        games_dir = tmp_path / "games"

        result = migrate_to_per_game(str(games_json), str(games_dir))

        assert result.migrated == 0
        # Empty JSON — nothing to migrate, file is still renamed
        assert (tmp_path / "games.json.migrated").exists()

    def test_migrate_no_json(self, tmp_path):
        games_dir = tmp_path / "games"
        result = migrate_to_per_game(str(tmp_path / "nope.json"), str(games_dir))
        # load_games_json returns [] for missing files — no error, nothing to migrate
        assert result.migrated == 0
        assert result.errors == []
        # No source file to rename
        assert not (tmp_path / "nope.json.migrated").exists()

    def test_migrate_duplicates(self, tmp_path):
        games_json = tmp_path / "games.json"
        games_dir = tmp_path / "games"
        # Two games with same gameid
        _write_games_json(
            str(games_json),
            [
                Game(gameid="dup", title="First", path="/first"),
                Game(gameid="dup", title="Second", path="/second"),
            ],
        )

        result = migrate_to_per_game(str(games_json), str(games_dir))

        assert result.migrated == 1
        assert result.skipped_duplicate == 1
        library = GameLibrary(str(games_dir))
        game = library.load("dup")
        assert game is not None
        assert game.title == "First"  # first occurrence wins

    def test_migrate_dry_run(self, tmp_path, sample_games):
        games_json = tmp_path / "games.json"
        games_dir = tmp_path / "games"
        _write_games_json(str(games_json), sample_games)

        result = migrate_to_per_game(
            str(games_json), str(games_dir), dry_run=True
        )

        assert result.migrated == 2
        # Old file NOT renamed in dry run
        assert games_json.exists()
        assert not (tmp_path / "games.json.migrated").exists()