-
-
Notifications
You must be signed in to change notification settings - Fork 598
Expand file tree
/
Copy pathtest_igdb_handler.py
More file actions
881 lines (768 loc) · 31 KB
/
Copy pathtest_igdb_handler.py
File metadata and controls
881 lines (768 loc) · 31 KB
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
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
"""Tests for the IGDB metadata handler."""
import json
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from adapters.services.igdb_types import GameType
from handler.metadata.base_handler import PS1_SERIAL_INDEX_KEY
from handler.metadata.igdb_handler import (
FAMICOM_IGDB_ID,
NES_IGDB_ID,
PS1_IGDB_ID,
SNES_IGDB_ID,
SUPER_FAMICOM_IGDB_ID,
IGDBHandler,
_build_platforms_where,
_platform_igdb_ids_with_twin,
get_igdb_preferred_locale,
)
from handler.redis_handler import async_cache
GENESIS_IGDB_ID = 29
def _make_game(
game_id: int,
name: str,
alternative_names: list[str] | None = None,
game_localizations: list[str] | None = None,
) -> dict:
"""Build a minimal IGDB Game dict for testing.
``alternative_names`` and ``game_localizations`` accept plain title strings
and are wrapped into the ``{"name": ...}`` shape IGDB returns.
"""
return {
"id": game_id,
"name": name,
"slug": name.lower().replace(" ", "-"),
"summary": "",
"total_rating": 0.0,
"aggregated_rating": 0.0,
"first_release_date": None,
"artworks": [],
"cover": None,
"screenshots": [],
"platforms": [{"id": GENESIS_IGDB_ID, "name": "Sega Mega Drive/Genesis"}],
"alternative_names": [{"name": n} for n in (alternative_names or [])],
"genres": [],
"franchise": None,
"franchises": [],
"collections": [],
"game_modes": [],
"involved_companies": [],
"expansions": [],
"dlcs": [],
"remasters": [],
"remakes": [],
"expanded_games": [],
"ports": [],
"similar_games": [],
"videos": [],
"age_ratings": [],
"multiplayer_modes": [],
"game_localizations": [{"name": n} for n in (game_localizations or [])],
}
class TestGetIGDBPreferredLocale:
def test_multi_region_rom_respects_user_priority(self):
"""The configured priority wins over filename tag order."""
rom = MagicMock()
rom.regions = ["Japan", "USA"]
config = MagicMock(SCAN_REGION_PRIORITY=["JP", "us"])
with patch("handler.metadata.igdb_handler.cm.get_config", return_value=config):
locale = get_igdb_preferred_locale(rom)
assert locale == "ja-JP"
class TestSearchRomGameTypeFilter:
"""Tests for _search_rom game_type filtering."""
@pytest.mark.asyncio
async def test_standalone_expansion_included_in_game_type_filter(self):
"""Searching with game_type filter must include STANDALONE_EXPANSION
so that games like 'Ecco: The Tides of Time' are found on the first
search pass and not confused with their parent game."""
handler = IGDBHandler()
ecco_dolphin = _make_game(1799, "Ecco the Dolphin")
ecco_tides = _make_game(5379, "Ecco: The Tides of Time")
async def mock_list_games(
search_term=None, fields=None, where=None, limit=None
):
# First call (with game_type filter): return both games
if where and "game_type" in where:
# Verify STANDALONE_EXPANSION (4) is in the filter
assert (
str(int(GameType.STANDALONE_EXPANSION)) in where
), f"STANDALONE_EXPANSION should be in game_type filter, got: {where}"
# Simulate IGDB returning both games when the search includes
# standalone expansions
if search_term and "tides of time" in search_term.lower():
return [ecco_dolphin, ecco_tides]
return [ecco_dolphin]
return []
with (
patch(
"handler.metadata.igdb_handler.IGDBHandler.is_enabled",
return_value=True,
),
patch.object(
handler.igdb_service,
"list_games",
side_effect=mock_list_games,
),
patch.object(
handler.igdb_service,
"search",
new_callable=AsyncMock,
return_value=[],
),
):
result = await handler._search_rom(
"ecco the tides of time", GENESIS_IGDB_ID, with_game_type=True
)
assert result is not None
assert (
result["id"] == 5379
), f"Expected Ecco: The Tides of Time (id=5379), got {result.get('name')} (id={result.get('id')})"
@pytest.mark.asyncio
async def test_expanded_search_uses_all_results_not_just_first(self):
"""When the primary search fails and the expanded IGDB search endpoint
is used, all unique game IDs from the results must be fetched and
the best match selected — not just the first result."""
handler = IGDBHandler()
ecco_dolphin = _make_game(1799, "Ecco the Dolphin")
ecco_tides = _make_game(5379, "Ecco: The Tides of Time")
# Primary search returns nothing useful
async def mock_list_games(
search_term=None, fields=None, where=None, limit=None
):
if where and "game_type" not in where and not where.startswith("("):
# Primary search pass — return no results so we fall through to
# the expanded search
return []
if where and where.startswith("("):
# Expanded game details lookup — return both candidates
return [ecco_dolphin, ecco_tides]
return []
# Expanded search returns two results — wrong game FIRST, correct game second
expanded_results = [
{"game": {"id": 1799}, "name": "Ecco the Dolphin"},
{"game": {"id": 5379}, "name": "Ecco: The Tides of Time"},
]
with (
patch(
"handler.metadata.igdb_handler.IGDBHandler.is_enabled",
return_value=True,
),
patch.object(
handler.igdb_service,
"list_games",
side_effect=mock_list_games,
),
patch.object(
handler.igdb_service,
"search",
new_callable=AsyncMock,
return_value=expanded_results,
),
):
result = await handler._search_rom(
"ecco the tides of time", GENESIS_IGDB_ID, with_game_type=False
)
assert result is not None
assert result["id"] == 5379, (
f"Expected Ecco: The Tides of Time (id=5379), got {result.get('name')} (id={result.get('id')}). "
"The expanded search must consider ALL results, not just the first."
)
class TestSearchRomLocalizedNames:
"""Tests for matching ROMs by localized / alternative titles.
Regression coverage for issue #3435: a ROM whose No-Intro / ReDump filename
uses a localized title (e.g. ``007 - Die Welt Ist Nicht Genug (Germany)``)
must match the IGDB game that lists that title in ``alternative_names`` or
``game_localizations``, not only the primary English ``name``.
"""
# James Bond 007: The World Is Not Enough, IGDB id 158962, has the German
# alternative name "007 - Die Welt Ist Nicht Genug" (issue #3435).
ENGLISH_NAME = "James Bond 007: The World Is Not Enough"
GERMAN_TITLE = "007 - Die Welt Ist Nicht Genug"
GAME_ID = 158962
@pytest.mark.asyncio
async def test_alt_name_match_in_primary_games_search(self):
"""A localized filename must match when IGDB returns the game on the
primary games-endpoint pass and the term only matches an alternative
name, not the primary English name."""
handler = IGDBHandler()
game = _make_game(
self.GAME_ID,
self.ENGLISH_NAME,
alternative_names=[self.GERMAN_TITLE],
)
async def mock_list_games(
search_term=None, fields=None, where=None, limit=None
):
# Primary games-endpoint pass returns the game (IGDB's fuzzy search
# surfaces it via the alt name), but the term won't match the
# English primary name on its own.
return [game]
with (
patch(
"handler.metadata.igdb_handler.IGDBHandler.is_enabled",
return_value=True,
),
patch.object(
handler.igdb_service,
"list_games",
side_effect=mock_list_games,
),
patch.object(
handler.igdb_service,
"search",
new_callable=AsyncMock,
return_value=[],
),
):
result = await handler._search_rom(
"007 die welt ist nicht genug", GENESIS_IGDB_ID
)
assert result is not None
assert result["id"] == self.GAME_ID, (
f"Expected {self.ENGLISH_NAME} (id={self.GAME_ID}) via its German "
f"alternative name, got {result.get('name')} (id={result.get('id')})"
)
@pytest.mark.asyncio
async def test_alt_name_match_in_expanded_search(self):
"""A localized filename must match when the game is only discovered via
the expanded ``/search`` alternative_name query and the term matches an
alternative name rather than the primary English name."""
handler = IGDBHandler()
game = _make_game(
self.GAME_ID,
self.ENGLISH_NAME,
alternative_names=[self.GERMAN_TITLE],
)
async def mock_list_games(
search_term=None, fields=None, where=None, limit=None
):
# Expanded game-details lookup (id filter) returns the full game.
if where and where.startswith("("):
return [game]
# Primary pass returns nothing useful.
return []
expanded_results = [{"game": {"id": self.GAME_ID}, "name": self.ENGLISH_NAME}]
with (
patch(
"handler.metadata.igdb_handler.IGDBHandler.is_enabled",
return_value=True,
),
patch.object(
handler.igdb_service,
"list_games",
side_effect=mock_list_games,
),
patch.object(
handler.igdb_service,
"search",
new_callable=AsyncMock,
return_value=expanded_results,
),
):
result = await handler._search_rom(
"007 die welt ist nicht genug", GENESIS_IGDB_ID
)
assert result is not None
assert result["id"] == self.GAME_ID, (
f"Expected {self.ENGLISH_NAME} (id={self.GAME_ID}) via its German "
f"alternative name, got {result.get('name')} (id={result.get('id')})"
)
@pytest.mark.asyncio
async def test_localization_name_match_in_expanded_search(self):
"""A localized filename must match when the matching title lives in
``game_localizations`` rather than ``alternative_names``."""
handler = IGDBHandler()
game = _make_game(
self.GAME_ID,
self.ENGLISH_NAME,
game_localizations=[self.GERMAN_TITLE],
)
async def mock_list_games(
search_term=None, fields=None, where=None, limit=None
):
if where and where.startswith("("):
return [game]
return []
expanded_results = [{"game": {"id": self.GAME_ID}, "name": self.ENGLISH_NAME}]
with (
patch(
"handler.metadata.igdb_handler.IGDBHandler.is_enabled",
return_value=True,
),
patch.object(
handler.igdb_service,
"list_games",
side_effect=mock_list_games,
),
patch.object(
handler.igdb_service,
"search",
new_callable=AsyncMock,
return_value=expanded_results,
),
):
result = await handler._search_rom(
"007 die welt ist nicht genug", GENESIS_IGDB_ID
)
assert result is not None
assert result["id"] == self.GAME_ID
@pytest.mark.asyncio
async def test_primary_english_name_still_matches(self):
"""Indexing alternative titles must not regress matching by the primary
English name."""
handler = IGDBHandler()
game = _make_game(
self.GAME_ID,
self.ENGLISH_NAME,
alternative_names=[self.GERMAN_TITLE],
)
async def mock_list_games(
search_term=None, fields=None, where=None, limit=None
):
return [game]
with (
patch(
"handler.metadata.igdb_handler.IGDBHandler.is_enabled",
return_value=True,
),
patch.object(
handler.igdb_service,
"list_games",
side_effect=mock_list_games,
),
patch.object(
handler.igdb_service,
"search",
new_callable=AsyncMock,
return_value=[],
),
):
result = await handler._search_rom(
"james bond 007 the world is not enough", GENESIS_IGDB_ID
)
assert result is not None
assert result["id"] == self.GAME_ID
@pytest.mark.asyncio
async def test_primary_name_wins_over_other_games_alt_name(self):
"""When a search term equals one game's primary name and another game's
alternative name, the primary-name owner must win (alt titles fill in
only names not already claimed by a primary name)."""
handler = IGDBHandler()
primary = _make_game(100, "Contra")
# A different, higher-id game that lists "Contra" as an alt title.
other = _make_game(200, "Probotector", alternative_names=["Contra"])
async def mock_list_games(
search_term=None, fields=None, where=None, limit=None
):
return [other, primary]
with (
patch(
"handler.metadata.igdb_handler.IGDBHandler.is_enabled",
return_value=True,
),
patch.object(
handler.igdb_service,
"list_games",
side_effect=mock_list_games,
),
patch.object(
handler.igdb_service,
"search",
new_callable=AsyncMock,
return_value=[],
),
):
result = await handler._search_rom("contra", GENESIS_IGDB_ID)
assert result is not None
assert result["id"] == 100, (
"Expected the game whose primary name is 'Contra' (id=100), not the "
f"game that merely lists it as an alternative name; got id={result.get('id')}"
)
class TestRegionalTwinPlatformHelpers:
"""Unit tests for the regional-twin platform helpers (issue #3462).
IGDB files a console and its regional twin (SNES/Super Famicom,
NES/Famicom) under separate platform ids, so a search must include both to
match region-exclusive titles.
"""
def test_twin_pairs_are_bidirectional(self):
"""Each console resolves to its regional twin in both directions."""
assert _platform_igdb_ids_with_twin(SNES_IGDB_ID) == [
SNES_IGDB_ID,
SUPER_FAMICOM_IGDB_ID,
]
assert _platform_igdb_ids_with_twin(SUPER_FAMICOM_IGDB_ID) == [
SUPER_FAMICOM_IGDB_ID,
SNES_IGDB_ID,
]
assert _platform_igdb_ids_with_twin(NES_IGDB_ID) == [
NES_IGDB_ID,
FAMICOM_IGDB_ID,
]
assert _platform_igdb_ids_with_twin(FAMICOM_IGDB_ID) == [
FAMICOM_IGDB_ID,
NES_IGDB_ID,
]
def test_non_twin_platform_has_no_twin(self):
"""A platform without a regional twin resolves to itself only."""
assert _platform_igdb_ids_with_twin(GENESIS_IGDB_ID) == [GENESIS_IGDB_ID]
def test_build_where_single_platform_is_unparenthesized(self):
"""A non-twin platform keeps the original single-clause shape."""
assert (
_build_platforms_where(GENESIS_IGDB_ID) == f"platforms=[{GENESIS_IGDB_ID}]"
)
assert (
_build_platforms_where(GENESIS_IGDB_ID, field="game.platforms")
== f"game.platforms=[{GENESIS_IGDB_ID}]"
)
def test_build_where_twin_platform_is_an_or_group(self):
"""A twin platform produces a parenthesized OR of both platform ids."""
assert (
_build_platforms_where(SNES_IGDB_ID)
== f"(platforms=[{SNES_IGDB_ID}] | platforms=[{SUPER_FAMICOM_IGDB_ID}])"
)
assert (
_build_platforms_where(NES_IGDB_ID, field="game.platforms")
== f"(game.platforms=[{NES_IGDB_ID}] | game.platforms=[{FAMICOM_IGDB_ID}])"
)
class TestSearchRomRegionalTwinPlatforms:
"""Tests that IGDB search includes a platform's regional twin (issue #3462).
A Japan-only Super Famicom title (e.g. *Rudra no Hihou*) lives only under
IGDB's Super Famicom platform, so an ``snes`` scan that filtered to the SNES
platform alone would silently drop it. The search must query both twins.
"""
@pytest.mark.asyncio
async def test_snes_search_matches_super_famicom_only_game(self):
"""A Super-Famicom-only game must match when scanned from ``snes``."""
handler = IGDBHandler()
# Rudra no Hihou is catalogued under Super Famicom (58) only.
rudra = _make_game(829, "Rudra no Hihou")
captured_wheres: list[str] = []
async def mock_list_games(
search_term=None, fields=None, where=None, limit=None
):
captured_wheres.append(where or "")
# IGDB only surfaces the game when the Super Famicom platform is
# part of the filter.
if where and f"platforms=[{SUPER_FAMICOM_IGDB_ID}]" in where:
return [rudra]
return []
with (
patch(
"handler.metadata.igdb_handler.IGDBHandler.is_enabled",
return_value=True,
),
patch.object(
handler.igdb_service,
"list_games",
side_effect=mock_list_games,
),
patch.object(
handler.igdb_service,
"search",
new_callable=AsyncMock,
return_value=[],
),
):
result = await handler._search_rom(
"rudra no hihou", SNES_IGDB_ID, with_game_type=True
)
assert result is not None
assert result["id"] == 829, (
"Expected Rudra no Hihou (id=829) to match from an snes scan via the "
f"Super Famicom platform; got {result.get('name')} (id={result.get('id')})"
)
# The primary platform filter must mention both twins.
assert any(
f"platforms=[{SNES_IGDB_ID}]" in w
and f"platforms=[{SUPER_FAMICOM_IGDB_ID}]" in w
for w in captured_wheres
), f"Expected SNES + Super Famicom in the platform filter, got: {captured_wheres}"
@pytest.mark.asyncio
async def test_nes_search_matches_famicom_only_game(self):
"""A Famicom-only game must match when scanned from ``nes``."""
handler = IGDBHandler()
famicom_only = _make_game(1234, "Famicom Mukashi Banashi")
captured_wheres: list[str] = []
async def mock_list_games(
search_term=None, fields=None, where=None, limit=None
):
captured_wheres.append(where or "")
if where and f"platforms=[{FAMICOM_IGDB_ID}]" in where:
return [famicom_only]
return []
with (
patch(
"handler.metadata.igdb_handler.IGDBHandler.is_enabled",
return_value=True,
),
patch.object(
handler.igdb_service,
"list_games",
side_effect=mock_list_games,
),
patch.object(
handler.igdb_service,
"search",
new_callable=AsyncMock,
return_value=[],
),
):
result = await handler._search_rom(
"famicom mukashi banashi", NES_IGDB_ID, with_game_type=True
)
assert result is not None
assert result["id"] == 1234
assert any(
f"platforms=[{NES_IGDB_ID}]" in w and f"platforms=[{FAMICOM_IGDB_ID}]" in w
for w in captured_wheres
), f"Expected NES + Famicom in the platform filter, got: {captured_wheres}"
@pytest.mark.asyncio
async def test_super_famicom_search_matches_snes_only_game(self):
"""A Western-only SNES game must match when scanned from ``sfam``."""
handler = IGDBHandler()
snes_only = _make_game(4321, "EarthBound")
captured_wheres: list[str] = []
async def mock_list_games(
search_term=None, fields=None, where=None, limit=None
):
captured_wheres.append(where or "")
if where and f"platforms=[{SNES_IGDB_ID}]" in where:
return [snes_only]
return []
with (
patch(
"handler.metadata.igdb_handler.IGDBHandler.is_enabled",
return_value=True,
),
patch.object(
handler.igdb_service,
"list_games",
side_effect=mock_list_games,
),
patch.object(
handler.igdb_service,
"search",
new_callable=AsyncMock,
return_value=[],
),
):
result = await handler._search_rom(
"earthbound", SUPER_FAMICOM_IGDB_ID, with_game_type=True
)
assert result is not None
assert result["id"] == 4321
@pytest.mark.asyncio
async def test_non_twin_platform_filter_is_single_platform(self):
"""A platform without a twin must keep querying only its own id."""
handler = IGDBHandler()
game = _make_game(1799, "Ecco the Dolphin")
captured_wheres: list[str] = []
async def mock_list_games(
search_term=None, fields=None, where=None, limit=None
):
captured_wheres.append(where or "")
return [game]
with (
patch(
"handler.metadata.igdb_handler.IGDBHandler.is_enabled",
return_value=True,
),
patch.object(
handler.igdb_service,
"list_games",
side_effect=mock_list_games,
),
patch.object(
handler.igdb_service,
"search",
new_callable=AsyncMock,
return_value=[],
),
):
result = await handler._search_rom(
"ecco the dolphin", GENESIS_IGDB_ID, with_game_type=True
)
assert result is not None
assert result["id"] == 1799
# No twin → no OR group, just the single platform clause.
assert all(
" | " not in w for w in captured_wheres
), f"Non-twin platform should not OR a twin platform, got: {captured_wheres}"
assert any(
f"platforms=[{GENESIS_IGDB_ID}]" in w for w in captured_wheres
), captured_wheres
class TestSonySerialFilenames:
"""Tests for Sony serial resolution in get_rom."""
@pytest.mark.asyncio
async def test_serial_at_filename_start_resolves_title(self):
"""A serial in the first two characters of the filename must still hit
the serial index. Regression: re.IGNORECASE was passed as the ``pos``
argument of ``Pattern.search()``, skipping the first two characters,
so files named by their serial (e.g. ``SCUS-94163.bin``) were never
resolved."""
handler = IGDBHandler()
with (
patch(
"handler.metadata.igdb_handler.IGDBHandler.is_enabled",
return_value=True,
),
patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget,
patch.object(
IGDBHandler, "_search_rom", new_callable=AsyncMock, return_value=None
),
):
mock_hget.return_value = json.dumps({"title": "Gran Turismo"})
result = await handler.get_rom(MagicMock(), "SCUS-94163.bin", PS1_IGDB_ID)
mock_hget.assert_awaited_once_with(PS1_SERIAL_INDEX_KEY, "SCUS-94163")
assert result.get("name") == "Gran Turismo"
assert result["igdb_id"] is None
class TestIsPrefixSupersetMatch:
"""Unit tests for the prefix/superset title heuristic (issue #3805)."""
@pytest.mark.parametrize(
("search_term", "candidate", "expected"),
[
# A more specific variant's search term extends the base title.
(
"metal gear solid portable ops plus",
"Metal Gear Solid: Portable Ops",
True,
),
# Reversed: the base term is a prefix of the variant candidate.
(
"Metal Gear Solid: Portable Ops",
"Metal Gear Solid: Portable Ops Plus",
True,
),
("pokemon ranger shadows of almia", "Pokemon Ranger", True),
# Extra word is not a trailing suffix, so not a prefix relationship.
("sonic hedgehog", "Sonic the Hedgehog", False),
# Identical titles are an exact match, not a prefix ambiguity.
("Metal Gear Solid", "metal gear solid", False),
# Unrelated titles.
("contra", "Probotector", False),
],
)
def test_prefix_superset_detection(self, search_term, candidate, expected):
handler = IGDBHandler()
assert handler._is_prefix_superset_match(search_term, candidate) is expected
class TestSearchRomPrefixSupersetVariant:
"""A base title that is a prefix of the searched variant must not be
accepted when the more specific variant exists (issue #3805).
'Metal Gear Solid - Portable Ops Plus' and 'Portable Ops' (and the Pokemon
Ranger series) scored the same IGDB id because the first search pass only
returned the base game and its ~0.99 Jaro-Winkler score cleared the match
threshold.
"""
BASE_ID = 1001
VARIANT_ID = 1002
BASE_NAME = "Metal Gear Solid: Portable Ops"
VARIANT_NAME = "Metal Gear Solid: Portable Ops Plus"
@pytest.mark.asyncio
async def test_variant_excluded_by_game_type_is_recovered(self):
"""When the game_type filter hides the variant (IGDB classifies it as an
expansion), dropping the filter must surface it so the exact match wins
over the base near-miss."""
handler = IGDBHandler()
base = _make_game(self.BASE_ID, self.BASE_NAME)
variant = _make_game(self.VARIANT_ID, self.VARIANT_NAME)
async def mock_list_games(
search_term=None, fields=None, where=None, limit=None
):
# game_type-filtered pass excludes the variant (an expansion type).
if where and "game_type" in where:
return [base]
# Re-query without the game_type filter surfaces both.
return [base, variant]
with (
patch(
"handler.metadata.igdb_handler.IGDBHandler.is_enabled",
return_value=True,
),
patch.object(
handler.igdb_service,
"list_games",
side_effect=mock_list_games,
),
patch.object(
handler.igdb_service,
"search",
new_callable=AsyncMock,
return_value=[],
),
):
result = await handler._search_rom(
"metal gear solid portable ops plus",
GENESIS_IGDB_ID,
with_game_type=True,
)
assert result is not None
assert result["id"] == self.VARIANT_ID, (
f"Expected the '{self.VARIANT_NAME}' variant (id={self.VARIANT_ID}), "
f"got {result.get('name')} (id={result.get('id')}). The base title is "
"only a prefix near-miss and must not win over the exact variant."
)
@pytest.mark.asyncio
async def test_base_title_still_matches_when_it_is_the_target(self):
"""Scanning the base game itself must return the base on the first pass
without any widening (exact match short-circuits)."""
handler = IGDBHandler()
base = _make_game(self.BASE_ID, self.BASE_NAME)
variant = _make_game(self.VARIANT_ID, self.VARIANT_NAME)
search_mock = AsyncMock(return_value=[])
async def mock_list_games(
search_term=None, fields=None, where=None, limit=None
):
# First pass includes both; the base is an exact match.
if where and "game_type" in where:
return [base, variant]
raise AssertionError("widening should not run for an exact match")
with (
patch(
"handler.metadata.igdb_handler.IGDBHandler.is_enabled",
return_value=True,
),
patch.object(
handler.igdb_service,
"list_games",
side_effect=mock_list_games,
),
patch.object(handler.igdb_service, "search", search_mock),
):
result = await handler._search_rom(
"metal gear solid portable ops",
GENESIS_IGDB_ID,
with_game_type=True,
)
assert result is not None
assert result["id"] == self.BASE_ID
search_mock.assert_not_awaited()
@pytest.mark.asyncio
async def test_non_prefix_fuzzy_match_does_not_widen(self):
"""A benign non-exact match that is not a prefix/superset must be
returned from the first pass without extra queries."""
handler = IGDBHandler()
game = _make_game(42, "Sonic the Hedgehog")
search_mock = AsyncMock(return_value=[])
async def mock_list_games(
search_term=None, fields=None, where=None, limit=None
):
if where and "game_type" in where:
return [game]
raise AssertionError("widening should not run for a non-prefix match")
with (
patch(
"handler.metadata.igdb_handler.IGDBHandler.is_enabled",
return_value=True,
),
patch.object(
handler.igdb_service,
"list_games",
side_effect=mock_list_games,
),
patch.object(handler.igdb_service, "search", search_mock),
):
result = await handler._search_rom(
"sonic hedgehog", GENESIS_IGDB_ID, with_game_type=True
)
assert result is not None
assert result["id"] == 42
search_mock.assert_not_awaited()