init
This commit is contained in:
30 files changed
+1757
No files matched your search
@@ -0,0 +1,63 @@
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from warehouse_allocation.api import create_app
|
||||
from warehouse_allocation.config import Settings
|
||||
from warehouse_allocation.infrastructure.inventory import InMemoryInventoryRepository
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def inventory() -> InMemoryInventoryRepository:
|
||||
return InMemoryInventoryRepository()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def client(
|
||||
inventory: InMemoryInventoryRepository,
|
||||
) -> AsyncIterator[httpx.AsyncClient]:
|
||||
app = create_app(Settings(inventory_backend="memory"), inventory)
|
||||
async with app.router.lifespan_context(app):
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def allocation_payload() -> dict[str, object]:
|
||||
return {
|
||||
"requestId": "order-1001",
|
||||
"customerLocation": {"latitude": 35.7219, "longitude": 51.3347},
|
||||
"items": [{"sku": "SKU-RED-42", "quantity": 2}],
|
||||
"transportationCosts": [
|
||||
{
|
||||
"warehouseId": "tehran-west",
|
||||
"fixedCost": 100,
|
||||
"distanceKm": 12,
|
||||
"costPerKm": 2,
|
||||
"baseDeliveryMinutes": 60,
|
||||
},
|
||||
{
|
||||
"warehouseId": "karaj",
|
||||
"fixedCost": 90,
|
||||
"distanceKm": 50,
|
||||
"costPerKm": 2,
|
||||
"baseDeliveryMinutes": 100,
|
||||
},
|
||||
],
|
||||
"logisticsConstraints": [
|
||||
{
|
||||
"warehouseId": "tehran-west",
|
||||
"trafficMultiplier": 1.2,
|
||||
"fleetPriority": 1.1,
|
||||
"handlingMinutes": 10,
|
||||
},
|
||||
{
|
||||
"warehouseId": "karaj",
|
||||
"trafficMultiplier": 1,
|
||||
"fleetPriority": 1,
|
||||
"handlingMinutes": 10,
|
||||
},
|
||||
],
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import httpx
|
||||
|
||||
from warehouse_allocation.infrastructure.inventory import InMemoryInventoryRepository
|
||||
|
||||
|
||||
async def seed(repository: InMemoryInventoryRepository) -> None:
|
||||
await repository.set_levels("tehran-west", {"SKU-RED-42": 10})
|
||||
await repository.set_levels("karaj", {"SKU-RED-42": 10})
|
||||
|
||||
|
||||
async def test_allocation_contract_and_selection(
|
||||
client: httpx.AsyncClient,
|
||||
inventory: InMemoryInventoryRepository,
|
||||
allocation_payload: dict[str, object],
|
||||
) -> None:
|
||||
await seed(inventory)
|
||||
|
||||
response = await client.post("/v1/allocations", json=allocation_payload)
|
||||
|
||||
assert response.status_code == 200, response.text
|
||||
assert response.headers["x-process-time-ms"]
|
||||
body = response.json()
|
||||
assert body["requestId"] == "order-1001"
|
||||
assert body["warehouseId"] == "tehran-west"
|
||||
assert body["estimatedDeliveryTime"] == 75
|
||||
assert body["totalCost"] == 116.11
|
||||
assert 0 <= body["routeOptimizationScore"] <= 100
|
||||
assert body["scoreBreakdown"]["feasibleWarehouseCount"] == 2
|
||||
|
||||
|
||||
async def test_reservation_decrements_inventory(
|
||||
client: httpx.AsyncClient,
|
||||
inventory: InMemoryInventoryRepository,
|
||||
allocation_payload: dict[str, object],
|
||||
) -> None:
|
||||
await inventory.set_levels("tehran-west", {"SKU-RED-42": 2})
|
||||
await inventory.set_levels("karaj", {"SKU-RED-42": 0})
|
||||
allocation_payload["reserveInventory"] = True
|
||||
|
||||
first = await client.post("/v1/allocations", json=allocation_payload)
|
||||
second = await client.post("/v1/allocations", json=allocation_payload)
|
||||
|
||||
assert first.status_code == 200, first.text
|
||||
assert first.json()["inventoryReserved"] is True
|
||||
assert second.status_code == 409
|
||||
assert second.json()["error"]["code"] == "NO_FEASIBLE_WAREHOUSE"
|
||||
|
||||
|
||||
async def test_no_single_warehouse_can_split_fulfillment(
|
||||
client: httpx.AsyncClient,
|
||||
inventory: InMemoryInventoryRepository,
|
||||
allocation_payload: dict[str, object],
|
||||
) -> None:
|
||||
await inventory.set_levels("tehran-west", {"SKU-RED-42": 1})
|
||||
await inventory.set_levels("karaj", {"SKU-RED-42": 1})
|
||||
|
||||
response = await client.post("/v1/allocations", json=allocation_payload)
|
||||
|
||||
assert response.status_code == 409
|
||||
|
||||
|
||||
async def test_inventory_upsert_and_health_endpoints(client: httpx.AsyncClient) -> None:
|
||||
upsert = await client.put(
|
||||
"/v1/inventory",
|
||||
json={"warehouseId": "w1", "levels": [{"sku": "A", "quantity": 5}]},
|
||||
)
|
||||
live = await client.get("/health/live")
|
||||
ready = await client.get("/health/ready")
|
||||
metrics = await client.get("/metrics")
|
||||
|
||||
assert upsert.status_code == 204, upsert.text
|
||||
assert live.json()["status"] == "ok"
|
||||
assert ready.json()["inventory"] == "ok"
|
||||
assert "warehouse_allocation_requests_total" in metrics.text
|
||||
|
||||
|
||||
async def test_validation_error_is_structured(
|
||||
client: httpx.AsyncClient, allocation_payload: dict[str, object]
|
||||
) -> None:
|
||||
allocation_payload["customerLocation"] = {"latitude": 200, "longitude": 51}
|
||||
|
||||
response = await client.post("/v1/allocations", json=allocation_payload)
|
||||
|
||||
assert response.status_code == 422
|
||||
assert response.json()["detail"]
|
||||
@@ -0,0 +1,72 @@
|
||||
import pytest
|
||||
|
||||
from warehouse_allocation.application import AllocationService
|
||||
from warehouse_allocation.config import Settings
|
||||
from warehouse_allocation.domain.exceptions import CandidateLimitExceededError
|
||||
from warehouse_allocation.domain.models import AllocationRequest
|
||||
from warehouse_allocation.infrastructure.inventory import InMemoryInventoryRepository
|
||||
|
||||
|
||||
def allocation_request(*, reserve: bool = False) -> AllocationRequest:
|
||||
return AllocationRequest.model_validate(
|
||||
{
|
||||
"requestId": "fallback-test",
|
||||
"customerLocation": {"latitude": 35, "longitude": 51},
|
||||
"items": [{"sku": "A", "quantity": 2}],
|
||||
"transportationCosts": [
|
||||
{
|
||||
"warehouseId": "w1",
|
||||
"fixedCost": 10,
|
||||
"distanceKm": 1,
|
||||
"baseDeliveryMinutes": 10,
|
||||
},
|
||||
{
|
||||
"warehouseId": "w2",
|
||||
"fixedCost": 20,
|
||||
"distanceKm": 2,
|
||||
"baseDeliveryMinutes": 20,
|
||||
},
|
||||
],
|
||||
"reserveInventory": reserve,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def test_quote_does_not_mutate_inventory() -> None:
|
||||
inventory = InMemoryInventoryRepository()
|
||||
await inventory.set_levels("w1", {"A": 2})
|
||||
service = AllocationService(inventory, Settings())
|
||||
|
||||
response = await service.allocate(allocation_request())
|
||||
|
||||
assert response.warehouse_id == "w1"
|
||||
assert response.inventory_reserved is False
|
||||
assert await inventory.feasible_warehouses(["w1"], {"A": 2}) == {"w1"}
|
||||
|
||||
|
||||
async def test_reservation_falls_back_after_concurrent_stock_change() -> None:
|
||||
inventory = InMemoryInventoryRepository()
|
||||
await inventory.set_levels("w1", {"A": 1})
|
||||
await inventory.set_levels("w2", {"A": 2})
|
||||
service = AllocationService(inventory, Settings())
|
||||
|
||||
# Simulate an optimistic feasibility read that becomes stale before the atomic reservation.
|
||||
original_feasible = inventory.feasible_warehouses
|
||||
|
||||
async def stale_feasible(*args: object, **kwargs: object) -> set[str]:
|
||||
del args, kwargs
|
||||
return {"w1", "w2"}
|
||||
|
||||
inventory.feasible_warehouses = stale_feasible # type: ignore[method-assign]
|
||||
response = await service.allocate(allocation_request(reserve=True))
|
||||
inventory.feasible_warehouses = original_feasible # type: ignore[method-assign]
|
||||
|
||||
assert response.warehouse_id == "w2"
|
||||
assert response.inventory_reserved is True
|
||||
|
||||
|
||||
async def test_candidate_limit_is_enforced() -> None:
|
||||
service = AllocationService(InMemoryInventoryRepository(), Settings(max_candidate_warehouses=1))
|
||||
|
||||
with pytest.raises(CandidateLimitExceededError, match="at most 1"):
|
||||
await service.allocate(allocation_request())
|
||||
@@ -0,0 +1,27 @@
|
||||
import asyncio
|
||||
|
||||
from warehouse_allocation.infrastructure.inventory import InMemoryInventoryRepository
|
||||
|
||||
|
||||
async def test_feasibility_requires_every_sku() -> None:
|
||||
repository = InMemoryInventoryRepository()
|
||||
await repository.set_levels("w1", {"A": 3, "B": 1})
|
||||
await repository.set_levels("w2", {"A": 4, "B": 5})
|
||||
|
||||
feasible = await repository.feasible_warehouses(["w1", "w2", "w3"], {"A": 2, "B": 2})
|
||||
|
||||
assert feasible == {"w2"}
|
||||
|
||||
|
||||
async def test_concurrent_reservations_do_not_oversell() -> None:
|
||||
repository = InMemoryInventoryRepository()
|
||||
await repository.set_levels("w1", {"A": 5})
|
||||
|
||||
results = await asyncio.gather(
|
||||
repository.reserve("w1", {"A": 4}),
|
||||
repository.reserve("w1", {"A": 4}),
|
||||
)
|
||||
|
||||
assert sorted(results) == [False, True]
|
||||
assert await repository.feasible_warehouses(["w1"], {"A": 2}) == set()
|
||||
assert await repository.ping() is True
|
||||
@@ -0,0 +1,108 @@
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from warehouse_allocation.domain.models import AllocationRequest
|
||||
from warehouse_allocation.domain.optimizer import rank_warehouses
|
||||
|
||||
|
||||
def request_from(**overrides: object) -> AllocationRequest:
|
||||
payload: dict[str, object] = {
|
||||
"requestId": "optimizer-test",
|
||||
"customerLocation": {"latitude": 35.7, "longitude": 51.4},
|
||||
"items": [{"sku": "A", "quantity": 1}],
|
||||
"transportationCosts": [
|
||||
{
|
||||
"warehouseId": "cheap",
|
||||
"fixedCost": 100,
|
||||
"distanceKm": 0,
|
||||
"baseDeliveryMinutes": 120,
|
||||
},
|
||||
{
|
||||
"warehouseId": "fast",
|
||||
"fixedCost": 150,
|
||||
"distanceKm": 0,
|
||||
"baseDeliveryMinutes": 60,
|
||||
},
|
||||
],
|
||||
}
|
||||
payload.update(overrides)
|
||||
return AllocationRequest.model_validate(payload)
|
||||
|
||||
|
||||
def test_cost_weight_selects_cheaper_warehouse() -> None:
|
||||
ranked = rank_warehouses(request_from(), {"cheap", "fast"})
|
||||
|
||||
assert ranked[0].warehouse_id == "cheap"
|
||||
assert ranked[0].score == pytest.approx(70)
|
||||
assert ranked[0].breakdown.feasible_warehouse_count == 2
|
||||
|
||||
|
||||
def test_delivery_weight_selects_faster_warehouse() -> None:
|
||||
request = request_from(weights={"cost": 0.2, "deliveryTime": 0.8})
|
||||
|
||||
ranked = rank_warehouses(request, {"cheap", "fast"})
|
||||
|
||||
assert ranked[0].warehouse_id == "fast"
|
||||
|
||||
|
||||
def test_traffic_and_fleet_change_effective_time_and_cost() -> None:
|
||||
request = request_from(
|
||||
logisticsConstraints=[
|
||||
{
|
||||
"warehouseId": "cheap",
|
||||
"trafficMultiplier": 2,
|
||||
"fleetPriority": 0.5,
|
||||
"handlingMinutes": 20,
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
ranked = rank_warehouses(request, {"cheap", "fast"})
|
||||
|
||||
assert ranked[0].warehouse_id == "fast"
|
||||
cheap = next(candidate for candidate in ranked if candidate.warehouse_id == "cheap")
|
||||
assert cheap.delivery_minutes == pytest.approx(520)
|
||||
assert cheap.total_cost == pytest.approx(230)
|
||||
|
||||
|
||||
def test_sla_overrun_adds_bounded_penalty() -> None:
|
||||
ranked = rank_warehouses(
|
||||
request_from(promisedDeliveryMinutes=30),
|
||||
{"cheap", "fast"},
|
||||
)
|
||||
|
||||
assert all(candidate.breakdown.sla_penalty == 0.25 for candidate in ranked)
|
||||
|
||||
|
||||
def test_unavailable_and_infeasible_candidates_are_removed() -> None:
|
||||
request = request_from(logisticsConstraints=[{"warehouseId": "cheap", "available": False}])
|
||||
|
||||
assert rank_warehouses(request, {"cheap"}) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"override",
|
||||
[
|
||||
{"weights": {"cost": 0.4, "deliveryTime": 0.4}},
|
||||
{"items": [{"sku": "A", "quantity": 1}, {"sku": "A", "quantity": 2}]},
|
||||
{
|
||||
"transportationCosts": [
|
||||
{
|
||||
"warehouseId": "duplicate",
|
||||
"fixedCost": 1,
|
||||
"distanceKm": 1,
|
||||
"baseDeliveryMinutes": 1,
|
||||
},
|
||||
{
|
||||
"warehouseId": "duplicate",
|
||||
"fixedCost": 2,
|
||||
"distanceKm": 1,
|
||||
"baseDeliveryMinutes": 1,
|
||||
},
|
||||
]
|
||||
},
|
||||
],
|
||||
)
|
||||
def test_invalid_requests_are_rejected(override: dict[str, object]) -> None:
|
||||
with pytest.raises(ValidationError):
|
||||
request_from(**override)
|
||||
@@ -0,0 +1,106 @@
|
||||
import pytest
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from warehouse_allocation.domain.exceptions import InventoryUnavailableError
|
||||
from warehouse_allocation.infrastructure.inventory import RedisInventoryRepository
|
||||
|
||||
|
||||
class FakePipeline:
|
||||
def __init__(self, rows: dict[str, dict[str, int]], fails: bool = False) -> None:
|
||||
self.rows = rows
|
||||
self.fails = fails
|
||||
self.queries: list[tuple[str, list[str]]] = []
|
||||
|
||||
async def __aenter__(self) -> "FakePipeline":
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *args: object) -> None:
|
||||
return None
|
||||
|
||||
def hmget(self, key: str, fields: list[str]) -> None:
|
||||
self.queries.append((key, fields))
|
||||
|
||||
async def execute(self) -> list[list[int | None]]:
|
||||
if self.fails:
|
||||
raise RedisError("down")
|
||||
return [
|
||||
[self.rows.get(key, {}).get(field) for field in fields] for key, fields in self.queries
|
||||
]
|
||||
|
||||
|
||||
class FakeRedis:
|
||||
def __init__(self, *, fails: bool = False) -> None:
|
||||
self.rows: dict[str, dict[str, int]] = {
|
||||
"inventory:w1": {"A": 3, "B": 2},
|
||||
"inventory:w2": {"A": 1, "B": 5},
|
||||
}
|
||||
self.fails = fails
|
||||
self.closed = False
|
||||
self.eval_result = 1
|
||||
|
||||
def pipeline(self, transaction: bool = False) -> FakePipeline:
|
||||
assert transaction is False
|
||||
return FakePipeline(self.rows, self.fails)
|
||||
|
||||
async def eval(self, *args: object) -> int:
|
||||
if self.fails:
|
||||
raise RedisError("down")
|
||||
assert args[1] == 1
|
||||
return self.eval_result
|
||||
|
||||
async def hset(self, key: str, mapping: dict[str, int]) -> int:
|
||||
if self.fails:
|
||||
raise RedisError("down")
|
||||
self.rows.setdefault(key, {}).update(mapping)
|
||||
return len(mapping)
|
||||
|
||||
async def ping(self) -> bool:
|
||||
if self.fails:
|
||||
raise RedisError("down")
|
||||
return True
|
||||
|
||||
async def aclose(self) -> None:
|
||||
self.closed = True
|
||||
|
||||
|
||||
def repository(client: FakeRedis) -> RedisInventoryRepository:
|
||||
return RedisInventoryRepository(client) # type: ignore[arg-type]
|
||||
|
||||
|
||||
async def test_pipeline_feasibility_and_missing_values() -> None:
|
||||
result = await repository(FakeRedis()).feasible_warehouses(
|
||||
["w1", "w2", "missing"], {"A": 2, "B": 2}
|
||||
)
|
||||
|
||||
assert result == {"w1"}
|
||||
|
||||
|
||||
async def test_reserve_set_ping_and_close() -> None:
|
||||
client = FakeRedis()
|
||||
adapter = repository(client)
|
||||
|
||||
assert await adapter.reserve("w1", {"A": 2, "B": 1}) is True
|
||||
client.eval_result = 0
|
||||
assert await adapter.reserve("w1", {"A": 99}) is False
|
||||
await adapter.set_levels("w3", {"A": 7})
|
||||
assert client.rows["inventory:w3"] == {"A": 7}
|
||||
assert await adapter.ping() is True
|
||||
await adapter.close()
|
||||
assert client.closed is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("operation", ["feasible", "reserve", "set_levels"])
|
||||
async def test_redis_errors_become_domain_errors(operation: str) -> None:
|
||||
adapter = repository(FakeRedis(fails=True))
|
||||
|
||||
with pytest.raises(InventoryUnavailableError):
|
||||
if operation == "feasible":
|
||||
await adapter.feasible_warehouses(["w1"], {"A": 1})
|
||||
elif operation == "reserve":
|
||||
await adapter.reserve("w1", {"A": 1})
|
||||
else:
|
||||
await adapter.set_levels("w1", {"A": 1})
|
||||
|
||||
|
||||
async def test_failed_ping_reports_not_ready() -> None:
|
||||
assert await repository(FakeRedis(fails=True)).ping() is False
|
||||
Reference in new issue
Block a user