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

125 lines
3.3 KiB
Python

"""账号供给库存与定向补货测试。"""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from web.backend.models import (
Account,
AccountCommodityState,
AccountLease,
AccountSupplyTarget,
AccountWorkItem,
User,
)
from web.backend.services.account_supply_service import (
VALUE_HIGH,
enqueue_supply_replenishment,
evaluate_supply_target,
)
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