-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathconftest.py
More file actions
269 lines (211 loc) · 7.25 KB
/
conftest.py
File metadata and controls
269 lines (211 loc) · 7.25 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
"""
File conftest.py contains pytest fixtures that are used in numerous
test functions. Refer to https://docs.pytest.org/en/stable/fixture.html
for more details on pytest
"""
import datetime
import json
import os
import pytest
from app import create_app
from flask import url_for
from flask_login import current_user as _current_user
from init import db as _db
from shopyo_auth.models import User
from shopyo_settings.models import Settings
from sqlalchemy import event
# run in shopyo/shopyo
# python -m pytest . or python -m pytest -v
if os.path.exists("testing.db"):
os.remove("testing.db")
@pytest.fixture(scope="session")
def unconfirmed_user():
"""
A pytest fixture that returns a non admin user
"""
user = User()
user.email = "[email protected]"
user.password = "pass"
user.is_email_confirmed = False
return user
@pytest.fixture(scope="session")
def non_admin_user():
"""
A pytest fixture that returns a non admin user
"""
user = User()
user.email = "[email protected]"
user.password = "pass"
user.is_email_confirmed = True
user.email_confirm_date = datetime.datetime.now()
return user
@pytest.fixture(scope="session")
def admin_user():
"""
A pytest fixture that returns an admin user
"""
user = User()
user.email = "[email protected]"
user.password = "pass"
user.is_admin = True
user.is_email_confirmed = True
user.email_confirm_date = datetime.datetime.now()
return user
@pytest.fixture(scope="session")
def flask_app():
flask_app = create_app("testing")
return flask_app
@pytest.fixture(scope="session")
def app(request):
"""
Returns session-wide application.
"""
return create_app("testing")
@pytest.fixture(scope="session")
def current_user():
return _current_user
@pytest.fixture(scope="session")
def test_client(flask_app):
"""
setups up and returns the flask testing app
"""
# Create a test client using the Flask application configured for testing
with flask_app.test_client() as testing_client:
# Establish an application context
with flask_app.app_context():
yield testing_client # this is where the testing happens!
@pytest.fixture(scope="session")
def db(test_client, non_admin_user, admin_user, unconfirmed_user):
"""
creates and returns the initial testing database
"""
# Create the database and the database table
_db.app = test_client
_db.create_all()
# Insert admin, non admin, and unconfirmed if they don't exist
for u in [non_admin_user, admin_user, unconfirmed_user]:
if not User.query.filter_by(email=u.email).first():
_db.session.add(u)
# add the default settings
with open("config.json") as config:
config = json.load(config)
for name, value in config["settings"].items():
existing = Settings.query.filter_by(setting=name).first()
if not existing:
s = Settings(setting=name, value=value)
_db.session.add(s)
else:
existing.value = value
# Commit the changes
_db.session.commit()
yield _db # this is where the testing happens!
_db.drop_all()
@pytest.fixture(scope="function", autouse=True)
def db_session(db):
"""
Creates a new database session for a test. Note you must use this fixture
if your test connects to db. Autouse is set to true which implies
that the fixture will be setup before each test
Here we not only support commit calls but also rollback calls in tests.
"""
connection = db.engine.connect()
transaction = connection.begin()
options = dict(bind=connection, binds={})
try:
session = db._make_scoped_session(options=options)
except:
session = db.create_scoped_session(options=options)
db.session = session
yield session
transaction.rollback()
connection.close()
session.remove()
# @pytest.fixture(scope="function", autouse=True)
# def db_session(app, db, request):
# """
# Returns function-scoped session.
# """
# with app.app_context():
# conn = _db.engine.connect()
# txn = conn.begin()
# options = dict(bind=conn, binds={})
# sess = _db.create_scoped_session(options=options)
# # establish a SAVEPOINT just before beginning the test
# # (http://docs.sqlalchemy.org/en/latest/orm/session_transaction.html#using-savepoint)
# sess.begin_nested()
# @event.listens_for(sess(), "after_transaction_end")
# def restart_savepoint(sess2, trans):
# # Detecting whether this is indeed the nested transaction of the test
# if trans.nested and not trans._parent.nested:
# # The test should have normally called session.commit(),
# # but to be safe we explicitly expire the session
# sess2.expire_all()
# sess.begin_nested()
# _db.session = sess
# yield sess
# # Cleanup
# sess.remove()
# # This instruction rollsback any commit that were executed in the tests.
# txn.rollback()
# conn.close()
@pytest.fixture
def login_unconfirmed_user(auth, unconfirmed_user):
"""Login with unconfirmed and logout during teadown"""
auth.login(unconfirmed_user)
yield
auth.logout()
@pytest.fixture
def login_admin_user(auth, admin_user):
"""Login with admin and logout during teadown"""
auth.login(admin_user)
yield
auth.logout()
@pytest.fixture
def login_non_admin_user(auth, non_admin_user):
"""Login with non-admin and logout during teadown"""
auth.login(non_admin_user)
yield
auth.logout()
@pytest.fixture
def auth(test_client):
return AuthActions(test_client)
class AuthActions:
def __init__(self, client):
self._client = client
def login(self, user, password="pass"):
return self._client.post(
url_for("shopyo_auth.login"),
data=dict(email=user.email, password=password),
follow_redirects=True,
)
def logout(self):
return self._client.get(url_for("shopyo_auth.logout"), follow_redirects=True)
# Want TO USE THE BELOW 2 FIXTURES TO DYNAMICALLY
# GET THE ROUTES FOR A GIVEN MODULE BUT UNABLE TO
# PARAMETERIZE THE LIST OF ROUTES RETURNED FROM THE FIXTURE
# CURRENTLY THIS NOT POSSIBLE WITH FIXTURES IN PYTEST @rehmanis
# @pytest.fixture(scope="module")
# def get_module_routes(request, get_routes):
# module_prefix = getattr(request.module, "module_prefix", "/")
# return get_routes[module_prefix]
# @pytest.fixture(scope="session")
# def get_routes(flask_app):
# routes_dict = {}
# relative_path = "/"
# prefix = "/"
# for route in flask_app.url_map.iter_rules():
# split_route = list(filter(None, str(route).split("/", 2)))
# if len(split_route) == 0:
# prefix = "/"
# relative_path = ""
# elif len(split_route) == 1:
# prefix = "/" + split_route[0]
# relative_path = "/"
# else:
# prefix = "/" + split_route[0]
# relative_path = split_route[1]
# if prefix in routes_dict:
# routes_dict[prefix].append(relative_path)
# else:
# routes_dict[prefix] = [relative_path]
# return routes_dict