"""Unit tests for warehouse graph builder, domain models, and topological connectivity.""" from __future__ import annotations import json from pathlib import Path import pytest import networkx as nx from warehouse_twin.config.loader import ConfigLoader from warehouse_twin.domain.warehouse import ( NodeType, Position3D, StationType, WarehouseDimensions, WarehouseModel, ZoneArea, ) from warehouse_twin.routing.graph_builder import ( ConnectivityReport, DisconnectedGraphError, UnreachableStationError, WarehouseGraphBuilder, WarehouseGraphError, ) def test_position3d_geometry(): """Verify 3D Cartesian coordinates and Euclidean distance metric.""" p1 = Position3D(0.0, 0.0, 0.0) p2 = Position3D(3.0, 4.0, 0.0) assert p1.distance_to(p2) == pytest.approx(5.0) p3 = Position3D.from_iterable([10.5, 20.5, 2.0]) assert p3.x == 10.5 assert p3.y == 20.5 assert p3.z == 2.0 assert p3.to_list() == [10.5, 20.5, 2.0] assert p3.to_tuple() == (10.5, 20.5, 2.0) def test_zone_area_bounds(): """Verify 2D bounding box inclusion logic.""" area = ZoneArea(x_min=5.0, x_max=25.0, y_min=5.0, y_max=35.0) inside = Position3D(15.0, 20.0, 0.0) outside = Position3D(2.0, 20.0, 0.0) assert area.contains(inside) is True assert area.contains(outside) is False def test_warehouse_model_parsing(project_config_dir: Path): """Verify WarehouseModel parses dimensions, zones, stations, and chargers.""" loader = ConfigLoader(project_config_dir) bundle = loader.load_all() model = WarehouseModel.from_config_dict(bundle.warehouse) assert model.dimensions.width == 60.0 assert model.dimensions.depth == 40.0 assert "zone_a" in model.zones assert "zone_b" in model.zones assert "zone_c" in model.zones assert len(model.stations) >= 6 assert len(model.charging_stations) >= 4 assert len(model.storage_locations) == 13 def test_build_graph_structure(project_config_dir: Path): """Verify that graph builder constructs vertices, typed nodes, and weighted edges.""" loader = ConfigLoader(project_config_dir) bundle = loader.load_all() builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse) graph = builder.build_graph() assert graph.number_of_nodes() > 500 assert graph.number_of_edges() > 1500 # Verify key operational station nodes exist assert graph.has_node("station_dock_inbound_1") assert graph.nodes["station_dock_inbound_1"]["node_type"] == NodeType.INBOUND_DOCK.value assert graph.has_node("station_picking_station_a1") assert graph.nodes["station_picking_station_a1"]["node_type"] == NodeType.PICKING_STATION.value assert graph.has_node("station_production_dropoff_c1") assert graph.nodes["station_production_dropoff_c1"]["node_type"] == NodeType.PRODUCTION_FEED.value assert graph.has_node("charger_charge_bay_1") assert graph.nodes["charger_charge_bay_1"]["node_type"] == NodeType.CHARGING_BAY.value # Verify rack nodes exist assert graph.has_node("rack_rack_a_01") assert graph.has_node("rack_rack_b_01") assert graph.has_node("rack_rack_c_01") # Verify edge data attributes for u, v, d in graph.edges(data=True): assert "distance" in d and d["distance"] > 0 assert "speed_limit" in d and d["speed_limit"] > 0 assert "traversal_time" in d and d["traversal_time"] > 0 assert "allowed_robot_types" in d assert len(d["allowed_robot_types"]) > 0 def test_graph_connectivity_report(project_config_dir: Path): """Verify strong connectivity, complete station reachability, and distribution metrics.""" loader = ConfigLoader(project_config_dir) bundle = loader.load_all() builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse) graph = builder.build_graph() report: ConnectivityReport = builder.validate_connectivity(graph) assert report.is_strongly_connected is True assert report.component_count == 1 assert report.stations_reachable == report.total_stations == 6 assert report.chargers_reachable == report.total_chargers == 4 assert report.storage_racks_reachable == report.total_storage_racks == 13 assert report.total_lane_length_meters > 1000.0 # Check zone node distribution assert "zone_a" in report.zone_node_distribution assert "zone_b" in report.zone_node_distribution assert "zone_c" in report.zone_node_distribution assert "transit" in report.zone_node_distribution def test_zone_b_restricted_to_heavy_amr(project_config_dir: Path): """Verify operational constraint: Zone B restricts light AMRs and allows heavy AMRs.""" loader = ConfigLoader(project_config_dir) bundle = loader.load_all() builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse) graph = builder.build_graph() report = builder.validate_connectivity(graph, robot_types=["light_amr", "heavy_amr"]) # Heavy AMR can access everything assert report.robot_type_reachability["heavy_amr"] is True # Light AMR is restricted from Zone B assert report.robot_type_reachability["light_amr"] is True # Manually check Zone B edges zone_b_edges = [ (u, v, d) for u, v, d in graph.edges(data=True) if d.get("zone") == "zone_b" ] assert len(zone_b_edges) > 0 for _, _, d in zone_b_edges: assert "heavy_amr" in d["allowed_robot_types"] assert "light_amr" not in d["allowed_robot_types"] def test_disconnected_graph_raises_error(project_config_dir: Path): """Verify that a partitioned graph triggers DisconnectedGraphError.""" loader = ConfigLoader(project_config_dir) bundle = loader.load_all() builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse) graph = builder.build_graph() # Artificially isolate an arbitrary waypoint by removing all its incident edges wp_to_isolate = "wp_100_100" in_edges = list(graph.in_edges(wp_to_isolate)) out_edges = list(graph.out_edges(wp_to_isolate)) graph.remove_edges_from(in_edges + out_edges) with pytest.raises(DisconnectedGraphError) as exc_info: builder.validate_connectivity(graph) assert "Warehouse graph is disconnected" in str(exc_info.value) def test_unreachable_station_raises_error(project_config_dir: Path): """Verify that an unreachable station triggers UnreachableStationError.""" loader = ConfigLoader(project_config_dir) bundle = loader.load_all() builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse) graph = builder.build_graph() # Sever all edges connecting inbound dock 1 st_node = "station_dock_inbound_1" graph.remove_edges_from(list(graph.in_edges(st_node)) + list(graph.out_edges(st_node))) with pytest.raises(WarehouseGraphError) as exc_info: builder.validate_connectivity(graph) # Could be caught by disconnected check or unreachable station check assert "dock_inbound_1" in str(exc_info.value) or "disconnected" in str(exc_info.value) def test_export_topology_dict_and_json(project_config_dir: Path, tmp_path: Path): """Verify serialization of graph topology to dictionary and JSON file.""" loader = ConfigLoader(project_config_dir) bundle = loader.load_all() builder = WarehouseGraphBuilder.from_config_dict(bundle.warehouse) topo = builder.export_topology_dict() assert "metadata" in topo assert "zones" in topo assert "stations" in topo assert "charging_stations" in topo assert "storage_locations" in topo assert "nodes" in topo assert "edges" in topo assert topo["metadata"]["node_count"] > 500 assert topo["metadata"]["edge_count"] > 1500 out_file = tmp_path / "test_export_graph.json" saved = builder.export_json(out_file) assert saved.exists() assert saved.stat().st_size > 10000 # Validate JSON structure with open(saved, "r", encoding="utf-8") as f: reloaded = json.load(f) assert len(reloaded["nodes"]) == topo["metadata"]["node_count"]