Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions tests/resources/test_plr_registration_hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,49 @@ def test_core_preset_classes_deserialize_in_a_fresh_process(tmp_path):
assert {"BottleCarrier", "Bottle", "WareHouse", "RegularContainer"} <= classes


def test_class_check_finds_core_presets_before_any_tree_is_rebuilt(tmp_path):
"""Host 在已有数据库上重启:先逐台核对设备物料的 config.type(``require_plr_config_type``),再建 PLR 实例。

核对找不到类时只会懒加载注册表条目所在的模块。驱动包的工厂函数常在函数体里才 import 它返回的类
(这里返回核心预设 ``BottleCarrier``),条目模块被导入后类仍不可见,设备误进维护模式。全新数据库不出现,
因为建图时会调用工厂。核对前要先导入登记的模块(含内置预设),不能指望驱动包在模块顶层 import。
"""

import os
import subprocess

pkg = tmp_path / "lazy_carrier_pkg"
pkg.mkdir()
(pkg / "__init__.py").write_text("", encoding="utf-8")
(pkg / "warehouses.py").write_text(
"def process_warehouse(name='wh'):\n"
" from unilabos.resources.presets.itemized_carrier import BottleCarrier\n"
" return BottleCarrier(name, size_x=10, size_y=10, size_z=10, sites={})\n",
encoding="utf-8",
)
script = (
"import sys\n"
"from unilabos.registry.registry import lab_registry\n"
"from unilabos.resources.resource_tracker import find_plr_resource_class, require_plr_config_type\n"
"lab_registry.resource_type_registry['pkg.process_warehouse'] = "
"{'class': {'module': 'lazy_carrier_pkg.warehouses:process_warehouse', 'type': 'pylabrobot'}}\n"
"assert not [m for m in sys.modules if m.startswith('unilabos.resources.presets')]\n"
"for name in ('BottleCarrier', 'Bottle', 'WareHouse', 'RegularContainer'):\n"
" require_plr_config_type({'type': name}, uuid='u-' + name, template_name='pkg.process_warehouse')\n"
" assert find_plr_resource_class(name).__name__ == name\n"
"print('ok')\n"
)
env = {
**os.environ,
"PYTHONPATH": os.pathsep.join(filter(None, [str(tmp_path), os.getcwd(), os.environ.get("PYTHONPATH")])),
}
completed = subprocess.run(
[sys.executable, "-c", script], capture_output=True, text=True, encoding="utf-8", env=env, timeout=300
)
assert completed.returncode == 0, completed.stderr[-3000:]
assert completed.stdout.strip().splitlines()[-1] == "ok"


@pytest.fixture()
def registry_pkg(tmp_path, monkeypatch):
"""注册表里登记了工厂函数、自己不主动登记的驱动包:类只有 import 工厂所在的模块后才可见。"""
Expand Down
18 changes: 18 additions & 0 deletions tests/test_action_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,24 @@ def test_result_info_distinguishes_three_success_types(suc_type, return_value):
assert serialized["return_value"] == return_value


def test_plr_material_in_result_is_returned_as_its_uuid_reference():
"""驱动直接返回 PLR 实例(单个、嵌在 dict / list 里)时,结果里是 ``{"uuid"}``,不是整个对象。"""

from pylabrobot.resources import Resource

beaker = Resource("beaker", size_x=10, size_y=10, size_z=10)
beaker.unilabos_uuid = "b-uuid"
plain = Resource("plain", size_x=1, size_y=1, size_z=1)

result = serialize_result_info("", True, {"beaker": beaker, "all": [beaker], "site": "S061"})
assert result["return_value"] == {"beaker": {"uuid": "b-uuid"}, "all": [{"uuid": "b-uuid"}], "site": "S061"}
assert serialize_result_info("", True, beaker)["return_value"] == {"uuid": "b-uuid"}
# 没有权威 uuid 的 PLR 对象不当作物料引用
from unilabos.utils.serialization import _material_reference

assert _material_reference(plain) is None


def test_failed_result_does_not_claim_success_type():
result = serialize_result_info("failed", False, None)

Expand Down
5 changes: 5 additions & 0 deletions unilabos/resources/resource_tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,11 @@ def find_plr_resource_class(class_name: str) -> Optional[type]:
from pylabrobot.resources import Resource as PLRResource
from pylabrobot.utils.object_parsing import find_subclass

from unilabos.resources import plr_additional_res_reg

# 先导入登记过的模块(内置预设 BottleCarrier / WareHouse 等 + 驱动包登记的):重启后核对设备物料时
# 还没有建过图;下面的注册表兜底只导入条目所在模块,工厂函数在函数体里才 import 的类仍不可见。
plr_additional_res_reg.register()
found = find_subclass(class_name, PLRResource)
if found is not None:
return found
Expand Down
19 changes: 19 additions & 0 deletions unilabos/utils/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,31 @@ def represent_ordereddict(dumper, data):
NoAliasDumper.add_representer(OrderedDict, represent_ordereddict)


def _material_reference(obj) -> Optional[dict]:
"""动作结果里的 PLR 物料实例按物料引用 ``{"uuid"}`` 返回(与 ResourceSlot 的结果形状一致)。

驱动直接返回 PLR 实例时不必自己转换;没有权威 uuid 的 PLR 对象不在此处理。
"""

uuid = getattr(obj, "unilabos_uuid", None)
if not uuid:
return None
try:
from pylabrobot.resources import Resource
except ImportError: # pragma: no cover - 核心总带 PLR
return None
return {"uuid": str(uuid)} if isinstance(obj, Resource) else None


class ResultInfoEncoder(json.JSONEncoder):
"""专门用于处理任务执行结果信息的JSON编码器"""

def default(self, obj):
if isinstance(obj, type):
return json_default(obj)
reference = _material_reference(obj)
if reference is not None:
return reference

try:
if hasattr(obj, "__dict__"):
Expand Down
Loading