Skip to content

Commit 58eb819

Browse files
committed
unit tests all functional and immutable
1 parent fd45a6f commit 58eb819

6 files changed

Lines changed: 42 additions & 49 deletions

File tree

‎domain/model.py‎

Lines changed: 20 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,45 @@
11
from __future__ import annotations
2-
from dataclasses import dataclass
2+
from dataclasses import dataclass, field, replace
33
from datetime import date
4-
from typing import Optional, List, Set
4+
from typing import Optional, Iterable, List, Set
55

66

77
class OutOfStock(Exception):
88
pass
99

1010

11-
def allocate(line: OrderLine, batches: List[Batch]) -> str:
12-
try:
13-
batch = next(b for b in sorted(batches) if b.can_allocate(line))
14-
batch.allocate(line)
15-
return batch.reference
16-
except StopIteration:
17-
raise OutOfStock(f"Out of stock for sku {line.sku}")
11+
def allocate(line: OrderLine, batches: List[Batch]) -> Optional[Batch]:
12+
for b in sorted(batches):
13+
if b.can_allocate(line):
14+
return b.allocate(line)
15+
raise OutOfStock(f"Out of stock for sku {line.sku}")
1816

1917

20-
@dataclass(unsafe_hash=True)
18+
@dataclass(frozen=True)
2119
class OrderLine:
2220
orderid: str
2321
sku: str
2422
qty: int
2523

2624

25+
@dataclass(frozen=True)
2726
class Batch:
28-
def __init__(self, ref: str, sku: str, qty: int, eta: Optional[date]):
29-
self.reference = ref
30-
self.sku = sku
31-
self.eta = eta
32-
self._purchased_quantity = qty
33-
self._allocations = set() # type: Set[OrderLine]
27+
ref: str
28+
sku: str
29+
_purchased_quantity: int
30+
eta: Optional[date]
31+
_allocations: Set[OrderLine] = field(default_factory=set)
3432

3533
def __repr__(self):
36-
return f"<Batch {self.reference}>"
34+
return f"<Batch {self.ref}>"
3735

3836
def __eq__(self, other):
3937
if not isinstance(other, Batch):
4038
return False
41-
return other.reference == self.reference
39+
return other.ref == self.ref
4240

4341
def __hash__(self):
44-
return hash(self.reference)
42+
return hash(self.ref)
4543

4644
def __gt__(self, other):
4745
if self.eta is None:
@@ -50,13 +48,12 @@ def __gt__(self, other):
5048
return True
5149
return self.eta > other.eta
5250

53-
def allocate(self, line: OrderLine):
51+
def allocate(self, line: OrderLine) -> Self:
5452
if self.can_allocate(line):
55-
self._allocations.add(line)
53+
return replace(self, _allocations=self._allocations | {line})
5654

5755
def deallocate(self, line: OrderLine):
58-
if line in self._allocations:
59-
self._allocations.remove(line)
56+
return replace(self, _allocations=self._allocations - {line})
6057

6158
@property
6259
def allocated_quantity(self) -> int:

‎requirements.txt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,5 @@ sqlalchemy
33
flask
44
psycopg2-binary
55
requests
6+
mypy
7+
black

‎service_layer/services.py‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,12 @@ def add_batch(
2626
def allocate(
2727
orderid: str, sku: str, qty: int,
2828
repo: AbstractRepository, session
29-
) -> str:
29+
) -> Optional[str]:
3030
line = OrderLine(orderid, sku, qty)
3131
batches = repo.list()
3232
if not is_valid_sku(line.sku, batches):
3333
raise InvalidSku(f"Invalid sku {line.sku}")
34-
batchref = model.allocate(line, batches)
34+
updated_batch = model.allocate(line, batches)
35+
3536
session.commit()
36-
return batchref
37+
return updated_batch.ref if updated_batch else None

‎tests/unit/test_allocate.py‎

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,10 @@ def test_prefers_current_stock_batches_to_shipments():
1212
shipment_batch = Batch("shipment-batch", "RETRO-CLOCK", 100, eta=tomorrow)
1313
line = OrderLine("oref", "RETRO-CLOCK", 10)
1414

15-
allocate(line, [in_stock_batch, shipment_batch])
15+
updated_batch = allocate(line, [in_stock_batch, shipment_batch])
1616

17-
assert in_stock_batch.available_quantity == 90
18-
assert shipment_batch.available_quantity == 100
17+
assert updated_batch.ref == in_stock_batch.ref
18+
assert updated_batch.available_quantity == 90
1919

2020

2121
def test_prefers_earlier_batches():
@@ -24,24 +24,17 @@ def test_prefers_earlier_batches():
2424
latest = Batch("slow-batch", "MINIMALIST-SPOON", 100, eta=later)
2525
line = OrderLine("order1", "MINIMALIST-SPOON", 10)
2626

27-
allocate(line, [medium, earliest, latest])
27+
updated_batch = allocate(line, [medium, earliest, latest])
2828

29-
assert earliest.available_quantity == 90
30-
assert medium.available_quantity == 100
31-
assert latest.available_quantity == 100
32-
33-
34-
def test_returns_allocated_batch_ref():
35-
in_stock_batch = Batch("in-stock-batch-ref", "HIGHBROW-POSTER", 100, eta=None)
36-
shipment_batch = Batch("shipment-batch-ref", "HIGHBROW-POSTER", 100, eta=tomorrow)
37-
line = OrderLine("oref", "HIGHBROW-POSTER", 10)
38-
allocation = allocate(line, [in_stock_batch, shipment_batch])
39-
assert allocation == in_stock_batch.reference
29+
assert updated_batch.ref == earliest.ref
30+
assert updated_batch.available_quantity == 90
4031

4132

4233
def test_raises_out_of_stock_exception_if_cannot_allocate():
4334
batch = Batch("batch1", "SMALL-FORK", 10, eta=today)
44-
allocate(OrderLine("order1", "SMALL-FORK", 10), [batch])
35+
updated_batch = allocate(OrderLine("order1", "SMALL-FORK", 10), [batch])
36+
assert updated_batch
4537

4638
with pytest.raises(OutOfStock, match="SMALL-FORK"):
47-
allocate(OrderLine("order2", "SMALL-FORK", 1), [batch])
39+
result = allocate(OrderLine("order2", "SMALL-FORK", 1), [updated_batch])
40+
assert result is None

‎tests/unit/test_batches.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33

44

55
def test_allocating_to_a_batch_reduces_the_available_quantity():
6-
batch = Batch("batch-001", "SMALL-TABLE", qty=20, eta=date.today())
6+
batch = Batch("batch-001", "SMALL-TABLE", 20, eta=date.today())
77
line = OrderLine("order-ref", "SMALL-TABLE", 2)
88

9-
batch.allocate(line)
9+
batch = batch.allocate(line)
1010

1111
assert batch.available_quantity == 18
1212

@@ -41,8 +41,8 @@ def test_cannot_allocate_if_skus_do_not_match():
4141

4242
def test_allocation_is_idempotent():
4343
batch, line = make_batch_and_line("ANGULAR-DESK", 20, 2)
44-
batch.allocate(line)
45-
batch.allocate(line)
44+
batch = batch.allocate(line)
45+
batch = batch.allocate(line)
4646
assert batch.available_quantity == 18
4747

4848

‎tests/unit/test_services.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ def __init__(self, batches):
1010
def add(self, batch):
1111
self._batches.add(batch)
1212

13-
def get(self, reference):
14-
return next(b for b in self._batches if b.reference == reference)
13+
def get(self, ref):
14+
return next(b for b in self._batches if b.ref == ref)
1515

1616
def list(self):
1717
return list(self._batches)

0 commit comments

Comments
 (0)