/
conftest.py
290 lines (236 loc) · 8.63 KB
/
conftest.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
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import datetime
import os
import tempfile
import pytest
import python_freeipa
from vcr import VCR
from noggin.app import create_app, ipa_admin
from noggin.representation.agreement import Agreement
from noggin.representation.otptoken import OTPToken
from noggin.security.ipa import maybe_ipa_login, untouched_ipa_client
@pytest.fixture(scope="session")
def app_config(ipa_cert):
return dict(
TESTING=True,
DEBUG=True,
WTF_CSRF_ENABLED=False,
# IPA settings
FREEIPA_SERVERS=['ipa.noggin.test'],
FREEIPA_CACERT=ipa_cert,
# Any user with admin privileges
FREEIPA_ADMIN_USER='admin',
FREEIPA_ADMIN_PASSWORD='password',
# Fernet secret
FERNET_SECRET=b'G8ObvrpEEwbjWUO9rU1qAkDQRafAFd39heVKYf6TZi8=',
# Session secret
SECRET_KEY=b'monkiesmonkiesmonkiesmonkiesmonkies!!!1111monkies',
# We don't do https for testing
SESSION_COOKIE_SECURE=False,
# Email sender
MAIL_DEFAULT_SENDER="Noggin <noggin@unit.tests>",
# Set a different password policy betweed the form and the server so we can test both
PASSWORD_POLICY={"min": 6},
# Don't delete the role we may have in the dev env
STAGE_USERS_ROLE="Testing Stage Users Admins",
# Turn on Fedora Messaging
FEDORA_MESSAGING_ENABLED=True,
)
@pytest.fixture(scope="session")
def app(app_config):
return create_app(app_config)
@pytest.fixture
def request_context(app):
with app.test_request_context('/'):
yield
@pytest.fixture(scope="session")
def ipa_cert():
"""Create a CA cert usable for tests.
The FreeIPA CA cert file must exist for client requests to work. Use the one provided by a local
install of FreeIPA if available, use an empty file otherwise (but in that case the requests must
have been recorded by VCR).
"""
with tempfile.NamedTemporaryFile(
prefix="ipa-ca-", suffix=".crt", delete=False
) as cert:
if os.path.exists("/etc/ipa/ca.crt"):
# Copy the proper CA file so tests that have no VCR cassette can run
with open("/etc/ipa/ca.crt", "rb") as orig_ca:
cert.write(orig_ca.read())
else:
# FreeIPA is not installed, this may be CI, just use an empty file
# because VCR will mock the requests anyway.
pass
cert.close()
yield cert.name
@pytest.fixture
def client(app, ipa_cert):
# app.config['FREEIPA_CACERT'] = ipa_cert
with app.test_client() as client:
with app.app_context():
yield client
@pytest.fixture(scope='module')
def vcr_cassette_dir(request):
# Put all cassettes in cassettes/{module}/{test}.yaml
test_dir = request.node.fspath.dirname
module_name = request.module.__name__.split(".")[-1]
return os.path.join(test_dir, 'cassettes', module_name)
@pytest.fixture(scope="session")
def vcr_session(request):
"""Setup VCR at session-level.
Borrowed from python-vcr.
"""
test_dir = os.path.abspath(os.path.dirname(__file__))
cassette_dir = os.path.join(test_dir, 'cassettes')
kwargs = dict(
cassette_library_dir=cassette_dir, path_transformer=VCR.ensure_suffix(".yaml")
)
record_mode = request.config.getoption('--vcr-record')
if record_mode:
kwargs['record_mode'] = record_mode
if request.config.getoption('--disable-vcr'):
# Set mode to record but discard all responses to disable both recording and playback
kwargs['record_mode'] = 'new_episodes'
kwargs['before_record_response'] = lambda *args, **kwargs: None
vcr = VCR(**kwargs)
yield vcr
@pytest.fixture(scope="session")
def ipa_testing_config(vcr_session, app):
"""Setup IPA with a testing configuration."""
with vcr_session.use_cassette("ipa_testing_config"), app.test_request_context('/'):
pwpolicy = ipa_admin.pwpolicy_show()
try:
ipa_admin.pwpolicy_mod(o_krbminpwdlife=0, o_krbpwdminlength=8)
except python_freeipa.exceptions.BadRequest as e:
if not e.message == "no modifications to be performed":
raise
# Stage users admin role
sua_role = app.config["STAGE_USERS_ROLE"]
ipa_admin.role_add(sua_role)
ipa_admin.role_add_privilege(
sua_role, o_privilege=["Stage User Administrators"]
)
yield
try:
ipa_admin.pwpolicy_mod(
o_krbminpwdlife=pwpolicy['result']['krbminpwdlife'][0],
o_krbpwdminlength=pwpolicy['result']['krbpwdminlength'][0],
)
except python_freeipa.exceptions.BadRequest as e:
if not e.message == "no modifications to be performed":
raise
ipa_admin.role_del(sua_role)
@pytest.fixture
def make_user(ipa_testing_config, app):
created_users = []
def _make_user(name):
now = datetime.datetime.utcnow().replace(microsecond=0)
password = f'{name}_password'
ipa_admin.user_add(
name,
o_givenname=name.title(),
o_sn='User',
o_cn=f'{name.title()} User',
o_mail=f"{name}@unit.tests",
o_userpassword=password,
o_loginshell='/bin/bash',
fascreationtime=f"{now.isoformat()}Z",
)
ipa = untouched_ipa_client(app)
ipa.change_password(name, password, password)
created_users.append(name)
yield _make_user
for name in created_users:
ipa_admin.user_del(name)
@pytest.fixture
def dummy_user(make_user):
make_user("dummy")
yield
@pytest.fixture
def dummy_user_with_case(make_user):
make_user("duMmy")
yield
@pytest.fixture
def make_group(ipa_testing_config, app):
created = []
def _make_group(name):
result = ipa_admin.group_add(
name,
o_description=f"The {name} group",
fasgroup=True,
fasurl=f"http://{name}.unit.tests",
fasmailinglist=f"{name}@lists.unit.tests",
fasircchannel=f"irc://irc.unit.tests/#{name}",
)
created.append(name)
return result
yield _make_group
for name in created:
ipa_admin.group_del(name)
@pytest.fixture
def dummy_group(make_group):
make_group("dummy-group")
@pytest.fixture
def dummy_user_as_group_manager(logged_in_dummy_user, dummy_group):
"""Make the dummy user a manager of the dummy-group group."""
ipa_admin.group_add_member(a_cn="dummy-group", o_user="dummy")
ipa_admin.group_add_member_manager(a_cn="dummy-group", o_user="dummy")
yield
@pytest.fixture
def password_min_time(dummy_group):
ipa_admin.pwpolicy_add(
a_cn="dummy-group", o_krbminpwdlife=1, o_cospriority=10, o_krbpwdminlength=8
)
@pytest.fixture
def logged_in_dummy_user(client, dummy_user, app):
with client.session_transaction() as sess:
ipa = maybe_ipa_login(
app, sess, username="dummy", userpassword="dummy_password"
)
yield ipa
ipa.logout()
with client.session_transaction() as sess:
sess.clear()
@pytest.fixture
def dummy_user_with_gpg_key(client, dummy_user):
ipa_admin.user_mod(a_uid="dummy", fasgpgkeyid=["dummy-gpg-key-id"])
@pytest.fixture
def dummy_user_with_otp(client, dummy_user):
result = ipa_admin.otptoken_add(
o_ipatokenowner="dummy", o_description="dummy's token"
)
token = OTPToken(result["result"])
yield token
# Deletion needs to be done as admin to remove the last token
ipa_admin.otptoken_del(token.uniqueid)
@pytest.fixture
def logged_in_dummy_user_with_otp(client, logged_in_dummy_user):
ipa = logged_in_dummy_user
result = ipa.otptoken_add(
o_ipatokenowner="dummy",
o_description="dummy's token",
)
token = OTPToken(result['result'])
yield token
# Deletion needs to be done as admin to remove the last token
try:
ipa_admin.otptoken_del(token.uniqueid)
except python_freeipa.exceptions.NotFound:
pass # Already deleted
@pytest.fixture
def cleanup_dummy_tokens():
yield
tokens = ipa_admin.otptoken_find(a_criteria="dummy")
for token in [OTPToken(t) for t in tokens["result"]]:
ipa_admin.otptoken_del(a_ipatokenuniqueid=token.uniqueid)
@pytest.fixture
def dummy_agreement():
agreement = ipa_admin.fasagreement_add(
"dummy agreement", description="i agree to dummy"
)
yield Agreement(agreement)
ipa_admin.fasagreement_del("dummy agreement")
@pytest.fixture
def dummy_group_with_agreement(dummy_group, dummy_agreement):
ipa_admin.fasagreement_add_group("dummy agreement", group="dummy-group")
yield
ipa_admin.fasagreement_remove_group("dummy agreement", group="dummy-group")