forked from opendatahub-io/opendatahub-tests
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconftest.py
More file actions
364 lines (312 loc) · 12.1 KB
/
conftest.py
File metadata and controls
364 lines (312 loc) · 12.1 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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
from contextlib import ExitStack
import pytest
from typing import Generator, List, Any
from _pytest.fixtures import FixtureRequest
from simple_logger.logger import get_logger
from ocp_resources.deployment import Deployment
from ocp_resources.infrastructure import Infrastructure
from ocp_resources.model_registry_modelregistry_opendatahub_io import ModelRegistry
from ocp_resources.oauth import OAuth
from ocp_resources.persistent_volume_claim import PersistentVolumeClaim
from ocp_resources.secret import Secret
from ocp_resources.service import Service
from ocp_resources.role_binding import RoleBinding
from ocp_resources.role import Role
from ocp_resources.group import Group
from ocp_resources.resource import ResourceEditor
from kubernetes.dynamic import DynamicClient
from pyhelper_utils.shell import run_command
from tests.model_registry.rbac.utils import wait_for_oauth_openshift_deployment, create_role_binding
from utilities.general import generate_random_name
from utilities.infra import login_with_user_password
from utilities.user_utils import UserTestSession, create_htpasswd_file, wait_for_user_creation
from tests.model_registry.rbac.group_utils import create_group
from tests.model_registry.constants import (
MR_INSTANCE_NAME,
)
LOGGER = get_logger(name=__name__)
@pytest.fixture(scope="function")
def add_user_to_group(
admin_client: DynamicClient,
test_idp_user: UserTestSession,
) -> Generator[str, None, None]:
"""
Fixture to create a group and add a test user to it.
Uses create_group context manager to ensure proper cleanup.
Args:
admin_client: The admin client for accessing the cluster
test_idp_user_session: The test user session containing user information
Yields:
str: The name of the created group
"""
group_name = "test-model-registry-group"
with create_group(
admin_client=admin_client,
group_name=group_name,
users=[test_idp_user.username],
) as group_name:
yield group_name
@pytest.fixture(scope="function")
def model_registry_group_with_user(
admin_client: DynamicClient,
test_idp_user: UserTestSession,
) -> Generator[Group, None, None]:
"""
Fixture to manage a test user in a specified group.
Adds the user to the group before the test, then removes them after.
Args:
admin_client: The admin client for accessing the cluster
test_idp_user_session: The test user session containing user information
Yields:
Group: The group with the test user added
"""
group_name = f"{MR_INSTANCE_NAME}-users"
group = Group(
client=admin_client,
name=group_name,
wait_for_resource=True,
)
# Add user to group
with ResourceEditor(
patches={
group: {
"metadata": {"name": group_name},
"users": [test_idp_user.username],
}
}
) as _:
LOGGER.info(f"Added user {test_idp_user.username} to {group_name} group")
yield group
@pytest.fixture(scope="module")
def user_credentials_rbac() -> dict[str, str]:
random_str = generate_random_name()
return {
"username": f"test-user-{random_str}",
"password": f"test-password-{random_str}",
"idp_name": f"test-htpasswd-idp-{random_str}",
"secret_name": f"test-htpasswd-secret-{random_str}",
}
@pytest.fixture(scope="session")
def original_user() -> str:
current_user = run_command(command=["oc", "whoami"])[1].strip()
LOGGER.info(f"Original user: {current_user}")
return current_user
@pytest.fixture(scope="module")
def created_htpasswd_secret(
original_user: str, user_credentials_rbac: dict[str, str]
) -> Generator[UserTestSession, None, None]:
"""
Session-scoped fixture that creates a test IDP user and cleans it up after all tests.
Returns a UserTestSession object that contains all necessary credentials and contexts.
"""
temp_path, htpasswd_b64 = create_htpasswd_file(
username=user_credentials_rbac["username"], password=user_credentials_rbac["password"]
)
try:
LOGGER.info(f"Creating secret {user_credentials_rbac['secret_name']} in openshift-config namespace")
with Secret(
name=user_credentials_rbac["secret_name"],
namespace="openshift-config",
htpasswd=htpasswd_b64,
type="Opaque",
wait_for_resource=True,
) as secret:
yield secret
finally:
# Clean up the temporary file
temp_path.unlink(missing_ok=True)
@pytest.fixture(scope="module")
def updated_oauth_config(
admin_client: DynamicClient, original_user: str, user_credentials_rbac: dict[str, str]
) -> Generator[Any, None, None]:
# Get current providers and add the new one
oauth = OAuth(name="cluster")
identity_providers = oauth.instance.spec.identityProviders
new_idp = {
"name": user_credentials_rbac["idp_name"],
"mappingMethod": "claim",
"type": "HTPasswd",
"htpasswd": {"fileData": {"name": user_credentials_rbac["secret_name"]}},
}
updated_providers = identity_providers + [new_idp]
LOGGER.info("Updating OAuth")
identity_providers_patch = ResourceEditor(patches={oauth: {"spec": {"identityProviders": updated_providers}}})
identity_providers_patch.update(backup_resources=True)
# Wait for OAuth server to be ready
wait_for_oauth_openshift_deployment()
LOGGER.info(f"Added IDP {user_credentials_rbac['idp_name']} to OAuth configuration")
yield
identity_providers_patch.restore()
wait_for_oauth_openshift_deployment()
@pytest.fixture(scope="module")
def test_idp_user(
original_user: str,
user_credentials_rbac: dict[str, str],
created_htpasswd_secret: Generator[UserTestSession, None, None],
updated_oauth_config: Generator[Any, None, None],
api_server_url: str,
) -> Generator[UserTestSession, None, None]:
"""
Session-scoped fixture that creates a test IDP user and cleans it up after all tests.
Returns a UserTestSession object that contains all necessary credentials and contexts.
"""
idp_session = None
try:
if wait_for_user_creation(
username=user_credentials_rbac["username"],
password=user_credentials_rbac["password"],
cluster_url=api_server_url,
):
# undo the login as test user if we were successful in logging in as test user
LOGGER.info(f"Undoing login as test user and logging in as {original_user}")
login_with_user_password(api_address=api_server_url, user=original_user)
idp_session = UserTestSession(
idp_name=user_credentials_rbac["idp_name"],
secret_name=user_credentials_rbac["secret_name"],
username=user_credentials_rbac["username"],
password=user_credentials_rbac["password"],
original_user=original_user,
api_server_url=api_server_url,
)
LOGGER.info(f"Created session test IDP user: {idp_session.username}")
yield idp_session
finally:
if idp_session:
LOGGER.info(f"Cleaning up test IDP user: {idp_session.username}")
idp_session.cleanup()
@pytest.fixture()
def login_as_test_user(
api_server_url: str, original_user: str, test_idp_user: UserTestSession
) -> Generator[None, None, None]:
LOGGER.info(f"Logging in as {test_idp_user.username}")
login_with_user_password(
api_address=api_server_url,
user=test_idp_user.username,
password=test_idp_user.password,
)
yield
LOGGER.info(f"Logging in as {original_user}")
login_with_user_password(
api_address=api_server_url,
user=original_user,
)
@pytest.fixture(scope="function")
def created_role_binding_group(
admin_client: DynamicClient,
model_registry_namespace: str,
mr_access_role: Role,
test_idp_user: UserTestSession,
add_user_to_group: str,
) -> Generator[RoleBinding, None, None]:
yield from create_role_binding(
admin_client=admin_client,
model_registry_namespace=model_registry_namespace,
name="test-model-registry-group-edit",
mr_access_role=mr_access_role,
subjects_kind="Group",
subjects_name=add_user_to_group,
)
@pytest.fixture(scope="function")
def created_role_binding_user(
admin_client: DynamicClient,
model_registry_namespace: str,
mr_access_role: Role,
test_idp_user: UserTestSession,
) -> Generator[RoleBinding, None, None]:
yield from create_role_binding(
admin_client=admin_client,
model_registry_namespace=model_registry_namespace,
name="test-model-registry-access",
mr_access_role=mr_access_role,
subjects_kind="User",
subjects_name=test_idp_user.username,
)
# =============================================================================
# RESOURCE FIXTURES PARMETRIZED
# =============================================================================
@pytest.fixture(scope="class")
def db_secret_parametrized(request: FixtureRequest, teardown_resources: bool) -> Generator[List[Secret], Any, Any]:
"""Create DB Secret parametrized"""
with ExitStack() as stack:
secrets = [
stack.enter_context(
Secret(
**param,
teardown=teardown_resources,
)
)
for param in request.param
]
yield secrets
@pytest.fixture(scope="class")
def db_pvc_parametrized(
request: FixtureRequest, teardown_resources: bool
) -> Generator[List[PersistentVolumeClaim], Any, Any]:
"""Create DB PVC parametrized"""
with ExitStack() as stack:
pvc = [
stack.enter_context(
PersistentVolumeClaim(
**param,
teardown=teardown_resources,
)
)
for param in request.param
]
yield pvc
@pytest.fixture(scope="class")
def db_service_parametrized(request: FixtureRequest, teardown_resources: bool) -> Generator[List[Service], Any, Any]:
"""Create DB Service parametrized"""
with ExitStack() as stack:
services = [
stack.enter_context(
Service(
**param,
teardown=teardown_resources,
)
)
for param in request.param
]
yield services
@pytest.fixture(scope="class")
def db_deployment_parametrized(
request: FixtureRequest, teardown_resources: bool
) -> Generator[List[Deployment], Any, Any]:
"""Create DB Deployment parametrized"""
with ExitStack() as stack:
deployments = [
stack.enter_context(
Deployment(
**param,
teardown=teardown_resources,
)
)
for param in request.param
]
for deployment in deployments:
deployment.wait_for_replicas(deployed=True)
yield deployments
@pytest.fixture(scope="class")
def model_registry_instance_parametrized(
request: FixtureRequest, admin_client: DynamicClient, teardown_resources: bool
) -> Generator[List[ModelRegistry], Any, Any]:
"""Create Model Registry instance parametrized"""
with ExitStack() as stack:
model_registry_instances = []
mr_instances = [stack.enter_context(ModelRegistry(**param)) for param in request.param]
for mr_instance in mr_instances:
# Common parameters for both ModelRegistry classes
mr_instance.wait_for_condition(condition="Available", status="True")
mr_instance.wait_for_condition(condition="OAuthProxyAvailable", status="True")
model_registry_instances.append(mr_instance)
LOGGER.info(
f"Created {len(model_registry_instances)} MR instances: {[mr.name for mr in model_registry_instances]}"
)
yield model_registry_instances
@pytest.fixture(scope="session")
def api_server_url(admin_client: DynamicClient) -> str:
"""
Get api server url from the cluster.
"""
infrastructure = Infrastructure(client=admin_client, name="cluster", ensure_exists=True)
return infrastructure.instance.status.apiServerURL