Files
syops/backend/tests/test_rpa_worker_heartbeat.py
T
hugo 9adb3ec077 fix(schedule): 收料 RPA 超时对账迁至每轮 tick 并按笔间静默判活
- 修复收料 run 卡「执行中」5 天:超时回收从 worker 启动一次性分支迁到每轮领取维护,长驻进程期间超时 run 不再永不终态
- 超时判据换为最后活动锚(笔间静默):补记单元 started_at,worker 每开始/完成一笔推进锚点,健康长批次不被误杀
- 心跳哨兵口径统一:库存与收料均要求共享哨兵
- 同步排程与心跳测试、worker 启动脚本、四份文档
2026-10-07 09:56:31 +08:00

585 lines
25 KiB
Python

"""
backend/tests/test_rpa_worker_heartbeat.py
用途:货代库存/上传 RPA Worker 心跳存储、共享目录校验、就绪检查与 API 契约单测。
依赖:rpa_worker_heartbeat、shipping_notice_tools heartbeat 路由。
逻辑:覆盖跨平台 scope、哨兵、Redis 策略、环境匹配、货代上传就绪与 fail-fast 断言。
"""
from __future__ import annotations
from datetime import datetime, timezone
from typing import Any
import pytest
from app.core.errors import ServiceUnavailableError
from app.services.shipping_notice.rpa_worker_heartbeat import (
FREIGHT_UPLOAD_CAPABILITY,
INVENTORY_EXPORT_CAPABILITY,
RECEIPT_EXPORT_CAPABILITY,
RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE,
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
RPA_WORKER_OFFLINE_MESSAGE,
assert_freight_upload_rpa_ready,
assert_inventory_rpa_worker_ready,
check_freight_upload_rpa_ready,
check_inventory_rpa_worker_ready,
record_rpa_worker_heartbeat,
resolve_backend_rpa_environment,
shared_sentinel_name,
)
def _write_shared_sentinel(trigger_dir, *, scope_id: str, host: str = "WIN-RPA") -> None:
body = "\n".join([
f"scope_id={scope_id}",
f"updated_at={datetime.now(timezone.utc).replace(tzinfo=None).isoformat()}",
f"host={host}",
])
(trigger_dir / shared_sentinel_name()).write_text(body + "\n", encoding="utf-8")
def _heartbeat_payload(
*,
worker_id: str = "win-rpa-1",
trigger_dir: str,
environment: str | None = None,
capabilities: list[str] | None = None,
shared_scope_id: str | None = None,
timestamp: str | None = None,
) -> dict:
return {
"worker_id": worker_id,
"hostname": "WIN-RPA-HOST",
"environment": environment or resolve_backend_rpa_environment(),
"capabilities": capabilities or [INVENTORY_EXPORT_CAPABILITY],
"status": "idle",
"trigger_dir": trigger_dir,
"drop_dir": str(trigger_dir).replace("triggers", "drop"),
"shared_scope_id": shared_scope_id or "",
"version": "test",
"timestamp": timestamp or datetime.now(timezone.utc).replace(tzinfo=None).isoformat(),
}
def _enable_prod_like_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-data"):
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
_write_shared_sentinel(trigger_dir, scope_id=scope_id)
app.config["ENV_NAME"] = "test"
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
return trigger_dir
def test_cross_platform_paths_ready_with_shared_scope_id(app, tmp_path):
"""Windows 与 Ubuntu 路径不同但 shared_scope_id 一致时应 ready。"""
trigger_dir = _enable_prod_like_checks(app, tmp_path)
windows_trigger = r"C:\HxopsRpaTest\data\inventory_triggers"
with app.app_context():
record_rpa_worker_heartbeat(
_heartbeat_payload(
trigger_dir=windows_trigger,
shared_scope_id="hxops-rpa-test-data",
)
)
result = check_inventory_rpa_worker_ready()
assert result.ready is True
assert not any("trigger_dir_mismatch" in reason for reason in result.reasons)
def test_environment_mismatch_marks_worker_ineligible(app, tmp_path):
"""Worker 环境与后端不一致时应判定离线。"""
trigger_dir = _enable_prod_like_checks(app, tmp_path)
app.config["ENV_NAME"] = "test"
with app.app_context():
record_rpa_worker_heartbeat(
_heartbeat_payload(
trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers",
environment="prod",
shared_scope_id="hxops-rpa-test-data",
)
)
result = check_inventory_rpa_worker_ready()
assert result.ready is False
assert any("environment_mismatch" in reason for reason in result.reasons)
def test_shared_scope_mismatch_marks_worker_ineligible(app, tmp_path):
"""Worker scope 与后端配置不一致时应离线。"""
trigger_dir = _enable_prod_like_checks(app, tmp_path)
with app.app_context():
record_rpa_worker_heartbeat(
_heartbeat_payload(
trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers",
shared_scope_id="hxops-rpa-prod-data",
)
)
result = check_inventory_rpa_worker_ready()
assert result.ready is False
assert any("shared_scope_mismatch" in reason for reason in result.reasons)
def test_missing_shared_sentinel_blocks_readiness_in_test_env(app, tmp_path):
"""test 环境缺少哨兵文件时应判定共享目录不可用。"""
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["ENV_NAME"] = "test"
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
with app.app_context():
record_rpa_worker_heartbeat(
_heartbeat_payload(
trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers",
shared_scope_id="hxops-rpa-test-data",
)
)
result = check_inventory_rpa_worker_ready()
assert result.ready is False
assert "shared_sentinel_missing" in result.reasons
def test_record_heartbeat_requires_redis_when_configured(app, tmp_path, monkeypatch):
"""生产策略要求 Redis 时,写入失败应抛存储不可用。"""
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat._redis_store_worker",
lambda _worker: False,
)
with app.app_context():
with pytest.raises(ServiceUnavailableError) as exc_info:
record_rpa_worker_heartbeat(_heartbeat_payload(trigger_dir=str(trigger_dir)))
assert exc_info.value.code == "RPA.HEARTBEAT_STORAGE_UNAVAILABLE"
assert exc_info.value.message == RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE
def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path, monkeypatch):
"""fail-fast 应附带 reasons 详情供排程日志与运维定位。"""
from app.services.shipping_notice.rpa_worker_heartbeat import (
reset_rpa_worker_heartbeat_state_for_tests,
)
# 隔离:强制无 Redis 分支(_redis_client 为模块级单例,config 置空不可靠,须 monkeypatch);
# 并清空心跳存储,确保走 no_worker_heartbeat + 进程内存储原因码。
from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module
monkeypatch.setattr(heartbeat_module, "_redis_client", lambda: None)
reset_rpa_worker_heartbeat_state_for_tests()
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
_write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data")
app.config["ENV_NAME"] = "test"
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
with app.app_context():
with pytest.raises(ServiceUnavailableError) as exc_info:
assert_inventory_rpa_worker_ready()
assert exc_info.value.message == RPA_WORKER_OFFLINE_MESSAGE
reasons = (exc_info.value.details or {}).get("reasons", [])
assert "no_worker_heartbeat" in reasons
# [断言意图] 无 Redis 时心跳存储为本进程内存,必须给出原因码与本地测试指引
assert "heartbeat_store_process_local" in reasons
assert (exc_info.value.details or {}).get("detail_message")
def test_assert_receipt_rpa_worker_ready_includes_reason_details(app, tmp_path, monkeypatch):
"""收料 fail-fast 应附带 reasons,且与库存同口径要求共享哨兵。"""
from app.core.errors import ServiceUnavailableError
from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module
from app.services.shipping_notice.rpa_worker_heartbeat import (
RPA_WORKER_OFFLINE_MESSAGE,
assert_receipt_rpa_worker_ready,
reset_rpa_worker_heartbeat_state_for_tests,
)
monkeypatch.setattr(heartbeat_module, '_redis_client', lambda: None)
reset_rpa_worker_heartbeat_state_for_tests()
trigger_dir = tmp_path / 'receipt_triggers'
trigger_dir.mkdir()
app.config['ENV_NAME'] = 'test'
app.config['FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR'] = str(trigger_dir)
app.config['FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED'] = True
app.config['FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK'] = True
app.config['FREIGHT_RPA_WORKER_MOCK'] = 'false'
with app.app_context():
with pytest.raises(ServiceUnavailableError) as exc_info:
assert_receipt_rpa_worker_ready()
# [断言意图] 与库存同构的用户可见文案与 reasons;缺哨兵与无心跳同时暴露,
# 对应部署侧必须由 ps1 注入 FREIGHT_RPA_SHARED_SCOPE_ID 写哨兵。
assert exc_info.value.message == RPA_WORKER_OFFLINE_MESSAGE
reasons = (exc_info.value.details or {}).get('reasons', [])
assert 'no_worker_heartbeat' in reasons
assert 'shared_sentinel_missing' in reasons
def test_check_inventory_rpa_worker_ready_rejects_stale_heartbeat(app, tmp_path, monkeypatch):
"""超过 TTL 的心跳应视为离线。"""
import time as time_module
trigger_dir = _enable_prod_like_checks(app, tmp_path)
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS"] = 90
base_now = time_module.time()
with app.app_context():
record_rpa_worker_heartbeat(
_heartbeat_payload(
trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers",
shared_scope_id="hxops-rpa-test-data",
)
)
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat.time.time",
lambda: base_now + 120,
)
result = check_inventory_rpa_worker_ready()
assert result.ready is False
assert any("heartbeat_stale" in reason for reason in result.reasons)
def test_rpa_heartbeat_api_records_worker(client, app, tmp_path):
"""POST /rpa/heartbeat 应写入心跳并返回 ok。"""
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "test-tool-key"
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve()))
res = client.post(
"/api/shipping-notice/rpa/heartbeat",
headers={"X-Integration-Key": "test-tool-key"},
json=payload,
)
assert res.status_code == 200
body = res.get_json()
assert body.get("status") == "ok"
assert body.get("data", {}).get("worker_id") == payload["worker_id"]
def test_rpa_heartbeat_api_rejects_missing_auth(client, app, tmp_path):
"""心跳接口缺少鉴权应返回未授权。"""
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "test-tool-key"
payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve()))
res = client.post("/api/shipping-notice/rpa/heartbeat", json=payload)
assert res.status_code == 401
def test_rpa_heartbeat_api_rejects_invalid_auth(client, app, tmp_path):
"""心跳接口错误 key 应返回未授权。"""
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "test-tool-key"
payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve()))
res = client.post(
"/api/shipping-notice/rpa/heartbeat",
headers={"X-Integration-Key": "wrong-key"},
json=payload,
)
assert res.status_code == 401
def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypatch):
"""排程触发时 worker 离线应立即 failed,不进入 awaiting_rpa_callback。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, User
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module
from app.services.shipping_notice.rpa_worker_heartbeat import (
reset_rpa_worker_heartbeat_state_for_tests,
)
# 隔离:强制无 Redis 分支(防真实心跳/单例缓存混入测试窗口)并清空存储,锁定离线 fail-fast 分支。
monkeypatch.setattr(heartbeat_module, "_redis_client", lambda: None)
reset_rpa_worker_heartbeat_state_for_tests()
trigger_dir = _enable_prod_like_checks(app, tmp_path)
with app.app_context():
user = User(username="hb_offline_user", email="hb_offline_user@example.com")
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no="SCH-HB-OFFLINE",
name="货代库存每日导出",
schedule_type="platform_job",
platform_api_path="shipping-inventory-rpa",
owner_user_id=user.id,
cron_expr="0 3 * * *",
enabled=True,
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(run_no="RUN20260711080000", schedule_task_id=task.id, status="running")
db.session.add(run)
db.session.commit()
total, success, failed, skipped, _details, errors, logs = run_shipping_inventory_rpa_schedule(task, run)
assert total >= 1
assert success == 0
assert failed >= 1
assert skipped == 0
assert errors
assert RPA_WORKER_OFFLINE_MESSAGE in errors[0]
assert not list(trigger_dir.glob("inventory_export_batch_*.json"))
failed_log = next(log for log in logs if isinstance(log, dict) and log.get("status") == "failed")
assert failed_log["detail"].get("reasons")
assert not any(
isinstance(log, dict) and log.get("status") == "awaiting_rpa_callback"
for log in logs
)
def test_redis_read_failure_reports_storage_unavailable_not_offline(app, tmp_path, monkeypatch):
"""Redis 读取异常应报 heartbeat_storage_unavailable,而非 no_worker_heartbeat。"""
trigger_dir = _enable_prod_like_checks(app, tmp_path)
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
class BrokenRedis:
def smembers(self, _key):
raise ConnectionError("redis read failed")
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat._redis_client",
lambda: BrokenRedis(),
)
with app.app_context():
result = check_inventory_rpa_worker_ready()
assert result.ready is False
assert "heartbeat_storage_unavailable" in result.reasons
assert "no_worker_heartbeat" not in result.reasons
assert result.message == RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE
def test_redis_store_and_list_ready_with_prod_policy(app, tmp_path, monkeypatch):
"""test/prod Redis 策略:写入+读取成功时应 ready。"""
trigger_dir = _enable_prod_like_checks(app, tmp_path)
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
bucket: dict[str, Any] = {"index": set()}
class FakeRedis:
def set(self, key, value, ex=None):
bucket[key] = value
def sadd(self, key, value):
bucket.setdefault(key, set()).add(value)
def expire(self, _key, _ttl):
return True
def smembers(self, key):
return bucket.get(key, set())
def get(self, key):
return bucket.get(key)
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat._redis_client",
lambda: FakeRedis(),
)
with app.app_context():
record_rpa_worker_heartbeat(
_heartbeat_payload(
trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers",
shared_scope_id="hxops-rpa-test-data",
)
)
result = check_inventory_rpa_worker_ready()
assert result.ready is True
def test_shared_scope_id_derived_from_mount_path_when_env_missing(app, tmp_path):
"""未显式配置 scope 时,可从 /mnt/hxops-rpa-* 挂载路径推导。"""
from app.services.shipping_notice.rpa_worker_heartbeat import shared_scope_id
trigger_dir = tmp_path / "mnt" / "hxops-rpa-test-data" / "inventory_triggers"
trigger_dir.mkdir(parents=True)
_write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data")
app.config.pop("FREIGHT_RPA_SHARED_SCOPE_ID", None)
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
with app.app_context():
assert shared_scope_id() == "hxops-rpa-test-data"
def _enable_freight_upload_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-data"):
"""配置货代上传 trigger/queue 与心跳策略,供上传就绪单测复用。"""
upload_trigger = tmp_path / "upload_triggers"
upload_queue = tmp_path / "upload_queue"
upload_trigger.mkdir()
upload_queue.mkdir()
_write_shared_sentinel(upload_trigger, scope_id=scope_id)
app.config["ENV_NAME"] = "test"
app.config["FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(upload_trigger)
app.config["FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(upload_queue)
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id
app.config["FREIGHT_RPA_CREDENTIAL_KEY"] = "dGVzdC1rZXktMzItYnl0ZXMtZm9yLWZlcm5ldCE="
app.config["INTERNAL_API_BASE_URL"] = "http://127.0.0.1:5052"
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
return upload_trigger
def test_check_freight_upload_rpa_ready_requires_freight_upload_capability(app, tmp_path):
"""仅 inventory_export 能力时货代上传不得 ready。"""
upload_trigger = _enable_freight_upload_checks(app, tmp_path)
with app.app_context():
record_rpa_worker_heartbeat(
_heartbeat_payload(
trigger_dir=str(upload_trigger),
shared_scope_id="hxops-rpa-test-data",
capabilities=[INVENTORY_EXPORT_CAPABILITY],
)
)
result = check_freight_upload_rpa_ready()
# 关键断言:缺少 freight_upload 能力必须阻断自动上传。
assert result.ready is False
assert any("missing_freight_upload_capability" in reason for reason in result.reasons)
def test_check_freight_upload_rpa_ready_when_worker_and_dirs_ok(app, tmp_path):
"""Worker 声明 freight_upload 且目录/凭据齐全时应 ready。"""
upload_trigger = _enable_freight_upload_checks(app, tmp_path)
with app.app_context():
record_rpa_worker_heartbeat(
_heartbeat_payload(
trigger_dir=str(upload_trigger),
shared_scope_id="hxops-rpa-test-data",
capabilities=[INVENTORY_EXPORT_CAPABILITY, FREIGHT_UPLOAD_CAPABILITY],
)
)
result = check_freight_upload_rpa_ready()
assert result.ready is True
def test_assert_freight_upload_rpa_ready_includes_reasons(app, tmp_path):
"""上传 fail-fast 须带 reasons,供建单前/触发时展示阻断原因。"""
from app.services.shipping_notice.rpa_worker_heartbeat import (
reset_rpa_worker_heartbeat_state_for_tests,
)
_enable_freight_upload_checks(app, tmp_path)
# 去掉凭据主密钥:即使 Redis 残留心跳,静态配置缺失也必须阻断。
app.config.pop("FREIGHT_RPA_CREDENTIAL_KEY", None)
reset_rpa_worker_heartbeat_state_for_tests()
with app.app_context():
with pytest.raises(ServiceUnavailableError) as exc_info:
assert_freight_upload_rpa_ready()
assert exc_info.value.message == RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE
reasons = (exc_info.value.details or {}).get("reasons", [])
assert "credential_key_missing" in reasons
def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path):
"""收料 ready 与库存同口径:要求共享哨兵;仅有库存 Worker 不能冒充收料在线。"""
from app.services.shipping_notice.rpa_worker_heartbeat import (
check_receipt_rpa_worker_ready,
reset_rpa_worker_heartbeat_state_for_tests,
serialize_rpa_worker_status,
)
receipt_trigger = tmp_path / "receipt" / "triggers"
receipt_trigger.mkdir(parents=True)
inventory_trigger = tmp_path / "inventory" / "triggers"
inventory_trigger.mkdir(parents=True)
_write_shared_sentinel(inventory_trigger, scope_id="hxops-rpa-test-data")
app.config["ENV_NAME"] = "test"
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(inventory_trigger)
app.config["FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR"] = str(receipt_trigger)
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
reset_rpa_worker_heartbeat_state_for_tests()
with app.app_context():
record_rpa_worker_heartbeat(_heartbeat_payload(
worker_id="HOST-inventory",
trigger_dir=str(inventory_trigger),
shared_scope_id="hxops-rpa-test-data",
))
receipt_offline = check_receipt_rpa_worker_ready()
assert receipt_offline.ready is False
assert receipt_offline.workers == []
# 无哨兵时即便有收料心跳也不得 ready。
record_rpa_worker_heartbeat(_heartbeat_payload(
worker_id="HOST-receipt",
trigger_dir=str(receipt_trigger),
shared_scope_id="hxops-rpa-test-data",
capabilities=[RECEIPT_EXPORT_CAPABILITY],
))
without_sentinel = check_receipt_rpa_worker_ready()
assert without_sentinel.ready is False
_write_shared_sentinel(receipt_trigger, scope_id="hxops-rpa-test-data")
receipt_ready = check_receipt_rpa_worker_ready()
assert receipt_ready.ready is True
assert [w["worker_id"] for w in receipt_ready.workers] == ["HOST-receipt"]
payload = serialize_rpa_worker_status(scope="receipt")
assert payload["scope"] == "receipt"
assert payload["ready"] is True
assert payload["trigger_dir"] == str(receipt_trigger)
assert [w["worker_id"] for w in payload["workers"]] == ["HOST-receipt"]
def test_receipt_worker_recognized_by_trigger_dir_without_receipt_suffix(app, tmp_path):
"""未注入 *-receipt 身份时,仍可用收料 trigger_dir 识别在线收料 Worker。"""
from app.services.shipping_notice.rpa_worker_heartbeat import (
check_receipt_rpa_worker_ready,
reset_rpa_worker_heartbeat_state_for_tests,
)
receipt_trigger = tmp_path / "receipt" / "triggers"
receipt_trigger.mkdir(parents=True)
app.config["ENV_NAME"] = "dev"
app.config["FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR"] = str(receipt_trigger)
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = ""
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
reset_rpa_worker_heartbeat_state_for_tests()
with app.app_context():
record_rpa_worker_heartbeat(_heartbeat_payload(
worker_id="Hugo-30820",
trigger_dir=str(receipt_trigger),
shared_scope_id="",
capabilities=[RECEIPT_EXPORT_CAPABILITY],
))
result = check_receipt_rpa_worker_ready()
assert result.ready is True
assert [w["worker_id"] for w in result.workers] == ["Hugo-30820"]