feat(phase-0): initialize project foundation, packaging, logging, configs, and tests
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Test suite for Warehouse Robot Fleet Digital Twin."""
|
||||
@@ -0,0 +1,96 @@
|
||||
"""Shared pytest fixtures for Warehouse Digital Twin."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def project_root() -> Path:
|
||||
"""Return the absolute path to the project root directory."""
|
||||
return Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def project_config_dir(project_root: Path) -> Path:
|
||||
"""Return the path to the real project configuration directory."""
|
||||
return project_root / "config"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def temp_config_dir(tmp_path: Path) -> Path:
|
||||
"""Create a temporary directory with valid configuration files for testing."""
|
||||
config_dir = tmp_path / "config"
|
||||
config_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
warehouse_data = {
|
||||
"coordinate_system": {"type": "right_handed_cartesian", "units": "meters"},
|
||||
"dimensions": {"width": 60.0, "depth": 40.0, "height": 8.0},
|
||||
"zones": {
|
||||
"zone_a": {"name": "Zone A"},
|
||||
"zone_b": {"name": "Zone B"},
|
||||
"zone_c": {"name": "Zone C"},
|
||||
},
|
||||
"stations": [{"station_id": "st_1", "type": "dock", "position": [1.0, 1.0, 0.0]}],
|
||||
"charging_stations": [{"station_id": "ch_1", "position": [2.0, 2.0, 0.0], "capacity": 1}],
|
||||
}
|
||||
|
||||
robots_data = {
|
||||
"robot_types": {
|
||||
"light_amr": {
|
||||
"payload_capacity_kg": 150.0,
|
||||
"max_speed_mps": 1.8,
|
||||
"battery_capacity_kwh": 3.0,
|
||||
}
|
||||
},
|
||||
"fleet": [
|
||||
{
|
||||
"robot_id": "amr_1",
|
||||
"robot_type": "light_amr",
|
||||
"initial_position": [0.0, 0.0, 0.0],
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
inventory_data = {
|
||||
"categories": {
|
||||
"zone_a_items": {
|
||||
"name": "Zone A Items",
|
||||
"items": [
|
||||
{
|
||||
"item_id": "item_1",
|
||||
"name": "Filter HF-1",
|
||||
"unit_weight_kg": 2.0,
|
||||
"initial_stock": 100,
|
||||
}
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
simulation_data = {
|
||||
"simulation": {
|
||||
"duration_seconds": 3600.0,
|
||||
"random_seed": 42,
|
||||
}
|
||||
}
|
||||
|
||||
dispatch_data = {
|
||||
"active_policy": "nearest_idle",
|
||||
"available_policies": ["nearest_idle", "priority_first"],
|
||||
}
|
||||
|
||||
for name, data in [
|
||||
("warehouse.json", warehouse_data),
|
||||
("robots.json", robots_data),
|
||||
("inventory.json", inventory_data),
|
||||
("simulation.json", simulation_data),
|
||||
("dispatch_policies.json", dispatch_data),
|
||||
]:
|
||||
with open(config_dir / name, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f)
|
||||
|
||||
return config_dir
|
||||
@@ -0,0 +1 @@
|
||||
"""Unit tests package."""
|
||||
@@ -0,0 +1,172 @@
|
||||
"""Unit tests for configuration loader and schema validation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from warehouse_twin.config.loader import ConfigLoader, ConfigurationError
|
||||
|
||||
|
||||
def test_load_real_project_configurations(project_config_dir: Path):
|
||||
"""Verify that the real project configurations in config/ load and validate cleanly."""
|
||||
loader = ConfigLoader(config_dir=project_config_dir)
|
||||
bundle = loader.load_all()
|
||||
|
||||
# Warehouse checks
|
||||
assert bundle.warehouse["dimensions"]["width"] == 60.0
|
||||
assert "zone_a" in bundle.warehouse["zones"]
|
||||
assert "zone_b" in bundle.warehouse["zones"]
|
||||
assert "zone_c" in bundle.warehouse["zones"]
|
||||
assert len(bundle.warehouse["stations"]) >= 4
|
||||
assert len(bundle.warehouse["charging_stations"]) >= 2
|
||||
|
||||
# Robot checks
|
||||
assert "light_amr" in bundle.robots["robot_types"]
|
||||
assert "heavy_amr" in bundle.robots["robot_types"]
|
||||
assert len(bundle.robots["fleet"]) >= 4
|
||||
|
||||
# Inventory checks
|
||||
assert len(bundle.inventory["categories"]) >= 3
|
||||
# Check specific items from prompt
|
||||
all_items = []
|
||||
for cat in bundle.inventory["categories"].values():
|
||||
all_items.extend([i["item_id"] for i in cat.get("items", [])])
|
||||
assert any("filter" in i for i in all_items)
|
||||
assert any("transmission" in i for i in all_items)
|
||||
assert any("coil" in i for i in all_items)
|
||||
|
||||
# Simulation checks
|
||||
assert bundle.simulation["simulation"]["duration_seconds"] > 0
|
||||
assert bundle.simulation["simulation"]["random_seed"] == 42
|
||||
|
||||
# Dispatch checks
|
||||
assert bundle.dispatch_policies["active_policy"] in bundle.dispatch_policies["available_policies"]
|
||||
|
||||
|
||||
def test_missing_config_file_raises_error(tmp_path: Path):
|
||||
"""Ensure missing required configuration file raises a clear ConfigurationError."""
|
||||
empty_dir = tmp_path / "empty_cfg"
|
||||
empty_dir.mkdir()
|
||||
|
||||
loader = ConfigLoader(config_dir=empty_dir)
|
||||
with pytest.raises(ConfigurationError) as exc_info:
|
||||
loader.load_all()
|
||||
|
||||
assert "Missing required configuration file" in str(exc_info.value)
|
||||
|
||||
|
||||
def test_invalid_json_syntax_raises_error(temp_config_dir: Path):
|
||||
"""Ensure malformed JSON syntax raises ConfigurationError with line details."""
|
||||
broken_file = temp_config_dir / "warehouse.json"
|
||||
broken_file.write_text("{ unquoted_bad_json: true, }", encoding="utf-8")
|
||||
|
||||
loader = ConfigLoader(config_dir=temp_config_dir)
|
||||
with pytest.raises(ConfigurationError) as exc_info:
|
||||
loader.load_all()
|
||||
|
||||
assert "Invalid JSON syntax" in str(exc_info.value)
|
||||
|
||||
|
||||
def test_missing_warehouse_zone_raises_error(temp_config_dir: Path):
|
||||
"""Ensure omitting a mandatory zone (zone_a, zone_b, zone_c) fails validation."""
|
||||
wh_file = temp_config_dir / "warehouse.json"
|
||||
with open(wh_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
|
||||
# Delete zone_c
|
||||
del data["zones"]["zone_c"]
|
||||
with open(wh_file, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f)
|
||||
|
||||
loader = ConfigLoader(config_dir=temp_config_dir)
|
||||
with pytest.raises(ConfigurationError) as exc_info:
|
||||
loader.load_all()
|
||||
|
||||
assert "missing required zone specification: 'zone_c'" in str(exc_info.value)
|
||||
|
||||
|
||||
def test_invalid_warehouse_dimensions_raises_error(temp_config_dir: Path):
|
||||
"""Ensure non-positive dimensions trigger validation failure."""
|
||||
wh_file = temp_config_dir / "warehouse.json"
|
||||
with open(wh_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
|
||||
data["dimensions"]["width"] = -10.0
|
||||
with open(wh_file, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f)
|
||||
|
||||
loader = ConfigLoader(config_dir=temp_config_dir)
|
||||
with pytest.raises(ConfigurationError) as exc_info:
|
||||
loader.load_all()
|
||||
|
||||
assert "must be a positive number" in str(exc_info.value)
|
||||
|
||||
|
||||
def test_undefined_robot_type_raises_error(temp_config_dir: Path):
|
||||
"""Ensure fleet member referencing an unknown robot_type fails validation."""
|
||||
robots_file = temp_config_dir / "robots.json"
|
||||
with open(robots_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
|
||||
data["fleet"].append({
|
||||
"robot_id": "alien_bot_99",
|
||||
"robot_type": "quantum_antigravity_bot", # Not in robot_types
|
||||
"initial_position": [0, 0, 0]
|
||||
})
|
||||
with open(robots_file, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f)
|
||||
|
||||
loader = ConfigLoader(config_dir=temp_config_dir)
|
||||
with pytest.raises(ConfigurationError) as exc_info:
|
||||
loader.load_all()
|
||||
|
||||
assert "references undefined robot_type 'quantum_antigravity_bot'" in str(exc_info.value)
|
||||
|
||||
|
||||
def test_duplicate_item_id_in_inventory_raises_error(temp_config_dir: Path):
|
||||
"""Ensure duplicate item_id in inventory fails validation."""
|
||||
inv_file = temp_config_dir / "inventory.json"
|
||||
with open(inv_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
|
||||
# Add duplicate item_1
|
||||
data["categories"]["zone_a_items"]["items"].append({
|
||||
"item_id": "item_1",
|
||||
"name": "Duplicate Item 1",
|
||||
})
|
||||
with open(inv_file, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f)
|
||||
|
||||
loader = ConfigLoader(config_dir=temp_config_dir)
|
||||
with pytest.raises(ConfigurationError) as exc_info:
|
||||
loader.load_all()
|
||||
|
||||
assert "Duplicate item_id 'item_1' detected" in str(exc_info.value)
|
||||
|
||||
|
||||
def test_invalid_active_dispatch_policy_raises_error(temp_config_dir: Path):
|
||||
"""Ensure active policy not present in available_policies raises error."""
|
||||
disp_file = temp_config_dir / "dispatch_policies.json"
|
||||
with open(disp_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
|
||||
data["active_policy"] = "non_existent_policy"
|
||||
with open(disp_file, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f)
|
||||
|
||||
loader = ConfigLoader(config_dir=temp_config_dir)
|
||||
with pytest.raises(ConfigurationError) as exc_info:
|
||||
loader.load_all()
|
||||
|
||||
assert "is not in available_policies" in str(exc_info.value)
|
||||
|
||||
|
||||
def test_config_dir_env_var_override(temp_config_dir: Path, monkeypatch):
|
||||
"""Verify that WAREHOUSE_TWIN_CONFIG_DIR env var is respected."""
|
||||
monkeypatch.setenv("WAREHOUSE_TWIN_CONFIG_DIR", str(temp_config_dir))
|
||||
loader = ConfigLoader() # No explicit config_dir passed
|
||||
assert loader.config_dir == temp_config_dir.resolve()
|
||||
bundle = loader.load_all()
|
||||
assert bundle is not None
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Unit tests for environment validation and system requirements."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from unittest.mock import MagicMock, patch
|
||||
import pytest
|
||||
|
||||
from warehouse_twin import __version__
|
||||
from warehouse_twin.cli import check_environment
|
||||
|
||||
|
||||
def test_package_metadata():
|
||||
"""Verify that package version and name are properly defined."""
|
||||
assert __version__ == "0.1.0"
|
||||
|
||||
|
||||
def test_python_version():
|
||||
"""Ensure runtime Python meets the minimum requirement of >= 3.10."""
|
||||
major, minor = sys.version_info[:2]
|
||||
assert (major, minor) >= (3, 10), f"Python version {major}.{minor} is below minimum 3.10"
|
||||
|
||||
|
||||
def test_required_dependencies_importable():
|
||||
"""Verify that core simulation dependencies can be imported successfully."""
|
||||
import simpy
|
||||
import networkx
|
||||
import pytest as pt
|
||||
|
||||
assert simpy.__version__ is not None
|
||||
assert networkx.__version__ is not None
|
||||
assert pt.__version__ is not None
|
||||
|
||||
|
||||
def test_check_environment_passes():
|
||||
"""Verify that the check_environment CLI routine executes and passes."""
|
||||
exit_code = check_environment()
|
||||
assert exit_code == 0
|
||||
|
||||
|
||||
def test_check_environment_detects_low_disk(monkeypatch):
|
||||
"""Verify that critical low disk space (<2GB) generates a failure return code."""
|
||||
# Mock shutil.disk_usage to return 1 GB free
|
||||
fake_usage = MagicMock()
|
||||
fake_usage.free = 1 * (1024**3) # 1 GB
|
||||
fake_usage.total = 100 * (1024**3)
|
||||
|
||||
with patch("shutil.disk_usage", return_value=fake_usage):
|
||||
exit_code = check_environment()
|
||||
assert exit_code == 1, "check_environment should fail when disk space is below 2 GB"
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Unit tests for structured and rotating logging configuration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from warehouse_twin.logging_config import (
|
||||
get_logger,
|
||||
get_simulation_logger,
|
||||
setup_logging,
|
||||
)
|
||||
|
||||
|
||||
def test_logging_directory_creation(tmp_path: Path):
|
||||
"""Verify that setup_logging automatically creates the requested log directory."""
|
||||
test_log_dir = tmp_path / "custom_logs"
|
||||
assert not test_log_dir.exists()
|
||||
|
||||
setup_logging(log_dir=test_log_dir, force_reinit=True)
|
||||
assert test_log_dir.exists()
|
||||
assert test_log_dir.is_dir()
|
||||
|
||||
|
||||
def test_log_files_created_and_written(tmp_path: Path):
|
||||
"""Verify application.log, simulation.log, and errors.log creation and message routing."""
|
||||
test_log_dir = tmp_path / "test_logs"
|
||||
setup_logging(
|
||||
log_dir=test_log_dir,
|
||||
console_level=logging.WARNING,
|
||||
file_level=logging.DEBUG,
|
||||
force_reinit=True,
|
||||
)
|
||||
|
||||
app_logger = get_logger("test_module")
|
||||
sim_logger = get_simulation_logger()
|
||||
|
||||
# Emit various levels of logs
|
||||
app_logger.debug("Test debug message")
|
||||
app_logger.info("Test info message")
|
||||
app_logger.error("Test error message occurred")
|
||||
|
||||
sim_logger.info("Simulation order released: ORD-1001")
|
||||
|
||||
# Flush all handlers
|
||||
for handler in logging.getLogger().handlers:
|
||||
handler.flush()
|
||||
for handler in sim_logger.handlers:
|
||||
handler.flush()
|
||||
|
||||
app_log = test_log_dir / "application.log"
|
||||
err_log = test_log_dir / "errors.log"
|
||||
sim_log = test_log_dir / "simulation.log"
|
||||
|
||||
assert app_log.exists(), "application.log was not created"
|
||||
assert err_log.exists(), "errors.log was not created"
|
||||
assert sim_log.exists(), "simulation.log was not created"
|
||||
|
||||
app_content = app_log.read_text(encoding="utf-8")
|
||||
err_content = err_log.read_text(encoding="utf-8")
|
||||
sim_content = sim_log.read_text(encoding="utf-8")
|
||||
|
||||
# application.log should contain debug, info, and error
|
||||
assert "Test debug message" in app_content
|
||||
assert "Test info message" in app_content
|
||||
assert "Test error message occurred" in app_content
|
||||
|
||||
# errors.log must ONLY contain the error, not debug or info
|
||||
assert "Test error message occurred" in err_content
|
||||
assert "Test info message" not in err_content
|
||||
assert "Test debug message" not in err_content
|
||||
|
||||
# simulation.log must contain the simulation event
|
||||
assert "ORD-1001" in sim_content
|
||||
|
||||
|
||||
def test_log_file_rotation(tmp_path: Path):
|
||||
"""Verify that log files rotate when exceeding the configured max_bytes."""
|
||||
test_log_dir = tmp_path / "rotating_logs"
|
||||
# Set a very small max_bytes threshold (250 bytes) with 3 backups
|
||||
setup_logging(
|
||||
log_dir=test_log_dir,
|
||||
file_level=logging.INFO,
|
||||
max_bytes=250,
|
||||
backup_count=3,
|
||||
force_reinit=True,
|
||||
)
|
||||
|
||||
logger = get_logger("rotator")
|
||||
|
||||
# Write enough lines to exceed 250 bytes multiple times
|
||||
for i in range(40):
|
||||
logger.info(f"Writing log rotation payload line {i:03d} - padding to exceed byte limit")
|
||||
|
||||
for handler in logging.getLogger().handlers:
|
||||
handler.flush()
|
||||
|
||||
app_log = test_log_dir / "application.log"
|
||||
backup_1 = test_log_dir / "application.log.1"
|
||||
|
||||
assert app_log.exists()
|
||||
assert backup_1.exists(), "Expected rotated backup log file 'application.log.1' to exist"
|
||||
Reference in New Issue
Block a user