fix(douyu): 登录后自动复检 CK 并收紧分配池

This commit is contained in:
yml
2026-11-20 20:46:55 +08:00
parent d42b4528c4
commit 00c30cc24e
9 changed files with 239 additions and 114 deletions
+5 -1
View File
@@ -11,7 +11,7 @@ S4 之前的状态(都是「定义了却从没发过」):
本文件守住修复后的行为。
"""
from datetime import UTC, datetime
from datetime import UTC, datetime, timedelta
import pytest
@@ -46,6 +46,10 @@ class _Base:
email_password="ep",
cookie=kwargs.pop("cookie", "acf_uid=1"),
ck_check_status=kwargs.pop("ck_check_status", "valid"),
cookie_updated_at=kwargs.pop(
"cookie_updated_at", NOW - timedelta(seconds=1)
),
ck_checked_at=kwargs.pop("ck_checked_at", NOW),
**kwargs,
)
self.session.add(account)
+43 -7
View File
@@ -12,14 +12,20 @@
「筛出未分配 → 一键分给某人」不必先勾选。显式 `account_ids` 的旧路径不变。
"""
from datetime import UTC, datetime, timedelta
import pytest
from fastapi import HTTPException
from tests.support.db import get_test_engine, make_test_session
from web.backend.models import Account, User
from web.backend.routers.accounts import (
assign_account,
assignments_summary,
batch_assign_accounts,
list_accounts,
)
from web.backend.schemas import BatchAssign
from web.backend.schemas import AccountAssign, BatchAssign
class _Base:
@@ -31,11 +37,13 @@ class _Base:
self.other = User(username="af-kf2", password_hash="h", role="support")
self.session.add_all([self.admin, self.support, self.other])
self.session.commit()
self.now = datetime.now(UTC)
def teardown_method(self):
self.session.close()
def make_account(self, name: str, **kwargs) -> Account:
ck_check_status = kwargs.pop("ck_check_status", "valid")
account = Account(
username=name,
password="p",
@@ -43,6 +51,11 @@ class _Base:
email_password="ep",
# 默认持有 CK —— 分配接口只接受「还拿着 CK」的账号
cookie=kwargs.pop("cookie", "acf_uid=1"),
ck_check_status=ck_check_status,
cookie_updated_at=kwargs.pop(
"cookie_updated_at", self.now - timedelta(seconds=1)
),
ck_checked_at=kwargs.pop("ck_checked_at", self.now),
**kwargs,
)
self.session.add(account)
@@ -102,19 +115,23 @@ class TestAssignFilter(_Base):
class TestAssignablePool(_Base):
"""分配池口径:CK 失效的号必须先修复,不能混进「未分配」让人误分配。"""
"""分配池口径:只收当前 Cookie 的新鲜有效检测结果。"""
def test_assignable_only_excludes_invalid_ck(self):
def test_assignable_only_requires_fresh_valid_ck(self):
self.make_account("ap-valid", ck_check_status="valid")
self.make_account("ap-unchecked") # 还没检测过:按可用处理
self.make_account("ap-error", ck_check_status="error") # 查不到 ≠ 失效
self.make_account("ap-unchecked", ck_check_status="", ck_checked_at=None)
self.make_account("ap-error", ck_check_status="error")
self.make_account("ap-invalid", ck_check_status="invalid")
self.make_account(
"ap-stale-valid",
ck_check_status="valid",
cookie_updated_at=self.now,
ck_checked_at=self.now - timedelta(seconds=1),
)
self.make_account("ap-disabled", ck_check_status="valid", status="disabled")
assert self.names(assign_status="unassigned", assignable_only=True) == [
"ap-valid",
"ap-unchecked",
"ap-error",
]
def test_summary_counts_only_assignable(self):
@@ -160,6 +177,25 @@ class TestAssignablePool(_Base):
assert valid.assigned_to == self.support.id
assert invalid.assigned_to is None
def test_single_assign_rejects_stale_valid_verdict(self):
stale = self.make_account(
"single-stale",
ck_check_status="valid",
cookie_updated_at=self.now,
ck_checked_at=self.now - timedelta(seconds=1),
)
with pytest.raises(HTTPException) as exc_info:
assign_account(
stale.id,
AccountAssign(assigned_to=self.support.id),
db=self.session,
current=self.admin,
)
assert exc_info.value.status_code == 400
assert "有效 CK 检测" in exc_info.value.detail
class TestAllMatchingAssign(_Base):
def test_assigns_every_matching_unassigned(self):
+68 -15
View File
@@ -86,8 +86,31 @@ class TestLoginAttemptIsolation:
def teardown_method(self):
self.session.close()
def _run_batch(self, monkeypatch, *, mode="login", account_ids=None, stop=False):
def _run_batch(
self,
monkeypatch,
*,
mode="login",
account_ids=None,
stop=False,
cookie_check=None,
):
monkeypatch.setattr(login_service, "DouyuLogin", _FakeLogin)
monkeypatch.setattr(
login_service,
"check_douyu_cookie",
cookie_check
or (
lambda _cookie: {
"valid": True,
"message": "ok",
"fish_ball": 1,
"nickname": "n",
"level": 1,
"checked_at": datetime.now(UTC),
}
),
)
# 批次结束时 runner 会关掉自己的会话,因此单独给它一个。
runner_db = sessionmaker(bind=self.engine)()
runner = login_service.LoginBatchRunner(
@@ -163,7 +186,7 @@ class TestLoginAttemptIsolation:
task = self._fresh(self.task_id)
account = self._fresh_account()
assert task.status == "success"
assert task.message == "登录成功"
assert task.message == "登录成功,Cookie 有效"
assert task.attempt_status == "success"
assert task.attempt_at is not None
assert task.batch_id != "old-batch"
@@ -171,6 +194,9 @@ class TestLoginAttemptIsolation:
assert account.cookie == "new-cookie"
assert account.cookie_updated_at is not None
assert account.cookie_source == "web"
assert account.ck_check_status == "valid"
assert account.ck_checked_at >= account.cookie_updated_at
assert account.status == "active"
def test_relogin_success_writes_ck_verdict_on_the_account(self, monkeypatch):
"""重登成功后的复检必须写到账号上,不能写到登录器的临时对象上。
@@ -181,19 +207,6 @@ class TestLoginAttemptIsolation:
"""
self.account.ck_check_status = "invalid"
self.session.commit()
monkeypatch.setattr(
login_service,
"check_douyu_cookie",
lambda _cookie: {
"valid": True,
"message": "ok",
"fish_ball": 1,
"nickname": "n",
"level": 1,
"checked_at": datetime.now(UTC),
},
)
self._run_batch(monkeypatch, mode="relogin")
task = self._fresh(self.task_id)
@@ -203,6 +216,46 @@ class TestLoginAttemptIsolation:
assert account.cookie == "new-cookie"
assert account.ck_check_status == "valid"
def test_normal_login_replaces_stale_invalid_verdict_after_probe(self, monkeypatch):
self.account.ck_check_status = "invalid"
self.account.status = "invalid"
self.session.commit()
self._run_batch(monkeypatch)
task = self._fresh(self.task_id)
account = self._fresh_account()
assert task.attempt_status == "success"
assert task.message == "登录成功,Cookie 有效"
assert account.cookie == "new-cookie"
assert account.ck_check_status == "valid"
assert account.ck_checked_at >= account.cookie_updated_at
assert account.status == "active"
def test_login_success_with_failed_probe_keeps_account_out_of_pool(
self, monkeypatch
):
self.account.ck_check_status = "invalid"
self.account.status = "invalid"
self.session.commit()
self._run_batch(
monkeypatch,
cookie_check=lambda _cookie: {
"valid": False,
"message": "Cookie 已失效",
"checked_at": datetime.now(UTC),
},
)
task = self._fresh(self.task_id)
account = self._fresh_account()
assert task.attempt_status == "success"
assert "Cookie 有效性检测失败" in task.message
assert account.cookie == "new-cookie"
assert account.ck_check_status == "invalid"
assert account.status == "invalid"
def test_stopped_batch_keeps_existing_cookie(self, monkeypatch):
self._run_batch(monkeypatch, stop=True)