-
Notifications
You must be signed in to change notification settings - Fork 0
/
pytest_sqlalchemy.py
102 lines (71 loc) · 2.57 KB
/
pytest_sqlalchemy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# -*- coding: utf-8 -*-
import os
from sqlalchemy import create_engine
from sqlalchemy.engine.url import make_url
from sqlalchemy.exc import ProgrammingError
import logging
import pytest
logger = logging.getLogger(__name__)
def pytest_addoption(parser):
group = parser.getgroup('sqlalchemy')
group.addoption(
'--test-db-prefix',
action='store',
dest='test_db_prefix',
default='test',
help='Define a prefix for the test database that is created'
)
parser.addini('test_db_prefix', 'Prefix for test database')
parser.addini('drop_existing_test_db', 'Drop existing test database for each session')
@pytest.fixture(scope='session')
def test_db_prefix():
return 'test_'
@pytest.fixture(scope='session')
def database_url():
return os.environ['DATABASE_URL']
@pytest.fixture(scope='session')
def test_database_url(test_db_prefix, database_url):
test_url = make_url(database_url)
test_url.database = test_db_prefix + test_url.database
return test_url
@pytest.fixture(scope='session')
def test_db(database_url, test_database_url):
engine = create_engine(database_url)
conn = engine.connect()
conn.execution_options(autocommit=False)
conn.execute('ROLLBACK')
try:
conn.execute("DROP DATABASE {}".format(test_database_url.database))
except ProgrammingError:
pass
finally:
conn.execute('ROLLBACK')
logger.debug('Creating Test Database {}'.format(test_database_url.database))
conn.execute("CREATE DATABASE {}".format(test_database_url.database))
conn.close()
engine.dispose()
@pytest.fixture(scope='session')
def sqlalchemy_base():
raise ValueError('Please supply sqlalchemy_base fixture')
@pytest.fixture(scope='session')
def sqlalchemy_session_class():
raise ValueError('Please supply sqlalchemy_session_class fixture')
@pytest.fixture(scope='session')
def engine(test_database_url):
return create_engine(test_database_url)
@pytest.yield_fixture(scope='session')
def tables(engine, sqlalchemy_base, test_db):
sqlalchemy_base.metadata.create_all(engine)
yield
sqlalchemy_base.metadata.drop_all(engine)
@pytest.yield_fixture(scope='function')
def db_session(engine, tables, sqlalchemy_session_class):
sqlalchemy_session_class.remove()
with engine.connect() as connection:
transaction = connection.begin_nested()
sqlalchemy_session_class.configure(bind=connection)
session = sqlalchemy_session_class()
session.begin_nested()
yield session
session.close()
transaction.rollback()