Files
live-hub-py/tests/test_account_protection_service.py
T

340 lines
9.6 KiB
Python

"""履约保护账号的动态成员、目标和巡检/重登优先级测试。"""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from web.backend.models import (
Account,
AutomationJob,
DouyuExternalOrder,
PlatformFulfillmentTask,
User,
)
from web.backend.routers.douyu import update_account_protection_target
from web.backend.schemas import DouyuAccountProtectionTargetUpdate
from web.backend.services.account_observability import account_platform_status
from web.backend.services.account_protection_service import (
PROTECTION_CONFIG_KEY,
evaluate_protection_targets,
load_protection_snapshot,
update_protection_group,
)
from web.backend.services.automation.jobs import ck_health, ck_relogin
NOW = datetime.now(UTC).replace(microsecond=0)
def _account(
name: str,
*,
ck_status: str = "valid",
checked_at: datetime | None = None,
points: int = 0,
) -> Account:
return Account(
username=name,
password="p",
email=f"{name}@example.com",
email_password="ep",
cookie="acf_uid=100",
cookie_updated_at=NOW,
ck_check_status=ck_status,
ck_checked_at=checked_at or NOW,
status="active",
auto_managed=True,
points=points,
)
def _presale_task(account: Account, *, execution_status: str = "bound") -> PlatformFulfillmentTask:
return PlatformFulfillmentTask(
source_order_id=f"order-{account.id or account.username}",
source_order_item_id=f"item-{account.id or account.username}",
sale_mode="presale",
account_id=account.id,
binding_status=(
"bound" if execution_status not in {"completed", "cancelled"} else "not_started"
),
execution_status=execution_status,
)
def _collab_order(
account: Account,
*,
order_no: str | None = None,
status: str = "incomplete",
archived_at: datetime | None = None,
) -> DouyuExternalOrder:
return DouyuExternalOrder(
order_no=order_no or f"collab-{account.username}",
account_id=account.id,
account_username=account.username,
status=status,
archived_at=archived_at,
)
def _health_job(config: dict | None = None) -> AutomationJob:
return AutomationJob(
key=ck_health.JOB_KEY,
interval_seconds=6 * 3600,
batch_size=200,
concurrency=3,
config=config,
)
def test_protection_membership_uses_active_fulfillment_relationships(db):
shared = _account("protection-shared")
presale_only = _account("protection-presale")
collab_only = _account("protection-collab")
finished = _account("protection-finished")
db.add_all([shared, presale_only, collab_only, finished])
db.flush()
db.add_all(
[
_presale_task(shared),
_presale_task(presale_only),
_presale_task(finished, execution_status="completed"),
_collab_order(shared),
_collab_order(collab_only),
_collab_order(finished, status="done"),
_collab_order(
finished,
order_no="collab-finished-archived",
archived_at=NOW,
),
]
)
db.commit()
snapshot = load_protection_snapshot(db, job_config=None)
assert snapshot.group_account_ids["presale_bound"] == frozenset(
{shared.id, presale_only.id}
)
assert snapshot.group_account_ids["collab_bound"] == frozenset(
{shared.id, collab_only.id}
)
assert snapshot.monitored_ids == frozenset(
{shared.id, presale_only.id, collab_only.id}
)
def test_protection_target_reports_ck_health_and_shortage(db):
valid = _account("protection-valid")
invalid = _account("protection-invalid", ck_status="invalid")
db.add_all([valid, invalid])
db.flush()
db.add_all([_presale_task(valid), _presale_task(invalid)])
job = _health_job(
{
PROTECTION_CONFIG_KEY: {
"presale_bound": {
"enabled": True,
"target_count": 3,
"probe_interval_minutes": 30,
"auto_relogin": True,
}
}
}
)
db.add(job)
db.commit()
rows = evaluate_protection_targets(db, job_config=job.config, now=NOW)
presale = next(row for row in rows if row["group_key"] == "presale_bound")
status = account_platform_status(db, now=NOW)
assert presale["bound_count"] == 2
assert presale["ck_valid"] == 1
assert presale["ck_invalid"] == 1
assert presale["target_shortage"] == 2
assert presale["needs_attention"] is True
assert {
alert["code"] for alert in status["alerts"]
} >= {
"account_protection_ck_affected",
"account_protection_target_shortage",
}
def test_protection_target_counts_missing_cookie_without_full_account_load(db):
account = _account("protection-no-cookie")
account.cookie = ""
db.add(account)
db.flush()
db.add(_presale_task(account))
db.add(_health_job())
db.commit()
rows = evaluate_protection_targets(db, now=NOW)
presale = next(row for row in rows if row["group_key"] == "presale_bound")
assert presale["bound_count"] == 1
assert presale["without_cookie"] == 1
def test_ck_health_probes_protected_account_at_its_shorter_interval_first(db):
protected = _account(
"protection-due",
checked_at=NOW - timedelta(minutes=90),
)
regular_due = _account(
"protection-regular-due",
checked_at=NOW - timedelta(days=2),
)
regular_due.points = None
regular_due.gold_balance = 0
regular_due.elite_opened = False
regular_due.overview_queried_at = NOW
regular_fresh = _account(
"protection-regular-fresh",
checked_at=NOW - timedelta(minutes=30),
)
db.add_all([protected, regular_due, regular_fresh])
db.flush()
db.add(_presale_task(protected))
job = _health_job(
{
PROTECTION_CONFIG_KEY: {
"presale_bound": {
"enabled": True,
"target_count": 1,
"probe_interval_minutes": 60,
"auto_relogin": True,
}
}
}
)
db.add(job)
db.commit()
selected = ck_health._select_accounts(db, job, NOW)
assert [account.id for account in selected] == [protected.id, regular_due.id]
def test_ck_relogin_prioritizes_protected_invalid_account(db):
protected = _account(
"protection-relogin-first",
ck_status="invalid",
)
high_value = _account(
"protection-high-value",
ck_status="invalid",
points=1000,
)
db.add_all([protected, high_value])
db.flush()
db.add(_presale_task(protected))
db.add(_health_job())
relogin_job = AutomationJob(
key=ck_relogin.JOB_KEY,
interval_seconds=6 * 3600,
batch_size=2,
concurrency=1,
)
db.commit()
selected = ck_relogin.build_select_query(
db,
relogin_job,
NOW,
batch_limit=2,
).all()
assert [account.id for account in selected] == [protected.id, high_value.id]
def test_ck_relogin_can_be_disabled_for_a_protection_group(db):
protected = _account("protection-no-auto-relogin", ck_status="invalid")
ordinary = _account("protection-ordinary-auto-relogin", ck_status="invalid")
db.add_all([protected, ordinary])
db.flush()
db.add(_presale_task(protected))
db.add(
_health_job(
{
PROTECTION_CONFIG_KEY: {
"presale_bound": {
"enabled": True,
"target_count": 1,
"probe_interval_minutes": 60,
"auto_relogin": False,
}
}
}
)
)
relogin_job = AutomationJob(
key=ck_relogin.JOB_KEY,
interval_seconds=6 * 3600,
batch_size=10,
concurrency=1,
)
db.commit()
selected = ck_relogin.build_select_query(
db,
relogin_job,
NOW,
batch_limit=10,
).all()
assert [account.id for account in selected] == [ordinary.id]
def test_update_protection_group_preserves_other_job_config(db):
job = _health_job({"unrelated": {"keep": True}})
db.add(job)
db.commit()
updated, groups = update_protection_group(
db,
group_key="collab_bound",
enabled=False,
target_count=25,
probe_interval_minutes=90,
auto_relogin=False,
)
db.commit()
assert updated.config["unrelated"] == {"keep": True}
assert groups["collab_bound"]["target_count"] == 25
assert updated.config[PROTECTION_CONFIG_KEY]["collab_bound"]["enabled"] is False
def test_protection_target_update_route_returns_current_status(db):
user = User(
username="protection-admin",
password_hash="h",
role="super_admin",
is_active=True,
)
account = _account("protection-route")
db.add_all([user, account])
db.flush()
db.add_all([_presale_task(account), _health_job()])
db.commit()
result = update_account_protection_target(
"presale_bound",
DouyuAccountProtectionTargetUpdate(
enabled=True,
target_count=5,
probe_interval_minutes=45,
auto_relogin=True,
),
db=db,
current=user,
)
assert result["group_key"] == "presale_bound"
assert result["bound_count"] == 1
assert result["target_count"] == 5
assert result["target_shortage"] == 4
assert result["probe_interval_minutes"] == 45