|
| 1 | +import pytest |
1 | 2 | from allocation.domain import model |
2 | 3 | from allocation.service_layer import unit_of_work |
3 | 4 |
|
| 5 | + |
4 | 6 | def insert_batch(session, ref, sku, qty, eta): |
5 | 7 | session.execute( |
6 | 8 | 'INSERT INTO batches (reference, sku, _purchased_quantity, eta)' |
7 | 9 | ' VALUES (:ref, :sku, :qty, :eta)', |
8 | 10 | dict(ref=ref, sku=sku, qty=qty, eta=eta) |
9 | 11 | ) |
10 | 12 |
|
| 13 | + |
11 | 14 | def get_allocated_batch_ref(session, orderid, sku): |
12 | 15 | [[orderlineid]] = session.execute( |
13 | 16 | 'SELECT id FROM order_lines WHERE orderid=:orderid AND sku=:sku', |
@@ -35,3 +38,28 @@ def test_uow_can_retrieve_a_batch_and_allocate_to_it(session_factory): |
35 | 38 |
|
36 | 39 | batchref = get_allocated_batch_ref(session, 'o1', 'HIPSTER-WORKBENCH') |
37 | 40 | assert batchref == 'batch1' |
| 41 | + |
| 42 | + |
| 43 | +def test_rolls_back_uncommitted_work_by_default(session_factory): |
| 44 | + uow = unit_of_work.SqlAlchemyUnitOfWork(session_factory) |
| 45 | + with uow: |
| 46 | + insert_batch(uow.session, 'batch1', 'MEDIUM-PLINTH', 100, None) |
| 47 | + |
| 48 | + new_session = session_factory() |
| 49 | + rows = list(new_session.execute('SELECT * FROM "batches"')) |
| 50 | + assert rows == [] |
| 51 | + |
| 52 | + |
| 53 | +def test_rolls_back_on_error(session_factory): |
| 54 | + class MyException(Exception): |
| 55 | + pass |
| 56 | + |
| 57 | + uow = unit_of_work.SqlAlchemyUnitOfWork(session_factory) |
| 58 | + with pytest.raises(MyException): |
| 59 | + with uow: |
| 60 | + insert_batch(uow.session, 'batch1', 'LARGE-FORK', 100, None) |
| 61 | + raise MyException() |
| 62 | + |
| 63 | + new_session = session_factory() |
| 64 | + rows = list(new_session.execute('SELECT * FROM "batches"')) |
| 65 | + assert rows == [] |
0 commit comments