Files
2026-07-23 06:40:30 +03:30

73 lines
2.7 KiB
Python

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())