|
| 1 | +import uuid |
1 | 2 | import pytest |
2 | 3 | from allocation import model |
3 | 4 | from allocation import unit_of_work |
4 | 5 |
|
5 | | -def insert_batch(session, ref, sku, qty, eta): |
| 6 | +def random_ref(prefix): |
| 7 | + return prefix + '-' + uuid.uuid4().hex[:10] |
| 8 | + |
| 9 | +def insert_batch(session, ref, sku, qty, eta, product_version=1): |
6 | 10 | session.execute( |
7 | | - 'INSERT INTO products (sku) VALUES (:sku)', |
8 | | - dict(sku=sku), |
| 11 | + 'INSERT INTO products (sku, version_number) VALUES (:sku, :version)', |
| 12 | + dict(sku=sku, version=product_version), |
9 | 13 | ) |
10 | 14 | session.execute( |
11 | 15 | 'INSERT INTO batches (reference, sku, _purchased_quantity, eta)' |
@@ -65,3 +69,48 @@ class MyException(Exception): |
65 | 69 | new_session = session_factory() |
66 | 70 | rows = list(new_session.execute('SELECT * FROM "batches"')) |
67 | 71 | assert rows == [] |
| 72 | + |
| 73 | + |
| 74 | +import threading |
| 75 | +import traceback |
| 76 | +import time |
| 77 | + |
| 78 | +def try_to_allocate(sku, session_factory, exceptions): |
| 79 | + line = model.OrderLine(random_ref('o'), sku, 10) |
| 80 | + try: |
| 81 | + with unit_of_work.start(session_factory) as uow: |
| 82 | + product = uow.products.get(sku=sku) |
| 83 | + product.allocate(line) |
| 84 | + time.sleep(0.2) |
| 85 | + uow.commit() |
| 86 | + except Exception as e: |
| 87 | + print(traceback.format_exc()) |
| 88 | + exceptions.append(e) |
| 89 | + |
| 90 | + |
| 91 | +def test_concurrent_sessions_cannot_both_increment_product_version(postgres_session_factory): |
| 92 | + sku, batch = random_ref('s'), random_ref('b') |
| 93 | + session = postgres_session_factory() |
| 94 | + insert_batch(session, batch, sku, 100, eta=None, product_version=3) |
| 95 | + session.commit() |
| 96 | + |
| 97 | + exceptions = [] |
| 98 | + target = lambda: try_to_allocate(sku, postgres_session_factory, exceptions) |
| 99 | + t1 = threading.Thread(target=target) |
| 100 | + t2 = threading.Thread(target=target) |
| 101 | + t1.start() |
| 102 | + t2.start() |
| 103 | + t1.join() |
| 104 | + t2.join() |
| 105 | + |
| 106 | + [[version]] = session.execute( |
| 107 | + "SELECT version_number FROM products WHERE sku=:sku", |
| 108 | + dict(sku=sku), |
| 109 | + ) |
| 110 | + assert exceptions == [] |
| 111 | + assert version == 4 |
| 112 | + assert list(session.execute( |
| 113 | + "SELECT * FROM allocations JOIN batches ON allocations.batch_id = batches.id WHERE sku=:sku", |
| 114 | + dict(sku=sku), |
| 115 | + )) == [] |
| 116 | + |
0 commit comments