"""直播账号履约服务端集成接口测试。""" from __future__ import annotations import asyncio from datetime import UTC, datetime, timedelta import pytest from fastapi import HTTPException from starlette.requests import ClientDisconnect from web.backend.models import ( Account, AccountLease, DouyuTask, PlatformFulfillmentTask, User, ) from web.backend.routers.platform_fulfillment_integration import ( require_integration_key, sync_order_event, ) from web.backend.services.platform_fulfillment import service def test_integration_key_is_required(monkeypatch): monkeypatch.setenv("PLATFORM_FULFILLMENT_INTEGRATION_KEY", "secret") require_integration_key("secret") with pytest.raises(HTTPException) as missing: require_integration_key("") with pytest.raises(HTTPException) as invalid: require_integration_key("wrong") assert missing.value.status_code == 401 assert invalid.value.status_code == 401 def test_webhook_client_disconnect_is_not_an_application_error(monkeypatch): monkeypatch.setenv("PLATFORM_FULFILLMENT_INTEGRATION_KEY", "secret") class DisconnectingRequest: async def body(self): raise ClientDisconnect() result = asyncio.run( sync_order_event( request=DisconnectingRequest(), db=object(), x_integration_key="secret", x_integration_event_id="", x_integration_timestamp="", x_integration_signature="", ) ) assert result == { "fetched": 0, "created": 0, "updated": 0, "disconnected": True, } def test_customer_binding_out_hides_internal_account_data(db): user = User( username="integration-actor", password_hash="h", role="super_admin", is_active=True, ) account = Account( username="internal-douyu-account", password="p", email="internal@example.com", email_password="ep", cookie="secret-cookie", ) db.add_all([user, account]) db.flush() lease = AccountLease( account_id=account.id, holder_user_id=user.id, purpose="platform_fulfillment", status="active", ) bind = DouyuTask( batch_id="bind", account_id=account.id, account_assigned_to=user.id, task_type="get_bind_qr", handbook_scope="elite", status="running", message="等待扫码", result={ "url": "https://livenlink.example/private-qr-token", "bind_phase": "waiting_scan", "qr_generated_at": datetime.now(UTC).isoformat(), "qr_expires_at": (datetime.now(UTC) + timedelta(minutes=10)).isoformat(), }, created_by=user.id, ) db.add_all([lease, bind]) db.flush() task = PlatformFulfillmentTask( source_system="order_site", source_order_id="order-1", source_order_item_id="item-1", platform_order_id="DY-001", sku_name="斗鱼精英宝典", quantity=1, account_id=account.id, lease_id=lease.id, bind_task_id=bind.id, binding_status="qr_pending", execution_status="waiting_bind", ) db.add(task) db.commit() payload = service.customer_binding_out(db, task.id) assert payload["sessionId"] == task.id assert payload["qrUrl"] == "https://livenlink.example/private-qr-token" assert payload["accountReady"] is True assert "account" not in payload assert "cookie" not in payload assert "points" not in payload assert "lease" not in payload batch = service.customer_refresh_bindings(db, task_ids=[task.id, 999999]) assert [item["sessionId"] for item in batch["items"]] == [task.id] assert batch["items"][0]["qrUrl"] == "https://livenlink.example/private-qr-token" def test_binding_qr_expiry_uses_customer_ttl(): now = datetime.now(UTC) task = DouyuTask( batch_id="expired", account_id=1, account_assigned_to=1, task_type="get_bind_qr", handbook_scope="elite", status="success", message="", result={ "qr_expires_at": (now - timedelta(seconds=1)).isoformat(), }, created_by=1, ) task.created_at = now - timedelta(minutes=5) assert service._binding_qr_expired(task, now=now) is True def test_auto_order_sync_is_throttled(monkeypatch): calls: list[int] = [] monkeypatch.setattr( service.order_sync, "_AUTO_SYNC_LAST_ATTEMPT", float("-inf"), ) monkeypatch.setattr( service.order_sync, "sync_pending_tasks", lambda _db, *, limit: calls.append(limit) or {"fetched": 1}, ) assert service.sync_pending_tasks_if_due(object(), limit=100, now=100.0) == { "fetched": 1 } assert service.sync_pending_tasks_if_due(object(), limit=100, now=110.0) is None assert service.sync_pending_tasks_if_due(object(), limit=100, now=999.0) is None assert service.sync_pending_tasks_if_due(object(), limit=100, now=1000.0) == { "fetched": 1 } assert calls == [100, 100] def test_emit_binding_state_allows_a_b_a_and_skips_same_hash(db): from web.backend.models import IntegrationOutbox from web.backend.services.platform_fulfillment import binding, outbox task = PlatformFulfillmentTask( source_system="order_site", source_order_id="order-aba", source_order_item_id="item-aba", platform_order_id="DY-ABA-1", sku_name="斗鱼精英宝典", quantity=1, flow_version=binding.FLOW_VERSION_CLEAN, binding_status="unallocated", execution_status="pending", ) db.add(task) db.commit() assert outbox._emit_order_site_binding_state(db, task.id) is True db.commit() db.refresh(task) assert task.state_version == 1 assert task.last_emitted_state_hash assert outbox._emit_order_site_binding_state(db, task.id) is False assert ( db.query(IntegrationOutbox) .filter(IntegrationOutbox.dedupe_key.like(f"binding-state:{task.id}:%")) .count() == 1 ) task.binding_status = "qr_pending" db.flush() assert outbox._emit_order_site_binding_state(db, task.id) is True task.binding_status = "unallocated" db.flush() assert outbox._emit_order_site_binding_state(db, task.id) is True db.commit() db.refresh(task) assert task.state_version == 3 keys = [ row.dedupe_key for row in db.query(IntegrationOutbox) .filter(IntegrationOutbox.dedupe_key.like(f"binding-state:{task.id}:%")) .order_by(IntegrationOutbox.id.asc()) .all() ] assert keys == [ f"binding-state:{task.id}:v1", f"binding-state:{task.id}:v2", f"binding-state:{task.id}:v3", ] def test_reconcile_binding_state_outbox_skips_legacy_and_unchanged_clean_tasks(db): from web.backend.models import IntegrationOutbox from web.backend.services.platform_fulfillment import binding, common, views legacy = PlatformFulfillmentTask( source_system="order_site", source_order_id="order-legacy", source_order_item_id="item-legacy", platform_order_id="DY-LEGACY-1", sku_name="斗鱼精英宝典", quantity=1, flow_version=common.FLOW_VERSION_LEGACY, binding_status="unallocated", execution_status="pending", ) unchanged = PlatformFulfillmentTask( source_system="order_site", source_order_id="order-clean-ok", source_order_item_id="item-clean-ok", platform_order_id="DY-CLEAN-OK", sku_name="斗鱼精英宝典", quantity=1, flow_version=binding.FLOW_VERSION_CLEAN, binding_status="unallocated", execution_status="pending", state_version=1, ) drifted = PlatformFulfillmentTask( source_system="order_site", source_order_id="order-clean-drift", source_order_item_id="item-clean-drift", platform_order_id="DY-CLEAN-DRIFT", sku_name="斗鱼精英宝典", quantity=1, flow_version=binding.FLOW_VERSION_CLEAN, binding_status="qr_pending", execution_status="waiting_bind", state_version=1, last_emitted_state_hash="outdated-hash", ) db.add_all([legacy, unchanged, drifted]) db.flush() unchanged.last_emitted_state_hash = binding.binding_state_hash( views.customer_binding_out(db, unchanged.id) ) db.commit() result = service.reconcile_binding_state_outbox(db, limit=100) assert result["queued"] == 1 queued_keys = { row.dedupe_key for row in db.query(IntegrationOutbox).all() } assert f"binding-state:{drifted.id}:v2" in queued_keys assert not any(k.startswith(f"binding-state:{legacy.id}:") for k in queued_keys) assert not any(k.startswith(f"binding-state:{unchanged.id}:") for k in queued_keys) def test_load_supply_snapshot_inventories_allows_stale_snapshots(db, monkeypatch): from web.backend.models import AccountSupplySnapshot, AccountSupplyTarget from web.backend.services import account_observability, account_supply_service target = AccountSupplyTarget( platform="douyu", scope="elite", commodity_id="", value_class="normal", target_covered=10, target_available=5, target_allocatable=5, safety_buffer=1, enabled=True, ) db.add(target) db.flush() stale_at = (datetime.now(UTC) - timedelta(hours=2)).replace(microsecond=0) snapshot = AccountSupplySnapshot( target_id=target.id, covered=12, available=7, allocatable=6, checked_at=stale_at, ) db.add(snapshot) db.commit() def _boom(*_args, **_kwargs): raise AssertionError("stale HTTP snapshot read must not recompute supply") monkeypatch.setattr(account_supply_service, "refresh_supply_snapshots", _boom) monkeypatch.setattr(account_supply_service, "evaluate_supply_targets", _boom) inventories = account_supply_service.load_supply_snapshot_inventories( db, allow_stale_snapshots=True, ) assert len(inventories) == 1 assert inventories[0].covered == 12 assert inventories[0].available == 7 assert inventories[0].allocatable == 6 assert inventories[0].is_stale is True assert inventories[0].checked_at == stale_at http_snapshot = account_observability.account_supply_snapshot(db) assert http_snapshot["is_stale"] is True assert http_snapshot["checked_at"] == stale_at assert any( alert.get("code") == "supply_snapshot_stale" for alert in http_snapshot["alerts"] ) def test_cross_db_lookup_telemetry_and_cached_task_count(db): from web.backend.services import account_observability, external_order_source from web.backend.services.platform_fulfillment import views before = external_order_source.get_cross_db_lookup_counts().get("item_lookup", 0) external_order_source._record_cross_db_lookup("item_lookup", "sample") after = external_order_source.get_cross_db_lookup_counts().get("item_lookup", 0) assert after == before + 1 status = account_observability.account_platform_status( db, include_trends=False, include_supply=False, include_diagnostics=True, ) assert status["cross_db_lookups"]["item_lookup"] == after task = PlatformFulfillmentTask( source_system="order_site", source_order_id="order-count", source_order_item_id="item-count", platform_order_id="DY-COUNT-1", sku_name="斗鱼精英宝典", quantity=1, ) db.add(task) db.commit() views.invalidate_task_list_count_cache() total = views._cached_task_count( db, db.query(PlatformFulfillmentTask), key=("unit", "all"), ) assert total >= 1 def test_publish_after_commit_only_fires_on_commit(db, monkeypatch): from web.backend.services.platform_fulfillment import events published: list[tuple[str, str, int | None]] = [] monkeypatch.setattr( events.platform_fulfillment_events, "publish", lambda *, scope, action, actor_id=None: published.append( (scope, action, actor_id) ) or {}, ) events.publish_after_commit(db, scope="tasks", action="rollback_no_sql") assert published == [] db.rollback() assert published == [] db.add( PlatformFulfillmentTask( source_system="order_site", source_order_id="order-rb", source_order_item_id="item-rb", platform_order_id="DY-RB-1", sku_name="斗鱼精英宝典", quantity=1, ) ) db.flush() events.publish_after_commit(db, scope="tasks", action="rollback_with_sql") db.rollback() assert published == [] events.publish_after_commit(db, scope="tasks", action="commit_test", actor_id=7) db.flush() assert published == [] db.commit() assert published == [("tasks", "commit_test", 7)]