Skip to content

Commit c2aab09

Browse files
committed
use uow in services, flask app
1 parent 423c58b commit c2aab09

File tree

6 files changed

+48
-47
lines changed

6 files changed

+48
-47
lines changed

src/allocation/config.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import os
22

3+
34
def get_postgres_uri():
45
host = os.environ.get('DB_HOST', 'localhost')
56
port = 54321 if host == 'localhost' else 5432

src/allocation/entrypoints/flask_app.py

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,34 @@
11
from datetime import datetime
22
from flask import Flask, jsonify, request
3-
from sqlalchemy import create_engine
4-
from sqlalchemy.orm import sessionmaker
53

6-
from allocation import config
74
from allocation.domain import model
8-
from allocation.adapters import orm, repository
9-
from allocation.service_layer import services
5+
from allocation.adapters import orm
6+
from allocation.service_layer import services, unit_of_work
107

11-
orm.start_mappers()
12-
get_session = sessionmaker(bind=create_engine(config.get_postgres_uri()))
138
app = Flask(__name__)
9+
orm.start_mappers()
1410

1511

1612
@app.route("/add_batch", methods=['POST'])
1713
def add_batch():
18-
session = get_session()
19-
repo = repository.SqlAlchemyRepository(session)
2014
eta = request.json['eta']
2115
if eta is not None:
2216
eta = datetime.fromisoformat(eta).date()
2317
services.add_batch(
2418
request.json['ref'], request.json['sku'], request.json['qty'], eta,
25-
repo, session
19+
unit_of_work.SqlAlchemyUnitOfWork(),
2620
)
2721
return 'OK', 201
2822

2923

3024
@app.route("/allocate", methods=['POST'])
3125
def allocate_endpoint():
32-
session = get_session()
33-
repo = repository.SqlAlchemyRepository(session)
3426
try:
3527
batchref = services.allocate(
3628
request.json['orderid'],
3729
request.json['sku'],
3830
request.json['qty'],
39-
repo, session
31+
unit_of_work.SqlAlchemyUnitOfWork(),
4032
)
4133
except (model.OutOfStock, services.InvalidSku) as e:
4234
return jsonify({'message': str(e)}), 400

src/allocation/service_layer/services.py

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44

55
from allocation.domain import model
66
from allocation.domain.model import OrderLine
7-
from allocation.adapters.repository import AbstractRepository
7+
from allocation.service_layer import unit_of_work
8+
89

910
class InvalidSku(Exception):
1011
pass
@@ -16,19 +17,22 @@ def is_valid_sku(sku, batches):
1617

1718
def add_batch(
1819
ref: str, sku: str, qty: int, eta: Optional[date],
19-
repo: AbstractRepository, session,
20+
uow: unit_of_work.AbstractUnitOfWork
2021
):
21-
repo.add(model.Batch(ref, sku, qty, eta))
22-
session.commit()
22+
with uow:
23+
uow.batches.add(model.Batch(ref, sku, qty, eta))
24+
uow.commit()
2325

2426

2527
def allocate(
26-
orderid: str, sku: str, qty: int, repo: AbstractRepository, session
28+
orderid: str, sku: str, qty: int,
29+
uow: unit_of_work.AbstractUnitOfWork
2730
) -> str:
2831
line = OrderLine(orderid, sku, qty)
29-
batches = repo.list()
30-
if not is_valid_sku(line.sku, batches):
31-
raise InvalidSku(f'Invalid sku {line.sku}')
32-
batchref = model.allocate(line, batches)
33-
session.commit()
32+
with uow:
33+
batches = uow.batches.list()
34+
if not is_valid_sku(line.sku, batches):
35+
raise InvalidSku(f'Invalid sku {line.sku}')
36+
batchref = model.allocate(line, batches)
37+
uow.commit()
3438
return batchref

src/allocation/unit_of_work.py renamed to src/allocation/service_layer/unit_of_work.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from sqlalchemy.orm.session import Session
77

88
from allocation import config
9-
from allocation import repository
9+
from allocation.adapters import repository
1010

1111

1212
class AbstractUnitOfWork(abc.ABC):

tests/integration/test_uow.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
1-
import pytest
2-
from allocation import model
3-
from allocation import unit_of_work
1+
from allocation.domain import model
2+
from allocation.service_layer import unit_of_work
43

54
def insert_batch(session, ref, sku, qty, eta):
65
session.execute(

tests/unit/test_services.py

Lines changed: 25 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import pytest
2-
from allocation.domain import model
32
from allocation.adapters import repository
4-
from allocation.service_layer import services
3+
from allocation.service_layer import services, unit_of_work
54

65

76
class FakeRepository(repository.AbstractRepository):
@@ -19,38 +18,44 @@ def list(self):
1918
return list(self._batches)
2019

2120

22-
class FakeSession():
23-
committed = False
21+
class FakeUnitOfWork(unit_of_work.AbstractUnitOfWork):
22+
23+
def __init__(self):
24+
self.batches = FakeRepository([])
25+
self.committed = False
2426

2527
def commit(self):
2628
self.committed = True
2729

30+
def rollback(self):
31+
pass
32+
33+
2834

2935
def test_add_batch():
30-
repo, session = FakeRepository([]), FakeSession()
31-
services.add_batch("b1", "CRUNCHY-ARMCHAIR", 100, None, repo, session)
32-
assert repo.get("b1") is not None
33-
assert session.committed
36+
uow = FakeUnitOfWork()
37+
services.add_batch("b1", "CRUNCHY-ARMCHAIR", 100, None, uow)
38+
assert uow.batches.get("b1") is not None
39+
assert uow.committed
3440

3541

3642
def test_allocate_returns_allocation():
37-
repo, session = FakeRepository([]), FakeSession()
38-
services.add_batch("batch1", "COMPLICATED-LAMP", 100, None, repo, session)
39-
result = services.allocate("o1", "COMPLICATED-LAMP", 10, repo, session)
43+
uow = FakeUnitOfWork()
44+
services.add_batch("batch1", "COMPLICATED-LAMP", 100, None, uow)
45+
result = services.allocate("o1", "COMPLICATED-LAMP", 10, uow)
4046
assert result == "batch1"
4147

4248

4349
def test_allocate_errors_for_invalid_sku():
44-
repo, session = FakeRepository([]), FakeSession()
45-
services.add_batch("b1", "AREALSKU", 100, None, repo, session)
50+
uow = FakeUnitOfWork()
51+
services.add_batch("b1", "AREALSKU", 100, None, uow)
4652

4753
with pytest.raises(services.InvalidSku, match="Invalid sku NONEXISTENTSKU"):
48-
services.allocate("o1", "NONEXISTENTSKU", 10, repo, FakeSession())
54+
services.allocate("o1", "NONEXISTENTSKU", 10, uow)
4955

5056

51-
def test_commits():
52-
repo, session = FakeRepository([]), FakeSession()
53-
session = FakeSession()
54-
services.add_batch("b1", "OMINOUS-MIRROR", 100, None, repo, session)
55-
services.allocate("o1", "OMINOUS-MIRROR", 10, repo, session)
56-
assert session.committed is True
57+
def test_allocate_commits():
58+
uow = FakeUnitOfWork()
59+
services.add_batch("b1", "OMINOUS-MIRROR", 100, None, uow)
60+
services.allocate("o1", "OMINOUS-MIRROR", 10, uow)
61+
assert uow.committed

0 commit comments

Comments
 (0)