feat(douyu): 完成账号平台阶段一到四并接入最新协议
This commit is contained in:
@@ -13,7 +13,15 @@ from unittest.mock import Mock
|
||||
import pytest
|
||||
|
||||
from tests.support.db import get_test_engine, make_test_session
|
||||
from web.backend.models import Account, AccountEvent, DouyuTask, User
|
||||
from web.backend.models import (
|
||||
Account,
|
||||
AccountCommodityState,
|
||||
AccountEvent,
|
||||
AccountSyncState,
|
||||
AccountWorkItem,
|
||||
DouyuTask,
|
||||
User,
|
||||
)
|
||||
from web.backend.services.douyu_runner_overview import (
|
||||
DEFAULT_HIGH_VALUE_GOODS,
|
||||
OverviewMixin,
|
||||
@@ -423,6 +431,176 @@ class TestOverviewAggregation:
|
||||
self.session.refresh(self.account)
|
||||
assert self.account.status == status_before
|
||||
|
||||
def test_reuses_fresh_overview_without_calling_official_helpers(
|
||||
self,
|
||||
monkeypatch,
|
||||
):
|
||||
monkeypatch.setenv("DOUYU_OVERVIEW_CACHE_SECONDS", "600")
|
||||
self.account.overview_snapshot = {
|
||||
"queried_at": datetime.now(UTC).isoformat(),
|
||||
"assets": {"gold_balance": 7},
|
||||
"high_value_goods": [
|
||||
{"name": "套装-兔兔白日梦", "owned": True, "missing": False}
|
||||
],
|
||||
}
|
||||
self.account.overview_queried_at = datetime.now(UTC)
|
||||
self.session.commit()
|
||||
probe = _Harness(_FakeClient())
|
||||
assert probe._cached_overview(
|
||||
self.account,
|
||||
self.task,
|
||||
now=datetime.now(UTC),
|
||||
) is not None
|
||||
|
||||
h = self._run(client=object())
|
||||
result = h.marked["result"]
|
||||
|
||||
assert h.marked["status"] == "success"
|
||||
assert result["cache_hit"] is True
|
||||
assert result["assets"]["gold_balance"] == 7
|
||||
assert "兔兔白日梦" in h.marked["message"]
|
||||
|
||||
def test_stale_storehome_projection_is_queued_without_official_query(self):
|
||||
now = datetime.now(UTC)
|
||||
self.account.overview_queried_at = now - timedelta(hours=1)
|
||||
self.account.overview_snapshot = {
|
||||
"queried_at": self.account.overview_queried_at.isoformat(),
|
||||
"high_value_goods": [],
|
||||
}
|
||||
self.session.add_all(
|
||||
[
|
||||
AccountSyncState(
|
||||
account_id=self.account.id,
|
||||
platform="douyu",
|
||||
domain="storehome",
|
||||
status="success",
|
||||
last_success_at=now - timedelta(hours=1),
|
||||
valid_until=now - timedelta(minutes=1),
|
||||
),
|
||||
AccountCommodityState(
|
||||
account_id=self.account.id,
|
||||
platform="douyu",
|
||||
scope="elite",
|
||||
commodity_id=RABBIT_ID,
|
||||
commodity_name="套装-兔兔白日梦",
|
||||
availability="available",
|
||||
observed_at=now - timedelta(hours=1),
|
||||
valid_until=now - timedelta(minutes=1),
|
||||
raw_json=GOODS_AVAILABLE,
|
||||
),
|
||||
]
|
||||
)
|
||||
self.session.commit()
|
||||
seen: list[str] = []
|
||||
|
||||
class _Client(_FakeClient):
|
||||
def list_goods(self, *, manual_id, rid):
|
||||
seen.append(manual_id)
|
||||
return super().list_goods(manual_id=manual_id, rid=rid)
|
||||
|
||||
result = self._run(client=_Client()).marked["result"]
|
||||
work = self.session.query(AccountWorkItem).one()
|
||||
|
||||
assert seen == []
|
||||
assert result["pending_domains"] == ["storehome"]
|
||||
assert result["goods_source"] == "local_stale_projection"
|
||||
assert result["limited_goods_total"] == 1
|
||||
assert work.work_type == "storehome_sync"
|
||||
assert work.account_id == self.account.id
|
||||
|
||||
def test_fresh_storehome_projection_skips_official_query(self):
|
||||
now = datetime.now(UTC)
|
||||
self.session.add_all(
|
||||
[
|
||||
AccountSyncState(
|
||||
account_id=self.account.id,
|
||||
platform="douyu",
|
||||
domain="storehome",
|
||||
status="success",
|
||||
last_success_at=now,
|
||||
valid_until=now + timedelta(minutes=10),
|
||||
),
|
||||
AccountCommodityState(
|
||||
account_id=self.account.id,
|
||||
platform="douyu",
|
||||
scope="elite",
|
||||
commodity_id=RABBIT_ID,
|
||||
commodity_name="套装-兔兔白日梦",
|
||||
availability="available",
|
||||
observed_at=now,
|
||||
valid_until=now + timedelta(minutes=10),
|
||||
raw_json=GOODS_AVAILABLE,
|
||||
),
|
||||
]
|
||||
)
|
||||
self.session.commit()
|
||||
seen: list[str] = []
|
||||
|
||||
class _Client(_FakeClient):
|
||||
def list_goods(self, *, manual_id, rid):
|
||||
seen.append(manual_id)
|
||||
return super().list_goods(manual_id=manual_id, rid=rid)
|
||||
|
||||
result = self._run(client=_Client()).marked["result"]
|
||||
|
||||
assert seen == []
|
||||
assert result["goods_source"] == "local_fresh_projection"
|
||||
assert result["pending_domains"] == []
|
||||
assert result["limited_goods_total"] == 1
|
||||
assert self.session.query(AccountWorkItem).count() == 0
|
||||
|
||||
def test_stale_esports_and_exchange_records_use_local_projection_and_queue(self):
|
||||
now = datetime.now(UTC)
|
||||
self.account.esports_opened = True
|
||||
self.account.esports_points = 88
|
||||
self.account.esports_expire_time = 1795967999
|
||||
self.session.add_all(
|
||||
[
|
||||
AccountSyncState(
|
||||
account_id=self.account.id,
|
||||
platform="douyu",
|
||||
domain="esports",
|
||||
status="success",
|
||||
last_success_at=now - timedelta(hours=1),
|
||||
valid_until=now - timedelta(minutes=1),
|
||||
raw_payload_json={"manual_type": 2, "manual_score": 88},
|
||||
),
|
||||
AccountSyncState(
|
||||
account_id=self.account.id,
|
||||
platform="douyu",
|
||||
domain="exchange_records",
|
||||
status="success",
|
||||
last_success_at=now - timedelta(hours=1),
|
||||
valid_until=now - timedelta(minutes=1),
|
||||
raw_payload_json={
|
||||
"elite": [
|
||||
{
|
||||
"commodityId": "cached-item",
|
||||
"commodityName": "缓存套装",
|
||||
}
|
||||
]
|
||||
},
|
||||
),
|
||||
]
|
||||
)
|
||||
self.session.commit()
|
||||
|
||||
result = self._run().marked["result"]
|
||||
work_types = {
|
||||
row.work_type
|
||||
for row in self.session.query(AccountWorkItem)
|
||||
.filter_by(account_id=self.account.id)
|
||||
.all()
|
||||
}
|
||||
|
||||
assert result["domain_sources"]["esports"] == "queued_stale"
|
||||
assert result["domain_sources"]["exchange_records"] == "queued_stale"
|
||||
assert result["esports"]["opened"] is True
|
||||
assert result["esports"]["points"] == 88
|
||||
assert result["exchange_records"]["elite"][0]["commodityId"] == "cached-item"
|
||||
assert {"esports", "exchange_records"}.issubset(result["pending_domains"])
|
||||
assert work_types == {"esports_sync", "exchange_records_sync"}
|
||||
|
||||
|
||||
class TestOverviewTaskTypeWiring:
|
||||
def test_declared_for_all_workbenches(self):
|
||||
|
||||
@@ -8,11 +8,14 @@ from tests.support.db import make_test_session
|
||||
from web.backend.models import (
|
||||
Account,
|
||||
AccountCommodityState,
|
||||
AccountEvent,
|
||||
AccountSyncState,
|
||||
AccountWorkItem,
|
||||
DouyuConfig,
|
||||
)
|
||||
from web.backend.services.account_sync_runner import (
|
||||
WORK_ESPORTS_SYNC,
|
||||
WORK_EXCHANGE_RECORDS_SYNC,
|
||||
WORK_STOREHOME_SYNC,
|
||||
execute_account_work_item,
|
||||
run_account_sync_queue,
|
||||
@@ -25,11 +28,12 @@ from web.backend.services.account_work_queue import (
|
||||
from web.backend.services.douyu_read_gateway import StorehomeSnapshot
|
||||
|
||||
|
||||
def _config(db) -> None:
|
||||
def _config(db, **overrides) -> None:
|
||||
db.add(
|
||||
DouyuConfig(
|
||||
manual_id="manual",
|
||||
rid="room",
|
||||
**overrides,
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
@@ -161,6 +165,122 @@ def test_work_item_failure_returns_to_pending_for_retry(db):
|
||||
assert work_row.due_at > datetime.now(UTC)
|
||||
|
||||
|
||||
def test_esports_profile_sync_persists_data_without_rewriting_ck(db):
|
||||
_config(db, esports_manual_id="esports-manual")
|
||||
account = _account("sync-esports")
|
||||
db.add(account)
|
||||
db.commit()
|
||||
work = enqueue_account_work(
|
||||
db,
|
||||
account_id=account.id,
|
||||
work_type=WORK_ESPORTS_SYNC,
|
||||
)
|
||||
db.commit()
|
||||
claim_account_work(db, work_types=(WORK_ESPORTS_SYNC,), limit=1)
|
||||
db.commit()
|
||||
seen: dict = {}
|
||||
|
||||
def probe(_account, _config, **kwargs):
|
||||
seen.update(kwargs)
|
||||
return {
|
||||
"probe_id": "work:1",
|
||||
"identity": {"uid": "100", "username": "sync-esports"},
|
||||
# 单项资料同步没有独立执行 CK 探针;即使内部推导出 invalid,
|
||||
# 也不能覆盖账号主表已有的有效 CK。
|
||||
"session": {"status": "invalid", "message": "推导值"},
|
||||
"elite": {},
|
||||
"eligibility": {},
|
||||
"roles": {},
|
||||
"gold": {},
|
||||
"goods": {},
|
||||
"esports": {
|
||||
"status": "ok",
|
||||
"opened": True,
|
||||
"manual_type": 2,
|
||||
"manual_score": 321,
|
||||
"expire_time": 1795967999,
|
||||
},
|
||||
"errors": {},
|
||||
}
|
||||
|
||||
result = execute_account_work_item(
|
||||
work.id,
|
||||
session_factory=make_test_session,
|
||||
client_factory=lambda _cookie: object(),
|
||||
probe_fetcher=probe,
|
||||
)
|
||||
|
||||
with make_test_session() as verify:
|
||||
row = verify.get(Account, account.id)
|
||||
state = (
|
||||
verify.query(AccountSyncState)
|
||||
.filter_by(account_id=account.id, domain="esports")
|
||||
.one()
|
||||
)
|
||||
assert result["ok"] is True
|
||||
assert seen["with_esports"] is True
|
||||
assert seen["with_elite"] is False
|
||||
assert row.ck_check_status == "valid"
|
||||
assert row.esports_opened is True
|
||||
assert row.esports_points == 321
|
||||
assert row.esports_expire_time == 1795967999
|
||||
assert state.status == "success"
|
||||
|
||||
|
||||
def test_exchange_record_work_persists_events_and_raw_projection(db):
|
||||
_config(db, esports_manual_id="esports-manual")
|
||||
account = _account("sync-exchange")
|
||||
db.add(account)
|
||||
db.commit()
|
||||
work = enqueue_account_work(
|
||||
db,
|
||||
account_id=account.id,
|
||||
work_type=WORK_EXCHANGE_RECORDS_SYNC,
|
||||
)
|
||||
db.commit()
|
||||
claim_account_work(db, work_types=(WORK_EXCHANGE_RECORDS_SYNC,), limit=1)
|
||||
db.commit()
|
||||
|
||||
class _Client:
|
||||
def exchange_records(self, *, manual_id, limit, offset=0):
|
||||
return {
|
||||
"records": [
|
||||
{
|
||||
"commodityId": f"{manual_id}-item",
|
||||
"commodityName": "测试套装",
|
||||
"score": "18",
|
||||
"time": "1795967997",
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
result = execute_account_work_item(
|
||||
work.id,
|
||||
session_factory=make_test_session,
|
||||
client_factory=lambda _cookie: _Client(),
|
||||
)
|
||||
|
||||
with make_test_session() as verify:
|
||||
state = (
|
||||
verify.query(AccountSyncState)
|
||||
.filter_by(account_id=account.id, domain="exchange_records")
|
||||
.one()
|
||||
)
|
||||
events = (
|
||||
verify.query(AccountEvent)
|
||||
.filter_by(account_id=account.id, event_type="exchange")
|
||||
.all()
|
||||
)
|
||||
assert result["ok"] is True
|
||||
assert result["item_count"] == 2
|
||||
assert set(state.raw_payload_json) == {"elite", "esports"}
|
||||
assert state.raw_payload_json["elite"][0]["commodityId"] == "manual-item"
|
||||
assert {event.subject_key for event in events} == {
|
||||
"manual-item",
|
||||
"esports-manual-item",
|
||||
}
|
||||
|
||||
|
||||
def test_run_account_sync_queue_claims_and_executes(db):
|
||||
_config(db)
|
||||
account = _account("sync-runner")
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
"""2026-11-21 斗鱼积分/鱼翅最新协议回归。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from core.douyu import DouyuActivityClient
|
||||
from web.backend.services.douyu_activity_query import extract_points_expire_time
|
||||
|
||||
|
||||
def _client(cookie: str = "acf_uid=100; acf_ccn=csrf-cookie") -> DouyuActivityClient:
|
||||
return DouyuActivityClient(cookie)
|
||||
|
||||
|
||||
def test_acf_ccn_reuses_existing_cookie_without_http(monkeypatch):
|
||||
client = _client()
|
||||
|
||||
def fail(*_args, **_kwargs):
|
||||
raise AssertionError("Cookie 已有 acf_ccn 时不应请求补 token")
|
||||
|
||||
monkeypatch.setattr(client, "_request", fail)
|
||||
|
||||
assert client.acf_ccn(refresh_subscribe=False) == "csrf-cookie"
|
||||
|
||||
|
||||
def test_points_uses_latest_multipart_and_returns_expiry(monkeypatch):
|
||||
client = _client()
|
||||
calls: list[tuple[str, str, dict[str, Any]]] = []
|
||||
|
||||
def request_json(method, url, source, **kwargs):
|
||||
calls.append((method, url, kwargs))
|
||||
return {
|
||||
"error": 0,
|
||||
"data": {
|
||||
"userId": 100,
|
||||
"balance": 300,
|
||||
"recentlyWillExpireBalance": 200,
|
||||
"willExpireTime": 1803052799,
|
||||
},
|
||||
}
|
||||
|
||||
monkeypatch.setattr(client, "_request_json", request_json)
|
||||
|
||||
result = client.query_points(uid="100", ctn="csrf-cookie")
|
||||
|
||||
assert calls[0][0:2] == (
|
||||
"post",
|
||||
"https://www.douyu.com/japi/oms/web/peace/credit/balance",
|
||||
)
|
||||
assert calls[0][2]["files"] == {"uid": (None, "100")}
|
||||
assert "json" not in calls[0][2]
|
||||
assert result["points"] == 300
|
||||
assert result["recently_expiring_points"] == 200
|
||||
assert result["will_expire_time"] == 1803052799
|
||||
|
||||
|
||||
def test_points_expiry_extractor_supports_normalized_and_raw_shapes():
|
||||
assert (
|
||||
extract_points_expire_time({"will_expire_time": "1803052799"})
|
||||
== 1803052799
|
||||
)
|
||||
assert (
|
||||
extract_points_expire_time(
|
||||
{"raw": {"data": {"willExpireTime": 1803052799000}}}
|
||||
)
|
||||
== 1803052799
|
||||
)
|
||||
|
||||
|
||||
def test_gold_account_uses_web_endpoint_and_converts_cents(monkeypatch):
|
||||
client = _client()
|
||||
seen: list[tuple[str, str]] = []
|
||||
|
||||
def request_json(method, url, source, **_kwargs):
|
||||
seen.append((method, url))
|
||||
return {
|
||||
"code": 0,
|
||||
"success": True,
|
||||
"data": {"amount": 1000},
|
||||
}
|
||||
|
||||
monkeypatch.setattr(client, "_request_json", request_json)
|
||||
|
||||
result = client.gold_account()
|
||||
|
||||
assert seen == [
|
||||
("get", "https://www.douyu.com/japi/web/gold/account"),
|
||||
]
|
||||
assert result["amount_cents"] == 1000
|
||||
assert result["gold"] == 10
|
||||
|
||||
|
||||
def test_gold_qr_uses_init_then_get_qr_and_returns_polling_token(monkeypatch):
|
||||
client = _client()
|
||||
calls: list[tuple[str, str, dict[str, Any]]] = []
|
||||
monkeypatch.setattr(
|
||||
client,
|
||||
"acf_ccn",
|
||||
lambda **_kwargs: "csrf-cookie",
|
||||
)
|
||||
|
||||
def request_json(method, url, source, **kwargs):
|
||||
calls.append((method, url, kwargs))
|
||||
if url.endswith("/init"):
|
||||
return {
|
||||
"code": 0,
|
||||
"success": True,
|
||||
"data": {"uid": 100, "nickName": "测试用户", "scene": "web"},
|
||||
}
|
||||
return {
|
||||
"code": 0,
|
||||
"success": True,
|
||||
"data": {
|
||||
"token": "pay-token",
|
||||
"code_url": "https://cz.douyu.com/pages/one-pay/order/pay-token",
|
||||
"polling_url": (
|
||||
"https://www.douyu.com/japi/web/gold/getQrState"
|
||||
"?token=pay-token"
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
monkeypatch.setattr(client, "_request_json", request_json)
|
||||
|
||||
result = client.create_gold_qr(amount=10, pay_type=1)
|
||||
|
||||
assert calls[0][0:2] == (
|
||||
"post",
|
||||
"https://www.douyu.com/japi/web/gold/init",
|
||||
)
|
||||
assert calls[0][2]["data"] == {"ctn": "csrf-cookie", "scene": "web"}
|
||||
assert calls[1][0:2] == (
|
||||
"get",
|
||||
"https://www.douyu.com/japi/web/gold/getQrCode",
|
||||
)
|
||||
assert calls[1][2]["params"] == {
|
||||
"payType": "1",
|
||||
"productId": "DYTV_Product_Gold_10",
|
||||
"number": "1",
|
||||
"source": "",
|
||||
"toName": "",
|
||||
}
|
||||
assert result["token"] == "pay-token"
|
||||
assert result["pay_url"].endswith("/pay-token")
|
||||
|
||||
|
||||
def test_gold_qr_state_maps_success_order(monkeypatch):
|
||||
client = _client()
|
||||
|
||||
def request_json(method, url, source, **kwargs):
|
||||
assert method == "get"
|
||||
assert url == "https://www.douyu.com/japi/web/gold/getQrState"
|
||||
assert kwargs["params"] == {"token": "pay-token"}
|
||||
return {
|
||||
"code": 0,
|
||||
"success": True,
|
||||
"data": {
|
||||
"state": 2,
|
||||
"quantity": 10,
|
||||
"nickname": "测试用户",
|
||||
"orderId": "order-100",
|
||||
},
|
||||
}
|
||||
|
||||
monkeypatch.setattr(client, "_request_json", request_json)
|
||||
|
||||
result = client.query_gold_qr_state("pay-token")
|
||||
|
||||
assert result["state"] == 2
|
||||
assert result["quantity"] == 10
|
||||
assert result["order_id"] == "order-100"
|
||||
@@ -20,10 +20,13 @@ READ_METHODS = {
|
||||
"exchange_orders",
|
||||
"exchange_records",
|
||||
"gold_account",
|
||||
"query_gold_qr_state",
|
||||
"list_esports_goods",
|
||||
"list_goods",
|
||||
"query_limited_goods",
|
||||
"query_points",
|
||||
"query_points_expirations",
|
||||
"query_points_ledger",
|
||||
"xpd_bind_info",
|
||||
}
|
||||
|
||||
|
||||
@@ -144,6 +144,49 @@ class TestDouyuGoldRechargeChannel:
|
||||
assert self.task.queue_lane == ""
|
||||
assert self.task.result["gold_recharged"] is True
|
||||
|
||||
def test_wallet_gold_qr_uses_official_paid_state_before_balance_delta(self):
|
||||
config = {
|
||||
"gold_recharge_channel": "wechat_qr",
|
||||
"gold_pay_type": 1,
|
||||
}
|
||||
self.task.result = {
|
||||
"payment_amount": 10,
|
||||
"payment_channel": "wechat_qr",
|
||||
"payment_token": "pay-token",
|
||||
"baseline_gold_balance": 0,
|
||||
}
|
||||
self.session.commit()
|
||||
client = Mock()
|
||||
client.query_gold_qr_state.return_value = {
|
||||
"state": 2,
|
||||
"quantity": 10,
|
||||
"order_id": "gold-order-10",
|
||||
}
|
||||
self.runner._client = Mock(return_value=client)
|
||||
self.runner._refresh_account_gold_balance = Mock(
|
||||
return_value={
|
||||
"gold_balance": 10,
|
||||
"exchange_balance": 0,
|
||||
"gold": {"gold": 10},
|
||||
"exchange_balance_query": {"count": 0},
|
||||
}
|
||||
)
|
||||
|
||||
self.runner._poll_create_gold_qr_once(
|
||||
self.session,
|
||||
self.task,
|
||||
self.account,
|
||||
"acf_uid=10001",
|
||||
config,
|
||||
)
|
||||
|
||||
self.session.refresh(self.task)
|
||||
assert self.task.status == "success"
|
||||
assert self.task.queue_lane == ""
|
||||
assert self.task.result["gold_confirm_source"] == "gold_qr_state"
|
||||
assert self.task.result["order_id"] == "gold-order-10"
|
||||
assert self.task.result["gold_refreshed_after_success"] is True
|
||||
|
||||
@patch("web.backend.services.douyu_runner_gold.FishFinRechargeClient")
|
||||
def test_supplier_channel_creates_order_using_nickname_and_finishes_on_success(
|
||||
self, client_class
|
||||
|
||||
@@ -12,6 +12,8 @@ from sqlalchemy import create_engine, inspect, text
|
||||
import web.backend.database as database_module
|
||||
from tests.support.db import get_mysql_credentials
|
||||
|
||||
TARGET_REVISION = "20261106_0065"
|
||||
|
||||
|
||||
def test_0065_upgrade_downgrade_roundtrip():
|
||||
creds = get_mysql_credentials()
|
||||
@@ -91,7 +93,7 @@ def test_0065_upgrade_downgrade_roundtrip():
|
||||
},
|
||||
)
|
||||
|
||||
command.upgrade(cfg, "head")
|
||||
command.upgrade(cfg, TARGET_REVISION)
|
||||
|
||||
insp = inspect(engine)
|
||||
cols = {c["name"] for c in insp.get_columns("accounts")}
|
||||
@@ -144,7 +146,7 @@ def test_0065_upgrade_downgrade_roundtrip():
|
||||
},
|
||||
)
|
||||
conn.execute(text("UPDATE alembic_version SET version_num='20261021_0064'"))
|
||||
command.upgrade(cfg, "head")
|
||||
command.upgrade(cfg, TARGET_REVISION)
|
||||
with engine.connect() as conn:
|
||||
resumed = conn.execute(
|
||||
text(
|
||||
@@ -200,7 +202,7 @@ def test_0065_upgrade_downgrade_roundtrip():
|
||||
assert old_values["downgrade-1"] == ["套装-兔兔白日梦"]
|
||||
assert old_values["downgrade-2"] == ["套装-兔兔白日梦", "套装-狂战萌兔"]
|
||||
|
||||
command.upgrade(cfg, "head")
|
||||
command.upgrade(cfg, TARGET_REVISION)
|
||||
insp = inspect(engine)
|
||||
cols = {c["name"] for c in insp.get_columns("accounts")}
|
||||
assert "high_value_owned" not in cols
|
||||
|
||||
Reference in New Issue
Block a user