Skip to content

Commit 68132fd

Browse files
committed
faffing abotu trynna get an async repo working
1 parent 1ef602f commit 68132fd

5 files changed

Lines changed: 149 additions & 70 deletions

File tree

‎adapters/repository.py‎

Lines changed: 70 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,58 @@
11
import abc
22
from domain import model
3-
from typing import Iterable
3+
from typing import Iterable, AsyncIterator
4+
from sqlalchemy import text
5+
from sqlalchemy.ext.asyncio import AsyncSession
46

57

68
class AbstractRepository(abc.ABC):
79
@abc.abstractmethod
8-
def add(self, batch: model.Batch):
10+
async def add(self, batch: model.Batch) -> None:
911
raise NotImplementedError
1012

1113
@abc.abstractmethod
12-
def get(self, reference) -> model.Batch:
14+
async def get(self, ref: str) -> model.Batch:
1315
raise NotImplementedError
1416

1517

1618
class SqlAlchemyRepository(AbstractRepository):
17-
def __init__(self, session):
19+
def __init__(self, session: AsyncSession):
1820
self._session = session
1921

20-
async def add(self, batch):
22+
async def add(self, batch: model.Batch) -> None:
2123
batch_id = await self._add_batch(batch)
2224
await self._add_allocations(batch_id, batch._allocations)
2325

24-
async def _add_batch(self, batch: model.Batch):
26+
async def _add_batch(self, batch: model.Batch) -> int:
2527
async with self._session as session:
2628
async with session.begin():
2729
result = await session.execute(
28-
"""
29-
INSERT INTO batches (ref, sku, _purchased_quantity, eta)
30-
VALUES ( :ref, :sku, :_purchased_quantity, :eta )
31-
RETURNING id
32-
""",
33-
dict(ref=batch.ref, sku=batch.sku, _purchased_quantity=batch._purchased_quantity, eta=batch.eta),
34-
30+
text(
31+
"""
32+
INSERT INTO batches (ref, sku, _purchased_quantity, eta)
33+
VALUES ( :ref, :sku, :_purchased_quantity, :eta )
34+
RETURNING id
35+
"""
36+
),
37+
dict(
38+
ref=batch.ref,
39+
sku=batch.sku,
40+
_purchased_quantity=batch._purchased_quantity,
41+
eta=batch.eta,
42+
),
3543
)
36-
[batch_id] = result
37-
return batch_id
44+
[[batch_id]] = result
45+
return int(batch_id)
3846

39-
async def _add_allocations(self, batch_id: int, allocations: Iterable[model.OrderLine]):
47+
async def _add_allocations(
48+
self, batch_id: int, allocations: Iterable[model.OrderLine]
49+
) -> None:
4050
return
4151
# for line in allocations:
4252
# async with self._session as session:
4353
# await session.execute(
4454
# """
45-
# INSERT INTO order_lines (orderline_id, batch_id)
55+
# INSERT INTO order_lines (orderline_id, batch_id)
4656
# VALUES ( %{orderline_id}d, %{batch_id}d )
4757
# ON CONFLICT DO UPDATE SET
4858
# orderline_id=%{orderline_id}d,
@@ -51,8 +61,48 @@ async def _add_allocations(self, batch_id: int, allocations: Iterable[model.Orde
5161
# dict(batch_id=batch_id, orderline_id=
5262
# )
5363

54-
def get(self, reference):
55-
return self.session.query(model.Batch).filter_by(reference=reference).one()
64+
async def get(self, ref: str) -> model.Batch:
65+
async with self._session as session:
66+
[row] = await session.execute(
67+
text(
68+
"""
69+
SELECT id, ref, sku, _purchased_quantity, eta
70+
FROM batches
71+
WHERE ref = :ref
72+
"""
73+
),
74+
dict(ref=ref),
75+
)
76+
return model.Batch(
77+
ref=row.ref,
78+
sku=row.sku,
79+
_purchased_quantity=row._purchased_quantity,
80+
eta=row.eta
81+
_allocations=self._get_order_lines(batch_id=row.id)
82+
)
83+
84+
async def _get_order_lines(self, batch_id: int) -> AsyncIterator[model.OrderLine]:
85+
async with self._session as session:
86+
rows = await session.execute(
87+
text(
88+
"""
89+
SELECT orderid, sky, qty
90+
FROM allocations
91+
JOIN order_lines ON allocations.orderline_id = order_lines.id
92+
WHERE batch_id = :batch_id
93+
"""
94+
),
95+
dict(batch_id=batch_id),
96+
)
97+
for row in rows:
98+
yield model.OrderLine(
99+
orderid=row.orderid,
100+
sku=row.sku,
101+
qty=row.qty
102+
)
103+
56104

57-
def list(self):
105+
"""
106+
async def list(self) -> List[model.Batch]:
58107
return self.session.query(model.Batch).all()
108+
"""

‎domain/model.py‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from __future__ import annotations
22
from dataclasses import dataclass, field, replace
33
from datetime import date
4-
from typing import Optional, Iterable, List, Set
4+
from typing import Any, Optional, Iterable, List, Set
55

66

77
class OutOfStock(Exception):
@@ -30,29 +30,30 @@ class Batch:
3030
eta: Optional[date]
3131
_allocations: Set[OrderLine] = field(default_factory=set)
3232

33-
def __repr__(self):
33+
def __repr__(self) -> str:
3434
return f"<Batch {self.ref}>"
3535

36-
def __eq__(self, other):
36+
def __eq__(self, other: Any) -> bool:
3737
if not isinstance(other, Batch):
3838
return False
3939
return other.ref == self.ref
4040

41-
def __hash__(self):
41+
def __hash__(self) -> int:
4242
return hash(self.ref)
4343

44-
def __gt__(self, other):
44+
def __gt__(self, other: Batch) -> bool:
4545
if self.eta is None:
4646
return False
4747
if other.eta is None:
4848
return True
4949
return self.eta > other.eta
5050

51-
def allocate(self, line: OrderLine) -> Self:
51+
def allocate(self, line: OrderLine) -> Optional[Batch]:
5252
if self.can_allocate(line):
5353
return replace(self, _allocations=self._allocations | {line})
54+
return None
5455

55-
def deallocate(self, line: OrderLine):
56+
def deallocate(self, line: OrderLine) -> Batch:
5657
return replace(self, _allocations=self._allocations - {line})
5758

5859
@property

‎mypy.ini‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
[mypy]
2-
ignore_missing_imports = False
2+
strict = True
33
plugins = sqlalchemy.ext.mypy.plugin

‎tests/conftest.py‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,17 +27,19 @@ async def in_memory_db() -> AsyncEngine:
2727
await conn.run_sync(metadata.create_all)
2828
return engine
2929

30+
AsyncSessionMaker = Callable[[], AsyncSession]
3031

3132
@pytest_asyncio.fixture
32-
async def session_maker(in_memory_db: AsyncEngine):
33+
async def session_maker(in_memory_db: AsyncEngine) -> AsyncSessionMaker:
3334
return sessionmaker(bind=in_memory_db, class_=AsyncSession)
3435

3536

36-
def wait_for_postgres_to_come_up(engine):
37+
"""
38+
def wait_for_postgres_to_come_up(engine: AsyncEngine):
3739
deadline = time.time() + 10
3840
while time.time() < deadline:
3941
try:
40-
return engine.connect()
42+
return await engine.connect()
4143
except OperationalError:
4244
time.sleep(0.5)
4345
pytest.fail("Postgres never came up")
@@ -74,3 +76,4 @@ def restart_api():
7476
(Path(__file__).parent / "../entrypoints/flask_app.py").touch()
7577
time.sleep(0.5)
7678
wait_for_webapp_to_come_up()
79+
"""

‎tests/integration/test_repository.py‎

Lines changed: 64 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,15 @@
22
import pytest
33
from domain import model
44
from adapters import repository
5+
from typing import Callable
6+
from sqlalchemy.ext.asyncio import AsyncSession
7+
from sqlalchemy import text
8+
9+
AsyncSessionMaker = Callable[[], AsyncSession]
510

611

712
@pytest.mark.asyncio
8-
async def test_repository_can_save_a_batch(session_maker):
13+
async def test_repository_can_save_a_batch(session_maker: AsyncSessionMaker) -> None:
914
batch = model.Batch("batch1", "RUSTY-SOAPDISH", 100, eta=None)
1015

1116
async with session_maker() as session:
@@ -15,57 +20,77 @@ async def test_repository_can_save_a_batch(session_maker):
1520
async with session_maker() as session:
1621
async with session.begin():
1722
rows = await session.execute(
18-
'SELECT ref, sku, _purchased_quantity, eta FROM "batches"'
23+
text('SELECT ref, sku, _purchased_quantity, eta FROM "batches"')
1924
)
2025
assert list(rows) == [("batch1", "RUSTY-SOAPDISH", 100, None)]
2126

22-
if False:
23-
def insert_order_line(session):
24-
session.execute(
27+
28+
async def insert_order_line(session: AsyncSession) -> int:
29+
await session.execute(
30+
text(
2531
"INSERT INTO order_lines (orderid, sku, qty)"
2632
' VALUES ("order1", "GENERIC-SOFA", 12)'
2733
)
28-
[[orderline_id]] = session.execute(
29-
"SELECT id FROM order_lines WHERE orderid=:orderid AND sku=:sku",
30-
dict(orderid="order1", sku="GENERIC-SOFA"),
31-
)
32-
return orderline_id
34+
)
35+
[[orderline_id]] = await session.execute(
36+
text("SELECT id FROM order_lines WHERE orderid=:orderid AND sku=:sku"),
37+
dict(orderid="order1", sku="GENERIC-SOFA"),
38+
)
39+
return int(orderline_id)
3340

3441

35-
def insert_batch(session, batch_id):
36-
session.execute(
37-
"INSERT INTO batches (reference, sku, _purchased_quantity, eta)"
38-
' VALUES (:batch_id, "GENERIC-SOFA", 100, null)',
39-
dict(batch_id=batch_id),
40-
)
41-
[[batch_id]] = session.execute(
42-
'SELECT id FROM batches WHERE reference=:batch_id AND sku="GENERIC-SOFA"',
43-
dict(batch_id=batch_id),
44-
)
45-
return batch_id
42+
async def insert_batch(session: AsyncSession, batch_ref: str) -> int:
43+
await session.execute(
44+
text(
45+
"INSERT INTO batches (ref, sku, _purchased_quantity, eta)"
46+
' VALUES (:batch_ref, "GENERIC-SOFA", 100, null)'
47+
),
48+
dict(batch_ref=batch_ref),
49+
)
50+
[[batch_id]] = await session.execute(
51+
text(
52+
'SELECT id FROM batches WHERE ref=:batch_ref AND sku="GENERIC-SOFA"'
53+
),
54+
dict(batch_ref=batch_ref),
55+
)
56+
return int(batch_id)
4657

4758

48-
def insert_allocation(session, orderline_id, batch_id):
49-
session.execute(
59+
async def insert_allocation(
60+
session: AsyncSession, orderline_id: int, batch_id: int
61+
) -> None:
62+
await session.execute(
63+
text(
5064
"INSERT INTO allocations (orderline_id, batch_id)"
5165
" VALUES (:orderline_id, :batch_id)",
52-
dict(orderline_id=orderline_id, batch_id=batch_id),
53-
)
66+
),
67+
dict(orderline_id=orderline_id, batch_id=batch_id),
68+
)
5469

5570

56-
def test_repository_can_retrieve_a_batch_with_allocations(session):
57-
orderline_id = insert_order_line(session)
58-
batch1_id = insert_batch(session, "batch1")
59-
insert_batch(session, "batch2")
60-
insert_allocation(session, orderline_id, batch1_id)
71+
@pytest.mark.asyncio
72+
async def test_repository_can_retrieve_a_batch_with_allocations(
73+
session_maker: AsyncSessionMaker,
74+
) -> None:
75+
async with session_maker() as session:
76+
async with session.begin():
77+
orderline_id = await insert_order_line(session)
78+
batch1_id = await insert_batch(session, "batch1")
79+
await insert_batch(session, "batch2")
80+
await insert_allocation(session, orderline_id, batch1_id)
81+
82+
async with session_maker() as session:
83+
rows = await session.execute("SELECT * from batches")
84+
print(list(rows))
6185

86+
async with session_maker() as session:
6287
repo = repository.SqlAlchemyRepository(session)
63-
retrieved = repo.get("batch1")
64-
65-
expected = model.Batch("batch1", "GENERIC-SOFA", 100, eta=None)
66-
assert retrieved == expected # Batch.__eq__ only compares reference
67-
assert retrieved.sku == expected.sku
68-
assert retrieved._purchased_quantity == expected._purchased_quantity
69-
assert retrieved._allocations == {
70-
model.OrderLine("order1", "GENERIC-SOFA", 12),
71-
}
88+
retrieved = await repo.get("batch1")
89+
90+
expected = model.Batch("batch1", "GENERIC-SOFA", 100, eta=None)
91+
assert retrieved == expected # Batch.__eq__ only compares ref
92+
assert retrieved.sku == expected.sku
93+
assert retrieved._purchased_quantity == expected._purchased_quantity
94+
assert retrieved._allocations == {
95+
model.OrderLine("order1", "GENERIC-SOFA", 12),
96+
}

0 commit comments

Comments
 (0)