feat(phase2): implement AMR robot state machine, task lifecycles, inventory catalog, and Phase 2 OpenUSD scene
This commit is contained in:
@@ -94,3 +94,38 @@ def temp_config_dir(tmp_path: Path) -> Path:
|
||||
json.dump(data, f)
|
||||
|
||||
return config_dir
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_robot_types():
|
||||
"""Return dictionary of RobotTypeSpec instances."""
|
||||
from tests.fixtures.sample_models import create_sample_robot_types
|
||||
return create_sample_robot_types()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_light_robot():
|
||||
"""Return an initialized Light AMR instance."""
|
||||
from tests.fixtures.sample_models import create_sample_light_robot
|
||||
return create_sample_light_robot()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_heavy_robot():
|
||||
"""Return an initialized Heavy AMR instance."""
|
||||
from tests.fixtures.sample_models import create_sample_heavy_robot
|
||||
return create_sample_heavy_robot()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_tasks():
|
||||
"""Return a dictionary of sample tasks across zones."""
|
||||
from tests.fixtures.sample_models import create_sample_tasks
|
||||
return create_sample_tasks()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_inventory_catalog():
|
||||
"""Return an initialized InventoryCatalog instance."""
|
||||
from tests.fixtures.sample_models import create_sample_inventory_catalog
|
||||
return create_sample_inventory_catalog()
|
||||
|
||||
Vendored
+17
@@ -0,0 +1,17 @@
|
||||
"""Test fixtures package."""
|
||||
|
||||
from tests.fixtures.sample_models import (
|
||||
create_sample_heavy_robot,
|
||||
create_sample_inventory_catalog,
|
||||
create_sample_light_robot,
|
||||
create_sample_robot_types,
|
||||
create_sample_tasks,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"create_sample_heavy_robot",
|
||||
"create_sample_inventory_catalog",
|
||||
"create_sample_light_robot",
|
||||
"create_sample_robot_types",
|
||||
"create_sample_tasks",
|
||||
]
|
||||
Vendored
+183
@@ -0,0 +1,183 @@
|
||||
"""Deterministic test fixtures and model factories for unit and scenario tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Dict, List
|
||||
|
||||
from warehouse_twin.domain.inventory import InventoryCatalog, InventoryItem
|
||||
from warehouse_twin.domain.robot import Robot, RobotState, RobotTypeSpec
|
||||
from warehouse_twin.domain.task import Task, TaskStatus, TaskType
|
||||
from warehouse_twin.domain.warehouse import Position3D
|
||||
|
||||
|
||||
def create_sample_robot_types() -> Dict[str, RobotTypeSpec]:
|
||||
"""Return standard AMR type specifications."""
|
||||
light_spec = RobotTypeSpec(
|
||||
type_id="light_amr",
|
||||
name="Agile Lightweight AMR",
|
||||
description="Zone A fast parts and transit",
|
||||
payload_capacity_kg=150.0,
|
||||
max_speed_mps=1.8,
|
||||
acceleration_mps2=0.8,
|
||||
battery_capacity_kwh=3.0,
|
||||
power_consumption_kw={
|
||||
"idle": 0.05,
|
||||
"moving_empty": 0.35,
|
||||
"moving_loaded": 0.65,
|
||||
"handling": 0.15,
|
||||
},
|
||||
allowed_zones={"zone_a", "zone_c"}, # Prohibited from Zone B
|
||||
dimensions=(0.8, 0.6, 0.35),
|
||||
)
|
||||
|
||||
heavy_spec = RobotTypeSpec(
|
||||
type_id="heavy_amr",
|
||||
name="Heavy-Duty Pallet AMR",
|
||||
description="Zone B heavy parts and Zone C raw materials",
|
||||
payload_capacity_kg=1500.0,
|
||||
max_speed_mps=1.1,
|
||||
acceleration_mps2=0.4,
|
||||
battery_capacity_kwh=15.0,
|
||||
power_consumption_kw={
|
||||
"idle": 0.12,
|
||||
"moving_empty": 0.90,
|
||||
"moving_loaded": 2.20,
|
||||
"handling": 0.50,
|
||||
},
|
||||
allowed_zones={"zone_a", "zone_b", "zone_c"},
|
||||
dimensions=(1.4, 1.0, 0.45),
|
||||
)
|
||||
|
||||
return {"light_amr": light_spec, "heavy_amr": heavy_spec}
|
||||
|
||||
|
||||
def create_sample_light_robot(robot_id: str = "amr_light_01") -> Robot:
|
||||
"""Create a standard Light AMR for tests."""
|
||||
specs = create_sample_robot_types()
|
||||
spec = specs["light_amr"]
|
||||
return Robot(
|
||||
robot_id=robot_id,
|
||||
robot_type="light_amr",
|
||||
position=Position3D(2.0, 36.0, 0.0),
|
||||
maximum_speed=spec.max_speed_mps,
|
||||
payload_capacity=spec.payload_capacity_kg,
|
||||
battery_level=spec.battery_capacity_kwh,
|
||||
battery_capacity=spec.battery_capacity_kwh,
|
||||
energy_consumption=dict(spec.power_consumption_kw),
|
||||
allowed_zones=set(spec.allowed_zones),
|
||||
)
|
||||
|
||||
|
||||
def create_sample_heavy_robot(robot_id: str = "amr_heavy_01") -> Robot:
|
||||
"""Create a standard Heavy AMR for tests."""
|
||||
specs = create_sample_robot_types()
|
||||
spec = specs["heavy_amr"]
|
||||
return Robot(
|
||||
robot_id=robot_id,
|
||||
robot_type="heavy_amr",
|
||||
position=Position3D(6.0, 36.0, 0.0),
|
||||
maximum_speed=spec.max_speed_mps,
|
||||
payload_capacity=spec.payload_capacity_kg,
|
||||
battery_level=spec.battery_capacity_kwh,
|
||||
battery_capacity=spec.battery_capacity_kwh,
|
||||
energy_consumption=dict(spec.power_consumption_kw),
|
||||
allowed_zones=set(spec.allowed_zones),
|
||||
)
|
||||
|
||||
|
||||
def create_sample_tasks() -> Dict[str, Task]:
|
||||
"""Create a dictionary of representative tasks across all zones."""
|
||||
return {
|
||||
"light_order": Task(
|
||||
task_id="task_ord_001",
|
||||
task_type=TaskType.ORDER_PICK,
|
||||
source="rack_a_01",
|
||||
destination="picking_station_a1",
|
||||
priority=2,
|
||||
release_time=10.0,
|
||||
required_payload=12.5,
|
||||
item_id="filter_hydraulic_hf1",
|
||||
quantity=5,
|
||||
target_zone="zone_a",
|
||||
),
|
||||
"heavy_order": Task(
|
||||
task_id="task_ord_002",
|
||||
task_type=TaskType.ORDER_PICK,
|
||||
source="rack_b_01",
|
||||
destination="picking_station_b1",
|
||||
priority=2,
|
||||
release_time=25.0,
|
||||
required_payload=650.0,
|
||||
item_id="transmission_combine_ct8",
|
||||
quantity=1,
|
||||
target_zone="zone_b",
|
||||
),
|
||||
"production_feed": Task(
|
||||
task_id="task_feed_001",
|
||||
task_type=TaskType.PRODUCTION_LINE_FEED,
|
||||
source="rack_c_01",
|
||||
destination="production_dropoff_c1",
|
||||
priority=1,
|
||||
release_time=50.0,
|
||||
deadline=350.0,
|
||||
required_payload=1100.0,
|
||||
item_id="raw_steel_coil_sc5",
|
||||
quantity=1,
|
||||
target_zone="zone_c",
|
||||
),
|
||||
"replenishment": Task(
|
||||
task_id="task_replen_001",
|
||||
task_type=TaskType.REPLENISHMENT,
|
||||
source="dock_inbound_1",
|
||||
destination="rack_a_03",
|
||||
priority=3,
|
||||
release_time=100.0,
|
||||
required_payload=75.0,
|
||||
item_id="hardware_bolt_pack_m12",
|
||||
quantity=15,
|
||||
target_zone="zone_a",
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def create_sample_inventory_catalog() -> InventoryCatalog:
|
||||
"""Create a deterministic catalog containing items from Zones A, B, and C."""
|
||||
items = {
|
||||
"filter_hydraulic_hf1": InventoryItem(
|
||||
item_id="filter_hydraulic_hf1",
|
||||
name="Hydraulic Oil Filter HF-1",
|
||||
category="Fast-moving Inventory",
|
||||
zone="zone_a",
|
||||
unit_weight_kg=2.5,
|
||||
initial_stock=200,
|
||||
current_stock=200,
|
||||
minimum_stock=50,
|
||||
replenishment_batch=100,
|
||||
storage_location="rack_a_01",
|
||||
),
|
||||
"transmission_combine_ct8": InventoryItem(
|
||||
item_id="transmission_combine_ct8",
|
||||
name="Heavy Combine Transmission Unit CT-8",
|
||||
category="Slow-moving and Specialized",
|
||||
zone="zone_b",
|
||||
unit_weight_kg=650.0,
|
||||
initial_stock=8,
|
||||
current_stock=8,
|
||||
minimum_stock=2,
|
||||
replenishment_batch=4,
|
||||
storage_location="rack_b_01",
|
||||
),
|
||||
"raw_steel_coil_sc5": InventoryItem(
|
||||
item_id="raw_steel_coil_sc5",
|
||||
name="Hot-Rolled Sheet Steel Coil SC-5",
|
||||
category="Raw Materials and Production Supply",
|
||||
zone="zone_c",
|
||||
unit_weight_kg=1100.0,
|
||||
initial_stock=10,
|
||||
current_stock=10,
|
||||
minimum_stock=3,
|
||||
replenishment_batch=5,
|
||||
storage_location="rack_c_01",
|
||||
),
|
||||
}
|
||||
return InventoryCatalog(items)
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Unit tests for simulation event schema and serialization."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pytest
|
||||
|
||||
from warehouse_twin.domain.events import SimulationEvent, SimulationEventType
|
||||
|
||||
|
||||
def test_simulation_event_serialization():
|
||||
"""Verify SimulationEvent to_dict and to_jsonl formatting."""
|
||||
evt = SimulationEvent(
|
||||
event_id="evt_001",
|
||||
simulation_time=124.5678,
|
||||
event_type=SimulationEventType.TASK_ASSIGNED,
|
||||
entity_id="amr_light_01",
|
||||
task_id="task_ord_001",
|
||||
metadata={"priority": 1, "battery_pct": 98.5},
|
||||
)
|
||||
|
||||
data = evt.to_dict()
|
||||
assert data["event_id"] == "evt_001"
|
||||
assert data["simulation_time"] == 124.568
|
||||
assert data["event_type"] == "TASK_ASSIGNED"
|
||||
assert data["entity_id"] == "amr_light_01"
|
||||
assert data["task_id"] == "task_ord_001"
|
||||
assert data["metadata"]["priority"] == 1
|
||||
|
||||
jsonl_str = evt.to_jsonl()
|
||||
reparsed = json.loads(jsonl_str)
|
||||
assert reparsed["event_type"] == "TASK_ASSIGNED"
|
||||
assert reparsed["metadata"]["battery_pct"] == 98.5
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Unit tests for inventory domain models, stock reservation, and catalog manager."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from warehouse_twin.config.loader import ConfigLoader
|
||||
from warehouse_twin.domain.inventory import (
|
||||
InsufficientStockError,
|
||||
InventoryCatalog,
|
||||
InventoryItem,
|
||||
)
|
||||
|
||||
|
||||
def test_inventory_item_reservation_lifecycle():
|
||||
"""Verify stock reservation, consumption, and release."""
|
||||
item = InventoryItem(
|
||||
item_id="filter_hf1",
|
||||
name="Oil Filter",
|
||||
category="Zone A Fast",
|
||||
zone="zone_a",
|
||||
unit_weight_kg=2.5,
|
||||
initial_stock=100,
|
||||
current_stock=100,
|
||||
minimum_stock=20,
|
||||
)
|
||||
|
||||
assert item.available_stock == 100
|
||||
assert item.needs_replenishment() is False
|
||||
|
||||
# Reserve 30 units
|
||||
item.reserve(30)
|
||||
assert item.reserved_stock == 30
|
||||
assert item.current_stock == 100
|
||||
assert item.available_stock == 70
|
||||
|
||||
# Consume 20 of the reserved units
|
||||
item.consume(20)
|
||||
assert item.reserved_stock == 10
|
||||
assert item.current_stock == 80
|
||||
assert item.available_stock == 70
|
||||
|
||||
# Release remaining 10 reserved units
|
||||
item.release_reservation(10)
|
||||
assert item.reserved_stock == 0
|
||||
assert item.available_stock == 80
|
||||
|
||||
|
||||
def test_insufficient_stock_errors():
|
||||
"""Verify InsufficientStockError when exceeding available or current quantities."""
|
||||
item = InventoryItem(
|
||||
item_id="item_scarce",
|
||||
name="Scarce Part",
|
||||
category="Specialized",
|
||||
zone="zone_b",
|
||||
unit_weight_kg=10.0,
|
||||
initial_stock=5,
|
||||
current_stock=5,
|
||||
minimum_stock=2,
|
||||
)
|
||||
|
||||
# Exceed reservation
|
||||
with pytest.raises(InsufficientStockError) as exc_info:
|
||||
item.reserve(10)
|
||||
assert "Only 5 available" in str(exc_info.value)
|
||||
|
||||
# Exceed consumption
|
||||
with pytest.raises(InsufficientStockError):
|
||||
item.consume(15)
|
||||
|
||||
|
||||
def test_replenishment_trigger_and_restocking():
|
||||
"""Verify needs_replenishment detection and stock restocking."""
|
||||
item = InventoryItem(
|
||||
item_id="belt_bd10",
|
||||
name="V-Belt",
|
||||
category="Zone A Fast",
|
||||
zone="zone_a",
|
||||
unit_weight_kg=1.0,
|
||||
initial_stock=50,
|
||||
current_stock=50,
|
||||
minimum_stock=15,
|
||||
replenishment_batch=30,
|
||||
)
|
||||
|
||||
assert item.needs_replenishment() is False
|
||||
|
||||
# Consume down to threshold
|
||||
item.reserve(35)
|
||||
item.consume(35)
|
||||
assert item.current_stock == 15
|
||||
assert item.needs_replenishment() is True
|
||||
|
||||
# Replenish with batch
|
||||
item.replenish(item.replenishment_batch)
|
||||
assert item.current_stock == 45
|
||||
assert item.needs_replenishment() is False
|
||||
|
||||
|
||||
def test_inventory_catalog_loading(project_config_dir: Path):
|
||||
"""Verify InventoryCatalog loads real project inventory configuration."""
|
||||
loader = ConfigLoader(project_config_dir)
|
||||
bundle = loader.load_all()
|
||||
catalog = InventoryCatalog.from_config_dict(bundle.inventory)
|
||||
|
||||
assert catalog.total_sku_count() == 13
|
||||
|
||||
# Check Zone A items
|
||||
zone_a_items = catalog.get_items_by_zone("zone_a")
|
||||
assert len(zone_a_items) == 5
|
||||
assert any(i.item_id == "filter_hydraulic_hf1" for i in zone_a_items)
|
||||
assert any(i.item_id == "belt_drive_bd10" for i in zone_a_items)
|
||||
|
||||
# Check Zone B items
|
||||
zone_b_items = catalog.get_items_by_zone("zone_b")
|
||||
assert len(zone_b_items) == 4
|
||||
assert any(i.item_id == "transmission_combine_ct8" for i in zone_b_items)
|
||||
assert any(i.item_id == "structural_chassis_frame_sf3" for i in zone_b_items)
|
||||
|
||||
# Check Zone C items
|
||||
zone_c_items = catalog.get_items_by_zone("zone_c")
|
||||
assert len(zone_c_items) == 4
|
||||
assert any(i.item_id == "raw_steel_coil_sc5" for i in zone_c_items)
|
||||
assert any(i.item_id == "electronic_control_module_ecm9" for i in zone_c_items)
|
||||
@@ -0,0 +1,176 @@
|
||||
"""Unit tests for robot domain models, state machine transitions, and compatibility rules."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from warehouse_twin.domain.robot import (
|
||||
IncompatibleRobotTaskError,
|
||||
InvalidStateTransitionError,
|
||||
Robot,
|
||||
RobotState,
|
||||
RobotTypeSpec,
|
||||
)
|
||||
from warehouse_twin.domain.task import Task, TaskStatus, TaskType
|
||||
from warehouse_twin.domain.warehouse import Position3D
|
||||
|
||||
|
||||
def test_robot_initialization_and_properties(sample_light_robot: Robot):
|
||||
"""Verify AMR initial attributes, battery percentage, and capacity ratings."""
|
||||
assert sample_light_robot.robot_id == "amr_light_01"
|
||||
assert sample_light_robot.robot_type == "light_amr"
|
||||
assert sample_light_robot.current_state == RobotState.IDLE
|
||||
assert sample_light_robot.battery_percent == pytest.approx(100.0)
|
||||
assert sample_light_robot.payload_capacity == 150.0
|
||||
assert sample_light_robot.maximum_speed == 1.8
|
||||
assert sample_light_robot.accumulated_distance == 0.0
|
||||
|
||||
|
||||
def test_robot_normal_cycle_state_transitions(sample_light_robot: Robot):
|
||||
"""Verify full operational lifecycle: IDLE -> DISPATCHED -> PICKING -> LOADED_TRANSIT -> DROPPING -> IDLE."""
|
||||
r = sample_light_robot
|
||||
sim_time = 0.0
|
||||
|
||||
# 1. IDLE -> DISPATCHED
|
||||
r.transition_to(RobotState.DISPATCHED, sim_time=10.0)
|
||||
assert r.current_state == RobotState.DISPATCHED
|
||||
assert r.idle_time == pytest.approx(10.0)
|
||||
|
||||
# 2. DISPATCHED -> PICKING
|
||||
r.transition_to(RobotState.PICKING, sim_time=25.0)
|
||||
assert r.current_state == RobotState.PICKING
|
||||
assert r.busy_time == pytest.approx(15.0)
|
||||
|
||||
# 3. PICKING -> LOADED_TRANSIT
|
||||
r.transition_to(RobotState.LOADED_TRANSIT, sim_time=35.0)
|
||||
assert r.current_state == RobotState.LOADED_TRANSIT
|
||||
assert r.busy_time == pytest.approx(25.0)
|
||||
|
||||
# 4. LOADED_TRANSIT -> DROPPING
|
||||
r.transition_to(RobotState.DROPPING, sim_time=50.0)
|
||||
assert r.current_state == RobotState.DROPPING
|
||||
assert r.busy_time == pytest.approx(40.0)
|
||||
|
||||
# 5. DROPPING -> IDLE
|
||||
r.transition_to(RobotState.IDLE, sim_time=60.0)
|
||||
assert r.current_state == RobotState.IDLE
|
||||
assert r.busy_time == pytest.approx(50.0)
|
||||
assert r.idle_time == pytest.approx(10.0)
|
||||
|
||||
|
||||
def test_robot_charging_state_transitions(sample_light_robot: Robot):
|
||||
"""Verify charging cycle: IDLE -> TRANSIT_TO_CHARGE -> CHARGING -> IDLE."""
|
||||
r = sample_light_robot
|
||||
|
||||
r.transition_to(RobotState.TRANSIT_TO_CHARGE, sim_time=100.0)
|
||||
assert r.current_state == RobotState.TRANSIT_TO_CHARGE
|
||||
assert r.idle_time == pytest.approx(100.0)
|
||||
|
||||
r.transition_to(RobotState.CHARGING, sim_time=120.0)
|
||||
assert r.current_state == RobotState.CHARGING
|
||||
|
||||
r.transition_to(RobotState.IDLE, sim_time=300.0)
|
||||
assert r.current_state == RobotState.IDLE
|
||||
assert r.charging_time == pytest.approx(180.0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("invalid_target", [
|
||||
RobotState.DROPPING,
|
||||
RobotState.LOADED_TRANSIT,
|
||||
RobotState.PICKING,
|
||||
])
|
||||
def test_illegal_transitions_from_idle_rejected(sample_light_robot: Robot, invalid_target: RobotState):
|
||||
"""Ensure invalid transitions from IDLE immediately raise InvalidStateTransitionError."""
|
||||
with pytest.raises(InvalidStateTransitionError) as exc_info:
|
||||
sample_light_robot.transition_to(invalid_target, sim_time=1.0)
|
||||
assert f"Cannot transition from IDLE to {invalid_target.value}" in str(exc_info.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("from_state,to_state", [
|
||||
(RobotState.PICKING, RobotState.CHARGING),
|
||||
(RobotState.LOADED_TRANSIT, RobotState.IDLE),
|
||||
(RobotState.CHARGING, RobotState.LOADED_TRANSIT),
|
||||
(RobotState.DROPPING, RobotState.PICKING),
|
||||
])
|
||||
def test_various_illegal_transitions_rejected(sample_light_robot: Robot, from_state: RobotState, to_state: RobotState):
|
||||
"""Verify arbitrary illegal state combinations are rejected."""
|
||||
sample_light_robot.current_state = from_state
|
||||
with pytest.raises(InvalidStateTransitionError):
|
||||
sample_light_robot.transition_to(to_state, sim_time=5.0)
|
||||
|
||||
|
||||
def test_payload_capacity_compatibility(sample_light_robot: Robot, sample_heavy_robot: Robot, sample_tasks: dict):
|
||||
"""Verify payload rules: Light AMR rejects heavy parts; Heavy AMR accepts them."""
|
||||
light_bot = sample_light_robot # 150 kg rating
|
||||
heavy_bot = sample_heavy_robot # 1500 kg rating
|
||||
|
||||
light_task = sample_tasks["light_order"] # 12.5 kg
|
||||
heavy_task = sample_tasks["heavy_order"] # 650.0 kg
|
||||
feed_task = sample_tasks["production_feed"] # 1100.0 kg
|
||||
|
||||
# Light task (12.5 kg) is compatible with both
|
||||
assert light_bot.can_carry_payload(light_task.required_payload) is True
|
||||
assert heavy_bot.can_carry_payload(light_task.required_payload) is True
|
||||
|
||||
# Heavy task (650 kg) is rejected by light AMR, accepted by heavy AMR
|
||||
assert light_bot.can_carry_payload(heavy_task.required_payload) is False
|
||||
assert heavy_bot.can_carry_payload(heavy_task.required_payload) is True
|
||||
|
||||
with pytest.raises(IncompatibleRobotTaskError) as exc_info:
|
||||
light_bot.assign_task(heavy_task)
|
||||
assert "exceeds robot 'amr_light_01' capacity" in str(exc_info.value)
|
||||
|
||||
# Heavy bot can assign heavy task
|
||||
heavy_bot.assign_task(heavy_task)
|
||||
assert heavy_bot.current_task_id == heavy_task.task_id
|
||||
assert heavy_task.assigned_robot_id == heavy_bot.robot_id
|
||||
|
||||
|
||||
def test_zone_accessibility_compatibility(sample_light_robot: Robot, sample_tasks: dict):
|
||||
"""Verify operational rule: Light AMR is restricted from Zone B tasks."""
|
||||
light_bot = sample_light_robot
|
||||
heavy_task_in_zone_b = sample_tasks["heavy_order"] # target_zone='zone_b'
|
||||
|
||||
# Even if payload were reduced to 10 kg, zone_b should still block light AMR
|
||||
heavy_task_in_zone_b.required_payload = 10.0
|
||||
compatible, reason = light_bot.validate_task_compatibility(heavy_task_in_zone_b)
|
||||
|
||||
assert compatible is False
|
||||
assert "restricted from entering target zone 'zone_b'" in reason
|
||||
|
||||
with pytest.raises(IncompatibleRobotTaskError):
|
||||
light_bot.assign_task(heavy_task_in_zone_b)
|
||||
|
||||
|
||||
def test_busy_robot_assignment_rejected(sample_light_robot: Robot, sample_tasks: dict):
|
||||
"""Verify that busy robots cannot be assigned new tasks."""
|
||||
light_bot = sample_light_robot
|
||||
task = sample_tasks["light_order"]
|
||||
|
||||
light_bot.transition_to(RobotState.DISPATCHED, sim_time=10.0)
|
||||
compatible, reason = light_bot.validate_task_compatibility(task)
|
||||
|
||||
assert compatible is False
|
||||
assert "is currently busy in state DISPATCHED" in reason
|
||||
|
||||
with pytest.raises(IncompatibleRobotTaskError):
|
||||
light_bot.assign_task(task)
|
||||
|
||||
|
||||
def test_energy_consumption_and_charging(sample_light_robot: Robot):
|
||||
"""Verify energy deductions and charging calculations."""
|
||||
r = sample_light_robot
|
||||
initial = r.battery_level
|
||||
|
||||
# Consume energy moving empty for 360 seconds at 0.35 kW
|
||||
consumed = r.consume_energy(360.0, mode="moving_empty")
|
||||
expected_kwh = (0.35 * 360.0) / 3600.0
|
||||
assert consumed == pytest.approx(expected_kwh)
|
||||
assert r.battery_level == pytest.approx(initial - expected_kwh)
|
||||
|
||||
# Set battery level to 1.0 kWh to ensure headroom for charging test
|
||||
r.battery_level = 1.0
|
||||
added = r.charge_energy(60.0, charging_rate_kw=25.0)
|
||||
expected_charge = (25.0 * 60.0) / 3600.0 # 0.4167 kWh
|
||||
assert added == pytest.approx(expected_charge)
|
||||
assert r.battery_level == pytest.approx(1.0 + expected_charge)
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Unit tests for task domain models, lifecycle transitions, and deadlines."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from warehouse_twin.domain.robot import InvalidStateTransitionError
|
||||
from warehouse_twin.domain.task import Task, TaskStatus, TaskType
|
||||
|
||||
|
||||
def test_task_initialization():
|
||||
"""Verify task initialization, priorities, and default attributes."""
|
||||
task = Task(
|
||||
task_id="task_001",
|
||||
task_type=TaskType.ORDER_PICK,
|
||||
source="rack_a_01",
|
||||
destination="picking_station_a1",
|
||||
priority=1,
|
||||
release_time=100.0,
|
||||
deadline=400.0,
|
||||
required_payload=25.0,
|
||||
item_id="filter_hydraulic_hf1",
|
||||
quantity=10,
|
||||
)
|
||||
|
||||
assert task.task_id == "task_001"
|
||||
assert task.status == TaskStatus.PENDING
|
||||
assert task.priority == 1
|
||||
assert task.turnaround_time() is None
|
||||
assert task.execution_time() is None
|
||||
assert task.waiting_time(150.0) == pytest.approx(50.0)
|
||||
assert task.is_overdue(200.0) is False
|
||||
|
||||
|
||||
def test_task_normal_lifecycle_transitions():
|
||||
"""Verify PENDING -> ASSIGNED -> IN_PROGRESS -> COMPLETED."""
|
||||
task = Task(
|
||||
task_id="task_002",
|
||||
task_type=TaskType.ORDER_PICK,
|
||||
source="rack_a_02",
|
||||
destination="picking_station_a1",
|
||||
release_time=50.0,
|
||||
)
|
||||
|
||||
# 1. PENDING -> ASSIGNED
|
||||
task.transition_to(TaskStatus.ASSIGNED, sim_time=60.0)
|
||||
assert task.status == TaskStatus.ASSIGNED
|
||||
|
||||
# 2. ASSIGNED -> IN_PROGRESS
|
||||
task.transition_to(TaskStatus.IN_PROGRESS, sim_time=80.0)
|
||||
assert task.status == TaskStatus.IN_PROGRESS
|
||||
assert task.start_time == 80.0
|
||||
assert task.waiting_time() == pytest.approx(30.0)
|
||||
|
||||
# 3. IN_PROGRESS -> COMPLETED
|
||||
task.transition_to(TaskStatus.COMPLETED, sim_time=150.0)
|
||||
assert task.status == TaskStatus.COMPLETED
|
||||
assert task.completion_time == 150.0
|
||||
assert task.turnaround_time() == pytest.approx(100.0)
|
||||
assert task.execution_time() == pytest.approx(70.0)
|
||||
|
||||
|
||||
def test_task_cancellation_and_preemption():
|
||||
"""Verify preemption (ASSIGNED -> PENDING) and cancellation."""
|
||||
task = Task(
|
||||
task_id="task_003",
|
||||
task_type=TaskType.REPLENISHMENT,
|
||||
source="dock_inbound_1",
|
||||
destination="rack_c_01",
|
||||
release_time=0.0,
|
||||
)
|
||||
|
||||
# PENDING -> ASSIGNED
|
||||
task.transition_to(TaskStatus.ASSIGNED, sim_time=10.0)
|
||||
# Preemption: ASSIGNED -> PENDING
|
||||
task.transition_to(TaskStatus.PENDING, sim_time=20.0)
|
||||
assert task.status == TaskStatus.PENDING
|
||||
|
||||
# PENDING -> CANCELLED
|
||||
task.transition_to(TaskStatus.CANCELLED, sim_time=30.0)
|
||||
assert task.status == TaskStatus.CANCELLED
|
||||
assert task.completion_time == 30.0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("invalid_from,invalid_to", [
|
||||
(TaskStatus.PENDING, TaskStatus.COMPLETED),
|
||||
(TaskStatus.PENDING, TaskStatus.IN_PROGRESS),
|
||||
(TaskStatus.COMPLETED, TaskStatus.IN_PROGRESS),
|
||||
(TaskStatus.CANCELLED, TaskStatus.PENDING),
|
||||
(TaskStatus.FAILED, TaskStatus.COMPLETED),
|
||||
])
|
||||
def test_illegal_task_transitions_rejected(invalid_from: TaskStatus, invalid_to: TaskStatus):
|
||||
"""Ensure invalid task lifecycle jumps raise InvalidStateTransitionError."""
|
||||
task = Task(
|
||||
task_id="task_invalid",
|
||||
task_type=TaskType.ORDER_PICK,
|
||||
source="s",
|
||||
destination="d",
|
||||
)
|
||||
task.status = invalid_from
|
||||
with pytest.raises(InvalidStateTransitionError):
|
||||
task.transition_to(invalid_to, sim_time=10.0)
|
||||
|
||||
|
||||
def test_deadline_and_overdue_tracking():
|
||||
"""Verify strict deadline tracking for production line feed tasks."""
|
||||
task = Task(
|
||||
task_id="feed_critical",
|
||||
task_type=TaskType.PRODUCTION_LINE_FEED,
|
||||
source="rack_c_01",
|
||||
destination="production_dropoff_c1",
|
||||
release_time=100.0,
|
||||
deadline=300.0, # 200s window
|
||||
)
|
||||
|
||||
assert task.is_overdue(250.0) is False
|
||||
assert task.is_overdue(301.0) is True
|
||||
|
||||
# Completed on time
|
||||
task.transition_to(TaskStatus.ASSIGNED, 110.0)
|
||||
task.transition_to(TaskStatus.IN_PROGRESS, 120.0)
|
||||
task.transition_to(TaskStatus.COMPLETED, 280.0)
|
||||
assert task.is_overdue(500.0) is False # Finished at 280 <= 300, so not overdue
|
||||
@@ -251,3 +251,26 @@ def test_export_usda_scene(project_config_dir: Path, tmp_path: Path):
|
||||
assert 'def Xform "picking_station_a1"' in content
|
||||
assert 'def Xform "charge_bay_1"' in content
|
||||
assert 'def Xform "rack_a_01"' in content
|
||||
|
||||
|
||||
def test_export_usda_with_robots(project_config_dir: Path, tmp_path: Path):
|
||||
"""Verify OpenUSD scene generation includes AMR fleet entities when provided."""
|
||||
from warehouse_twin.interfaces.usd_generator import WarehouseUSDGenerator
|
||||
|
||||
loader = ConfigLoader(project_config_dir)
|
||||
bundle = loader.load_all()
|
||||
|
||||
generator = WarehouseUSDGenerator.from_config_bundle(bundle)
|
||||
usda_path = tmp_path / "test_warehouse_phase2.usda"
|
||||
saved = generator.export_usda(usda_path)
|
||||
|
||||
assert saved.exists()
|
||||
content = saved.read_text(encoding="utf-8")
|
||||
|
||||
assert 'def Scope "Robots"' in content
|
||||
assert 'def Xform "amr_light_01"' in content
|
||||
assert 'def Xform "amr_light_02"' in content
|
||||
assert 'def Xform "amr_heavy_01"' in content
|
||||
assert 'def Xform "amr_heavy_02"' in content
|
||||
assert 'def Cube "StatusDome"' in content
|
||||
|
||||
|
||||
Reference in New Issue
Block a user