about summary refs log tree commit diff stats
path: root/tests/test_proton_manager.py
blob: 773d59522a6e7e17b1cc59646d01158fb33e6e50 (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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
"""Tests for fungus.proton_manager — pure logic helpers.

Covers:
  - _cache_key
  - get_arch_asset
  - get_cache_dir
  - clear_cache
  - get_installed_path
  - remove_path
  - fetch_releases (via mocked requests.get)
  - _fetch_with_cache (via mocked requests.get + tmp cache)
"""

import json
from unittest.mock import MagicMock, patch

import pytest


# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------


@pytest.fixture()
def mock_user_config(tmp_path):
    """Patch PathManager.user_config to return a controlled path.

    Returns the patched config directory path.
    """
    from fungus import path_manager as pm

    config_dir = tmp_path / "test_config"
    config_dir.mkdir()

    original = pm.PathManager.user_config
    pm.PathManager.user_config = staticmethod(lambda *a: str(config_dir / a[0]) if a else str(config_dir))
    yield config_dir
    pm.PathManager.user_config = original


@pytest.fixture()
def mock_compat_path(tmp_path):
    """Patch STEAM_COMPATIBILITY_PATH to point to a controlled directory.

    Returns (patched_path, original_path).
    """
    from fungus import proton_manager as pm

    compat_dir = tmp_path / "compatibilitytools.d"
    compat_dir.mkdir()
    original = pm.STEAM_COMPATIBILITY_PATH
    pm.STEAM_COMPATIBILITY_PATH = compat_dir
    yield compat_dir
    pm.STEAM_COMPATIBILITY_PATH = original


# ---------------------------------------------------------------------------
# _cache_key
# ---------------------------------------------------------------------------


class TestCacheKey:
    """Tests for fungus.proton_manager._cache_key."""

    def test_deterministic(self):
        """Same URL always produces the same key."""
        from fungus.proton_manager import _cache_key

        key1 = _cache_key("https://example.com/releases")
        key2 = _cache_key("https://example.com/releases")
        assert key1 == key2

    def test_different_urls_different_keys(self):
        from fungus.proton_manager import _cache_key

        key1 = _cache_key("https://url-a.com/releases")
        key2 = _cache_key("https://url-b.com/releases")
        assert key1 != key2

    def test_safe_filename(self):
        """Key should be a safe filename (prefix + hex hash + .json)."""
        from fungus.proton_manager import _cache_key

        key = _cache_key("https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases")
        assert key.startswith("proton-releases-")
        assert key.endswith(".json")
        hash_part = key[len("proton-releases-"):-len(".json")]
        assert all(c in "0123456789abcdef" for c in hash_part)
        assert len(hash_part) == 16

    def test_empty_url(self):
        from fungus.proton_manager import _cache_key

        key = _cache_key("")
        assert key.startswith("proton-releases-")


# ---------------------------------------------------------------------------
# get_arch_asset
# ---------------------------------------------------------------------------


class TestGetArchAsset:
    """Tests for fungus.proton_manager.get_arch_asset."""

    def _make_asset(self, name, size=1234):
        return {"name": name, "size": size}

    def test_exact_arch_match(self):
        """Asset with arch suffix is selected first."""
        from fungus.proton_manager import get_arch_asset

        assets = [
            self._make_asset("GE-Proton11-1.tar.gz"),
            self._make_asset("GE-Proton11-1-x86_64.tar.gz"),
        ]
        result = get_arch_asset(assets)
        assert result is not None
        assert result["name"] == "GE-Proton11-1-x86_64.tar.gz"

    def test_aarch64_exact_match(self, monkeypatch):
        """On aarch64, the -aarch64 asset is selected."""
        from fungus.proton_manager import get_arch_asset

        monkeypatch.setattr("fungus.proton_manager.MACHINE_ARCH", "aarch64")
        assets = [
            self._make_asset("GE-Proton11-1.tar.gz"),
            self._make_asset("GE-Proton11-1-aarch64.tar.gz"),
        ]
        result = get_arch_asset(assets)
        assert result is not None
        assert result["name"] == "GE-Proton11-1-aarch64.tar.gz"

    def test_default_build_for_x86_64(self, monkeypatch):
        """On x86_64, the default build (no arch suffix) is selected
        when no explicit arch match exists."""
        from fungus.proton_manager import get_arch_asset

        monkeypatch.setattr("fungus.proton_manager.MACHINE_ARCH", "x86_64")
        assets = [
            self._make_asset("GE-Proton11-1-aarch64.tar.gz"),
            self._make_asset("GE-Proton11-1.tar.gz"),
        ]
        result = get_arch_asset(assets)
        assert result is not None
        assert result["name"] == "GE-Proton11-1.tar.gz"

    def test_default_build_not_selected_when_aarch64_exists(self, monkeypatch):
        """On x86_64, the default build is NOT selected if an aarch64
        variant is available (it's a false match)."""
        from fungus.proton_manager import get_arch_asset

        monkeypatch.setattr("fungus.proton_manager.MACHINE_ARCH", "x86_64")
        assets = [
            self._make_asset("GE-Proton11-1-aarch64.tar.gz"),
        ]
        result = get_arch_asset(assets)
        # Falls through to fallback (first tar archive)
        assert result is not None
        assert result["name"] == "GE-Proton11-1-aarch64.tar.gz"

    def test_fallback_to_first_tar(self, monkeypatch):
        """When no arch match, returns the first tar archive."""
        from fungus.proton_manager import get_arch_asset

        monkeypatch.setattr("fungus.proton_manager.MACHINE_ARCH", "armv7l")
        assets = [
            self._make_asset("GE-Proton11-1.tar.gz"),
            self._make_asset("GE-Proton11-1-x86_64.tar.gz"),
        ]
        result = get_arch_asset(assets)
        assert result is not None
        assert result["name"] == "GE-Proton11-1.tar.gz"

    def test_no_matching_extensions_returns_none(self):
        """No tar.gz/tar.xz assets → None."""
        from fungus.proton_manager import get_arch_asset

        assets = [
            self._make_asset("GE-Proton11-1.zip"),
            self._make_asset("GE-Proton11-1.sha256"),
        ]
        result = get_arch_asset(assets)
        assert result is None

    def test_empty_list_returns_none(self):
        from fungus.proton_manager import get_arch_asset

        result = get_arch_asset([])
        assert result is None

    def test_tar_xz_extension(self, monkeypatch):
        """Works with .tar.xz files too."""
        from fungus.proton_manager import get_arch_asset

        monkeypatch.setattr("fungus.proton_manager.MACHINE_ARCH", "x86_64")
        assets = [
            self._make_asset("GE-Proton11-1-x86_64.tar.xz"),
        ]
        result = get_arch_asset(assets)
        assert result is not None
        assert result["name"] == "GE-Proton11-1-x86_64.tar.xz"

    def test_exact_arch_preferred_over_default(self, monkeypatch):
        """Explicit arch match is always preferred over default build."""
        from fungus.proton_manager import get_arch_asset

        monkeypatch.setattr("fungus.proton_manager.MACHINE_ARCH", "x86_64")
        assets = [
            self._make_asset("GE-Proton11-1.tar.gz"),
            self._make_asset("GE-Proton11-1-x86_64.tar.gz"),
            self._make_asset("GE-Proton11-1-aarch64.tar.gz"),
        ]
        result = get_arch_asset(assets)
        assert result is not None
        assert result["name"] == "GE-Proton11-1-x86_64.tar.gz"


# ---------------------------------------------------------------------------
# get_cache_dir
# ---------------------------------------------------------------------------


class TestGetCacheDir:
    """Tests for fungus.proton_manager.get_cache_dir."""

    def test_creates_cache_directory(self, mock_user_config):
        from fungus.proton_manager import get_cache_dir

        result = get_cache_dir()
        assert result.exists()
        assert result.is_dir()
        assert result.name == "cache"

    def test_returns_correct_path(self, mock_user_config):
        from fungus.proton_manager import get_cache_dir

        result = get_cache_dir()
        assert str(result).startswith(str(mock_user_config))
        assert result.name == "cache"


# ---------------------------------------------------------------------------
# clear_cache
# ---------------------------------------------------------------------------


class TestClearCache:
    """Tests for fungus.proton_manager.clear_cache."""

    def test_clears_specific_url(self, mock_user_config):
        from fungus.proton_manager import _cache_key, clear_cache, get_cache_dir

        cache_dir = get_cache_dir()
        # Create a fake cache file
        cache_file = cache_dir / _cache_key("https://example.com/releases")
        cache_file.write_text("{}")
        assert cache_file.exists()

        clear_cache(["https://example.com/releases"])
        assert not cache_file.exists()

    def test_clears_all_urls_by_default(self, mock_user_config):
        """Calling clear_cache() with no args clears all known upstreams."""
        from fungus.proton_manager import (
            DEFAULT_UPSTREAM_URLS,
            _cache_key,
            clear_cache,
            get_cache_dir,
        )

        cache_dir = get_cache_dir()
        # Create fake cache files for all upstreams
        for url in DEFAULT_UPSTREAM_URLS:
            (cache_dir / _cache_key(url)).write_text("{}")

        clear_cache()
        for url in DEFAULT_UPSTREAM_URLS:
            assert not (cache_dir / _cache_key(url)).exists()

    def test_clears_nonexistent_file_is_noop(self, mock_user_config):
        """Clearing a cache file that doesn't exist is a no-op."""
        from fungus.proton_manager import clear_cache

        # Should not raise
        clear_cache(["https://nonexistent.com/releases"])

    def test_clears_corrupt_file(self, mock_user_config):
        """Corrupt cache files are still removed."""
        from fungus.proton_manager import _cache_key, clear_cache, get_cache_dir

        cache_dir = get_cache_dir()
        cache_file = cache_dir / _cache_key("https://example.com/releases")
        cache_file.write_text("not json {{{")
        assert cache_file.exists()

        clear_cache(["https://example.com/releases"])
        assert not cache_file.exists()


# ---------------------------------------------------------------------------
# get_installed_path
# ---------------------------------------------------------------------------


class TestGetInstalledPath:
    """Tests for fungus.proton_manager.get_installed_path."""

    def test_exact_match(self, mock_compat_path):
        """Existing directory with matching name is returned."""
        from fungus.proton_manager import get_installed_path

        (mock_compat_path / "GE-Proton11-1").mkdir()
        result = get_installed_path("GE-Proton11-1")
        assert str(result).endswith("GE-Proton11-1")

    def test_ends_with_match(self, mock_compat_path):
        """Directory ending with tag name is matched."""
        from fungus.proton_manager import get_installed_path

        (mock_compat_path / "my-GE-Proton11-1").mkdir()
        result = get_installed_path("GE-Proton11-1")
        assert str(result).endswith("my-GE-Proton11-1")

    def test_proton_prefix_match(self, mock_compat_path):
        """'proton-11' matches folder ending with 'proton-11' suffix."""
        from fungus.proton_manager import get_installed_path

        # Folder must end with 'proton-11' for the endswith check to match
        (mock_compat_path / "my-proton-11").mkdir()
        result = get_installed_path("proton-11")
        assert str(result).endswith("my-proton-11")

    def test_no_match_returns_expected_path(self, mock_compat_path):
        """No matching directory → returns expected path."""
        from fungus.proton_manager import get_installed_path

        result = get_installed_path("NonExistent")
        assert str(result).endswith("NonExistent")

    def test_case_insensitive(self, mock_compat_path):
        """Matching is case-insensitive."""
        from fungus.proton_manager import get_installed_path

        (mock_compat_path / "ge-proton11-1").mkdir()
        result = get_installed_path("GE-Proton11-1")
        assert str(result).endswith("ge-proton11-1")

    def test_empty_compat_dir(self, mock_compat_path):
        """Empty compatibilitytools.d → returns expected path."""
        from fungus.proton_manager import get_installed_path

        result = get_installed_path("GE-Proton11-1")
        assert str(result).endswith("GE-Proton11-1")


# ---------------------------------------------------------------------------
# remove_path
# ---------------------------------------------------------------------------


class TestRemovePath:
    """Tests for fungus.proton_manager.remove_path."""

    def test_removes_existing_directory(self, tmp_path):
        from fungus.proton_manager import remove_path

        target = tmp_path / "to_remove"
        target.mkdir()
        (target / "file.txt").write_text("data")
        assert target.exists()

        remove_path(str(target))
        assert not target.exists()

    def test_noop_on_nonexistent_path(self, tmp_path):
        """Removing a non-existent path is a no-op."""
        from fungus.proton_manager import remove_path

        # Should not raise
        remove_path(str(tmp_path / "does_not_exist"))

    def test_noop_on_empty_string(self):
        from fungus.proton_manager import remove_path

        # Should not raise
        remove_path("")

    def test_noop_on_none(self):
        from fungus.proton_manager import remove_path

        # Should not raise
        remove_path(None)


# ---------------------------------------------------------------------------
# fetch_releases
# ---------------------------------------------------------------------------


def _mock_response(status_code, json_data):
    """Create a mock requests.Response."""
    resp = MagicMock()
    resp.status_code = status_code
    resp.json.return_value = json_data
    return resp


def _make_release(tag_name, assets=None):
    """Create a mock release dict."""
    if assets is None:
        assets = []
    return {
        "tag_name": tag_name,
        "assets": assets,
    }


def _make_asset(name):
    return {"name": name, "size": 1234}


class TestFetchReleases:
    """Tests for fungus.proton_manager.fetch_releases (mocked requests.get)."""

    def _fetch_with_mocked_requests(self, url, responses):
        """Helper to call fetch_releases with mocked requests.get."""
        with patch("fungus.proton_manager.requests.get", side_effect=responses):
            from fungus.proton_manager import fetch_releases
            return fetch_releases(url)

    def test_single_page_ge_proton(self):
        """Single page of GE-Proton releases is fetched and filtered."""
        releases = [
            _make_release("GE-Proton11-1", [_make_asset("GE-Proton11-1.tar.gz")]),
            _make_release("GE-Proton10-1", [_make_asset("GE-Proton10-1.tar.gz")]),
            _make_release("GE-Proton9-11", [_make_asset("GE-Proton9-11.tar.gz")]),
        ]
        responses = [_mock_response(200, releases), _mock_response(200, [])]

        result = self._fetch_with_mocked_requests(
            "https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases",
            responses,
        )
        assert len(result) == 3
        tags = [r["tag_name"] for r in result]
        assert "GE-Proton11-1" in tags
        assert "GE-Proton10-1" in tags
        assert "GE-Proton9-11" in tags

    def test_skips_old_ge_proton_versions(self):
        """GE-Proton versions < 9.1 are filtered out."""
        releases = [
            _make_release("GE-Proton8-22", [_make_asset("GE-Proton8-22.tar.gz")]),
            _make_release("GE-Proton9-0", [_make_asset("GE-Proton9-0.tar.gz")]),
            _make_release("GE-Proton9-1", [_make_asset("GE-Proton9-1.tar.gz")]),
            _make_release("GE-Proton9-2", [_make_asset("GE-Proton9-2.tar.gz")]),
        ]
        responses = [_mock_response(200, releases), _mock_response(200, [])]

        result = self._fetch_with_mocked_requests(
            "https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases",
            responses,
        )
        assert len(result) == 2
        tags = [r["tag_name"] for r in result]
        assert "GE-Proton9-1" in tags
        assert "GE-Proton9-2" in tags

    def test_skips_non_ge_proton_releases(self):
        """Non-GE-Proton releases are filtered out."""
        releases = [
            _make_release("GE-Proton11-1", [_make_asset("GE-Proton11-1.tar.gz")]),
            _make_release("SomeOther-1.0", [_make_asset("SomeOther-1.0.tar.gz")]),
            _make_release("Proton-11.0-1", [_make_asset("Proton-11.0-1.tar.gz")]),
        ]
        responses = [_mock_response(200, releases), _mock_response(200, [])]

        result = self._fetch_with_mocked_requests(
            "https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases",
            responses,
        )
        assert len(result) == 1
        assert result[0]["tag_name"] == "GE-Proton11-1"

    def test_skips_releases_without_tar_assets(self):
        """Releases without .tar.gz/.tar.xz assets are filtered out."""
        releases = [
            _make_release("GE-Proton11-1", [_make_asset("GE-Proton11-1.zip")]),
            _make_release("GE-Proton11-2", [_make_asset("GE-Proton11-2.tar.gz")]),
        ]
        responses = [_mock_response(200, releases), _mock_response(200, [])]

        result = self._fetch_with_mocked_requests(
            "https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases",
            responses,
        )
        assert len(result) == 1
        assert result[0]["tag_name"] == "GE-Proton11-2"

    def test_duplicate_tags_deduplicated(self):
        """Duplicate tag names are deduplicated (first wins)."""
        releases = [
            _make_release("GE-Proton11-1", [_make_asset("GE-Proton11-1.tar.gz")]),
            _make_release("GE-Proton11-1", [_make_asset("GE-Proton11-1-v2.tar.gz")]),
        ]
        responses = [_mock_response(200, releases), _mock_response(200, [])]

        result = self._fetch_with_mocked_requests(
            "https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases",
            responses,
        )
        assert len(result) == 1
        assert result[0]["tag_name"] == "GE-Proton11-1"

    def test_etaash_em_releases(self):
        """EM releases from Etaash-mathamsetty are filtered correctly."""
        releases = [
            _make_release("EM-1.0", [_make_asset("EM-1.0.tar.gz")]),
            _make_release("EM-2.0", [_make_asset("EM-2.0.tar.gz")]),
            _make_release("Other-1.0", [_make_asset("Other-1.0.tar.gz")]),
        ]
        responses = [_mock_response(200, releases), _mock_response(200, [])]

        result = self._fetch_with_mocked_requests(
            "https://api.github.com/repos/Etaash-mathamsetty/Proton/releases",
            responses,
        )
        assert len(result) == 2
        tags = [r["tag_name"] for r in result]
        assert "EM-1.0" in tags
        assert "EM-2.0" in tags

    def test_rate_limit_raises_error(self):
        """403 with rate limit message raises RateLimitError."""
        from fungus.proton_manager import RateLimitError

        rate_limited = _mock_response(
            403,
            {"message": "API rate limit exceeded"},
        )
        responses = [rate_limited]

        with patch("fungus.proton_manager.requests.get", side_effect=responses):
            with pytest.raises(RateLimitError, match="rate limit"):
                from fungus.proton_manager import fetch_releases
                fetch_releases("https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases")

    def test_empty_response_breaks_loop(self):
        """Empty response list ends pagination."""
        responses = [_mock_response(200, []), _mock_response(200, [])]

        result = self._fetch_with_mocked_requests(
            "https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases",
            responses,
        )
        assert result == []

    def test_two_page_pagination(self):
        """Multi-page releases are fetched and combined."""
        page1 = [
            _make_release("GE-Proton11-1", [_make_asset("GE-Proton11-1.tar.gz")]),
        ]
        page2 = [
            _make_release("GE-Proton10-1", [_make_asset("GE-Proton10-1.tar.gz")]),
        ]
        responses = [
            _mock_response(200, page1),
            _mock_response(200, page2),
            _mock_response(200, []),
        ]

        result = self._fetch_with_mocked_requests(
            "https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases",
            responses,
        )
        assert len(result) == 2

    def test_non_200_status_breaks_loop(self):
        """Non-200 status code ends the fetch loop."""
        responses = [
            _mock_response(500, {"error": "server error"}),
        ]

        result = self._fetch_with_mocked_requests(
            "https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases",
            responses,
        )
        assert result == []

    def test_ge_proton_version_parse_error_skipped(self):
        """Malformed tag names that can't be parsed are skipped."""
        releases = [
            _make_release("GE-Proton", [_make_asset("GE-Proton.tar.gz")]),
            _make_release("GE-Proton11-1", [_make_asset("GE-Proton11-1.tar.gz")]),
        ]
        responses = [_mock_response(200, releases), _mock_response(200, [])]

        result = self._fetch_with_mocked_requests(
            "https://api.github.com/repos/GloriousEggroll/proton-ge-custom/releases",
            responses,
        )
        assert len(result) == 1
        assert result[0]["tag_name"] == "GE-Proton11-1"


# ---------------------------------------------------------------------------
# _fetch_with_cache
# ---------------------------------------------------------------------------


class TestFetchWithCache:
    """Tests for fungus.proton_manager._fetch_with_cache."""

    def _fetch_with_mocked_requests(self, url, cache_dir, responses):
        """Helper to call _fetch_with_cache with mocked requests.get."""
        with patch("fungus.proton_manager.requests.get", side_effect=responses):
            from fungus.proton_manager import _fetch_with_cache
            return _fetch_with_cache(url, cache_dir=cache_dir)

    def test_cache_hit_returns_cached_data(self, tmp_path):
        """Valid cached data is returned without calling network."""
        cache_dir = tmp_path / "cache"
        cache_dir.mkdir()

        from fungus.proton_manager import _cache_key

        cached_data = [
            {"tag_name": "GE-Proton11-1", "assets": []},
        ]
        cache_file = cache_dir / _cache_key("https://example.com/releases")
        import time
        cache_file.write_text(json.dumps({"time": time.time(), "data": cached_data}))

        # requests.get should NOT be called
        with patch("fungus.proton_manager.requests.get") as mock_get:
            result = self._fetch_with_mocked_requests(
                "https://example.com/releases", cache_dir, []
            )

        assert result == cached_data
        mock_get.assert_not_called()

    def test_cache_expired_fetches_fresh(self, tmp_path):
        """Expired cached data triggers a fresh fetch."""
        import time

        cache_dir = tmp_path / "cache"
        cache_dir.mkdir()

        from fungus.proton_manager import _cache_key, CACHE_TTL

        cache_file = cache_dir / _cache_key("https://example.com/releases")
        cache_file.write_text(
            json.dumps({"time": time.time() - CACHE_TTL - 100, "data": []})
        )

        # Must include tar.gz asset so fetch_releases doesn't filter it out
        fresh_data = [
            {"tag_name": "GE-Proton11-1", "assets": [{"name": "GE-Proton11-1.tar.gz"}]},
        ]
        # fetch_releases calls requests.get twice (pagination loop: page 1 + empty page 2)
        responses = [
            _mock_response(200, fresh_data),
            _mock_response(200, []),
        ]

        result = self._fetch_with_mocked_requests(
            "https://example.com/releases", cache_dir, responses
        )
        assert result == fresh_data

    def test_corrupt_cache_ignored(self, tmp_path):
        """Corrupt cache file is ignored and fresh data is fetched."""
        cache_dir = tmp_path / "cache"
        cache_dir.mkdir()

        from fungus.proton_manager import _cache_key

        cache_file = cache_dir / _cache_key("https://example.com/releases")
        cache_file.write_text("not valid json {{{")

        # Must include tar.gz asset so fetch_releases doesn't filter it out
        fresh_data = [
            {"tag_name": "GE-Proton11-1", "assets": [{"name": "GE-Proton11-1.tar.gz"}]},
        ]
        # fetch_releases calls requests.get twice (pagination loop)
        responses = [
            _mock_response(200, fresh_data),
            _mock_response(200, []),
        ]

        result = self._fetch_with_mocked_requests(
            "https://example.com/releases", cache_dir, responses
        )
        assert result == fresh_data

    def test_cache_miss_fetches_fresh(self, tmp_path):
        """No cache file → fresh fetch."""
        cache_dir = tmp_path / "cache"
        cache_dir.mkdir()

        # Must include tar.gz asset so fetch_releases doesn't filter it out
        fresh_data = [
            {"tag_name": "GE-Proton11-1", "assets": [{"name": "GE-Proton11-1.tar.gz"}]},
        ]
        # fetch_releases calls requests.get twice (pagination loop)
        responses = [
            _mock_response(200, fresh_data),
            _mock_response(200, []),
        ]

        result = self._fetch_with_mocked_requests(
            "https://example.com/releases", cache_dir, responses
        )
        assert result == fresh_data

    def test_cache_write_after_fetch(self, tmp_path):
        """Fetched data is saved to cache."""
        cache_dir = tmp_path / "cache"
        cache_dir.mkdir()

        # Must include tar.gz asset so fetch_releases doesn't filter it out
        fresh_data = [
            {"tag_name": "GE-Proton11-1", "assets": [{"name": "GE-Proton11-1.tar.gz"}]},
        ]
        # fetch_releases calls requests.get twice (pagination loop)
        responses = [
            _mock_response(200, fresh_data),
            _mock_response(200, []),
        ]

        self._fetch_with_mocked_requests(
            "https://example.com/releases", cache_dir, responses
        )

        from fungus.proton_manager import _cache_key
        cache_file = cache_dir / _cache_key("https://example.com/releases")
        assert cache_file.exists()
        data = json.loads(cache_file.read_text())
        assert data["data"] == fresh_data

    def test_cache_read_error_continues(self, tmp_path):
        """KeyError on cache read falls through to fetch."""
        cache_dir = tmp_path / "cache"
        cache_dir.mkdir()

        from fungus.proton_manager import _cache_key

        # Valid JSON but missing 'data' key → KeyError → falls through
        cache_file = cache_dir / _cache_key("https://example.com/releases")
        cache_file.write_text('{"time": 0}')

        # Must include tar.gz asset so fetch_releases doesn't filter it out
        fresh_data = [
            {"tag_name": "GE-Proton11-1", "assets": [{"name": "GE-Proton11-1.tar.gz"}]},
        ]
        # fetch_releases calls requests.get twice (pagination loop)
        responses = [
            _mock_response(200, fresh_data),
            _mock_response(200, []),
        ]

        result = self._fetch_with_mocked_requests(
            "https://example.com/releases", cache_dir, responses
        )
        assert result == fresh_data