feat(huya): 统一实时商品目录并增加兑换代理开关

This commit is contained in:
yml
2026-11-13 20:12:42 +08:00
parent 563b32b7b7
commit ad782e1954
23 changed files with 930 additions and 511 deletions
+27 -92
View File
@@ -42,6 +42,7 @@ from web.backend.schemas import (
HuyaExternalOrderUpdate,
)
from web.backend.services import huya_collab_service as collab
from web.backend.services import huya_points_center as points_center
from web.backend.services.huya_collab_events import collab_events
@@ -840,32 +841,6 @@ class FakeBindResp:
}
class FakeGiftResp:
"""合成一份 ``getActPrizeList`` 响应(礼包列表)。"""
def __init__(self, *, status: int = 200, msg: str = "", goods: list | None = None):
self.status = status
self.msg = msg
self._goods = (
goods
if goods is not None
else [
{
"product_id": "hy-1001",
"name": "不朽伊人大礼包",
"price": 200,
"remain_text": "39%",
"category_name": "礼包",
},
{"product_id": "", "name": "缺 product_id 的脏数据"},
{"product_id": "hy-1002", "name": ""},
]
)
def to_dict(self) -> dict:
return {"status": self.status, "msg": self.msg, "goods": self._goods}
def points_center_blob(
*,
name: str = "不朽伊人大礼包",
@@ -968,18 +943,15 @@ class FakeProbeClient:
def __init__(
self,
*outcomes,
gifts: list | None = None,
points_gifts: list | None = None,
profile_nick: str | None = None,
profile_outcome: object | None = None,
):
self.outcomes = list(outcomes)
self.gift_outcomes = list(gifts or [])
self.point_outcomes = list(points_gifts or [])
self.profile_nick = profile_nick
self.profile_outcome = profile_outcome
self.calls: list[dict] = []
self.gift_calls: list[dict] = []
self.points_calls: list[dict] = []
self.profile_calls: list[dict] = []
self._current_bind_outcome: object | None = None
@@ -1001,13 +973,6 @@ class FakeProbeClient:
raise outcome
return outcome
def get_act_prize_list(self, **kwargs):
self.gift_calls.append(kwargs)
outcome = self.gift_outcomes.pop(0) if self.gift_outcomes else FakeGiftResp()
if isinstance(outcome, Exception):
raise outcome
return outcome
def play_mall_query_allocation(self, **kwargs):
self.points_calls.append(kwargs)
outcome = (
@@ -1492,7 +1457,6 @@ class TestCollabCkPreview(TestCollabBase):
assert "已拉取 1 个礼包(积分中心)" in preview["gifts_message"]
assert client.points_calls[0]["uid"] == 1199647239697
assert client.points_calls[0]["deep"] is True
assert client.gift_calls == []
def test_preview_of_invalid_ck_does_not_fetch_gifts(self):
client = FakeProbeClient(None)
@@ -1531,50 +1495,14 @@ class TestCollabCkPreview(TestCollabBase):
class TestCollabGifts(TestCollabBase):
def test_gift_fetch_skips_dirty_rows(self):
gifts, message = collab.fetch_activity_gifts(
1199647239697, fake_ck("1199647239697"), client=FakeProbeClient()
)
assert [gift["name"] for gift in gifts] == ["不朽伊人大礼包"]
assert message == "已拉取 1 个礼包"
def test_gift_fetch_reports_failure_without_raising(self):
gifts, message = collab.fetch_activity_gifts(
1199647239697,
fake_ck("1199647239697"),
client=FakeProbeClient(gifts=[FakeGiftResp(status=500, msg="活动已结束")]),
)
assert gifts == []
assert "拉取礼包失败" in message and "500" in message
def test_gift_fetch_survives_exception(self):
gifts, message = collab.fetch_activity_gifts(
1199647239697,
fake_ck("1199647239697"),
client=FakeProbeClient(gifts=[RuntimeError("boom")]),
)
assert gifts == []
assert "RuntimeError" in message
def test_gift_fetch_empty_list_hints_stale_sid(self):
"""200 但 0 个商品 = SID 不是当前活动(真机 2026-10-16:2203 → 0,2277 → 30)。"""
gifts, message = collab.fetch_activity_gifts(
1199647239697,
fake_ck("1199647239697"),
sid=2203,
client=FakeProbeClient(gifts=[FakeGiftResp(goods=[])]),
)
assert gifts == []
assert "SID=2203" in message and "工作台" in message
def test_points_center_gift_fetch_parses_fields(self):
gifts, message = collab.fetch_points_center_gifts(
catalog = points_center.fetch_points_center_catalog(
1199647239697,
fake_ck("1199647239697"),
client=FakeProbeClient(),
)
assert gifts == [
assert catalog.goods == [
{
"product_id": "hy-1001",
"name": "不朽伊人大礼包",
@@ -1587,7 +1515,7 @@ class TestCollabGifts(TestCollabBase):
"icon": "",
}
]
assert message == "已拉取 1 个礼包(积分中心)"
assert catalog.message == "已拉取 1 个礼包(积分中心)"
def test_points_center_gift_fetch_loads_all_discovered_tabs(self):
"""基础响应只给第一个页签;其余页签按 pageId + tabId 自动补拉。"""
@@ -1626,7 +1554,7 @@ class TestCollabGifts(TestCollabBase):
]
)
gifts, message = collab.fetch_points_center_gifts(
catalog = points_center.fetch_points_center_catalog(
1199647239697,
fake_ck("1199647239697"),
client=client,
@@ -1635,14 +1563,17 @@ class TestCollabGifts(TestCollabBase):
scene=8,
)
assert [gift["name"] for gift in gifts] == ["基础礼包", "套装-甜橙豚豚"]
assert [gift["name"] for gift in catalog.goods] == [
"基础礼包",
"套装-甜橙豚豚",
]
assert client.points_calls[0]["page_code"] == "custom_page"
assert client.points_calls[0]["source_id"] == "custom_source"
assert client.points_calls[0]["scene"] == 8
assert "waterfall_tab_id" not in client.points_calls[0]
assert client.points_calls[1]["page_id"] == 343
assert client.points_calls[1]["waterfall_tab_id"] == 433
assert "2 个页签" in message
assert "2 个页签" in catalog.message
def test_points_center_tab_override_uses_configured_ids(self):
base_payload = {
@@ -1670,7 +1601,7 @@ class TestCollabGifts(TestCollabBase):
]
)
gifts, message = collab.fetch_points_center_gifts(
catalog = points_center.fetch_points_center_catalog(
1199647239697,
fake_ck("1199647239697"),
client=client,
@@ -1678,39 +1609,42 @@ class TestCollabGifts(TestCollabBase):
tab_ids=[999],
)
assert [gift["name"] for gift in gifts] == ["基础礼包", "手工页签礼包"]
assert [gift["name"] for gift in catalog.goods] == [
"基础礼包",
"手工页签礼包",
]
assert client.points_calls[1]["page_id"] == 343
assert client.points_calls[1]["waterfall_tab_id"] == 999
assert "2 个页签" in message
assert "2 个页签" in catalog.message
def test_points_center_gift_fetch_reports_failure(self):
gifts, message = collab.fetch_points_center_gifts(
catalog = points_center.fetch_points_center_catalog(
1199647239697,
fake_ck("1199647239697"),
client=FakeProbeClient(
points_gifts=[FakePointsCenterResp(code=500, message="接口炸了")]
),
)
assert gifts == []
assert "拉取礼包失败" in message and "500" in message
assert catalog.goods == []
assert "拉取商品失败" in catalog.message and "500" in catalog.message
def test_points_center_gift_fetch_survives_exception(self):
gifts, message = collab.fetch_points_center_gifts(
catalog = points_center.fetch_points_center_catalog(
1199647239697,
fake_ck("1199647239697"),
client=FakeProbeClient(points_gifts=[RuntimeError("boom")]),
)
assert gifts == []
assert "RuntimeError" in message
assert catalog.goods == []
assert "RuntimeError" in catalog.message
def test_points_center_gift_fetch_empty_list(self):
gifts, message = collab.fetch_points_center_gifts(
catalog = points_center.fetch_points_center_catalog(
1199647239697,
fake_ck("1199647239697"),
client=FakeProbeClient(points_gifts=[FakePointsCenterResp(goods=[])]),
)
assert gifts == []
assert "积分中心" in message and "空的" in message
assert catalog.goods == []
assert "积分中心" in catalog.message and "空的" in catalog.message
def test_points_center_parser_reads_tag75_points(self):
from core.huya.shop_structs import parse_points_center_gifts
@@ -1771,7 +1705,7 @@ class TestCollabGifts(TestCollabBase):
)
self.db.commit()
assert collab.resolve_points_center_config(self.db) == {
assert points_center.resolve_points_center_config(self.db) == {
"page_code": "custom_page",
"source_id": "custom_source",
"scene": 8,
@@ -1793,6 +1727,7 @@ class TestCollabGifts(TestCollabBase):
assert dumped["points_scene"] == "8"
assert dumped["points_page_id"] == "343"
assert dumped["points_tab_ids"] == "431,433"
assert dumped["exchange_use_proxy"] == "0"
def test_preview_ignores_legacy_sid_and_uses_points_center(self):
self.db.add(HuyaConfig(sid="2277"))
+79 -3
View File
@@ -9,6 +9,7 @@ from unittest.mock import Mock
from core.huya.http_client import HuyaHttpClient
from web.backend.models import HuyaAccount, ProxyConfig
from web.backend.services import huya_points_exchange as exchange
from web.backend.services import huya_runner_goods
from web.backend.services.huya_runner import HuyaBatchRunner
@@ -76,6 +77,24 @@ def _direct_client():
return client
def _mock_live_goods(monkeypatch):
monkeypatch.setattr(
huya_runner_goods,
"fetch_points_center_catalog",
lambda *_args, **_kwargs: SimpleNamespace(
goods=[
{
"product_id": "hy-8315982",
"name": "gift",
"price": 20,
"remain_text": "100",
}
],
message="已拉取 1 个礼包",
),
)
def test_non_exchange_task_does_not_read_proxy_config():
db = Mock()
runner = HuyaBatchRunner(
@@ -98,6 +117,7 @@ def test_static_proxy_is_used_for_entire_exchange_task(monkeypatch):
)
)
client = _direct_client()
_mock_live_goods(monkeypatch)
calls = []
marks = []
@@ -119,7 +139,11 @@ def test_static_proxy_is_used_for_entire_exchange_task(monkeypatch):
SimpleNamespace(id=1),
HuyaAccount(uid="100", cookie="yyuid=100"),
{"uid": 100, "cookie": "yyuid=100"},
{"room_pid": "123", "pay_channel": "Zfb"},
{
"room_pid": "123",
"pay_channel": "Zfb",
"exchange_use_proxy": "1",
},
)
assert calls == [
@@ -141,6 +165,7 @@ def test_api_proxy_is_fetched_once_per_exchange_task(monkeypatch):
fetcher.fetch_new_proxy.return_value = "http://10.0.0.2:3128"
runner._proxy_fetcher = fetcher
client = _direct_client()
_mock_live_goods(monkeypatch)
calls = []
marks = []
@@ -162,7 +187,11 @@ def test_api_proxy_is_fetched_once_per_exchange_task(monkeypatch):
SimpleNamespace(id=2),
HuyaAccount(uid="100", cookie="yyuid=100"),
{"uid": 100, "cookie": "yyuid=100"},
{"room_pid": "123", "pay_channel": "Zfb"},
{
"room_pid": "123",
"pay_channel": "Zfb",
"exchange_use_proxy": "1",
},
)
fetcher.fetch_new_proxy.assert_called_once_with(max_attempts=3)
@@ -197,7 +226,7 @@ def test_enabled_proxy_without_source_fails_exchange_before_request(monkeypatch)
SimpleNamespace(id=3),
HuyaAccount(uid="100", cookie="yyuid=100"),
{"uid": 100, "cookie": "yyuid=100"},
{"room_pid": "123"},
{"room_pid": "123", "exchange_use_proxy": "1"},
)
assert marks == [
@@ -209,6 +238,53 @@ def test_enabled_proxy_without_source_fails_exchange_before_request(monkeypatch)
]
def test_exchange_proxy_switch_defaults_to_direct_connection(monkeypatch):
runner = _runner(
_cfg(
enabled=True,
http="http://10.0.0.1:8080",
https="http://10.0.0.1:8080",
)
)
client = _direct_client()
_mock_live_goods(monkeypatch)
calls = []
marks = []
monkeypatch.setattr(
runner,
"_http_client",
lambda **kwargs: calls.append(kwargs) or client,
)
monkeypatch.setattr(
runner,
"_exchange_proxies",
lambda: (_ for _ in ()).throw(
AssertionError("proxy switch is off; proxy config must not be read")
),
)
monkeypatch.setattr(
runner,
"_mark_task",
lambda _db, _task, status, message, result=None: marks.append(
(status, message, result)
),
)
runner._execute_exchange_goods(
None,
SimpleNamespace(id=4),
HuyaAccount(uid="100", cookie="yyuid=100"),
{"uid": 100, "cookie": "yyuid=100"},
{"room_pid": "123", "pay_channel": "Zfb"},
)
assert calls == [{"proxies": None}]
assert marks[-1][0] == "success"
assert marks[-1][2]["proxy_used"] is False
assert marks[-1][2]["proxy_source"] == "disabled"
def test_huya_http_client_routes_methods_through_configured_opener(monkeypatch):
opener = Mock()
opener.open.return_value = SimpleNamespace()
+143
View File
@@ -0,0 +1,143 @@
"""Huya live goods selection and stale snapshot protection tests."""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
from web.backend.models import HuyaAccount, HuyaGoodsSnapshot, User
from web.backend.routers.huya import list_goods, list_live_goods
from web.backend.services import huya_points_exchange as exchange
from web.backend.services import huya_runner_goods
from web.backend.services.huya_runner import HuyaBatchRunner
def _seed_account(db) -> tuple[User, HuyaAccount]:
user = User(username="operator", password_hash="hash", role="super_admin")
account = HuyaAccount(
uid="1199669301102",
yyuid="1199669301102",
nickname="小银紫资源",
cookie="yyuid=1199669301102; udb_uid=1199669301102",
)
db.add_all([user, account])
db.commit()
return user, account
def test_live_goods_endpoint_returns_current_spu(db, monkeypatch):
user, account = _seed_account(db)
monkeypatch.setattr(
"web.backend.routers.huya.workbench.fetch_points_center_catalog",
lambda *_args, **_kwargs: SimpleNamespace(
goods=[
{
"product_id": "hy-9391246",
"name": "小狗蛇点点大礼包",
"price": 3960,
"remain_text": "2703",
}
],
message="已拉取 1 个礼包",
sid=2277,
),
)
rows = list_live_goods(account_id=account.id, db=db, current=user)
assert [row.product_id for row in rows] == ["hy-9391246"]
assert rows[0].raw["product_id"] == "hy-9391246"
def test_list_goods_ignores_legacy_numeric_prize_ids(db):
user, account = _seed_account(db)
now = datetime.now(UTC)
db.add_all(
[
HuyaGoodsSnapshot(
account_id=account.id,
sid=2277,
product_id="13649",
name="小狗蛇点点大礼包",
updated_at=now,
),
HuyaGoodsSnapshot(
account_id=account.id,
sid=2277,
product_id="hy-9391246",
name="小狗蛇点点大礼包",
updated_at=now - timedelta(minutes=1),
),
]
)
db.commit()
rows = list_goods(db=db, current=user)
assert [row.product_id for row in rows] == ["hy-9391246"]
def test_exchange_resolves_stale_prize_id_to_current_live_spu(monkeypatch):
runner = HuyaBatchRunner(
db=None,
batch_id="live-goods-repair",
task_type="exchange_goods",
payload={
"product_id": "hy-13649",
"product_name": "小狗蛇点点大礼包",
},
)
client = SimpleNamespace()
marks = []
prepared_args = {}
monkeypatch.setattr(runner, "_http_client", lambda **_kwargs: client)
monkeypatch.setattr(
huya_runner_goods,
"fetch_points_center_catalog",
lambda *_args, **_kwargs: SimpleNamespace(
goods=[
{
"product_id": "hy-9391246",
"name": "小狗蛇点点大礼包",
"price": 3960,
"remain_text": "2703",
}
],
message="已拉取 1 个礼包",
),
)
def fake_prepare(_client, **kwargs):
prepared_args.update(kwargs)
return exchange.PointsExchangeOutcome(
exchange.EXCHANGE_STATUS_EXCHANGED,
"兑换成功",
target={"name": "小狗蛇点点大礼包"},
order={"order_id": 101},
)
monkeypatch.setattr(huya_runner_goods, "prepare_exchange", fake_prepare)
monkeypatch.setattr(
runner,
"_mark_task",
lambda _db, _task, status, message, result=None: marks.append(
(status, message, result)
),
)
runner._execute_exchange_goods(
None,
SimpleNamespace(id=1),
HuyaAccount(uid="1199669301102", cookie="yyuid=1199669301102"),
{
"uid": 1199669301102,
"cookie": "yyuid=1199669301102",
},
{"room_pid": "1199650619883", "pay_channel": "Zfb"},
)
assert prepared_args["spu_id"] == "hy-9391246"
assert marks[-1][0] == "success"
assert marks[-1][2]["submitted_product_id"] == "hy-13649"
assert marks[-1][2]["resolved_product_id"] == "hy-9391246"
+31 -7
View File
@@ -6,6 +6,7 @@ from types import SimpleNamespace
from web.backend.models import HuyaAccount
from web.backend.services import huya_points_exchange as exchange
from web.backend.services import huya_runner_goods
from web.backend.services.huya_runner import HuyaBatchRunner
from web.backend.services.huya_shop_flow import ShopOrderOutcome
@@ -79,6 +80,29 @@ def _state(*, full: bool, precondition: bool = True, plans=None):
)
def _mock_live_goods(
monkeypatch,
*,
product_id: str = "hy-8315982",
name: str = "幸运币礼包(小)",
):
monkeypatch.setattr(
huya_runner_goods,
"fetch_points_center_catalog",
lambda *_args, **_kwargs: SimpleNamespace(
goods=[
{
"product_id": product_id,
"name": name,
"price": 20,
"remain_text": "100",
}
],
message="已拉取 1 个礼包",
),
)
def test_points_enough_uses_create_order_v6_without_payment(monkeypatch):
client = _Client([_state(full=True)])
purchase_called = False
@@ -209,6 +233,7 @@ def test_precondition_failure_does_not_create_order():
def test_runner_uses_points_exchange_service_for_direct_redeem(monkeypatch):
client = _Client([_state(full=True)])
_mock_live_goods(monkeypatch)
runner = HuyaBatchRunner(
db=None,
batch_id="exchange-direct",
@@ -261,6 +286,7 @@ def test_runner_waits_points_payment_then_redeems(monkeypatch):
_state(full=True),
]
)
_mock_live_goods(monkeypatch)
runner = HuyaBatchRunner(
db=None,
batch_id="exchange-pay",
@@ -325,8 +351,6 @@ def test_runner_waits_points_payment_then_redeems(monkeypatch):
def test_runner_refresh_goods_uses_points_center_query(monkeypatch):
from web.backend.services import huya_collab_service
runner = HuyaBatchRunner(
db=None,
batch_id="refresh-points-goods",
@@ -351,12 +375,12 @@ def test_runner_refresh_goods_uses_points_center_query(monkeypatch):
added.append(item)
monkeypatch.setattr(
huya_collab_service,
"fetch_points_center_gifts",
huya_runner_goods,
"fetch_points_center_catalog",
lambda uid, cookie, **kwargs: (
calls.append((uid, cookie, kwargs))
or (
[
or SimpleNamespace(
goods=[
{
"product_id": "hy-8315982",
"name": "幸运币礼包(小)",
@@ -365,7 +389,7 @@ def test_runner_refresh_goods_uses_points_center_query(monkeypatch):
"stock": 11197,
}
],
"已拉取 1 个礼包",
message="已拉取 1 个礼包",
)
),
)