1+ # pylint: disable=redefined-outer-name
2+ import time
3+ from pathlib import Path
4+
15import pytest
26from sqlalchemy import create_engine
37from sqlalchemy .orm import sessionmaker , clear_mappers
48
59from orm import metadata , start_mappers
10+ from config import get_postgres_uri
611
712
813@pytest .fixture
@@ -18,3 +23,62 @@ def session(in_memory_db):
1823 yield sessionmaker (bind = in_memory_db )()
1924 clear_mappers ()
2025
26+
27+ @pytest .fixture (scope = 'session' )
28+ def postgres_db ():
29+ engine = create_engine (get_postgres_uri ())
30+ metadata .create_all (engine )
31+ return engine
32+
33+
34+ @pytest .fixture
35+ def postgres_session (postgres_db ):
36+ start_mappers ()
37+ yield sessionmaker (bind = postgres_db )()
38+ clear_mappers ()
39+
40+
41+ @pytest .fixture
42+ def add_stock (postgres_session ):
43+ batches_added = set ()
44+ skus_added = set ()
45+
46+ def _add_stock (lines ):
47+ for ref , sku , qty , eta in lines :
48+ postgres_session .execute (
49+ 'INSERT INTO batches (reference, sku, _purchased_quantity, eta)'
50+ ' VALUES (:ref, :sku, :qty, :eta)' ,
51+ dict (ref = ref , sku = sku , qty = qty , eta = eta ),
52+ )
53+ [[batch_id ]] = postgres_session .execute (
54+ 'SELECT id FROM batches WHERE reference=:ref AND sku=:sku' ,
55+ dict (ref = ref , sku = sku ),
56+ )
57+ batches_added .add (batch_id )
58+ skus_added .add (sku )
59+ postgres_session .commit ()
60+
61+ yield _add_stock
62+
63+ for batch_id in batches_added :
64+ postgres_session .execute (
65+ 'DELETE FROM allocations WHERE batch_id=:batch_id' ,
66+ dict (batch_id = batch_id ),
67+ )
68+ postgres_session .execute (
69+ 'DELETE FROM batches WHERE id=:batch_id' ,
70+ dict (batch_id = batch_id ),
71+ )
72+ for sku in skus_added :
73+ postgres_session .execute (
74+ 'DELETE FROM order_lines WHERE sku=:sku' ,
75+ dict (sku = sku ),
76+ )
77+ postgres_session .commit ()
78+
79+
80+ @pytest .fixture
81+ def restart_api ():
82+ (Path (__file__ ).parent / 'flask_app.py' ).touch ()
83+ time .sleep (0.3 )
84+
0 commit comments