mirror of
https://github.com/rommapp/romm.git
synced 2026-11-28 17:48:31 +01:00
* fix(hltb): send the search's platform in the form HowLongToBeat filters by
HowLongToBeat's search ignores a platform sent as a bare name, so every
search covered every platform: "gran turismo" for the PSP came back with
the PlayStation game first, and the retry on a subtitle alone could match
a game on any console. Its site sends the platform as
{"mode": "include", "values": [...]}, which the search does filter by, and
the payload now sends it that way. With no platform name the list is
empty, which searches every platform.
A name outside HowLongToBeat's platform list filters out every game. It
lists PlayStation VR games under PlayStation 4, so that is what a
PlayStation VR ROM searches, and it has no PlayStation Now, so that
platform no longer maps to HowLongToBeat.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TsLtVzsT8WBDnc6ZSRyp2u
* fix(hltb): key HowLongToBeat's VIC-20 on the VIC-20, not the Plus/4
The VIC-20 entry was keyed on the Plus/4, which made no difference while
HowLongToBeat ignored the platform. Now that the search filters by it, a
Plus/4 ROM would be searched among VIC-20 games. HowLongToBeat has no
Plus/4, so that platform no longer maps to it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TsLtVzsT8WBDnc6ZSRyp2u
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1083 lines
39 KiB
Python
1083 lines
39 KiB
Python
import asyncio
|
|
import json
|
|
from pathlib import Path
|
|
from typing import Any
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
|
|
import httpx2
|
|
import pytest
|
|
from fastapi import HTTPException, status
|
|
|
|
from handler.metadata.hltb_handler import HLTBHandler
|
|
from utils.hltb_search import (
|
|
HLTB_API_URL_FIXTURE,
|
|
HLTB_BASE_URL,
|
|
HLTB_USER_AGENT,
|
|
SESSION_MINT_SUFFIX,
|
|
)
|
|
|
|
SEARCH_URL = f"{HLTB_BASE_URL}/api/search/site"
|
|
|
|
|
|
def _handler_without_session() -> HLTBHandler:
|
|
"""A handler pointed at an endpoint, before any session has been minted."""
|
|
handler = HLTBHandler()
|
|
handler.search_url = SEARCH_URL
|
|
handler.search_init_url = f"{SEARCH_URL}{SESSION_MINT_SUFFIX}"
|
|
return handler
|
|
|
|
|
|
def _handler() -> HLTBHandler:
|
|
handler = _handler_without_session()
|
|
handler.security_token = "token-1"
|
|
handler.hp_key = "ign_aaaa"
|
|
handler.hp_val = "val-1"
|
|
return handler
|
|
|
|
|
|
def _response(
|
|
status_code: int = 200, json_body: dict[str, Any] | None = None
|
|
) -> MagicMock:
|
|
response = MagicMock()
|
|
response.status_code = status_code
|
|
if status_code >= 400:
|
|
response.raise_for_status.side_effect = httpx2.HTTPStatusError(
|
|
"error", request=MagicMock(), response=response
|
|
)
|
|
else:
|
|
response.json.return_value = json_body or {}
|
|
response.content = json.dumps(json_body or {}).encode()
|
|
return response
|
|
|
|
|
|
def _response_with_text(text: str) -> MagicMock:
|
|
response = _response()
|
|
response.text = text
|
|
return response
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def acquire():
|
|
with (
|
|
patch(
|
|
"handler.metadata.hltb_handler._rate_limiter.acquire",
|
|
new_callable=AsyncMock,
|
|
) as mock_acquire,
|
|
patch("handler.metadata.hltb_handler.asyncio.sleep", new_callable=AsyncMock),
|
|
):
|
|
yield mock_acquire
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_request_renews_session_and_retries_on_403(mock_ctx_httpx_client):
|
|
handler = _handler()
|
|
mock_client = AsyncMock()
|
|
mock_client.post.side_effect = [
|
|
_response(status.HTTP_403_FORBIDDEN),
|
|
_response(json_body={"data": [{"game_id": 1}]}),
|
|
]
|
|
# The renewal goes through /init and hands back a fresh session.
|
|
mock_client.get.return_value = _response(
|
|
json_body={"token": "token-2", "hpKey": "ign_bbbb", "hpVal": "val-2"}
|
|
)
|
|
mock_ctx_httpx_client.get.return_value = mock_client
|
|
|
|
result = await handler._request(handler.search_url, {"a": 1})
|
|
|
|
assert result == {"data": [{"game_id": 1}]}
|
|
assert mock_client.post.await_count == 2
|
|
mock_client.get.assert_awaited_once()
|
|
|
|
# The retry must carry the renewed session, not the rejected one.
|
|
retry_kwargs = mock_client.post.await_args_list[1].kwargs
|
|
assert retry_kwargs["headers"]["x-auth-token"] == "token-2"
|
|
assert retry_kwargs["headers"]["x-hp-key"] == "ign_bbbb"
|
|
assert retry_kwargs["headers"]["x-hp-val"] == "val-2"
|
|
# The rotated honeypot key replaces the old one rather than joining it.
|
|
assert retry_kwargs["json"] == {"a": 1, "ign_bbbb": "val-2"}
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_request_works_with_a_token_only_session(mock_ctx_httpx_client):
|
|
handler = _handler_without_session()
|
|
mock_client = AsyncMock()
|
|
mock_client.get.return_value = _response(json_body={"token": "token-1"})
|
|
mock_client.post.return_value = _response(json_body={"data": [{"game_id": 1}]})
|
|
mock_ctx_httpx_client.get.return_value = mock_client
|
|
|
|
result = await handler._request(handler.search_url, {"a": 1})
|
|
|
|
assert result == {"data": [{"game_id": 1}]}
|
|
post_call = mock_client.post.await_args
|
|
assert post_call is not None
|
|
kwargs = post_call.kwargs
|
|
assert kwargs["headers"]["x-auth-token"] == "token-1"
|
|
assert "x-hp-key" not in kwargs["headers"]
|
|
assert "x-hp-val" not in kwargs["headers"]
|
|
assert kwargs["json"] == {"a": 1}
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_request_does_not_mutate_caller_payload(mock_ctx_httpx_client):
|
|
handler = _handler()
|
|
mock_client = AsyncMock()
|
|
mock_client.post.return_value = _response(json_body={"data": []})
|
|
mock_ctx_httpx_client.get.return_value = mock_client
|
|
|
|
payload = {"a": 1}
|
|
await handler._request(handler.search_url, payload)
|
|
|
|
assert payload == {"a": 1}
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_request_uses_session_renewed_while_it_was_paced(
|
|
mock_ctx_httpx_client, acquire
|
|
):
|
|
# The handler is a shared singleton, so a peer scanning another ROM can renew
|
|
# the session while this call is waiting on the rate limiter.
|
|
handler = _handler()
|
|
mock_client = AsyncMock()
|
|
mock_client.post.return_value = _response(json_body={"data": []})
|
|
mock_ctx_httpx_client.get.return_value = mock_client
|
|
|
|
async def renew_while_waiting() -> None:
|
|
handler.security_token = "token-from-peer"
|
|
handler.hp_key = "ign_peer"
|
|
handler.hp_val = "val-peer"
|
|
|
|
acquire.side_effect = renew_while_waiting
|
|
|
|
await handler._request(handler.search_url, {"a": 1})
|
|
|
|
kwargs = mock_client.post.await_args.kwargs
|
|
assert kwargs["headers"]["x-auth-token"] == "token-from-peer"
|
|
assert kwargs["json"] == {"a": 1, "ign_peer": "val-peer"}
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_request_bails_if_session_is_lost_while_it_was_paced(
|
|
mock_ctx_httpx_client, acquire
|
|
):
|
|
handler = _handler()
|
|
mock_client = AsyncMock()
|
|
mock_ctx_httpx_client.get.return_value = mock_client
|
|
|
|
async def lose_session_while_waiting() -> None:
|
|
handler.security_token = None
|
|
|
|
acquire.side_effect = lose_session_while_waiting
|
|
|
|
assert await handler._request(handler.search_url, {}) == {}
|
|
mock_client.post.assert_not_awaited()
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_session_renewal_is_rate_limited_too(mock_ctx_httpx_client, acquire):
|
|
handler = _handler()
|
|
mock_client = AsyncMock()
|
|
mock_client.post.side_effect = [
|
|
_response(status.HTTP_403_FORBIDDEN),
|
|
_response(json_body={"data": []}),
|
|
]
|
|
mock_client.get.return_value = _response(
|
|
json_body={"token": "token-2", "hpKey": "ign_bbbb", "hpVal": "val-2"}
|
|
)
|
|
mock_ctx_httpx_client.get.return_value = mock_client
|
|
|
|
await handler._request(handler.search_url, {})
|
|
|
|
# Two POSTs plus the /init renewal in between, all paced.
|
|
assert acquire.await_count == 3
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_github_endpoint_fetch_is_not_rate_limited(
|
|
mock_ctx_httpx_client, acquire
|
|
):
|
|
# The endpoint fixture lives on GitHub, so it should not spend HLTB budget.
|
|
handler = HLTBHandler()
|
|
mock_client = AsyncMock()
|
|
mock_client.get.return_value = _response_with_text(
|
|
"https://howlongtobeat.com/api/rotated"
|
|
)
|
|
mock_ctx_httpx_client.get.return_value = mock_client
|
|
|
|
await handler._fetch_search_endpoint()
|
|
|
|
acquire.assert_not_awaited()
|
|
|
|
|
|
def test_the_bundled_endpoint_is_the_default():
|
|
handler = HLTBHandler()
|
|
|
|
assert handler.search_url == HLTB_API_URL_FIXTURE.read_text().strip()
|
|
assert handler.search_init_url == f"{handler.search_url}{SESSION_MINT_SUFFIX}"
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.discover_hltb_endpoint")
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_github_endpoint_is_used_without_discovery(
|
|
mock_ctx_httpx_client, mock_discover
|
|
):
|
|
handler = HLTBHandler()
|
|
mock_client = AsyncMock()
|
|
mock_client.get.return_value = _response_with_text(
|
|
"https://howlongtobeat.com/api/rotated\n"
|
|
)
|
|
mock_ctx_httpx_client.get.return_value = mock_client
|
|
|
|
await handler._fetch_search_endpoint()
|
|
|
|
assert handler.search_url == "https://howlongtobeat.com/api/rotated"
|
|
mock_discover.assert_not_called()
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"github_response",
|
|
[
|
|
pytest.param(_response(status.HTTP_404_NOT_FOUND), id="github-error"),
|
|
pytest.param(_response_with_text(" \n"), id="github-empty"),
|
|
],
|
|
)
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.discover_hltb_endpoint")
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_endpoint_is_discovered_from_hltb_when_github_fails(
|
|
mock_ctx_httpx_client, mock_discover, github_response: MagicMock
|
|
):
|
|
handler = HLTBHandler()
|
|
mock_client = AsyncMock()
|
|
mock_client.get.return_value = github_response
|
|
mock_ctx_httpx_client.get.return_value = mock_client
|
|
mock_discover.return_value = "https://howlongtobeat.com/api/discovered"
|
|
|
|
await handler._fetch_search_endpoint()
|
|
|
|
mock_discover.assert_called_once_with(HLTB_BASE_URL)
|
|
assert handler.search_url == "https://howlongtobeat.com/api/discovered"
|
|
assert handler.search_init_url == "https://howlongtobeat.com/api/discovered/init"
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.discover_hltb_endpoint", return_value=None)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_bundled_endpoint_is_kept_when_github_and_discovery_fail(
|
|
mock_ctx_httpx_client, mock_discover
|
|
):
|
|
handler = HLTBHandler()
|
|
bundled = handler.search_url
|
|
mock_client = AsyncMock()
|
|
mock_client.get.side_effect = httpx2.ConnectError("GitHub unreachable")
|
|
mock_ctx_httpx_client.get.return_value = mock_client
|
|
|
|
await handler._fetch_search_endpoint()
|
|
|
|
mock_discover.assert_called_once()
|
|
assert handler.search_url == bundled
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch(
|
|
"handler.metadata.hltb_handler.discover_hltb_endpoint",
|
|
side_effect=AttributeError("unexpected response shape"),
|
|
)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_a_discovery_error_keeps_the_bundled_endpoint(
|
|
mock_ctx_httpx_client, mock_discover
|
|
):
|
|
handler = HLTBHandler()
|
|
bundled = handler.search_url
|
|
mock_client = AsyncMock()
|
|
mock_client.get.side_effect = httpx2.ConnectError("GitHub unreachable")
|
|
mock_ctx_httpx_client.get.return_value = mock_client
|
|
|
|
# A failed discovery must not abort the scan that initializes the handler.
|
|
await handler._fetch_search_endpoint()
|
|
|
|
assert handler.search_url == bundled
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_debug_log_does_not_leak_session_material(mock_ctx_httpx_client):
|
|
# Logs are downloadable via /api/logs and routinely pasted into bug reports,
|
|
# and the token decodes to a string containing the host's public IP.
|
|
handler = _handler()
|
|
mock_client = AsyncMock()
|
|
mock_client.post.return_value = _response(json_body={"data": []})
|
|
mock_ctx_httpx_client.get.return_value = mock_client
|
|
|
|
with patch("handler.metadata.hltb_handler.log.debug") as mock_debug:
|
|
await handler._request(handler.search_url, {"searchTerms": ["Chrono"]})
|
|
|
|
logged = repr(mock_debug.call_args.args)
|
|
for secret in ("token-1", "ign_aaaa", "val-1"):
|
|
assert secret not in logged
|
|
|
|
# The parts that make the log useful are still there.
|
|
assert "Chrono" in logged
|
|
assert "[redacted]" in logged
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_request_backs_off_and_retries_on_429(mock_ctx_httpx_client):
|
|
handler = _handler()
|
|
mock_client = AsyncMock()
|
|
mock_client.post.side_effect = [
|
|
_response(status.HTTP_429_TOO_MANY_REQUESTS),
|
|
_response(json_body={"data": []}),
|
|
]
|
|
mock_ctx_httpx_client.get.return_value = mock_client
|
|
|
|
assert await handler._request(handler.search_url, {}) == {"data": []}
|
|
assert mock_client.post.await_count == 2
|
|
# A rate limit is not a session problem, so no renewal should be attempted.
|
|
mock_client.get.assert_not_awaited()
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_request_gives_up_when_session_renewal_fails(mock_ctx_httpx_client):
|
|
handler = _handler()
|
|
mock_client = AsyncMock()
|
|
mock_client.post.return_value = _response(status.HTTP_403_FORBIDDEN)
|
|
mock_client.get.return_value = _response(json_body={})
|
|
mock_ctx_httpx_client.get.return_value = mock_client
|
|
|
|
assert await handler._request(handler.search_url, {}) == {}
|
|
assert mock_client.post.await_count == 1
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_persistent_403_reports_session_cause_not_connectivity(
|
|
mock_ctx_httpx_client,
|
|
):
|
|
handler = _handler()
|
|
mock_client = AsyncMock()
|
|
mock_client.post.return_value = _response(status.HTTP_403_FORBIDDEN)
|
|
mock_client.get.return_value = _response(
|
|
json_body={"token": "token-2", "hpKey": "ign_bbbb", "hpVal": "val-2"}
|
|
)
|
|
mock_ctx_httpx_client.get.return_value = mock_client
|
|
|
|
with pytest.raises(HTTPException) as exc_info:
|
|
await handler._request(handler.search_url, {})
|
|
|
|
assert exc_info.value.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
|
|
assert "internet connection" not in exc_info.value.detail
|
|
assert "rejected the session" in exc_info.value.detail
|
|
assert mock_client.post.await_count == 3
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_rotated_endpoint_reports_404_cause(mock_ctx_httpx_client):
|
|
handler = _handler()
|
|
mock_client = AsyncMock()
|
|
mock_client.post.return_value = _response(status.HTTP_404_NOT_FOUND)
|
|
mock_ctx_httpx_client.get.return_value = mock_client
|
|
|
|
with pytest.raises(HTTPException) as exc_info:
|
|
await handler._request("https://howlongtobeat.com/api/find", {})
|
|
|
|
assert "rotated" in exc_info.value.detail
|
|
# A 404 is not retryable, so it should fail on the first attempt.
|
|
assert mock_client.post.await_count == 1
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_connect_error_still_reports_connectivity(mock_ctx_httpx_client):
|
|
handler = _handler()
|
|
mock_client = AsyncMock()
|
|
mock_client.post.side_effect = httpx2.ConnectError("no route")
|
|
mock_ctx_httpx_client.get.return_value = mock_client
|
|
|
|
with pytest.raises(HTTPException) as exc_info:
|
|
await handler._request(handler.search_url, {})
|
|
|
|
assert "internet connection" in exc_info.value.detail
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_request_returns_empty_without_a_session(mock_ctx_httpx_client):
|
|
handler = _handler_without_session()
|
|
mock_client = AsyncMock()
|
|
mock_client.get.return_value = _response(json_body={})
|
|
mock_ctx_httpx_client.get.return_value = mock_client
|
|
|
|
assert await handler._request(handler.search_url, {}) == {}
|
|
mock_client.post.assert_not_awaited()
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_request_mints_a_session_a_failed_startup_never_got(
|
|
mock_ctx_httpx_client,
|
|
):
|
|
handler = _handler_without_session()
|
|
mock_client = AsyncMock()
|
|
mock_client.get.return_value = _response(
|
|
json_body={"token": "token-late", "hpKey": "ign_late", "hpVal": "val-late"}
|
|
)
|
|
mock_client.post.return_value = _response(json_body={"data": []})
|
|
mock_ctx_httpx_client.get.return_value = mock_client
|
|
|
|
assert await handler._request(handler.search_url, {"a": 1}) == {"data": []}
|
|
|
|
# The mint has to address the endpoint being searched, not a stale default.
|
|
assert mock_client.get.await_args.args[0] == handler.search_init_url
|
|
kwargs = mock_client.post.await_args.kwargs
|
|
assert kwargs["headers"]["x-auth-token"] == "token-late"
|
|
assert kwargs["json"] == {"a": 1, "ign_late": "val-late"}
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_a_failed_mint_is_not_retried_by_every_lookup(mock_ctx_httpx_client):
|
|
handler = _handler_without_session()
|
|
mock_client = AsyncMock()
|
|
mock_client.get.return_value = _response(json_body={})
|
|
mock_ctx_httpx_client.get.return_value = mock_client
|
|
|
|
for _ in range(5):
|
|
assert await handler._request(handler.search_url, {}) == {}
|
|
|
|
# HLTB being down must not cost every ROM in a scan its own round trip.
|
|
mock_client.get.assert_awaited_once()
|
|
mock_client.post.assert_not_awaited()
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_concurrent_lookups_mint_one_shared_session(mock_ctx_httpx_client):
|
|
handler = _handler_without_session()
|
|
mock_client = AsyncMock()
|
|
mint_reached = asyncio.Event()
|
|
mint_may_finish = asyncio.Event()
|
|
|
|
async def blocking_mint(*args, **kwargs) -> MagicMock:
|
|
# Hold /init open so every other lookup reaches _ensure_session meanwhile.
|
|
mint_reached.set()
|
|
await mint_may_finish.wait()
|
|
return _response(
|
|
json_body={"token": "token-1", "hpKey": "ign_aaaa", "hpVal": "val-1"}
|
|
)
|
|
|
|
mock_client.get.side_effect = blocking_mint
|
|
mock_client.post.return_value = _response(json_body={"data": []})
|
|
mock_ctx_httpx_client.get.return_value = mock_client
|
|
|
|
lookups = [
|
|
asyncio.create_task(handler._request(handler.search_url, {})) for _ in range(5)
|
|
]
|
|
await mint_reached.wait()
|
|
mint_may_finish.set()
|
|
await asyncio.gather(*lookups)
|
|
|
|
# A scan starts many lookups at once, and HLTB must not see a mint from each.
|
|
mock_client.get.assert_awaited_once()
|
|
assert mock_client.post.await_count == 5
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_initialize_fetches_endpoint_then_session(mock_ctx_httpx_client):
|
|
handler = HLTBHandler()
|
|
mock_client = AsyncMock()
|
|
mock_client.get.side_effect = [
|
|
_response_with_text("https://howlongtobeat.com/api/rotated"),
|
|
_response(json_body={"token": "t", "hpKey": "k", "hpVal": "v"}),
|
|
]
|
|
mock_ctx_httpx_client.get.return_value = mock_client
|
|
|
|
await handler.initialize()
|
|
|
|
assert handler.search_url == "https://howlongtobeat.com/api/rotated"
|
|
assert handler.search_init_url == "https://howlongtobeat.com/api/rotated/init"
|
|
assert handler._has_session()
|
|
# The session must be requested from the rotated endpoint, not the stale default.
|
|
assert (
|
|
mock_client.get.await_args_list[1].args[0]
|
|
== "https://howlongtobeat.com/api/rotated/init"
|
|
)
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_heartbeat_sends_the_user_agent_hltb_requires(mock_ctx_httpx_client):
|
|
handler = HLTBHandler()
|
|
mock_client = AsyncMock()
|
|
mock_client.get.return_value = _response()
|
|
mock_ctx_httpx_client.get.return_value = mock_client
|
|
|
|
with patch.object(handler, "is_enabled", return_value=True):
|
|
assert await handler.heartbeat() is True
|
|
|
|
# HLTB's firewall rejects non-browser user agents.
|
|
headers = mock_client.get.await_args.kwargs["headers"]
|
|
assert headers["User-Agent"] == HLTB_USER_AGENT
|
|
assert headers["Referer"] == "https://howlongtobeat.com"
|
|
|
|
|
|
def _game(
|
|
game_id: int, name: str, *, alias: str = "", timed: bool = True
|
|
) -> dict[str, Any]:
|
|
"""A search result carrying only the fields matching depends on."""
|
|
time = 3600 if timed else 0
|
|
return {
|
|
"game_id": game_id,
|
|
"game_name": name,
|
|
"game_alias": alias,
|
|
"game_image": "",
|
|
"comp_main": time,
|
|
"comp_plus": time,
|
|
"comp_100": time,
|
|
"comp_all": time,
|
|
"comp_main_count": 1,
|
|
"comp_plus_count": 1,
|
|
"comp_100_count": 1,
|
|
"comp_all_count": 1,
|
|
"release_world": 2008,
|
|
"review_score": 70,
|
|
"count_review": 5,
|
|
"profile_popular": 3,
|
|
"count_comp": 4,
|
|
}
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
async def test_series_prefix_the_catalogue_omits_still_matches():
|
|
""" "007: Quantum of Solace" scores 0.838 against "Quantum of Solace",
|
|
under the gate, so the part after the separator has to be searched too."""
|
|
handler = _handler()
|
|
searched: list[str] = []
|
|
|
|
async def search_games(term: str, _platform_slug: str) -> list[dict[str, Any]]:
|
|
searched.append(term)
|
|
return [_game(7467, "Quantum of Solace")]
|
|
|
|
with patch.object(handler, "search_games", side_effect=search_games):
|
|
rom = await handler.get_rom("007 - Quantum of Solace (USA).chd", "ps2")
|
|
|
|
assert rom["hltb_id"] == 7467
|
|
assert searched == [
|
|
"007: quantum of solace",
|
|
"007 quantum of solace",
|
|
"quantum of solace",
|
|
]
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
async def test_separator_the_catalogue_omits_still_matches():
|
|
"""HowLongToBeat returns nothing for "pokemon: emerald version"."""
|
|
handler = _handler()
|
|
searched: list[str] = []
|
|
|
|
async def search_games(term: str, _platform_slug: str) -> list[dict[str, Any]]:
|
|
searched.append(term)
|
|
if term == "pokemon emerald version":
|
|
return [_game(6966, "Pokémon Emerald Version")]
|
|
return []
|
|
|
|
with patch.object(handler, "search_games", side_effect=search_games):
|
|
rom = await handler.get_rom("Pokemon - Emerald Version (USA).gba", "gba")
|
|
|
|
assert rom["hltb_id"] == 6966
|
|
assert searched == ["pokemon: emerald version", "pokemon emerald version"]
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
async def test_full_term_match_does_not_trigger_a_second_search():
|
|
handler = _handler()
|
|
searched: list[str] = []
|
|
|
|
async def search_games(term: str, _platform_slug: str) -> list[dict[str, Any]]:
|
|
searched.append(term)
|
|
return [_game(4806, "James Bond 007: Agent Under Fire")]
|
|
|
|
with patch.object(handler, "search_games", side_effect=search_games):
|
|
rom = await handler.get_rom(
|
|
"James Bond 007 - Agent Under Fire (USA).chd", "ps2"
|
|
)
|
|
|
|
assert rom["hltb_id"] == 4806
|
|
assert len(searched) == 1
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
async def test_term_without_a_separator_is_not_searched_twice():
|
|
handler = _handler()
|
|
searched: list[str] = []
|
|
|
|
async def search_games(term: str, _platform_slug: str) -> list[dict[str, Any]]:
|
|
searched.append(term)
|
|
return []
|
|
|
|
with patch.object(handler, "search_games", side_effect=search_games):
|
|
rom = await handler.get_rom("Nothing Like It (USA).chd", "ps2")
|
|
|
|
assert rom["hltb_id"] is None
|
|
assert searched == ["nothing like it"]
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
async def test_hyphen_inside_a_word_does_not_trigger_a_retry():
|
|
"""A retry on "man 2" would invite a match on an unrelated game."""
|
|
handler = _handler()
|
|
searched: list[str] = []
|
|
|
|
async def search_games(term: str, _platform_slug: str) -> list[dict[str, Any]]:
|
|
searched.append(term)
|
|
return []
|
|
|
|
with patch.object(handler, "search_games", side_effect=search_games):
|
|
rom = await handler.get_rom("Spider-Man 2 (USA).chd", "ps2")
|
|
|
|
assert rom["hltb_id"] is None
|
|
assert searched == ["spider-man 2"]
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
async def test_retry_still_requires_recorded_times():
|
|
"""A catalogue entry nobody has submitted a time for is not a match."""
|
|
handler = _handler()
|
|
|
|
async def search_games(_term: str, _platform_slug: str) -> list[dict[str, Any]]:
|
|
return [_game(7467, "Quantum of Solace", timed=False)]
|
|
|
|
with patch.object(handler, "search_games", side_effect=search_games):
|
|
rom = await handler.get_rom("007 - Quantum of Solace (USA).chd", "ps2")
|
|
|
|
assert rom["hltb_id"] is None
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
async def test_alias_beats_a_near_miss_on_another_game_name():
|
|
handler = _handler()
|
|
|
|
async def search_games(_term, _platform_slug):
|
|
return [
|
|
_game(5773, "Mega Man X", alias="Rockman X"),
|
|
_game(59383, "Rockman EXE WS"),
|
|
]
|
|
|
|
with patch.object(handler, "search_games", side_effect=search_games):
|
|
rom = await handler.get_rom("Rockman X (Japan).sfc", "snes")
|
|
|
|
assert rom["hltb_id"] == 5773
|
|
assert rom["name"] == "Mega Man X"
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
async def test_alias_matches_when_the_name_is_far_off():
|
|
handler = _handler()
|
|
|
|
async def search_games(_term, _platform_slug):
|
|
return [_game(9940, "Trials of Mana", alias="Seiken Densetsu 3")]
|
|
|
|
with patch.object(handler, "search_games", side_effect=search_games):
|
|
rom = await handler.get_rom("Seiken Densetsu 3 (Japan).sfc", "snes")
|
|
|
|
assert rom["hltb_id"] == 9940
|
|
assert rom["name"] == "Trials of Mana"
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
async def test_each_comma_separated_alias_is_scored():
|
|
handler = _handler()
|
|
|
|
async def search_games(_term, _platform_slug):
|
|
return [_game(9940, "Trials of Mana", alias="Seiken Densetsu 3, SD3")]
|
|
|
|
with patch.object(handler, "search_games", side_effect=search_games):
|
|
rom = await handler.get_rom("SD3 (Japan).sfc", "snes")
|
|
|
|
assert rom["hltb_id"] == 9940
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
async def test_an_alias_does_not_outrank_another_game_with_that_name():
|
|
handler = _handler()
|
|
|
|
async def search_games(_term, _platform_slug):
|
|
return [
|
|
_game(1, "Mega Man X Collection", alias="Mega Man X"),
|
|
_game(5773, "Mega Man X"),
|
|
]
|
|
|
|
with patch.object(handler, "search_games", side_effect=search_games):
|
|
rom = await handler.get_rom("Mega Man X (USA).sfc", "snes")
|
|
|
|
assert rom["hltb_id"] == 5773
|
|
|
|
|
|
def _game_page(game: dict[str, Any] | None) -> MagicMock:
|
|
"""A game page carrying its record in the Next.js hydration payload."""
|
|
games = [game] if game is not None else []
|
|
payload = json.dumps({"props": {"pageProps": {"game": {"data": {"game": games}}}}})
|
|
response = MagicMock()
|
|
response.status_code = 200
|
|
response.text = (
|
|
'<html><body><script id="__NEXT_DATA__" type="application/json">'
|
|
f"{payload}</script></body></html>"
|
|
)
|
|
return response
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_get_rom_by_id_reads_the_game_page(mock_ctx_httpx_client):
|
|
"""The by-ID lookup the manual edit form depends on: HLTB has no API for it,
|
|
so the record comes off the game page."""
|
|
handler = _handler()
|
|
client = MagicMock()
|
|
client.get = AsyncMock(return_value=_game_page(_game(7169, "Pokémon Red and Blue")))
|
|
mock_ctx_httpx_client.get.return_value = client
|
|
|
|
rom = await handler.get_rom_by_id(7169)
|
|
|
|
assert rom["hltb_id"] == 7169
|
|
assert rom["name"] == "Pokémon Red and Blue"
|
|
assert rom["hltb_metadata"]["main_story"] == 3600
|
|
assert rom["hltb_metadata"]["review_score"] == 70
|
|
|
|
# The `/game?id=` form answers with a redirect the shared client won't follow.
|
|
assert client.get.await_args.args[0] == "https://howlongtobeat.com/game/7169"
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_get_rom_by_id_sends_the_user_agent_hltb_requires(
|
|
mock_ctx_httpx_client,
|
|
):
|
|
handler = _handler()
|
|
client = MagicMock()
|
|
client.get = AsyncMock(return_value=_game_page(_game(7169, "Pokémon")))
|
|
mock_ctx_httpx_client.get.return_value = client
|
|
|
|
await handler.get_rom_by_id(7169)
|
|
|
|
assert client.get.await_args.kwargs["headers"]["User-Agent"] == HLTB_USER_AGENT
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_get_rom_by_id_reads_the_full_release_date(mock_ctx_httpx_client):
|
|
"""The game page dates a release in full where search returns just the year."""
|
|
handler = _handler()
|
|
game = _game(7169, "Pokémon Red and Blue") | {"release_world": "1996-02-27"}
|
|
client = MagicMock()
|
|
client.get = AsyncMock(return_value=_game_page(game))
|
|
mock_ctx_httpx_client.get.return_value = client
|
|
|
|
rom = await handler.get_rom_by_id(7169)
|
|
|
|
assert rom["hltb_metadata"]["release_year"] == 1996
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_get_rom_by_id_tolerates_a_page_without_popularity(
|
|
mock_ctx_httpx_client,
|
|
):
|
|
"""The game page omits the popularity search reports, so it must not fail."""
|
|
handler = _handler()
|
|
game = _game(7169, "Pokémon Red and Blue") | {"profile_popular": None}
|
|
client = MagicMock()
|
|
client.get = AsyncMock(return_value=_game_page(game))
|
|
mock_ctx_httpx_client.get.return_value = client
|
|
|
|
rom = await handler.get_rom_by_id(7169)
|
|
|
|
assert rom["hltb_id"] == 7169
|
|
assert "popularity" not in rom["hltb_metadata"]
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_unknown_id_is_not_reported_as_an_outage(mock_ctx_httpx_client):
|
|
"""A mistyped ID is the user's, not HLTB's, so it must not 503 the edit."""
|
|
handler = _handler()
|
|
client = MagicMock()
|
|
client.get = AsyncMock(return_value=_response(status.HTTP_404_NOT_FOUND))
|
|
mock_ctx_httpx_client.get.return_value = client
|
|
|
|
rom = await handler.get_rom_by_id(999999999)
|
|
|
|
assert rom["hltb_id"] is None
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_game_page_outage_reports_service_unavailable(mock_ctx_httpx_client):
|
|
handler = _handler()
|
|
client = MagicMock()
|
|
client.get = AsyncMock(
|
|
return_value=_response(status.HTTP_429_TOO_MANY_REQUESTS),
|
|
)
|
|
mock_ctx_httpx_client.get.return_value = client
|
|
|
|
with pytest.raises(HTTPException) as exc_info:
|
|
await handler.get_rom_by_id(7169)
|
|
|
|
assert exc_info.value.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
|
|
assert "rate limiting" in exc_info.value.detail
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_game_page_without_a_record_yields_no_match(mock_ctx_httpx_client):
|
|
"""An empty record list is HLTB answering honestly, not a rewrite."""
|
|
handler = _handler()
|
|
client = MagicMock()
|
|
client.get = AsyncMock(return_value=_game_page(None))
|
|
mock_ctx_httpx_client.get.return_value = client
|
|
|
|
rom = await handler.get_rom_by_id(7169)
|
|
|
|
assert rom["hltb_id"] is None
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_reshaped_game_page_reports_the_rewrite(mock_ctx_httpx_client):
|
|
"""A page RomM can no longer read has to say so: reported as a game with no
|
|
times it is indistinguishable from the bug this lookup exists to fix."""
|
|
handler = _handler()
|
|
response = MagicMock()
|
|
response.status_code = 200
|
|
response.text = "<html><body>no hydration payload here</body></html>"
|
|
client = MagicMock()
|
|
client.get = AsyncMock(return_value=response)
|
|
mock_ctx_httpx_client.get.return_value = client
|
|
|
|
with pytest.raises(HTTPException) as exc_info:
|
|
await handler.get_rom_by_id(7169)
|
|
|
|
assert exc_info.value.status_code == status.HTTP_502_BAD_GATEWAY
|
|
assert "changed their game page" in exc_info.value.detail
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_renamed_game_fields_report_the_rewrite(mock_ctx_httpx_client):
|
|
"""Defaulting every field would quietly turn a rename into an empty match."""
|
|
handler = _handler()
|
|
client = MagicMock()
|
|
client.get = AsyncMock(return_value=_game_page({"id": 7169, "name": "Pokémon"}))
|
|
mock_ctx_httpx_client.get.return_value = client
|
|
|
|
with pytest.raises(HTTPException) as exc_info:
|
|
await handler.get_rom_by_id(7169)
|
|
|
|
assert exc_info.value.status_code == status.HTTP_502_BAD_GATEWAY
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", False)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_get_rom_by_id_is_skipped_when_hltb_is_disabled(mock_ctx_httpx_client):
|
|
rom = await _handler().get_rom_by_id(7169)
|
|
|
|
assert rom["hltb_id"] is None
|
|
mock_ctx_httpx_client.get.assert_not_called()
|
|
|
|
|
|
async def test_the_live_page_shape_still_parses():
|
|
"""Captured from howlongtobeat.com/game/7169. If HLTB reshapes the page this
|
|
fixture goes stale, but it keeps our own parsing honest in the meantime."""
|
|
fixture = Path(__file__).parent / "hltb_game_page_example.json"
|
|
payload = json.loads(fixture.read_text(encoding="utf-8"))
|
|
|
|
response = MagicMock()
|
|
response.status_code = 200
|
|
response.text = (
|
|
'<script id="__NEXT_DATA__" type="application/json">'
|
|
f"{json.dumps(payload)}</script>"
|
|
)
|
|
client = MagicMock()
|
|
client.get = AsyncMock(return_value=response)
|
|
|
|
with (
|
|
patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True),
|
|
patch("handler.metadata.hltb_handler.ctx_httpx_client") as ctx,
|
|
):
|
|
ctx.get.return_value = client
|
|
rom = await _handler().get_rom_by_id(7169)
|
|
|
|
assert rom["hltb_id"] == 7169
|
|
assert rom["name"] == "Pokémon Red and Blue"
|
|
assert rom["url_cover"].endswith("7169_Pokmon_Red_and_Blue.png")
|
|
assert rom["hltb_metadata"] == {
|
|
"main_story": 92822,
|
|
"main_story_count": 594,
|
|
"main_plus_extra": 156016,
|
|
"main_plus_extra_count": 378,
|
|
"completionist": 354756,
|
|
"completionist_count": 202,
|
|
"all_styles": 139926,
|
|
"all_styles_count": 1174,
|
|
"release_year": 1996,
|
|
"review_score": 81,
|
|
"review_count": 1762,
|
|
"completions": 5364,
|
|
}
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"transport_error",
|
|
[
|
|
httpx2.ConnectTimeout("timed out"),
|
|
httpx2.PoolTimeout("pool exhausted"),
|
|
httpx2.ReadError("reset"),
|
|
httpx2.RemoteProtocolError("bad framing"),
|
|
],
|
|
)
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_transport_failures_report_service_unavailable(
|
|
mock_ctx_httpx_client, transport_error
|
|
):
|
|
"""A slow or unreachable HLTB must not surface as a bare 500 on the rom edit."""
|
|
handler = _handler()
|
|
client = MagicMock()
|
|
client.get = AsyncMock(side_effect=transport_error)
|
|
mock_ctx_httpx_client.get.return_value = client
|
|
|
|
with pytest.raises(HTTPException) as exc_info:
|
|
await handler.get_rom_by_id(7169)
|
|
|
|
assert exc_info.value.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
|
|
assert "check your internet connection" in exc_info.value.detail
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("label", "attributes"),
|
|
[
|
|
("plain", 'id="__NEXT_DATA__" type="application/json"'),
|
|
("csp nonce", 'id="__NEXT_DATA__" type="application/json" nonce="r4nd0m"'),
|
|
("reordered", 'type="application/json" id="__NEXT_DATA__"'),
|
|
("single quotes", "id='__NEXT_DATA__' type='application/json'"),
|
|
("crossorigin", 'crossorigin="" id="__NEXT_DATA__" type="application/json"'),
|
|
],
|
|
)
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_hydration_tag_is_found_however_it_is_marked_up(
|
|
mock_ctx_httpx_client, label, attributes
|
|
):
|
|
"""Markup around the payload is not the contract; the id is. Reporting a
|
|
rewrite over an added nonce would be a false alarm."""
|
|
payload = json.dumps(
|
|
{"props": {"pageProps": {"game": {"data": {"game": [_game(7169, "Pokémon")]}}}}}
|
|
)
|
|
response = MagicMock()
|
|
response.status_code = 200
|
|
response.text = f"<script {attributes}>{payload}</script>"
|
|
client = MagicMock()
|
|
client.get = AsyncMock(return_value=response)
|
|
mock_ctx_httpx_client.get.return_value = client
|
|
|
|
rom = await _handler().get_rom_by_id(7169)
|
|
|
|
assert rom["hltb_id"] == 7169, label
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_a_redirect_is_followed_rather_than_read_as_a_rewrite(
|
|
mock_ctx_httpx_client,
|
|
):
|
|
"""`raise_for_status` lets a 3xx through, so an unfollowed hop would reach
|
|
the parser as a page with no payload and be blamed on HLTB reshaping it."""
|
|
handler = _handler()
|
|
client = MagicMock()
|
|
client.get = AsyncMock(return_value=_game_page(_game(7169, "Pokémon")))
|
|
mock_ctx_httpx_client.get.return_value = client
|
|
|
|
await handler.get_rom_by_id(7169)
|
|
|
|
assert client.get.await_args.kwargs["follow_redirects"] is True
|
|
|
|
|
|
@patch("handler.metadata.hltb_handler.HLTB_API_ENABLED", True)
|
|
@patch("handler.metadata.hltb_handler.ctx_httpx_client")
|
|
async def test_an_unrelated_json_script_is_not_mistaken_for_the_payload(
|
|
mock_ctx_httpx_client,
|
|
):
|
|
"""The looser tag match must not start picking up other JSON blocks."""
|
|
handler = _handler()
|
|
response = MagicMock()
|
|
response.status_code = 200
|
|
response.text = (
|
|
'<script id="__OTHER_DATA__" type="application/json">{"game": []}</script>'
|
|
)
|
|
client = MagicMock()
|
|
client.get = AsyncMock(return_value=response)
|
|
mock_ctx_httpx_client.get.return_value = client
|
|
|
|
with pytest.raises(HTTPException) as exc_info:
|
|
await handler.get_rom_by_id(7169)
|
|
|
|
assert exc_info.value.status_code == status.HTTP_502_BAD_GATEWAY
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_search_games_propagates_an_unreachable_hltb():
|
|
"""A failed search has to stay distinguishable from a term with no hits."""
|
|
handler = _handler()
|
|
|
|
with (
|
|
patch.object(
|
|
handler,
|
|
"_request",
|
|
new_callable=AsyncMock,
|
|
side_effect=HTTPException(status_code=503, detail="down"),
|
|
),
|
|
pytest.raises(HTTPException),
|
|
):
|
|
await handler.search_games("Chrono Trigger", "snes")
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("platform_slug", "values"),
|
|
[
|
|
("psp", ["PlayStation Portable"]),
|
|
# HowLongToBeat lists PlayStation VR games under PlayStation 4.
|
|
("psvr", ["PlayStation 4"]),
|
|
("vic-20", ["Commodore VIC-20"]),
|
|
# HowLongToBeat has no Plus/4, so it isn't searched as another computer.
|
|
("c-plus-4", []),
|
|
("not-a-platform", []),
|
|
],
|
|
)
|
|
async def test_search_games_filters_by_the_roms_platform(platform_slug, values):
|
|
"""HowLongToBeat ignores a platform sent as a bare name, so "gran turismo"
|
|
for the PSP came back with the PlayStation game first."""
|
|
handler = _handler()
|
|
|
|
with patch.object(
|
|
handler, "_request", new_callable=AsyncMock, return_value={"data": []}
|
|
) as request:
|
|
await handler.search_games("gran turismo", platform_slug)
|
|
|
|
await_args = request.await_args
|
|
assert await_args is not None
|
|
payload = await_args.args[1]
|
|
assert payload["searchOptions"]["games"]["platform"] == {
|
|
"mode": "include",
|
|
"values": values,
|
|
}
|