Files
live-hub-py/tests/test_douyu_query_workbench.py
T
yml 6ad8025a86 feat(douyu): 查询工作台区分导入/查询数据、导入后自动查CK并修复登录刷新闪烁 (v0.4.29)
1) 闪烁修复:轮询(loadAccountsPage/loadManualBudget)改为静默模式,
   不再每 2.2s 点亮表格 loading 遮罩与预算 Tag spinner;活动结束后保留
   12s 宽限期继续静默刷新,避免登录刚完成就停刷导致行上残留「登录队列中」。

2) 导入后自动检测 CK:工作台 PUT 返回 imported_account_ids,前端分片
   并发检测并显示进度,失效/无 CK 账号直接标红;/accounts/ck-check 对
   无 CK、登录中的账号改为跳过(返回 checked/skipped)而不是整批报错。
   行内新增「重登/人工登录该账号」入口,走既有人工登录预算。

3) 数据来源区分:douyu_workbench_accounts 新增 data_state/imported_at/
   queried_at/relogin_at(迁移 20261130_0142)。导入标 imported,查询任务
   成功由 _mark_task 标 queried,人工重登入队标 stale;PUT 工作台改为
   upsert,不再整删整建以免重置状态。账号列表新增 workbench_scope/
   workbench_state 入参与 workbench_* 回填字段。

4) 重登后只查重登账号:新增 /query-workbench/pending-ids(导入未查 +
   重登待重查,仅含有可用 CK 者)与「只查待查询(N)」下拉;一键查询改为
   尊重当前筛选(跨页),修正原来无视筛选直接查整台的问题。

5) CSV 末尾追加「数据来源 / 数据更新说明」两列,保持原有列序不变。
2026-11-30 20:04:26 +08:00

957 lines
33 KiB
Python

"""斗鱼「查询工作台」单元与集成测试:
1. query_assets_and_bind:鱼翅/积分/换绑时间单次聚合查询、部分失败容错、全败判定与 runner 分发;
2. 账号可见性与筛选:include_all=true 包含 CK 失效/无 CK 账号,lookup 返回匹配与未匹配账号,invalid-ids 跨页提取;
3. 失效 CK 人工预算重登:权限校验、有 CK 重登 vs 无 CK 登录拆批、强制 category=CATEGORY_MANUAL、execution_worker 透传;
4. CSV 导出:UTF-8 BOM、表头与冷却字段、保持工作台/传入顺序。
"""
from __future__ import annotations
import csv
import io
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,
AccountSyncState,
DouyuTask,
DouyuWorkbenchAccount,
ExecutionJob,
LoginTask,
User,
)
from web.backend.routers.douyu import (
export_query_workbench_csv,
get_query_workbench_manual_budget,
list_query_workbench_invalid_ids,
list_task_accounts,
lookup_query_workbench_accounts,
relogin_query_workbench_invalid_accounts,
update_workbench_accounts,
)
from web.backend.schemas import (
DouyuQueryWorkbenchExportRequest,
DouyuQueryWorkbenchLookupRequest,
DouyuQueryWorkbenchReloginRequest,
DouyuWorkbenchAccountsUpdate,
)
from web.backend.services import douyu_runner_overview, execution_worker
from web.backend.services.douyu_runner_bind import BindMixin
from web.backend.services.douyu_runner_core import DouyuBatchRunnerCore
from web.backend.services.douyu_runner_overview import OverviewMixin
from web.backend.services.douyu_service import (
DOUYU_HANDBOOK_SCOPES,
DOUYU_HANDBOOK_TASK_TYPES,
SUPPORTED_DOUYU_TASK_TYPES,
create_douyu_planned_tasks,
)
from web.backend.services.execution_jobs import (
JOB_LOGIN_BATCH,
JOB_RELOGIN_BATCH,
LANE_AUTH,
claim_execution_jobs,
)
from web.backend.services.login_quota_service import CATEGORY_MANUAL
class _QueryFakeClient:
def acf_ccn(self, **_):
return "ctn-123"
class _QueryHarness(OverviewMixin, BindMixin, DouyuBatchRunnerCore):
def __init__(
self, *, fail_helpers: set[str] | None = None, wait_seconds: int = 3600
):
self.client = _QueryFakeClient()
self.fail_helpers = fail_helpers or set()
self.wait_seconds = wait_seconds
self.marked: dict = {}
def _client(self, cookie: str):
return self.client
def _mark_task(self, db, task, status, message, result=None):
self.marked = {
"status": status,
"message": message,
"result": result,
}
def _push_log(self, *a, **k):
pass
def _refresh_account_gold_balance(self, client, account):
if "gold" in self.fail_helpers:
raise RuntimeError("模拟鱼翅接口超时")
account.gold_balance = 66
account.exchange_balance = 12
return {"gold_balance": 66, "exchange_balance": 12}
def _refresh_account_points(self, client, account, cookie, *, ctn=None):
if "points" in self.fail_helpers:
raise RuntimeError("模拟积分接口异常")
account.points = 888
return {
"points": 888,
"points_query": {"raw": {"data": {"willExpireTime": "1800000000"}}},
}
def _refresh_elite_handbook(self, client, account, *, manual_id, rid=""):
del client, manual_id, rid
if "elite" in self.fail_helpers:
raise RuntimeError("模拟宝典接口异常")
account.elite_opened = True
account.elite_expire_time = 1800000000
return {
"elite_manual_type": 1,
"elite_manual_score": 888,
"elite_expire_time": 1800000000,
"elite_opened": True,
"elite_expired": False,
"points": 888,
}
class TestQueryAssetsAndBindExecution:
def setup_method(self):
self.engine = get_test_engine()
self.session = make_test_session(self.engine)
self.user = User(username="qw-admin", password_hash="h", role="super_admin")
self.session.add(self.user)
self.session.flush()
self.account = Account(
username="qw-acc",
uid="10086",
password="p",
email="q@e.com",
email_password="ep",
cookie="acf_uid=10086; acf_ltkid=1; acf_stk=2",
)
self.session.add(self.account)
self.session.commit()
self.task = DouyuTask(
batch_id="qw-batch",
account_id=self.account.id,
task_type="query_assets_and_bind",
handbook_scope="query",
status="running",
message="",
created_by=self.user.id,
)
self.session.add(self.task)
self.session.commit()
def teardown_method(self):
self.session.close()
def test_scope_and_task_registration(self):
assert "query" in DOUYU_HANDBOOK_SCOPES
assert "query_assets_and_bind" in SUPPORTED_DOUYU_TASK_TYPES
assert "query_assets_and_bind" in DOUYU_HANDBOOK_TASK_TYPES["query"]
batch_id, count = create_douyu_planned_tasks(
self.session,
[self.account.id],
"query_assets_and_bind",
"query",
self.user.id,
)
assert count == 1
row = self.session.query(DouyuTask).filter(DouyuTask.batch_id == batch_id).one()
assert row.handbook_scope == "query"
assert row.task_type == "query_assets_and_bind"
def test_updates_gold_points_and_bind_cooldown(self, monkeypatch):
def fake_resolve(client, config):
return {
"status": "bound",
"bind_infos": [
{
"act_alias": "B1",
"role_name": "测试召唤师",
"plat_name": "微信",
"area_name": "安卓一区",
"is_bound_role": True,
"is_bound_act": True,
"change_role_wait_time": 7200,
"can_change_time": 1800003600,
}
],
"errors": [],
}
monkeypatch.setattr(douyu_runner_overview, "resolve_elite_role", fake_resolve)
h = _QueryHarness()
h._execute_query_assets_and_bind(
self.session,
self.task,
self.account,
self.account.cookie,
{
"manual_id": "M1",
"rid": "R1",
"bind_act_alias": "B1",
"confirm_act_alias": "C1",
},
)
assert h.marked["status"] == "success"
res = h.marked["result"]
assert res["gold_balance"] == 66
assert res["exchange_balance"] == 12
assert res["points"] == 888
assert res["elite_opened"] is True
assert res["elite_expire_time"] == 1800000000
assert self.account.gold_balance == 66
assert self.account.points == 888
assert self.account.elite_opened is True
assert self.account.elite_expire_time == 1800000000
assert self.account.points_expire_at is not None
assert self.account.role_bind_status == "bound"
assert self.account.game_name == "测试召唤师"
assert self.account.role_change_available_at is not None
assert (
self.session.query(AccountSyncState)
.filter(AccountSyncState.account_id == self.account.id)
.count()
>= 2
)
def test_partial_failure_still_succeeds_with_other_fields(self, monkeypatch):
monkeypatch.setattr(
douyu_runner_overview,
"resolve_elite_role",
lambda client, config: {
"status": "unbound",
"bind_infos": [],
"errors": [],
},
)
h = _QueryHarness(fail_helpers={"gold"})
h._execute_query_assets_and_bind(
self.session,
self.task,
self.account,
self.account.cookie,
{"manual_id": "M1", "bind_act_alias": "B1"},
)
assert h.marked["status"] == "success"
assert "gold" in h.marked["result"]["errors"]
assert "部分异常: gold" in h.marked["message"]
assert h.marked["result"]["points"] == 888
assert self.account.role_bind_status == "unbound"
def test_all_failed_marks_task_failed(self, monkeypatch):
monkeypatch.setattr(
douyu_runner_overview,
"resolve_elite_role",
lambda client, config: {
"status": "error",
"bind_infos": [],
"errors": ["角色接口500"],
},
)
h = _QueryHarness(fail_helpers={"gold", "elite", "points"})
h._execute_query_assets_and_bind(
self.session,
self.task,
self.account,
self.account.cookie,
{"manual_id": "M1"},
)
assert h.marked["status"] == "failed"
assert "gold" in h.marked["message"]
assert "elite" in h.marked["message"]
assert "points" in h.marked["message"]
assert "bind" in h.marked["message"]
class TestQueryWorkbenchRouterAndExport:
def setup_method(self):
self.engine = get_test_engine()
self.session = make_test_session(self.engine)
self.admin = User(username="qw-admin", password_hash="h", role="super_admin")
self.support_no_login = User(
username="kf-no-login",
password_hash="h",
role="support",
custom_permissions=["account:view_assigned", "douyu:task"],
)
self.support_with_login = User(
username="kf-with-login",
password_hash="h",
role="support",
custom_permissions=["account:view_assigned", "douyu:task", "login:batch"],
)
self.session.add_all(
[self.admin, self.support_no_login, self.support_with_login]
)
self.session.flush()
now = datetime.now(UTC)
self.acc_valid = Account(
username="dy_valid",
uid="111",
nickname="有效号",
password="pw",
email="v@e.com",
email_password="ep",
cookie="acf_uid=111",
ck_check_status="valid",
gold_balance=100,
exchange_balance=5,
points=1280,
points_expire_at=now + timedelta(days=30),
role_bind_status="bound",
game_name="角色A",
game_channel="微信 / 苹果",
role_change_available_at=now - timedelta(hours=1),
role_change_official_at=now - timedelta(hours=1),
elite_opened=True,
elite_expire_time=1893456000,
assigned_to=self.support_with_login.id,
)
self.acc_invalid_ck = Account(
username="dy_invalid",
uid="222",
nickname="失效号",
password="pw",
email="i@e.com",
email_password="ep",
cookie="acf_uid=222",
ck_check_status="invalid",
status="invalid",
gold_balance=20,
points=300,
role_bind_status="bound",
game_name="角色B",
role_change_available_at=now + timedelta(hours=5),
elite_opened=False,
elite_expire_time=1,
assigned_to=self.support_with_login.id,
)
self.acc_no_ck = Account(
username="dy_nock",
uid="",
nickname="无CK号",
password="pw",
email="n@e.com",
email_password="ep",
cookie="",
status="imported",
assigned_to=self.support_with_login.id,
)
self.acc_wait_seconds = Account(
username="dy_wait_seconds",
password="pw",
email="w@e.com",
email_password="ep",
cookie="acf_uid=333",
ck_check_status="valid",
role_bind_status="bound",
game_name="角色C",
role_change_available_at=None,
change_role_wait_time=3600,
assigned_to=self.support_with_login.id,
)
self.acc_missing_cred = Account(
username="dy_nocred",
password="",
email="",
email_password="",
cookie="",
status="imported",
assigned_to=self.support_with_login.id,
)
self.session.add_all(
[
self.acc_valid,
self.acc_invalid_ck,
self.acc_no_ck,
self.acc_wait_seconds,
self.acc_missing_cred,
]
)
self.session.commit()
def teardown_method(self):
self.session.close()
def test_lookup_includes_invalid_and_nock_and_reports_unmatched(self):
res = lookup_query_workbench_accounts(
DouyuQueryWorkbenchLookupRequest(
account_names=["dy_invalid", "not_exists", "dy_nock", "dy_valid"]
),
db=self.session,
current=self.admin,
)
assert res["account_ids"] == [
self.acc_invalid_ck.id,
self.acc_no_ck.id,
self.acc_valid.id,
]
assert res["matched_names"] == ["dy_invalid", "dy_nock", "dy_valid"]
assert res["unmatched_names"] == ["not_exists"]
def test_list_accounts_include_all_and_ck_status_filters(self):
default_items = list_task_accounts(
search="",
tag="",
ids="",
account_names="",
page=None,
db=self.session,
current=self.admin,
)
assert {item.username for item in default_items} == {
"dy_valid",
"dy_invalid",
"dy_wait_seconds",
}
all_items = list_task_accounts(
search="",
tag="",
ids="",
account_names="",
include_all=True,
page=None,
db=self.session,
current=self.admin,
)
assert {item.username for item in all_items} == {
"dy_valid",
"dy_invalid",
"dy_nock",
"dy_wait_seconds",
"dy_nocred",
}
invalid_only = list_task_accounts(
search="",
tag="",
ids="",
account_names="",
include_all=True,
ck_status="invalid",
page=None,
db=self.session,
current=self.admin,
)
assert [item.username for item in invalid_only] == ["dy_invalid"]
cooldown_waiting = list_task_accounts(
search="",
tag="",
ids="",
account_names="",
include_all=True,
ck_status="cooldown_waiting",
page=None,
db=self.session,
current=self.admin,
)
assert [item.username for item in cooldown_waiting] == [
"dy_wait_seconds",
"dy_invalid",
]
cooldown_ready = list_task_accounts(
search="",
tag="",
ids="",
account_names="",
include_all=True,
ck_status="cooldown_ready",
page=None,
db=self.session,
current=self.admin,
)
assert [item.username for item in cooldown_ready] == ["dy_valid"]
def test_select_invalid_ids_and_export_csv_order(self):
self.acc_valid.nickname = '=HYPERLINK("https://example.invalid")'
self.session.flush()
desired = [self.acc_no_ck.id, self.acc_valid.id, self.acc_invalid_ck.id]
update_workbench_accounts(
DouyuWorkbenchAccountsUpdate(handbook_scope="query", account_ids=desired),
db=self.session,
current=self.admin,
)
assert (
self.session.query(DouyuWorkbenchAccount)
.filter(DouyuWorkbenchAccount.handbook_scope == "query")
.count()
== 3
)
invalid_res = list_query_workbench_invalid_ids(
db=self.session, current=self.admin
)
assert invalid_res["account_ids"] == [self.acc_no_ck.id, self.acc_invalid_ck.id]
assert invalid_res["invalid_ck_ids"] == [self.acc_invalid_ck.id]
assert invalid_res["no_cookie_ids"] == [self.acc_no_ck.id]
resp = export_query_workbench_csv(
DouyuQueryWorkbenchExportRequest(ids=[]),
db=self.session,
current=self.admin,
)
raw = resp.body.decode("utf-8-sig")
rows = list(csv.reader(io.StringIO(raw)))
assert rows[0][0] == "账号"
assert [r[0] for r in rows[1:]] == ["dy_nock", "dy_valid", "dy_invalid"]
assert rows[2][6] == "有效"
assert rows[2][2] == '\'=HYPERLINK("https://example.invalid")'
assert rows[2][8] == "100"
assert rows[2][10] == "1280"
assert rows[1][12] == "未查询"
assert rows[2][12] == "已开通"
assert rows[2][13].startswith("2030-01-01")
assert rows[3][12] == "已过期"
assert rows[2][17] == "可换绑"
assert rows[3][17] == "冷却中"
# 导出末尾两列区分「导入后的数据」与「一键查询后的数据」
assert rows[0][-2] == "数据来源"
assert rows[2][-2] == "导入未查询"
assert "导入于" in rows[2][-1]
from web.backend.services.douyu_query_workbench import mark_workbench_queried
mark_workbench_queried(self.session, [self.acc_valid.id])
resp = export_query_workbench_csv(
DouyuQueryWorkbenchExportRequest(ids=[self.acc_valid.id]),
db=self.session,
current=self.admin,
)
rows = list(csv.reader(io.StringIO(resp.body.decode("utf-8-sig"))))
assert rows[1][-2] == "已查询"
assert "查询于" in rows[1][-1]
def test_relogin_requires_login_batch_permission(self):
with pytest.raises(HTTPException) as exc:
relogin_query_workbench_invalid_accounts(
DouyuQueryWorkbenchReloginRequest(ids=[self.acc_invalid_ck.id]),
db=self.session,
current=self.support_no_login,
)
assert exc.value.status_code == 403
def test_relogin_splits_batches_skips_inflight_and_uses_manual_category(self):
# 构造一个已在排队登录的账号不应重复入队;valid 账号应跳过;缺凭据账号跳过
acc_queued = Account(
username="dy_queued",
password="pw",
email="q@e.com",
email_password="ep",
cookie="acf_uid=999",
ck_check_status="invalid",
assigned_to=self.support_with_login.id,
)
self.session.add(acc_queued)
self.session.flush()
self.session.add(
LoginTask(
batch_id="existing-pending",
account_id=acc_queued.id,
status="pending",
attempt_status="pending",
created_by=self.admin.id,
)
)
self.session.commit()
budget = get_query_workbench_manual_budget(
db=self.session, current=self.support_with_login
)
assert budget["category"] == CATEGORY_MANUAL
res = relogin_query_workbench_invalid_accounts(
DouyuQueryWorkbenchReloginRequest(
ids=[
self.acc_valid.id,
self.acc_invalid_ck.id,
self.acc_no_ck.id,
self.acc_missing_cred.id,
acc_queued.id,
]
),
db=self.session,
current=self.support_with_login,
)
assert res["success"] is True
assert res["category"] == CATEGORY_MANUAL
assert res["relogin_count"] == 1
assert res["login_count"] == 1
assert res["skipped_valid"] == 1
assert res["skipped_in_flight"] == 1
assert res["skipped_missing_credentials"] == 1
assert len(res["batch_ids"]) == 2
jobs = (
self.session.query(ExecutionJob)
.filter(ExecutionJob.batch_id.in_(res["batch_ids"]))
.all()
)
by_type = {job.job_type: job for job in jobs}
assert set(by_type.keys()) == {JOB_RELOGIN_BATCH, JOB_LOGIN_BATCH}
assert by_type[JOB_RELOGIN_BATCH].payload_json["mode"] == "relogin"
assert by_type[JOB_RELOGIN_BATCH].payload_json["category"] == CATEGORY_MANUAL
assert by_type[JOB_RELOGIN_BATCH].payload_json["trigger_source"] == "manual"
assert by_type[JOB_LOGIN_BATCH].payload_json["mode"] == "login"
assert by_type[JOB_LOGIN_BATCH].payload_json["category"] == CATEGORY_MANUAL
# 重复提交应识别已入队的 ExecutionJob 并拦截重复入队
with pytest.raises(HTTPException) as dup_exc:
relogin_query_workbench_invalid_accounts(
DouyuQueryWorkbenchReloginRequest(
ids=[self.acc_invalid_ck.id, self.acc_no_ck.id]
),
db=self.session,
current=self.support_with_login,
)
assert dup_exc.value.status_code == 400
assert "已在登录队列中" in str(dup_exc.value.detail)
def test_execution_worker_forwards_manual_category_for_relogin_batch(db, monkeypatch):
"""验证 ExecutionJobWorker 执行 JOB_RELOGIN_BATCH 时会透传 payload.category=manual_login。"""
user = User(
username="exec-manual-user",
password_hash="h",
role="super_admin",
is_active=True,
)
db.add(user)
db.commit()
acc = Account(
username="exec-manual-acc",
password="pw",
email="m@e.com",
email_password="ep",
cookie="acf_uid=321",
ck_check_status="invalid",
assigned_to=user.id,
)
db.add(acc)
db.commit()
res = relogin_query_workbench_invalid_accounts(
DouyuQueryWorkbenchReloginRequest(ids=[acc.id]),
db=db,
current=user,
)
job = db.query(ExecutionJob).filter(ExecutionJob.batch_id == res["batch_id"]).one()
worker = execution_worker.ExecutionJobWorker()
claimed = claim_execution_jobs(
lane_scopes=(LANE_AUTH,),
owner=worker._owner,
limit=1,
)
assert [row.id for row in claimed] == [job.id]
captured: dict = {}
class FakeLoginRunner:
def __init__(self, **kwargs):
captured.update(kwargs)
def run(self):
captured["ran"] = True
monkeypatch.setattr(execution_worker, "LoginBatchRunner", FakeLoginRunner)
worker._run_job(int(job.id))
assert captured.get("ran") is True
assert captured.get("mode") == "relogin"
assert captured.get("trigger_source") == "manual"
assert captured.get("category") == CATEGORY_MANUAL
class _MarkTaskHarness(DouyuBatchRunnerCore):
"""只用于驱动 `_mark_task` 的真实实现,绕过构造器里的代理/客户端依赖。"""
def __init__(self, db):
import threading
self.db = db
self.batch_id = "qw-mark-batch"
self.log_queue = None
self.loop = None
self.log_sink = None
self._hook_local = threading.local()
def _push_log(self, *args, **kwargs):
pass
class TestQueryWorkbenchDataState:
"""工作台必须能区分「导入后的数据」和「一键查询后的数据」。"""
def setup_method(self):
self.engine = get_test_engine()
self.session = make_test_session(self.engine)
self.admin = User(username="state-admin", password_hash="h", role="super_admin")
self.session.add(self.admin)
self.session.flush()
self.acc_a = Account(
username="state_a",
uid="9001",
password="pw",
email="a@e.com",
email_password="ep",
cookie="acf_uid=9001",
ck_check_status="valid",
assigned_to=self.admin.id,
)
self.acc_b = Account(
username="state_b",
uid="9002",
password="pw",
email="b@e.com",
email_password="ep",
cookie="acf_uid=9002",
ck_check_status="valid",
assigned_to=self.admin.id,
)
self.acc_nock = Account(
username="state_nock",
uid="",
password="pw",
email="c@e.com",
email_password="ep",
cookie="",
status="imported",
assigned_to=self.admin.id,
)
self.session.add_all([self.acc_a, self.acc_b, self.acc_nock])
self.session.commit()
def teardown_method(self):
self.session.close()
def _rows(self):
return {
int(row.account_id): row
for row in self.session.query(DouyuWorkbenchAccount).all()
}
def test_import_marks_imported_and_resave_preserves_state(self):
res = update_workbench_accounts(
DouyuWorkbenchAccountsUpdate(
handbook_scope="query", account_ids=[self.acc_a.id, self.acc_b.id]
),
db=self.session,
current=self.admin,
)
assert res["imported_account_ids"] == [self.acc_a.id, self.acc_b.id]
rows = self._rows()
assert rows[self.acc_a.id].data_state == "imported"
assert rows[self.acc_a.id].imported_at is not None
# 一键查询成功后应变成 queried
from web.backend.services.douyu_query_workbench import mark_workbench_queried
assert mark_workbench_queried(self.session, [self.acc_a.id]) == 1
rows = self._rows()
assert rows[self.acc_a.id].data_state == "queried"
assert rows[self.acc_a.id].queried_at is not None
# 再次导入新账号(增删集合)不能把已有行的查询状态重置掉
res = update_workbench_accounts(
DouyuWorkbenchAccountsUpdate(
handbook_scope="query",
account_ids=[self.acc_a.id, self.acc_b.id, self.acc_nock.id],
),
db=self.session,
current=self.admin,
)
assert res["imported_account_ids"] == [self.acc_nock.id]
rows = self._rows()
assert rows[self.acc_a.id].data_state == "queried"
assert rows[self.acc_b.id].data_state == "imported"
# 移出账号只删那一行
update_workbench_accounts(
DouyuWorkbenchAccountsUpdate(
handbook_scope="query", account_ids=[self.acc_a.id]
),
db=self.session,
current=self.admin,
)
assert set(self._rows().keys()) == {self.acc_a.id}
def test_pending_ids_excludes_no_cookie_and_filters_by_state(self):
update_workbench_accounts(
DouyuWorkbenchAccountsUpdate(
handbook_scope="query",
account_ids=[self.acc_a.id, self.acc_b.id, self.acc_nock.id],
),
db=self.session,
current=self.admin,
)
from web.backend.services.douyu_query_workbench import mark_workbench_stale
mark_workbench_stale(self.session, [self.acc_b.id])
from web.backend.routers.douyu import list_query_workbench_pending_ids
pending = list_query_workbench_pending_ids(db=self.session, current=self.admin)
assert pending["imported_ids"] == [self.acc_a.id]
assert pending["stale_ids"] == [self.acc_b.id]
assert pending["total"] == 2
stale_items = list_task_accounts(
search="",
tag="",
ids=",".join(
str(acc_id)
for acc_id in (self.acc_a.id, self.acc_b.id, self.acc_nock.id)
),
account_names="",
include_all=True,
workbench_scope="query",
workbench_state="stale",
page=None,
db=self.session,
current=self.admin,
)
assert [item.username for item in stale_items] == ["state_b"]
assert stale_items[0].workbench_data_state == "stale"
assert stale_items[0].workbench_relogin_at is not None
def test_ids_endpoint_supports_workbench_state_filter(self):
"""「一键查询筛选结果」依靠 /accounts/ids 的跨页筛选。"""
from web.backend.routers.douyu import list_task_account_ids
update_workbench_accounts(
DouyuWorkbenchAccountsUpdate(
handbook_scope="query",
account_ids=[self.acc_a.id, self.acc_b.id],
),
db=self.session,
current=self.admin,
)
from web.backend.services.douyu_query_workbench import mark_workbench_queried
mark_workbench_queried(self.session, [self.acc_b.id])
imported_only = list_task_account_ids(
search="",
tag="",
account_names="",
ck_status="",
include_all=True,
workbench_scope="query",
workbench_state="imported",
db=self.session,
current=self.admin,
)
assert imported_only["account_ids"] == [self.acc_a.id]
queried_only = list_task_account_ids(
search="",
tag="",
account_names="",
ck_status="",
include_all=True,
workbench_scope="query",
workbench_state="queried",
db=self.session,
current=self.admin,
)
assert queried_only["account_ids"] == [self.acc_b.id]
with pytest.raises(HTTPException) as exc:
list_task_account_ids(
search="",
tag="",
account_names="",
ck_status="",
include_all=True,
workbench_scope="query",
workbench_state="bogus",
db=self.session,
current=self.admin,
)
assert exc.value.status_code == 400
def test_relogin_marks_account_as_stale(self):
update_workbench_accounts(
DouyuWorkbenchAccountsUpdate(
handbook_scope="query", account_ids=[self.acc_a.id]
),
db=self.session,
current=self.admin,
)
self.acc_a.ck_check_status = "invalid"
self.session.commit()
res = relogin_query_workbench_invalid_accounts(
DouyuQueryWorkbenchReloginRequest(ids=[self.acc_a.id]),
db=self.session,
current=self.admin,
)
assert res["relogin_count"] == 1
row = self._rows()[self.acc_a.id]
assert row.data_state == "stale"
assert row.relogin_at is not None
def test_import_ck_check_skips_non_operable_ids_without_error(self):
"""导入整批传进来时,无 CK / 登录中的账号应被跳过而不是整批报错。"""
from web.backend.routers.douyu import check_task_accounts_ck
# 只传无 CK 账号:可检测集合为空,直接短路返回,不会发真实探测请求
res = check_task_accounts_ck(
ids=str(self.acc_nock.id),
db=self.session,
current=self.admin,
)
assert res["success"] is True
assert res["checked"] == 0
assert res["skipped"] == 1
assert res["results"] == []
def test_query_task_success_marks_queried_and_failure_keeps_state(self):
update_workbench_accounts(
DouyuWorkbenchAccountsUpdate(
handbook_scope="query", account_ids=[self.acc_a.id]
),
db=self.session,
current=self.admin,
)
runner = _MarkTaskHarness(self.session)
failed_task = DouyuTask(
batch_id="qw-mark-failed",
account_id=self.acc_a.id,
task_type="query_assets_and_bind",
handbook_scope="query",
status="running",
message="",
created_by=self.admin.id,
)
self.session.add(failed_task)
self.session.commit()
runner._mark_task(self.session, failed_task, "failed", "接口全失败", {})
assert self._rows()[self.acc_a.id].data_state == "imported"
ok_task = DouyuTask(
batch_id="qw-mark-ok",
account_id=self.acc_a.id,
task_type="query_assets_and_bind",
handbook_scope="query",
status="running",
message="",
created_by=self.admin.id,
)
self.session.add(ok_task)
self.session.commit()
runner._mark_task(self.session, ok_task, "success", "查询成功", {"points": 1})
row = self._rows()[self.acc_a.id]
assert row.data_state == "queried"
assert row.queried_at is not None