Files
live-hub-py/tests/test_douyu_activity_query.py
T
yml 1a49bcd481 feat(douyu): unify account probes and lifecycle writes
Centralize Douyu client creation, CK session probing, identity refresh, role alias resolution, capability persistence, cache and batch throttling across collaboration, fulfillment, tasks and cookie management. Add the account-name copy action in the collaboration table.
2026-11-20 01:55:25 +08:00

205 lines
6.1 KiB
Python

"""斗鱼只读活动查询统一入口的契约测试。"""
from __future__ import annotations
import ast
from pathlib import Path
from typing import cast
from core.douyu import DouyuActivityClient
from web.backend.models import Account, User
from web.backend.routers import douyu as douyu_api
from web.backend.services.douyu_account_probe import probe_account
READ_METHODS = {
"acf_ccn",
"bind_info",
"elite_user_info",
"esports_bind_info",
"exchange_balance",
"exchange_orders",
"exchange_records",
"gold_account",
"list_esports_goods",
"list_goods",
"query_limited_goods",
"query_points",
"xpd_bind_info",
}
class FakeActivityClient:
def __init__(self):
self.calls: list[str] = []
def acf_ccn(self, *, refresh_subscribe: bool = False):
self.calls.append("acf_ccn")
assert refresh_subscribe is False
return "csrf-token"
def elite_user_info(self, **_kwargs):
self.calls.append("elite_user_info")
return {"manual_type": 1, "manual_score": 5000}
def query_points(self, **_kwargs):
self.calls.append("query_points")
return {"points": 5200}
def query_limited_goods(self, **_kwargs):
self.calls.append("query_limited_goods")
return {
"limited_goods": [
{"commodityId": "limited-1", "commodityName": "套装-已达上限"},
{"commodityId": "limited-1", "commodityName": "重复项"},
{"commodityName": "无 ID 项"},
]
}
def list_goods(self, **_kwargs):
self.calls.append("list_goods")
return {
"goods": [
{
"commodityId": "gift-a",
"commodityName": "套装-兔兔白日梦",
"score": 1280,
"status": 0,
"openStatus": 1,
}
]
}
def test_account_probe_normalizes_exchange_eligibility_once():
client = FakeActivityClient()
account = Account(
id=1,
username="probe-account",
password="p",
email="probe@example.com",
email_password="ep",
uid="100",
cookie="acf_uid=100; acf_nickname=test",
)
result = probe_account(
account,
{
"manual_id": "manual-1",
"rid": "room-1",
},
client=cast(DouyuActivityClient, client),
session_checker=None,
with_elite_role=False,
with_eligibility=True,
)
assert result["elite"]["raw"]["manual_type"] == 1
assert result["eligibility"]["points"] == 5200
assert result["eligibility"]["limited_ids"] == ["limited-1"]
assert client.calls == [
"acf_ccn",
"elite_user_info",
"query_points",
"query_limited_goods",
]
def test_live_goods_endpoint_uses_shared_query_contract(db, monkeypatch):
user = User(username="goods-admin", password_hash="hash", role="super_admin")
db.add(user)
db.commit()
monkeypatch.setattr(
douyu_api,
"query_activity_goods",
lambda *_args, **_kwargs: [
{
"commodityId": "gift-a",
"commodityName": "套装-兔兔白日梦",
"score": 1280,
"status": 0,
"openStatus": 1,
"mark": "",
}
],
)
rows = douyu_api.list_live_goods(db=db, current=user)
assert len(rows) == 1
assert rows[0].commodity_id == "gift-a"
assert rows[0].name == "套装-兔兔白日梦"
assert rows[0].score == 1280
def test_douyu_read_queries_only_call_client_from_shared_module():
backend = Path(__file__).parents[1] / "web" / "backend"
allowed = backend / "services" / "douyu_activity_query.py"
violations: list[str] = []
paths = [
*backend.glob("services/douyu_*.py"),
*backend.glob("routers/douyu*.py"),
]
for path in paths:
if path == allowed:
continue
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
for node in ast.walk(tree):
if not isinstance(node, ast.Call):
continue
func = node.func
if isinstance(func, ast.Attribute) and func.attr in READ_METHODS:
violations.append(
f"{path.relative_to(backend)}:{node.lineno}:{func.attr}"
)
assert violations == []
def test_douyu_client_factory_and_role_query_stay_centralized():
backend = Path(__file__).parents[1] / "web" / "backend"
client_factory = backend / "services" / "douyu_activity_query.py"
role_probe = backend / "services" / "douyu_account_probe.py"
constructor_violations: list[str] = []
role_query_violations: list[str] = []
lifecycle_write_violations: list[str] = []
for path in [
*backend.glob("services/douyu_*.py"),
*backend.glob("routers/douyu*.py"),
]:
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
for node in ast.walk(tree):
if not isinstance(node, ast.Call):
continue
func = node.func
if (
isinstance(func, ast.Name)
and func.id == "DouyuActivityClient"
and path != client_factory
):
constructor_violations.append(
f"{path.relative_to(backend)}:{node.lineno}"
)
if (
isinstance(func, ast.Name)
and func.id == "query_bind_info"
and path != role_probe
):
role_query_violations.append(
f"{path.relative_to(backend)}:{node.lineno}"
)
if (
isinstance(func, ast.Name)
and func.id == "on_ck_verdict"
and path != role_probe
):
lifecycle_write_violations.append(
f"{path.relative_to(backend)}:{node.lineno}"
)
assert constructor_violations == []
assert role_query_violations == []
assert lifecycle_write_violations == []