forked from openedx/openedx-authz
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_data.py
More file actions
621 lines (482 loc) · 22.3 KB
/
test_data.py
File metadata and controls
621 lines (482 loc) · 22.3 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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
"""Test data for the authorization API."""
from unittest.mock import Mock, patch
from ddt import data, ddt, unpack
from django.test import TestCase
from opaque_keys.edx.locator import LibraryLocatorV2
from openedx_authz.api.data import (
ActionData,
ContentLibraryData,
PermissionData,
RoleAssignmentData,
RoleData,
ScopeData,
ScopeMeta,
SubjectData,
UserData,
)
from openedx_authz.constants import permissions, roles
@ddt
class TestNamespacedData(TestCase):
"""Test data for the authorization API."""
@data(
("instructor",),
("admin",),
)
@unpack
def test_role_data_namespace(self, external_key):
"""Test that RoleData correctly namespaces role names.
Expected Result:
- If input is 'instructor', expected is 'role^instructor'
- If input is 'admin', expected is 'role^admin'
"""
role = RoleData(external_key=external_key)
expected = f"{role.NAMESPACE}{role.SEPARATOR}{external_key}"
self.assertEqual(role.namespaced_key, expected)
@data(
("john_doe",),
("jane_smith",),
)
@unpack
def test_user_data_namespace(self, external_key):
"""Test that UserData correctly namespaces user IDs.
Expected Result:
- If input is 'john_doe', expected is 'user^john_doe'
- If input is 'jane_smith', expected is 'user^jane_smith'
"""
user = UserData(external_key=external_key)
expected = f"{user.NAMESPACE}{user.SEPARATOR}{external_key}"
self.assertEqual(user.namespaced_key, expected)
@data(
("read",),
("write",),
)
@unpack
def test_action_data_namespace(self, external_key):
"""Test that ActionData correctly namespaces action IDs.
Expected Result:
- If input is 'read', expected is 'act^read'
- If input is 'write', expected is 'act^write'
"""
action = ActionData(external_key=external_key)
expected = f"{action.NAMESPACE}{action.SEPARATOR}{external_key}"
self.assertEqual(action.namespaced_key, expected)
@data(
("lib:DemoX:CSPROB",),
)
@unpack
def test_scope_content_lib_data_namespace(self, external_key):
"""Test that ContentLibraryData correctly namespaces library IDs.
Expected Result:
- If input is 'lib:DemoX:CSPROB', expected is 'lib^lib:DemoX:CSPROB'
"""
scope = ContentLibraryData(external_key=external_key)
expected = f"{scope.NAMESPACE}{scope.SEPARATOR}{external_key}"
self.assertEqual(scope.namespaced_key, expected)
@ddt
class TestPolymorphicData(TestCase):
"""Test polymorphic factory pattern for SubjectData and ScopeData."""
@data(
("john_doe",),
("jane_smith",),
)
@unpack
def test_user_data_with_namespaced_key(self, external_key):
"""Test that UserData can be instantiated with namespaced_key.
Expected Result:
- UserData(namespaced_key='user^john_doe') creates UserData instance
"""
namespaced_key = f"{UserData.NAMESPACE}{UserData.SEPARATOR}{external_key}"
user = UserData(namespaced_key=namespaced_key)
self.assertIsInstance(user, UserData)
self.assertEqual(user.namespaced_key, namespaced_key)
self.assertEqual(user.external_key, external_key)
def test_subject_data_direct_instantiation_with_namespaced_key(self):
"""Test that SubjectData can be instantiated with namespaced_key.
Expected Result:
- SubjectData(namespaced_key='sub^generic') creates SubjectData instance
"""
namespaced_key = f"{SubjectData.NAMESPACE}{SubjectData.SEPARATOR}generic"
subject = SubjectData(namespaced_key=namespaced_key)
self.assertIsInstance(subject, SubjectData)
self.assertEqual(subject.namespaced_key, namespaced_key)
self.assertEqual(subject.external_key, "generic")
@data(
("math_101",),
("science_201",),
)
@unpack
def test_content_library_data_with_namespaced_key(self, external_key):
"""Test that ContentLibraryData can be instantiated with namespaced_key.
Expected Result:
- ContentLibraryData(namespaced_key='lib^math_101') creates ContentLibraryData instance
"""
namespaced_key = f"{ContentLibraryData.NAMESPACE}{ContentLibraryData.SEPARATOR}{external_key}"
library = ContentLibraryData(namespaced_key=namespaced_key)
self.assertIsInstance(library, ContentLibraryData)
self.assertEqual(library.namespaced_key, namespaced_key)
self.assertEqual(library.external_key, external_key)
def test_scope_data_direct_instantiation_with_namespaced_key(self):
"""Test that ScopeData can be instantiated with namespaced_key.
Expected Result:
- ScopeData(namespaced_key='sc^generic') creates ScopeData instance
"""
namespaced_key = f"{ScopeData.NAMESPACE}{ScopeData.SEPARATOR}generic"
scope = ScopeData(namespaced_key=namespaced_key)
self.assertIsInstance(scope, ScopeData)
self.assertEqual(scope.namespaced_key, namespaced_key)
self.assertEqual(scope.external_key, "generic")
def test_user_data_direct_instantiation(self):
"""Test that UserData can be instantiated directly.
Expected Result:
- UserData(external_key='alice') creates UserData instance
"""
user = UserData(external_key="alice")
expected_namespaced = f"{user.NAMESPACE}{user.SEPARATOR}alice"
self.assertIsInstance(user, UserData)
self.assertEqual(user.namespaced_key, expected_namespaced)
self.assertEqual(user.external_key, "alice")
def test_content_library_direct_instantiation(self):
"""Test that ContentLibraryData can be instantiated directly.
Expected Result:
- ContentLibraryData(external_key='lib:Demo:CS') creates ContentLibraryData instance
"""
library = ContentLibraryData(external_key="lib:demo:cs")
expected_namespaced = f"{library.NAMESPACE}{library.SEPARATOR}lib:demo:cs"
self.assertIsInstance(library, ContentLibraryData)
self.assertEqual(library.namespaced_key, expected_namespaced)
self.assertEqual(library.external_key, "lib:demo:cs")
@data(
("lib:math_101",),
("lib:DemoX:CSPROB",),
)
@unpack
def test_content_library_data_with_external_key(self, external_key):
"""Test that ContentLibraryData with external_key generates correct namespaced_key.
Expected Result:
- ContentLibraryData(external_key='lib:math_101') creates ContentLibraryData instance
- namespaced_key is 'lib^lib:math_101'
"""
library = ContentLibraryData(external_key=external_key)
expected_namespaced_key = f"{library.NAMESPACE}{library.SEPARATOR}{external_key}"
self.assertIsInstance(library, ContentLibraryData)
self.assertEqual(library.external_key, external_key)
self.assertEqual(library.namespaced_key, expected_namespaced_key)
@ddt
class TestScopeMetaClass(TestCase):
"""Test the ScopeMeta metaclass functionality."""
def test_scope_data_registration(self):
"""Test that ScopeData and its subclasses are registered correctly.
Expected Result:
- 'sc' namespace maps to ScopeData class
- 'lib' namespace maps to ContentLibraryData class
"""
self.assertIn("sc", ScopeData.scope_registry)
self.assertIs(ScopeData.scope_registry["sc"], ScopeData)
self.assertIn("lib", ScopeData.scope_registry)
self.assertIs(ScopeData.scope_registry["lib"], ContentLibraryData)
@data(
("lib^lib:DemoX:CSPROB", ContentLibraryData),
("sc^generic_scope", ScopeData),
)
@unpack
def test_dynamic_instantiation_via_namespaced_key(self, namespaced_key, expected_class):
"""Test that ScopeData dynamically instantiates the correct subclass.
Expected Result:
- ScopeData(namespaced_key='lib^...') returns ContentLibraryData instance
- ScopeData(namespaced_key='sc^...') returns ScopeData instance
"""
instance = ScopeData(namespaced_key=namespaced_key)
self.assertIsInstance(instance, expected_class)
self.assertEqual(instance.namespaced_key, namespaced_key)
@data(
("lib^lib:DemoX:CSPROB", ContentLibraryData),
("sc^generic", ScopeData),
("unknown^something", ScopeData),
)
@unpack
def test_get_subclass_by_namespaced_key(self, namespaced_key, expected_class):
"""Test get_subclass_by_namespaced_key returns correct subclass.
Expected Result:
- 'lib^...' returns ContentLibraryData
- 'sc^...' returns ScopeData
- 'unknown^...' returns ScopeData (fallback)
"""
subclass = ScopeMeta.get_subclass_by_namespaced_key(namespaced_key)
self.assertIs(subclass, expected_class)
@data(
("lib:DemoX:CSPROB", ContentLibraryData),
("lib:edX:Demo", ContentLibraryData),
("sc:generic_scope", ScopeData),
)
@unpack
def test_get_subclass_by_external_key(self, external_key, expected_class):
"""Test get_subclass_by_external_key returns correct subclass.
Expected Result:
- 'lib:...' returns ContentLibraryData
- 'sc:...' returns ScopeData
"""
subclass = ScopeMeta.get_subclass_by_external_key(external_key)
self.assertIs(subclass, expected_class)
@data(
("lib:DemoX:CSPROB", True),
("lib:edX:Demo", True),
("invalid_library_key", False),
("lib-DemoX-CSPROB", False),
)
@unpack
def test_content_library_validate_external_key(self, external_key, expected_valid):
"""Test ContentLibraryData.validate_external_key validates library keys.
Expected Result:
- Valid library keys (lib:Org:Code) return True
- Invalid formats return False
"""
result = ContentLibraryData.validate_external_key(external_key)
self.assertEqual(result, expected_valid)
def test_direct_subclass_instantiation_bypasses_metaclass(self):
"""Test that direct subclass instantiation doesn't trigger metaclass logic.
Expected Result:
- ContentLibraryData(external_key='...') creates ContentLibraryData directly
- No metaclass dynamic instantiation occurs
"""
library = ContentLibraryData(external_key="lib:Demo:CS")
self.assertIsInstance(library, ContentLibraryData)
self.assertEqual(library.external_key, "lib:Demo:CS")
def test_base_scope_data_with_external_key(self):
"""Test ScopeData instantiation with external_key (not namespaced_key).
Expected Result:
- ScopeData(external_key='...') creates ScopeData instance
- No dynamic subclass selection occurs
"""
scope = ScopeData(external_key="sc:generic_scope")
expected_namespaced = f"{ScopeData.NAMESPACE}{ScopeData.SEPARATOR}sc:generic_scope"
self.assertIsInstance(scope, ScopeData)
self.assertEqual(scope.external_key, "sc:generic_scope")
self.assertEqual(scope.namespaced_key, expected_namespaced)
def test_empty_namespaced_key_raises_value_error(self):
"""Test that providing an empty namespaced_key raises ValueError.
Expected Result:
- ValueError is raised
"""
with self.assertRaises(ValueError):
ScopeData(namespaced_key="")
def test_empty_external_key_raises_value_error(self):
"""Test that providing an empty external_key raises ValueError.
Expected Result:
- ValueError is raised
"""
with self.assertRaises(ValueError):
SubjectData(external_key="")
@ddt
class TestDataRepresentation(TestCase):
"""Test the string representations of data classes."""
@data(
("john_doe", "john_doe", "user^john_doe"),
("jane_smith", "jane_smith", "user^jane_smith"),
)
@unpack
def test_user_data_str_and_repr(self, external_key, expected_str, expected_repr):
"""Test UserData __str__ and __repr__ methods.
Expected Result:
- __str__ returns the username (external_key)
- __repr__ returns the namespaced_key
"""
user = UserData(external_key=external_key)
actual_str = str(user)
actual_repr = repr(user)
self.assertEqual(actual_str, expected_str)
self.assertEqual(actual_repr, expected_repr)
@data(
("read", "Read", "act^read"),
("write", "Write", "act^write"),
(permissions.DELETE_LIBRARY.identifier, "Delete Library", "act^delete_library"),
("edit_content", "Edit Content", "act^edit_content"),
)
@unpack
def test_action_data_str_and_repr(self, external_key, expected_str, expected_repr):
"""Test ActionData __str__ and __repr__ methods.
Expected Result:
- __str__ returns the human-readable name (title case with spaces)
- __repr__ returns the namespaced_key
"""
action = ActionData(external_key=external_key)
actual_str = str(action)
actual_repr = repr(action)
self.assertEqual(actual_str, expected_str)
self.assertEqual(actual_repr, expected_repr)
@data(
("lib:DemoX:CSPROB", "lib:DemoX:CSPROB", "lib^lib:DemoX:CSPROB"),
("lib:edX:Demo", "lib:edX:Demo", "lib^lib:edX:Demo"),
)
@unpack
def test_scope_data_str_and_repr(self, external_key, expected_str, expected_repr):
"""Test ScopeData __str__ and __repr__ methods.
Expected Result:
- __str__ returns the external_key
- __repr__ returns the namespaced_key
"""
scope = ContentLibraryData(external_key=external_key)
actual_str = str(scope)
actual_repr = repr(scope)
self.assertEqual(actual_str, expected_str)
self.assertEqual(actual_repr, expected_repr)
@data(
("instructor", "Instructor", "role^instructor"),
(roles.LIBRARY_ADMIN.external_key, "Library Admin", "role^library_admin"),
("course_staff", "Course Staff", "role^course_staff"),
)
@unpack
def test_role_data_str_without_permissions(self, external_key, expected_name, expected_repr):
"""Test RoleData __str__ and __repr__ methods without permissions.
Expected Result:
- __str__ returns the role name with empty permissions list
- __repr__ returns the namespaced_key
"""
role = RoleData(external_key=external_key)
actual_str = str(role)
actual_repr = repr(role)
expected_str = f"{expected_name}: "
self.assertEqual(actual_str, expected_str)
self.assertEqual(actual_repr, expected_repr)
def test_role_data_str_with_permissions(self):
"""Test RoleData __str__ method with permissions.
Expected Result:
- __str__ returns role name followed by permissions list
"""
action1 = ActionData(external_key="read")
action2 = ActionData(external_key="write")
permission1 = PermissionData(action=action1, effect="allow")
permission2 = PermissionData(action=action2, effect="deny")
role = RoleData(external_key="instructor", permissions=[permission1, permission2])
actual_str = str(role)
expected_str = "Instructor: Read - allow, Write - deny"
self.assertEqual(actual_str, expected_str)
@data(
("read", "allow", "Read - allow", "act^read => allow"),
("write", "deny", "Write - deny", "act^write => deny"),
(
permissions.DELETE_LIBRARY.identifier,
"allow",
"Delete Library - allow",
"act^delete_library => allow",
),
)
@unpack
def test_permission_data_str_and_repr(self, action_key, effect, expected_str, expected_repr):
"""Test PermissionData __str__ and __repr__ methods.
Expected Result:
- __str__ returns 'Action Name - effect'
- __repr__ returns 'namespaced_key => effect'
"""
action = ActionData(external_key=action_key)
permission = PermissionData(action=action, effect=effect)
actual_str = str(permission)
actual_repr = repr(permission)
self.assertEqual(actual_str, expected_str)
self.assertEqual(actual_repr, expected_repr)
def test_role_assignment_data_str(self):
"""Test RoleAssignmentData __str__ method.
Expected Result:
- __str__ returns 'user => role names @ scope'
"""
user = UserData(external_key="john_doe")
role1 = RoleData(external_key="instructor")
role2 = RoleData(external_key=roles.LIBRARY_ADMIN.external_key)
scope = ContentLibraryData(external_key="lib:DemoX:CSPROB")
assignment = RoleAssignmentData(subject=user, roles=[role1, role2], scope=scope)
actual_str = str(assignment)
expected_str = "john_doe => Instructor, Library Admin @ lib:DemoX:CSPROB"
self.assertEqual(actual_str, expected_str)
def test_role_assignment_data_repr(self):
"""Test RoleAssignmentData __repr__ method.
Expected Result:
- __repr__ returns 'namespaced_subject => [namespaced_roles] @ namespaced_scope'
"""
user = UserData(external_key="john_doe")
role1 = RoleData(external_key="instructor")
role2 = RoleData(external_key=roles.LIBRARY_ADMIN.external_key)
scope = ContentLibraryData(external_key="lib:DemoX:CSPROB")
assignment = RoleAssignmentData(subject=user, roles=[role1, role2], scope=scope)
actual_repr = repr(assignment)
expected_repr = "user^john_doe => [role^instructor, role^library_admin] @ lib^lib:DemoX:CSPROB"
self.assertEqual(actual_repr, expected_repr)
@ddt
class TestContentLibraryData(TestCase):
"""Test the ContentLibraryData class."""
@patch("openedx_authz.api.data.ContentLibrary")
def test_get_object_success(self, mock_content_library_model):
"""Test get_object returns ContentLibrary when it exists with valid key.
Expected Result:
- Returns the ContentLibrary object when library exists
- Library key matches exactly (canonical validation passes)
"""
library_id = "lib:DemoX:CSPROB"
library_scope = ContentLibraryData(external_key=library_id)
mock_library_obj = Mock()
mock_library_obj.library_key = library_scope.library_key
mock_content_library_model.objects.get_by_key.return_value = mock_library_obj
result = library_scope.get_object()
self.assertEqual(result, mock_library_obj)
mock_content_library_model.objects.get_by_key.assert_called_once_with(library_scope.library_key)
@patch("openedx_authz.api.data.ContentLibrary")
def test_get_object_does_not_exist(self, mock_content_library_model):
"""Test get_object returns None when library does not exist.
Expected Result:
- Returns None when ContentLibrary.DoesNotExist is raised
"""
library_id = "lib:DemoX:NonExistent"
library_scope = ContentLibraryData(external_key=library_id)
mock_content_library_model.DoesNotExist = Exception
mock_content_library_model.objects.get_by_key.side_effect = mock_content_library_model.DoesNotExist
result = library_scope.get_object()
self.assertIsNone(result)
@patch("openedx_authz.api.data.ContentLibrary")
def test_get_object_invalid_key_format(self, mock_content_library_model):
"""Test get_object returns None when library_id has invalid format.
Expected Result:
- Returns None when InvalidKeyError is raised during key parsing
"""
mock_content_library_model.DoesNotExist = Exception
library_scope = ContentLibraryData(external_key="invalid-library-format")
result = library_scope.get_object()
self.assertIsNone(result)
mock_content_library_model.objects.get_by_key.assert_not_called()
@patch("openedx_authz.api.data.ContentLibrary")
def test_get_object_non_canonical_key(self, mock_content_library_model):
"""Test get_object returns None when library key is not canonical.
This test verifies the canonical key validation: get_by_key is case-insensitive,
but we require exact match to ensure authorization uses canonical library IDs.
Expected Result:
- Returns None when retrieved library's key doesn't match exactly
- Simulates case where user provides 'lib:demox:csprob' but canonical is 'lib:DemoX:CSPROB'
"""
library_id = "lib:DemoX:CSPROB"
library_key = LibraryLocatorV2.from_string(library_id)
# Convert to lowercase to simulate case-insensitive comparison
library_scope = ContentLibraryData(external_key=library_id.lower())
mock_content_library_model.objects.get_by_key.return_value = Mock(library_key=library_key)
mock_content_library_model.DoesNotExist = Exception
result = library_scope.get_object()
self.assertIsNone(result)
@patch("openedx_authz.api.data.ContentLibrary")
def test_exists_returns_true_when_library_exists(self, mock_content_library_model):
"""Test exists() returns True when get_object() returns a library.
Expected Result:
- exists() returns True when library object is found
"""
library_id = "lib:DemoX:CSPROB"
library_scope = ContentLibraryData(external_key=library_id)
mock_content_library_model.objects.get_by_key.return_value = Mock(library_key=library_scope.library_key)
result = library_scope.exists()
self.assertTrue(result)
@patch("openedx_authz.api.data.ContentLibrary")
def test_exists_returns_false_when_library_does_not_exist(self, mock_content_library_model):
"""Test exists() returns False when get_object() returns None.
Expected Result:
- exists() returns False when library is not found
"""
library_id = "lib:DemoX:NonExistent"
library_scope = ContentLibraryData(external_key=library_id)
mock_content_library_model.DoesNotExist = Exception
mock_content_library_model.objects.get_by_key.side_effect = mock_content_library_model.DoesNotExist
result = library_scope.exists()
self.assertFalse(result)