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

347 lines
10 KiB
Python

"""账号供给库存与定向补货测试。"""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from web.backend.models import (
Account,
AccountCommodityState,
AccountEvent,
AccountLease,
AccountSupplyTarget,
AccountSyncRun,
AccountSyncState,
AccountWorkItem,
LoginAttempt,
User,
)
from web.backend.routers.douyu import create_supply_target, list_supply_targets
from web.backend.schemas import DouyuSupplyTargetUpsert
from web.backend.services.account_observability import account_platform_status
from web.backend.services.account_supply_service import (
VALUE_HIGH,
enqueue_supply_replenishment,
ensure_default_supply_targets,
evaluate_supply_target,
upsert_supply_target,
)
from web.backend.services.account_work_queue import enqueue_account_work
NOW = datetime.now(UTC).replace(microsecond=0)
def _account(name: str, *, 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="valid",
ck_checked_at=NOW,
status="active",
auto_managed=True,
points=points,
)
def _state(account: Account, commodity_id: str = "C") -> AccountCommodityState:
return AccountCommodityState(
account_id=account.id,
platform="douyu",
scope="elite",
commodity_id=commodity_id,
availability="available",
observed_at=NOW,
valid_until=NOW + timedelta(hours=1),
available_from=NOW - timedelta(hours=1),
available_until=NOW + timedelta(hours=1),
)
def test_supply_inventory_separates_available_and_allocatable(db):
user = User(
username="supply-owner",
password_hash="h",
role="super_admin",
is_active=True,
)
first = _account("supply-free", points=400)
leased = _account("supply-leased", points=400)
db.add_all([user, first, leased])
db.flush()
db.add_all(
[
_state(first),
_state(leased),
AccountLease(
account_id=leased.id,
holder_user_id=user.id,
scope="elite",
purpose="platform_fulfillment",
status="active",
),
AccountSupplyTarget(
platform="douyu",
scope="elite",
commodity_id="C",
value_class=VALUE_HIGH,
target_covered=2,
target_available=2,
target_allocatable=2,
),
]
)
db.commit()
target = db.query(AccountSupplyTarget).one()
inventory = evaluate_supply_target(db, target, now=NOW)
assert inventory.covered == 2
assert inventory.available == 2
assert inventory.allocatable == 1
assert inventory.allocatable_shortage == 1
assert inventory.needs_replenishment is True
def test_supply_shortage_enqueues_missing_coverage(db):
account = _account("supply-missing", points=400)
db.add(account)
db.flush()
db.add(
AccountSupplyTarget(
platform="douyu",
scope="elite",
commodity_id="C",
value_class=VALUE_HIGH,
target_covered=1,
target_available=1,
target_allocatable=0,
)
)
db.commit()
result = enqueue_supply_replenishment(db, now=NOW, max_per_target=10)
work = db.query(AccountWorkItem).one()
assert result.targets == 1
assert result.shortages == 1
assert result.queued == 1
assert work.account_id == account.id
assert work.work_type == "storehome_sync"
assert work.priority == 35
def test_supply_target_configuration_is_idempotent(db):
first = upsert_supply_target(
db,
scope="elite",
commodity_id="C",
value_class=VALUE_HIGH,
target_covered=100,
target_available=80,
target_allocatable=50,
safety_buffer=10,
enabled=True,
updated_by=None,
)
second = upsert_supply_target(
db,
scope="elite",
commodity_id="C",
value_class=VALUE_HIGH,
target_covered=120,
target_available=90,
target_allocatable=60,
safety_buffer=15,
enabled=False,
updated_by=None,
)
assert second.id == first.id
assert db.query(AccountSupplyTarget).count() == 1
assert second.target_covered == 120
assert second.target_available == 90
assert second.target_allocatable == 60
assert second.safety_buffer == 15
assert second.enabled is False
def test_default_supply_targets_are_seeded_once(db, monkeypatch):
monkeypatch.setenv("DOUYU_DEFAULT_SUPPLY_TARGETS_ENABLED", "true")
assert ensure_default_supply_targets(db) == 2
assert ensure_default_supply_targets(db) == 0
targets = (
db.query(AccountSupplyTarget)
.order_by(AccountSupplyTarget.value_class.asc())
.all()
)
assert [row.value_class for row in targets] == ["high_value", "ordinary"]
assert all(row.scope == "elite" for row in targets)
assert all(row.enabled for row in targets)
def test_default_supply_targets_can_be_disabled(db, monkeypatch):
monkeypatch.setenv("DOUYU_DEFAULT_SUPPLY_TARGETS_ENABLED", "false")
assert ensure_default_supply_targets(db) == 0
assert db.query(AccountSupplyTarget).count() == 0
def test_supply_target_configuration_route_returns_inventory(db):
user = User(
username="supply-config-admin",
password_hash="h",
role="super_admin",
is_active=True,
)
db.add(user)
db.commit()
created = create_supply_target(
DouyuSupplyTargetUpsert(
scope="elite",
commodity_id="C",
value_class=VALUE_HIGH,
target_covered=10,
target_available=8,
target_allocatable=5,
safety_buffer=2,
),
db=db,
current=user,
)
listed = list_supply_targets(db=db, current=user)
assert created.id > 0
assert created.covered_shortage == 12
assert listed[0].id == created.id
assert listed[0].needs_replenishment is True
def test_account_platform_status_aggregates_queue_sync_and_supply(db):
account = _account("platform-status", points=400)
account.ck_expected_expires_at = NOW + timedelta(hours=12)
db.add(account)
db.flush()
db.add_all(
[
_state(account),
AccountSyncState(
account_id=account.id,
platform="douyu",
domain="storehome",
status="success",
last_success_at=NOW,
valid_until=NOW + timedelta(hours=1),
),
AccountSupplyTarget(
platform="douyu",
scope="elite",
commodity_id="C",
value_class=VALUE_HIGH,
target_covered=2,
target_available=2,
target_allocatable=1,
),
]
)
enqueue_account_work(
db,
account_id=account.id,
work_type="login_relogin",
)
db.commit()
status = account_platform_status(db, now=NOW)
assert status["accounts"]["ck_valid"] == 1
assert status["accounts"]["ck_expiring_24h"] == 1
assert status["work_queue"]["login_relogin"]["pending"] == 1
assert status["sync_domains"]["storehome"]["fresh"] == 1
assert status["commodities"]["fresh_available"] == 1
assert status["supply_targets"][0]["covered_shortage"] == 1
assert status["supply_targets"][0]["target_available"] == 2
assert {
alert["code"] for alert in status["alerts"]
} >= {"supply_shortage", "ck_expiring_24h"}
def test_account_platform_status_builds_seven_day_trends(db):
account = _account("platform-trends", points=400)
db.add(account)
db.flush()
db.add_all(
[
AccountSyncRun(
account_id=account.id,
domain="storehome",
started_at=NOW,
finished_at=NOW,
status="success",
duration_ms=120,
),
AccountSyncRun(
account_id=account.id,
domain="role",
started_at=NOW,
finished_at=NOW,
status="failed",
duration_ms=300,
),
LoginAttempt(
account_id=account.id,
category="manual_login",
trigger_source="manual",
started_at=NOW,
finished_at=NOW,
status="success",
quota_day=NOW.date(),
),
LoginAttempt(
account_id=account.id,
category="relogin_ordinary",
trigger_source="system",
started_at=NOW,
finished_at=NOW,
status="failed",
failure_kind="captcha",
quota_day=NOW.date(),
),
AccountEvent(
account_id=account.id,
event_type="ck_invalid",
category="auth",
occurred_at=NOW,
title="CK 失效",
source="pytest",
actor_type="system",
source_ref=f"pytest-trend:{account.id}",
),
]
)
db.commit()
status = account_platform_status(db, now=NOW)
today = NOW.date().isoformat()
query_today = next(row for row in status["trends"]["query"] if row["date"] == today)
login_today = next(row for row in status["trends"]["login"] if row["date"] == today)
lifecycle_today = next(
row for row in status["trends"]["lifecycle"] if row["date"] == today
)
assert status["trends"]["days"] == 7
assert query_today["total"] == 2
assert query_today["success"] == 1
assert query_today["failed"] == 1
assert query_today["success_rate"] == 50.0
assert "storehome" in query_today["domains"]
assert login_today["success"] == 1
assert login_today["failed"] == 1
assert login_today["success_rate"] == 50.0
assert lifecycle_today["ck_invalid"] == 1