fix(douyu): 修正绑定状态与换绑冷却判定

This commit is contained in:
yml
2026-11-22 02:10:29 +08:00
parent 21956d952c
commit fa75ce66ee
9 changed files with 636 additions and 104 deletions
+22 -3
View File
@@ -89,7 +89,8 @@ def test_role_resolver_uses_legacy_pending_role_when_current_is_empty():
assert result["source_alias"] == "cjm"
def test_role_resolver_does_not_treat_stale_same_role_as_new_pending():
def test_role_resolver_accepts_existing_action_alias_pending():
"""2026-11-22 成功 HAR:已有 bindAct=0 角色仍是可确认 pending。"""
role = "忧郁情潇藏心中"
client = RoleClient(
{
@@ -100,8 +101,26 @@ def test_role_resolver_does_not_treat_stale_same_role_as_new_pending():
result = resolve_elite_role(client, CONFIG)
assert result["status"] == ROLE_UNKNOWN
assert result["role_name"] == ""
assert result["status"] == ROLE_PENDING
assert result["role_name"] == role
assert result["source_alias"] == "current-alias"
assert result["decision"]["reason"] == "existing_actionable_pending"
def test_role_resolver_does_not_treat_bound_need_flag_as_pending():
"""2026-11-22 失败 HAR:bindAct=1 + needBindAct=1 仍是已绑定。"""
role = "狗鼻子弗尼亚bd"
client = RoleClient(
{
"current-alias": _bind(role, bound_act=True, bound_role=True),
"cjm": _bind(role, bound_role=True, need_act=False),
}
)
result = resolve_elite_role(client, CONFIG)
assert result["status"] == ROLE_BOUND
assert result["role_name"] == role
assert result["pending_role_name"] == ""
+64 -5
View File
@@ -5,7 +5,9 @@ from __future__ import annotations
from datetime import UTC, datetime
from typing import Any
from core.douyu import DouyuActivityClient
import pytest
from core.douyu import DouyuActivityClient, DouyuActivityError
from web.backend.models import Account
from web.backend.services.account_binding import (
BIND_BOUND,
@@ -195,7 +197,8 @@ def test_existing_pending_role_is_baseline_not_new_scan_result():
)
def test_existing_action_alias_pending_is_stale_without_transition():
def test_existing_action_alias_pending_is_confirmable_without_transition():
"""2026-11-22 成功 HAR:已有 bindAct=0 角色可直接确认。"""
role = "忧郁情潇藏心中"
baseline = _role_candidate(ACT_ALIAS, role, need_bind_act=True)
legacy = _role_candidate(LEGACY_ALIAS, role, need_bind_act=False)
@@ -218,9 +221,23 @@ def test_existing_action_alias_pending_is_stale_without_transition():
actionable_aliases=[ACT_ALIAS],
)
assert decision["confirmable"] is False
assert decision["reason"] == "same_role_stale_pending"
assert selected is None
assert decision["confirmable"] is True
assert decision["reason"] == "existing_actionable_pending"
assert selected is not None
assert selected["act_alias"] == ACT_ALIAS
def test_actionable_pending_without_baseline_is_confirmable():
role = "只为爱杰宝"
activity = _role_candidate(ACT_ALIAS, role, need_bind_act=True)
decision = binding_pending_decision(
activity,
actionable_aliases=[ACT_ALIAS],
)
assert decision["confirmable"] is True
assert decision["reason"] == "existing_actionable_pending"
def test_same_role_after_activity_bind_transition_is_pending():
@@ -323,6 +340,22 @@ def test_task_result_helpers_use_shared_same_role_transition_rule():
assert binding_role_from_result(same_role_scanned) == "少和我较劲"
def test_task_result_helpers_accept_existing_action_alias_pending():
activity = _role_candidate(ACT_ALIAS, "只为爱杰宝", need_bind_act=True)
result = {
**binding_snapshot(activity),
"act_alias": ACT_ALIAS,
"action_act_aliases": [ACT_ALIAS],
"before_bind_info": activity,
"baseline_role_name": "只为爱杰宝",
"bind_ready_for_confirm": True,
"bind_confirmed": False,
}
assert pending_binding_role_from_result(result) == "只为爱杰宝"
assert binding_role_from_result(result) == "只为爱杰宝"
def test_confirmed_new_role_replaces_account_current_role():
account = Account(
username="replace-role",
@@ -507,3 +540,29 @@ def test_qr_and_confirm_requests_follow_latest_har(monkeypatch):
"actAlias": (None, ACT_ALIAS),
"ctn": (None, "ctn"),
}
def test_confirm_bind_preserves_platform_cooldown_error_code(monkeypatch):
"""2026-11-22 失败 HAR:actBind 必须保留 -200001,不能只留中文消息。"""
client = DouyuActivityClient("acf_ccn=ctn")
monkeypatch.setattr(
client,
"acf_ccn",
lambda *, refresh_subscribe=True: "ctn",
)
payload = {
"error": -200001,
"msg": "该平台账号未到可换绑时间,请使用其他平台账号",
"data": None,
}
monkeypatch.setattr(
client,
"_request_json",
lambda *_args, **_kwargs: payload,
)
with pytest.raises(DouyuActivityError) as exc_info:
client.confirm_bind(ACT_ALIAS)
assert exc_info.value.code == -200001
assert exc_info.value.payload == payload
+251 -11
View File
@@ -6,6 +6,7 @@ from fastapi import HTTPException
from pydantic import ValidationError
from sqlalchemy import text
from core.douyu import DouyuActivityError
from tests.support.db import make_test_session
from web.backend.database import engine as app_engine
from web.backend.main import health
@@ -765,9 +766,107 @@ def test_deadline_poll_still_checks_role_once_before_timeout(db, monkeypatch):
assert task.result["bind_ready_for_confirm"] is True
def test_qr_preflight_treats_existing_action_alias_pending_as_baseline(
def test_confirm_bind_maps_platform_cooldown_and_keeps_old_role(
db, monkeypatch
):
"""2026-11-22 失败 HAR:-200001 是斗鱼账号冷却,旧绑定不能被新角色覆盖。"""
_, account, task = _fixtures(db, status="running")
old_role = "狗鼻子弗尼亚bd"
new_role = "巫师基尔斯84"
task.task_type = "confirm_bind"
task.result = {
"expected_role_name": new_role,
"baseline_role_name": old_role,
}
account.game_name = old_role
account.role_bind_status = "bound"
db.commit()
can_change_time = int(
(datetime.now(UTC) + timedelta(days=2)).timestamp()
)
old_bound = {
"act_alias": "20260120QYOOB",
"role_name": old_role,
"area_name": "微信",
"plat_name": "安卓(android)",
"is_bound_account": True,
"is_bound_role": True,
"is_bound_act": True,
"need_bind_act": True,
"need_bind_role": True,
"change_role_wait_time": 172_800,
"can_change_time": can_change_time,
"can_change_role": False,
}
new_pending = {
**old_bound,
"act_alias": "cjm",
"role_name": new_role,
"area_name": "微信",
"plat_name": "苹果(iOS)",
"is_bound_act": False,
"change_role_wait_time": 0,
"can_change_time": 0,
"can_change_role": True,
}
payload = {
"error": -200001,
"msg": "该平台账号未到可换绑时间,请使用其他平台账号",
"data": None,
}
class Client:
@staticmethod
def confirm_bind(_alias):
raise DouyuActivityError(
payload["msg"],
code=payload["error"],
payload=payload,
)
runner = DouyuBatchRunner(
db,
task.batch_id,
"confirm_bind",
close_db=False,
)
monkeypatch.setattr(runner, "_client", lambda _cookie: Client())
monkeypatch.setattr(
runner,
"_fetch_bind_info_candidates",
lambda *_args: [old_bound, new_pending],
)
runner._execute_confirm_bind(
db,
task,
account,
"PHPSESSID=x",
{
"bind_act_alias": "20260120QYOOB",
"confirm_act_alias": "20260120QYOOB",
"legacy_act_alias": "cjm",
},
)
db.refresh(task)
db.refresh(account)
assert task.status == "failed"
assert task.result["issue_code"] == "account_role_cooldown"
assert task.result["confirm_error_code"] == -200001
assert task.result["before_bound_bind_info"]["role_name"] == old_role
assert task.result["role_name"] == new_role
assert task.result["bind_ready_for_confirm"] is False
assert "斗鱼账号" in task.message
assert "更换斗鱼账号" in task.message
assert account.game_name == old_role
assert account.role_bind_status == "bound"
def test_qr_preflight_accepts_existing_action_alias_pending_from_har(
db, monkeypatch
):
"""2026-11-22 成功 HAR:已有 bindAct=0 角色无需等新一轮状态变化。"""
_, account, task = _fixtures(db, status="running")
role = "忧郁情潇藏心中"
legacy = {
@@ -821,17 +920,13 @@ def test_qr_preflight_treats_existing_action_alias_pending_as_baseline(
)
db.refresh(task)
assert task.status == "running"
assert task.status == "success"
assert task.result["url"] == "https://example.test/qr"
assert task.result["bind_phase"] == "waiting_scan"
assert task.result["bind_ready_for_confirm"] is False
assert "pending_role_name" not in task.result
action_decision = next(
item
for item in task.result["bind_candidate_decisions"]
if item["alias"] == "20260120QYOOB"
)
assert action_decision["reason"] == "same_role_stale_pending"
assert task.result["bind_phase"] == "role_ready"
assert task.result["bind_ready_for_confirm"] is True
assert task.result["pending_role_name"] == role
assert task.result["bind_decision"]["alias"] == "20260120QYOOB"
assert task.result["bind_decision"]["reason"] == "existing_actionable_pending"
def test_qr_preflight_keeps_bound_role_waiting_for_new_scan_transition(
@@ -905,6 +1000,77 @@ def test_qr_preflight_keeps_bound_role_waiting_for_new_scan_transition(
assert action_decision["reason"] == "already_bound"
def test_qr_preflight_blocks_platform_account_change_cooldown_from_har(
db, monkeypatch
):
"""2026-11-22 失败 HAR:canChangeTime 限制当前斗鱼号,发码前就必须拦截。"""
_, account, task = _fixtures(db, status="running")
role = "狗鼻子弗尼亚bd"
can_change_time = int(
(datetime.now(UTC) + timedelta(days=2)).timestamp()
)
activity = {
"act_alias": "20260120QYOOB",
"role_name": role,
"area_name": "微信",
"plat_name": "安卓(android)",
"is_bound_account": True,
"is_bound_role": True,
"is_bound_act": True,
"need_bind_act": True,
"need_bind_role": True,
"change_role_wait_time": 172_800,
"can_change_time": can_change_time,
"can_change_role": False,
}
account.game_name = role
account.role_bind_status = "bound"
db.commit()
client = type(
"Client",
(),
{
"get_bind_qr": lambda *_args: (_ for _ in ()).throw(
AssertionError("斗鱼账号冷却时不能生成二维码")
)
},
)()
runner = DouyuBatchRunner(
db,
task.batch_id,
"get_bind_qr",
close_db=False,
)
monkeypatch.setattr(runner, "_client", lambda _cookie: client)
monkeypatch.setattr(
runner,
"_fetch_bind_info_candidates",
lambda *_args: [activity],
)
runner._execute_get_bind_qr(
db,
task,
account,
"PHPSESSID=x",
{
"bind_act_alias": "20260120QYOOB",
"confirm_act_alias": "20260120QYOOB",
"legacy_act_alias": "cjm",
},
)
db.refresh(task)
db.refresh(account)
assert task.status == "failed"
assert task.result["bind_phase"] == "change_waiting"
assert task.result["issue_code"] == "account_role_cooldown"
assert "url" not in task.result
assert "斗鱼账号" in task.message
assert account.game_name == role
assert account.role_bind_status == "bound"
def test_binding_poll_accepts_existing_action_alias_pending_same_role(
db, monkeypatch
):
@@ -983,6 +1149,80 @@ def test_binding_poll_accepts_existing_action_alias_pending_same_role(
}
def test_binding_poll_accepts_unchanged_existing_action_alias_pending(
db, monkeypatch
):
"""2026-11-22 成功 HAR:已有动作 alias pending 不要求本轮状态变化。"""
_, account, task = _fixtures(db, status="running")
role = "只为爱杰宝"
legacy = {
"act_alias": "cjm",
"role_name": role,
"area_name": "手Q",
"plat_name": "安卓(android)",
"is_bound_account": True,
"is_bound_role": True,
"is_bound_act": False,
"need_bind_act": False,
"need_bind_role": True,
"change_role_wait_time": 0,
"can_change_time": 0,
"can_change_role": True,
}
activity = {
**legacy,
"act_alias": "20260120QYOOB",
"need_bind_act": True,
"change_role_wait_time": 2_592_000,
}
task.queue_lane = "binding_poll"
task.next_run_at = datetime.now(UTC)
task.run_deadline_at = datetime.now(UTC) + timedelta(minutes=10)
task.result = {
"url": "https://example.test/qr",
"query_act_aliases": ["cjm", "20260120QYOOB"],
"baseline_role_name": role,
"baseline_is_bound_act": False,
"before_bind_info": activity,
"bind_polling": True,
"qr_generated_at": datetime.now(UTC).isoformat(),
"poll_count": 2,
}
db.commit()
runner = DouyuBatchRunner(
db,
task.batch_id,
"get_bind_qr",
close_db=False,
)
monkeypatch.setattr(runner, "_client", lambda _cookie: object())
monkeypatch.setattr(
runner,
"_fetch_bind_info_candidates",
lambda _client, aliases: [
legacy if alias == "cjm" else activity for alias in aliases
],
)
runner.poll_bind_role_once(
db,
task,
account,
{
"bind_act_alias": "20260120QYOOB",
"confirm_act_alias": "20260120QYOOB",
"legacy_act_alias": "cjm",
},
)
db.refresh(task)
assert task.status == "success"
assert task.result["bind_phase"] == "role_ready"
assert task.result["role_name"] == role
assert task.result["bind_decision"]["alias"] == "20260120QYOOB"
assert task.result["bind_decision"]["reason"] == "existing_actionable_pending"
def test_active_task_budget_rejects_new_batch(db, monkeypatch):
user = User(username="budget-user", password_hash="hash", role="operation")
db.add(user)
+33
View File
@@ -2514,6 +2514,39 @@ class TestBindingAndCompletion(_Base):
live = service.customer_binding_out(self.session, task.id)
assert live["bindReadyForConfirm"] is False
def test_refresh_binding_uses_structured_platform_cooldown_issue(self):
"""2026-11-22 HAR:中文消息即使像角色冷却,也以 -200001 结构化码为准。"""
task = self._allocated()
bind_task = DouyuTask(
batch_id="bind-platform-cooldown-error-code",
account_id=task.account_id,
account_assigned_to=self.admin_id,
task_type="confirm_bind",
handbook_scope="elite",
status="failed",
message="待绑定游戏账号(测试角色)未到换绑时间,请重新换账号扫码绑定",
result={
"bind_phase": "confirm_failed",
"issue_code": "account_role_cooldown",
"confirm_error": "该平台账号未到可换绑时间,请使用其他平台账号",
"confirm_error_code": -200001,
"bind_ready_for_confirm": False,
},
created_by=self.admin_id,
)
self.session.add(bind_task)
self.session.flush()
task.bind_task_id = bind_task.id
task.binding_status = "role_ready"
task.execution_status = "role_ready"
self.session.commit()
detail = service.refresh_binding(self.session, task_id=task.id)
assert detail["task"]["issueCode"] == "account_role_cooldown"
assert detail["task"]["executionStatus"] == "manual_required"
assert "斗鱼账号" in detail["task"]["lastError"]
def test_list_hides_qr_but_detail_returns_it(self):
task = self._allocated()
bind_task = DouyuTask(