This commit is contained in:
Meghdad committed 2026-07-23 06:40:30 +03:30
1 parent 26d41cd03f
commit db57e0e4a2
30 files changed
+1757

No files matched your search

+72
View File
@@ -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())
+27
View File
@@ -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
+108
View File
@@ -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)
+106
View File
@@ -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