feat(fulfillment): 实时刷新斗鱼账号并支持租约时长设置
This commit is contained in:
+12
-4
@@ -147,12 +147,20 @@ def _add_missing_columns(engine: Engine) -> None:
|
||||
for table in Base.metadata.sorted_tables:
|
||||
if not inspector.has_table(table.name):
|
||||
continue
|
||||
existing = {column["name"] for column in inspector.get_columns(table.name)}
|
||||
existing_columns = {
|
||||
column["name"]: column for column in inspector.get_columns(table.name)
|
||||
}
|
||||
for column in table.columns:
|
||||
if column.name in existing:
|
||||
existing = existing_columns.get(column.name)
|
||||
if existing is None:
|
||||
ddl = CreateColumn(column).compile(dialect=engine.dialect)
|
||||
conn.execute(text(f"ALTER TABLE `{table.name}` ADD COLUMN {ddl}"))
|
||||
continue
|
||||
ddl = CreateColumn(column).compile(dialect=engine.dialect)
|
||||
conn.execute(text(f"ALTER TABLE `{table.name}` ADD COLUMN {ddl}"))
|
||||
if bool(existing["nullable"]) != bool(column.nullable):
|
||||
ddl = CreateColumn(column).compile(dialect=engine.dialect)
|
||||
conn.execute(
|
||||
text(f"ALTER TABLE `{table.name}` MODIFY COLUMN {ddl}")
|
||||
)
|
||||
|
||||
|
||||
def init_test_schema(engine: Engine | None = None) -> None:
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
"""斗鱼账号实时状态刷新与生命周期写回测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import cast
|
||||
|
||||
from core.douyu import DouyuActivityClient
|
||||
from web.backend.models import Account
|
||||
from web.backend.services.douyu_account_state import refresh_douyu_account_state
|
||||
|
||||
|
||||
class FakeClient:
|
||||
def acf_ccn(self, *, refresh_subscribe: bool = False):
|
||||
assert refresh_subscribe is False
|
||||
return "csrf"
|
||||
|
||||
def elite_user_info(self, **_kwargs):
|
||||
return {
|
||||
"manual_type": 1,
|
||||
"manual_score": 5200,
|
||||
"expire_time": 1799999999,
|
||||
}
|
||||
|
||||
def query_points(self, **_kwargs):
|
||||
return {
|
||||
"points": 5200,
|
||||
"willExpireTime": 1799999999,
|
||||
}
|
||||
|
||||
def query_limited_goods(self, **_kwargs):
|
||||
return {"limited_goods": [{"commodityId": "limited-goods"}]}
|
||||
|
||||
def bind_info(self, **_kwargs):
|
||||
return {
|
||||
"is_bound_role": False,
|
||||
"role_name": "",
|
||||
"change_role_wait_time": 3600,
|
||||
"area_name": "安卓",
|
||||
"plat_name": "QQ",
|
||||
}
|
||||
|
||||
|
||||
def test_refresh_writes_ck_elite_points_limited_and_bind_lifecycle(db):
|
||||
account = Account(
|
||||
username="refresh-account",
|
||||
password="p",
|
||||
email="refresh@example.com",
|
||||
email_password="ep",
|
||||
status="imported",
|
||||
ck_check_status="",
|
||||
cookie="acf_uid=100; acf_nickname=test",
|
||||
elite_opened=None,
|
||||
points=None,
|
||||
auto_managed=True,
|
||||
)
|
||||
db.add(account)
|
||||
db.commit()
|
||||
|
||||
state = refresh_douyu_account_state(
|
||||
db,
|
||||
account,
|
||||
manual_id="manual",
|
||||
rid="room",
|
||||
act_alias="alias",
|
||||
client=cast(DouyuActivityClient, FakeClient()),
|
||||
cookie_checker=lambda _cookie: {
|
||||
"valid": True,
|
||||
"message": "有效",
|
||||
"fish_ball": 10,
|
||||
"nickname": "测试",
|
||||
"level": 5,
|
||||
"checked_at": datetime.now(UTC),
|
||||
},
|
||||
)
|
||||
|
||||
db.refresh(account)
|
||||
assert state.ck_verdict == "valid"
|
||||
assert state.limited_ids == frozenset({"limited-goods"})
|
||||
assert account.status == "active"
|
||||
assert account.ck_check_status == "valid"
|
||||
assert account.elite_opened is True
|
||||
assert account.points == 5200
|
||||
assert account.role_bind_status == "unbound"
|
||||
assert account.change_role_wait_time == 3600
|
||||
assert account.role_change_available_at is None
|
||||
assert state.role_change_available_at is None
|
||||
assert state.role_change_blocked is False
|
||||
assert account.overview_queried_at is not None
|
||||
assert account.overview_snapshot is not None
|
||||
assert (
|
||||
account.overview_snapshot["limited_goods"][0]["commodityId"] == "limited-goods"
|
||||
)
|
||||
|
||||
|
||||
def test_invalid_ck_writes_lifecycle_without_querying_activity(db):
|
||||
account = Account(
|
||||
username="invalid-account",
|
||||
password="p",
|
||||
email="invalid@example.com",
|
||||
email_password="ep",
|
||||
status="active",
|
||||
ck_check_status="",
|
||||
cookie="acf_uid=100",
|
||||
auto_managed=True,
|
||||
)
|
||||
db.add(account)
|
||||
db.commit()
|
||||
|
||||
state = refresh_douyu_account_state(
|
||||
db,
|
||||
account,
|
||||
manual_id="manual",
|
||||
rid="room",
|
||||
act_alias="alias",
|
||||
client=cast(DouyuActivityClient, FakeClient()),
|
||||
cookie_checker=lambda _cookie: {
|
||||
"valid": False,
|
||||
"message": "未登录",
|
||||
"fish_ball": None,
|
||||
"nickname": None,
|
||||
"level": None,
|
||||
"checked_at": datetime.now(UTC),
|
||||
},
|
||||
)
|
||||
|
||||
db.refresh(account)
|
||||
assert state.ck_verdict == "invalid"
|
||||
assert account.ck_check_status == "invalid"
|
||||
assert account.status == "invalid"
|
||||
assert state.elite_opened is None
|
||||
@@ -35,7 +35,7 @@ TESTS_DIR = Path(__file__).resolve().parent
|
||||
PROJECT_ROOT = TESTS_DIR.parent
|
||||
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
|
||||
|
||||
HEAD_REVISION = "20261117_0084"
|
||||
HEAD_REVISION = "20261117_0085"
|
||||
|
||||
# 迁移新增、但不声明在模型里的复合查询索引。
|
||||
EXTRA_INDEXES = (
|
||||
|
||||
@@ -3,8 +3,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from tests.support.db import get_test_engine, make_test_session
|
||||
from web.backend.models import (
|
||||
@@ -17,7 +19,11 @@ from web.backend.models import (
|
||||
PlatformFulfillmentTask,
|
||||
User,
|
||||
)
|
||||
from web.backend.services.automation.jobs import platform_fulfillment_lease_reaper as reaper
|
||||
from web.backend.services.automation.jobs import (
|
||||
platform_fulfillment_lease_reaper as reaper,
|
||||
)
|
||||
from web.backend.services.douyu_account_state import DouyuLiveAccountState
|
||||
from web.backend.services.douyu_activity_query import DouyuEligibilityResult
|
||||
from web.backend.services.platform_fulfillment import account_selector, service
|
||||
|
||||
NOW = datetime.now(UTC).replace(microsecond=0)
|
||||
@@ -37,10 +43,31 @@ class _Base:
|
||||
self.session.add(self.admin)
|
||||
self.session.commit()
|
||||
self.admin_id = self.admin.id
|
||||
self.refresh_patch = patch.object(
|
||||
service,
|
||||
"refresh_douyu_account_state",
|
||||
side_effect=self._live_state,
|
||||
)
|
||||
self.refresh_mock = self.refresh_patch.start()
|
||||
|
||||
def teardown_method(self):
|
||||
self.refresh_patch.stop()
|
||||
self.session.close()
|
||||
|
||||
@staticmethod
|
||||
def _live_state(_db, account, **_kwargs):
|
||||
return DouyuLiveAccountState(
|
||||
account_id=account.id,
|
||||
account_name=account.username,
|
||||
checked_at=NOW,
|
||||
ck_verdict="valid",
|
||||
ck_message="有效",
|
||||
elite_opened=True,
|
||||
points=account.points or 2000,
|
||||
limited_ids=frozenset(),
|
||||
role_change_available_at=account.role_change_available_at,
|
||||
)
|
||||
|
||||
def account(
|
||||
self,
|
||||
name: str,
|
||||
@@ -216,6 +243,77 @@ class TestSyncAndMapping(_Base):
|
||||
|
||||
|
||||
class TestAccountSelection(_Base):
|
||||
def test_allocation_refreshes_live_state_instead_of_cached_filters(self):
|
||||
account = Account(
|
||||
username="live-refresh-account",
|
||||
password="p",
|
||||
email="live@example.com",
|
||||
email_password="ep",
|
||||
status="imported",
|
||||
ck_check_status="",
|
||||
cookie="PHPSESSID=live",
|
||||
elite_opened=None,
|
||||
points=None,
|
||||
gold_balance=100,
|
||||
auto_managed=True,
|
||||
)
|
||||
self.session.add(account)
|
||||
self.session.commit()
|
||||
task = self.task()
|
||||
|
||||
detail = service.allocate_task(
|
||||
self.session,
|
||||
task_id=task.id,
|
||||
current=self.admin,
|
||||
)
|
||||
|
||||
assert detail["task"]["account"]["id"] == account.id
|
||||
assert detail["task"]["executionStatus"] == "allocated"
|
||||
self.refresh_mock.assert_called()
|
||||
|
||||
def test_points_short_is_soft_and_does_not_block_allocation(self):
|
||||
account = self.account("points-short", points=100)
|
||||
task = self.task()
|
||||
|
||||
detail = service.allocate_task(
|
||||
self.session,
|
||||
task_id=task.id,
|
||||
current=self.admin,
|
||||
)
|
||||
|
||||
assert detail["task"]["account"]["id"] == account.id
|
||||
assert detail["task"]["executionStatus"] == "allocated"
|
||||
assert detail["task"]["exchangeStatus"] == "points_short"
|
||||
assert detail["task"]["issueCode"] == "points_short"
|
||||
|
||||
def test_elite_not_opened_is_soft_and_does_not_block_allocation(self):
|
||||
account = self.account("elite-closed", opened=False)
|
||||
self.refresh_mock.side_effect = lambda _db, row, **_kwargs: (
|
||||
DouyuLiveAccountState(
|
||||
account_id=row.id,
|
||||
account_name=row.username,
|
||||
checked_at=NOW,
|
||||
ck_verdict="valid",
|
||||
ck_message="有效",
|
||||
elite_opened=False,
|
||||
points=2000,
|
||||
limited_ids=frozenset(),
|
||||
role_change_available_at=None,
|
||||
)
|
||||
)
|
||||
task = self.task()
|
||||
|
||||
detail = service.allocate_task(
|
||||
self.session,
|
||||
task_id=task.id,
|
||||
current=self.admin,
|
||||
)
|
||||
|
||||
assert detail["task"]["account"]["id"] == account.id
|
||||
assert detail["task"]["executionStatus"] == "allocated"
|
||||
assert detail["task"]["exchangeStatus"] == "not_opened"
|
||||
assert detail["task"]["issueCode"] == "elite_not_opened"
|
||||
|
||||
def test_eligible_account_excludes_cooldown_and_uses_least_points(self):
|
||||
self.account("small", points=1300)
|
||||
self.account("large", points=9000)
|
||||
@@ -262,7 +360,10 @@ class TestAccountSelection(_Base):
|
||||
|
||||
assert first is not None
|
||||
assert second is None
|
||||
assert self.session.query(AccountLease).filter_by(account_id=account.id).count() == 1
|
||||
assert (
|
||||
self.session.query(AccountLease).filter_by(account_id=account.id).count()
|
||||
== 1
|
||||
)
|
||||
|
||||
def test_allocate_and_release_task(self):
|
||||
account = self.account("allocated")
|
||||
@@ -279,6 +380,7 @@ class TestAccountSelection(_Base):
|
||||
lease = self.session.query(AccountLease).one()
|
||||
assert lease.purpose == "platform_fulfillment"
|
||||
assert lease.status == "active"
|
||||
assert lease.expires_at is None
|
||||
|
||||
released = service.release_task_account(
|
||||
self.session,
|
||||
@@ -289,6 +391,31 @@ class TestAccountSelection(_Base):
|
||||
self.session.refresh(lease)
|
||||
assert lease.status == "released"
|
||||
|
||||
def test_lease_settings_support_unlimited_and_finite_duration(self):
|
||||
self.account("settings-account")
|
||||
task = self.task()
|
||||
service.allocate_task(self.session, task_id=task.id, current=self.admin)
|
||||
lease = self.session.query(AccountLease).one()
|
||||
assert lease.expires_at is None
|
||||
|
||||
finite = service.update_settings(
|
||||
self.session,
|
||||
lease_duration_minutes=90,
|
||||
current=self.admin,
|
||||
)
|
||||
self.session.refresh(lease)
|
||||
assert finite["leaseDurationMinutes"] == 90
|
||||
assert lease.expires_at is not None
|
||||
|
||||
unlimited = service.update_settings(
|
||||
self.session,
|
||||
lease_duration_minutes=None,
|
||||
current=self.admin,
|
||||
)
|
||||
self.session.refresh(lease)
|
||||
assert unlimited["leaseDurationMinutes"] is None
|
||||
assert lease.expires_at is None
|
||||
|
||||
|
||||
class TestBindingAndCompletion(_Base):
|
||||
def _allocated(self):
|
||||
@@ -366,6 +493,38 @@ class TestBindingAndCompletion(_Base):
|
||||
lease = self.session.query(AccountLease).one()
|
||||
assert lease.status == "released"
|
||||
|
||||
def test_points_short_after_binding_keeps_account_and_stays_bound(
|
||||
self, monkeypatch
|
||||
):
|
||||
task = self._allocated()
|
||||
account = (
|
||||
self.session.query(Account).filter(Account.id == task.account_id).one()
|
||||
)
|
||||
task.binding_status = "bound"
|
||||
task.execution_status = "bound"
|
||||
self.session.commit()
|
||||
monkeypatch.setattr(
|
||||
service,
|
||||
"query_exchange_eligibility",
|
||||
lambda *_args, **_kwargs: DouyuEligibilityResult(
|
||||
elite_user_info={"manual_type": 1},
|
||||
points=100,
|
||||
points_response={"points": 100},
|
||||
limited_goods=[],
|
||||
limited_ids=frozenset(),
|
||||
),
|
||||
)
|
||||
|
||||
detail = service.refresh_exchange_eligibility(
|
||||
self.session,
|
||||
task_id=task.id,
|
||||
current=self.admin,
|
||||
)
|
||||
|
||||
assert detail["task"]["executionStatus"] == "bound"
|
||||
assert detail["task"]["exchangeStatus"] == "points_short"
|
||||
assert detail["task"]["account"]["id"] == account.id
|
||||
|
||||
def test_expired_lease_moves_unfinished_task_to_manual(self):
|
||||
task = self._allocated()
|
||||
lease = self.session.query(AccountLease).one()
|
||||
@@ -384,6 +543,23 @@ class TestBindingAndCompletion(_Base):
|
||||
assert task.execution_status == "manual_required"
|
||||
assert task.issue_code == "lease_expired"
|
||||
|
||||
def test_unlimited_lease_is_ignored_by_reaper(self):
|
||||
task = self._allocated()
|
||||
lease = self.session.query(AccountLease).one()
|
||||
lease.expires_at = None
|
||||
self.session.commit()
|
||||
|
||||
job = AutomationJob(key=reaper.JOB_KEY, batch_size=100)
|
||||
result = reaper.run_platform_fulfillment_lease_reaper(
|
||||
self.session,
|
||||
job,
|
||||
now=NOW + timedelta(days=365),
|
||||
)
|
||||
|
||||
self.session.refresh(task)
|
||||
assert result["expired"] == 0
|
||||
assert task.execution_status == "allocated"
|
||||
|
||||
def test_completion_rejects_limited_exchange(self):
|
||||
task = self._allocated()
|
||||
task.binding_status = "bound"
|
||||
@@ -391,7 +567,7 @@ class TestBindingAndCompletion(_Base):
|
||||
task.exchange_status = "limited"
|
||||
self.session.commit()
|
||||
|
||||
with pytest.raises(Exception):
|
||||
with pytest.raises(HTTPException):
|
||||
service.complete_manual_exchange(
|
||||
self.session,
|
||||
task_id=task.id,
|
||||
|
||||
Reference in New Issue
Block a user