-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathtest_patch_op_validation.py
More file actions
646 lines (534 loc) · 21.8 KB
/
test_patch_op_validation.py
File metadata and controls
646 lines (534 loc) · 21.8 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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
from typing import Annotated
from typing import TypeVar
import pytest
from pydantic import ValidationError
from scim2_models import Group
from scim2_models import InvalidPathException
from scim2_models import InvalidValueException
from scim2_models import Mutability
from scim2_models import MutabilityException
from scim2_models import PatchOp
from scim2_models import PatchOperation
from scim2_models import User
from scim2_models.base import Context
from scim2_models.resources.resource import Resource
class ImmutableFieldResource(Resource):
locked: Annotated[str | None, Mutability.immutable] = None
def test_patch_op_add_invalid_extension_path():
user = User(user_name="john")
patch_op = PatchOp[User](
operations=[
PatchOperation[User](
op="add",
path="urn:ietf:params:scim:schemas:extension:enterprise:2.0:User",
value={"key": "value"},
)
]
)
with pytest.raises(InvalidPathException):
patch_op.patch(user)
def test_patch_op_replace_invalid_extension_path():
user = User(user_name="john")
patch_op = PatchOp[User](
operations=[
PatchOperation[User](
op="replace",
path="urn:ietf:params:scim:schemas:extension:enterprise:2.0:User.attr",
value="test",
)
]
)
with pytest.raises(InvalidPathException):
patch_op.patch(user)
def test_patch_op_remove_invalid_extension_path():
user = User(user_name="john")
patch_op = PatchOp[User](
operations=[
PatchOperation[User](
op="remove",
path="urn:ietf:params:scim:schemas:extension:enterprise:2.0:User.attr",
)
]
)
with pytest.raises(InvalidPathException):
patch_op.patch(user)
def test_patch_op_remove_invalid_extension_path_with_value():
user = User(user_name="john")
patch_op = PatchOp[User](
operations=[
PatchOperation[User](
op="remove",
path="urn:ietf:params:scim:schemas:extension:enterprise:2.0:User.attr",
value="some_value",
)
]
)
with pytest.raises(InvalidPathException):
patch_op.patch(user)
def test_patch_op_without_type_parameter():
"""Test that PatchOp cannot be instantiated without a type parameter."""
with pytest.raises(TypeError, match="PatchOp requires a type parameter"):
PatchOp(operations=[{"op": "replace", "path": "userName", "value": "test"}])
def test_patch_op_with_resource_type():
"""Test that PatchOp[Resource] is rejected."""
with pytest.raises(
TypeError,
match="PatchOp requires a concrete Resource subclass, not Resource itself",
):
PatchOp[Resource]
def test_patch_op_with_invalid_type():
"""Test that PatchOp with invalid types like str is rejected."""
with pytest.raises(
TypeError, match="PatchOp type parameter must be a concrete Resource subclass"
):
PatchOp[str]
def test_patch_op_union_types_not_supported():
"""Test that PatchOp with Union types are rejected."""
with pytest.raises(
TypeError, match="PatchOp type parameter must be a concrete Resource subclass"
):
PatchOp[User | Group]
def test_validate_patchop_case_insensitivity():
"""Validate that a patch operation's Op declaration is case-insensitive.
Note: While :rfc:`RFC7644 §3.4.2.2 <7644#section-3.4.2.2>` specifies case insensitivity
for attribute names and operators in filters, this implementation extends this principle
to PATCH operation names for Microsoft Entra compatibility.
"""
assert PatchOp[User].model_validate(
{
"operations": [
{"op": "Replace", "path": "userName", "value": "Rivard"},
{"op": "ADD", "path": "userName", "value": "Rivard"},
{"op": "ReMove", "path": "userName", "value": "Rivard"},
],
},
) == PatchOp[User](
operations=[
PatchOperation[User](
op=PatchOperation.Op.replace_, path="userName", value="Rivard"
),
PatchOperation[User](
op=PatchOperation.Op.add, path="userName", value="Rivard"
),
PatchOperation[User](
op=PatchOperation.Op.remove, path="userName", value="Rivard"
),
]
)
with pytest.raises(
ValidationError,
match="1 validation error for PatchOp",
):
PatchOp[User].model_validate(
{
"operations": [{"op": 42, "path": "userName", "value": "Rivard"}],
},
)
def test_path_required_for_remove_operations():
"""Test that path is required for remove operations.
:rfc:`RFC7644 §3.5.2.2 <7644#section-3.5.2.2>`: "If 'path' is unspecified,
the operation fails with HTTP status code 400 and a 'scimType' error code of 'noTarget'."
"""
PatchOp[User].model_validate(
{
"operations": [
{"op": "replace", "value": "foobar"},
],
},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
PatchOp[User].model_validate(
{
"operations": [
{"op": "add", "value": "foobar"},
],
},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
# RFC 7644 §3.5.2.2: remove without path returns noTarget error
with pytest.raises(ValidationError, match="Remove operation requires a path"):
PatchOp[User].model_validate(
{
"operations": [
{"op": "remove", "value": "foobar"},
],
},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
def test_value_required_for_add_operations():
"""Test that value is required for add operations.
:rfc:`RFC7644 §3.5.2.1 <7644#section-3.5.2.1>`: "The operation MUST contain a 'value'
member whose content specifies the value to be added."
"""
PatchOp[User].model_validate(
{
"operations": [
{"op": "replace", "path": "foobar"},
],
},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
with pytest.raises(ValidationError):
PatchOp[User].model_validate(
{
"operations": [
{"op": "add", "path": "foobar"},
],
},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
PatchOp[User].model_validate(
{
"operations": [
{"op": "remove", "path": "foobar"},
],
},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
def test_patch_operation_validation_contexts():
"""Test RFC7644 validation behavior in different contexts.
Validates that operations are only validated in PATCH request contexts,
following :rfc:`RFC7644 §3.5.2 <7644#section-3.5.2>` validation requirements.
"""
with pytest.raises(ValidationError, match="path"):
PatchOperation.model_validate(
{"op": "add", "path": " ", "value": "test"},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
# RFC 7644 §3.5.2.2: remove without path returns noTarget error
with pytest.raises(ValidationError, match="Remove operation requires a path"):
PatchOperation.model_validate(
{"op": "remove"},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
with pytest.raises(ValidationError, match="value is required for add operations"):
PatchOperation.model_validate(
{"op": "add", "path": "test"},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
operation = PatchOperation.model_validate({"op": "remove"})
assert operation.path is None
def test_validate_mutability_readonly_error():
"""Test mutability validation error for readOnly attributes."""
# Test add operation on readOnly field
with pytest.raises(ValidationError, match="mutability"):
PatchOp[User].model_validate(
{"operations": [{"op": "add", "path": "id", "value": "new-id"}]},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
# Test replace operation on readOnly field
with pytest.raises(ValidationError, match="mutability"):
PatchOp[User].model_validate(
{"operations": [{"op": "replace", "path": "id", "value": "new-id"}]},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
def test_validate_mutability_readonly_replace_via_complex_path():
"""Replacing a readOnly complex attribute path is rejected."""
with pytest.raises(ValidationError, match="mutability"):
PatchOp[User].model_validate(
{
"operations": [
{
"op": "replace",
"path": "groups.value",
"value": "new-group-id",
}
]
},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
def test_patch_remove_on_immutable_field_with_value_is_rejected():
"""Removing an existing immutable attribute via PATCH is rejected."""
resource = ImmutableFieldResource.model_construct(locked="existing")
patch_op = PatchOp[ImmutableFieldResource].model_validate(
{"operations": [{"op": "remove", "path": "locked"}]},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
with pytest.raises(MutabilityException):
patch_op.patch(resource)
def test_patch_remove_on_immutable_field_without_value_is_allowed():
"""Removing an unset immutable attribute is a no-op and is allowed."""
resource = ImmutableFieldResource.model_construct()
patch_op = PatchOp[ImmutableFieldResource].model_validate(
{"operations": [{"op": "remove", "path": "locked"}]},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
patch_op.patch(resource)
assert resource.locked is None
def test_patch_add_on_immutable_field_with_existing_value_is_rejected():
"""Adding to an immutable attribute that already has a value is rejected."""
resource = ImmutableFieldResource.model_construct(locked="existing")
patch_op = PatchOp[ImmutableFieldResource].model_validate(
{"operations": [{"op": "add", "path": "locked", "value": "new"}]},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
with pytest.raises(MutabilityException):
patch_op.patch(resource)
def test_patch_add_on_immutable_field_without_value_is_allowed():
"""Adding to an immutable attribute with no previous value is allowed per RFC 7644."""
resource = ImmutableFieldResource.model_construct()
patch_op = PatchOp[ImmutableFieldResource].model_validate(
{"operations": [{"op": "add", "path": "locked", "value": "initial"}]},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
patch_op.patch(resource)
assert resource.locked == "initial"
def test_patch_replace_on_immutable_field_with_different_value_is_rejected():
"""Replacing an immutable attribute with a different value is rejected."""
resource = ImmutableFieldResource.model_construct(locked="existing")
patch_op = PatchOp[ImmutableFieldResource].model_validate(
{"operations": [{"op": "replace", "path": "locked", "value": "other"}]},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
with pytest.raises(MutabilityException):
patch_op.patch(resource)
def test_patch_replace_on_immutable_field_with_same_value_is_allowed():
"""Replacing an immutable attribute with its current value is a no-op and is allowed."""
resource = ImmutableFieldResource.model_construct(locked="existing")
patch_op = PatchOp[ImmutableFieldResource].model_validate(
{"operations": [{"op": "replace", "path": "locked", "value": "existing"}]},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
patch_op.patch(resource)
assert resource.locked == "existing"
def test_patch_remove_on_readonly_field_is_rejected():
"""Removing a readOnly attribute via PATCH is rejected per RFC 7643 §7."""
with pytest.raises(ValidationError, match="mutability"):
PatchOp[User].model_validate(
{"operations": [{"op": "remove", "path": "id"}]},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
def test_patch_validation_allows_unknown_fields():
"""Patch operations on unknown fields pass without mutability checks."""
patch_op = PatchOp[User].model_validate(
{
"operations": [
{"op": "add", "path": "unknownField", "value": "some-value"},
]
},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
assert len(patch_op.operations) == 1
assert patch_op.operations[0].path == "unknownField"
def test_patch_operations_on_readwrite_fields_allowed():
"""All patch operations are allowed on readWrite fields."""
patch_op = PatchOp[User].model_validate(
{
"operations": [
{"op": "add", "path": "nickName", "value": "test-nick"},
{"op": "remove", "path": "nickName"},
]
},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
assert len(patch_op.operations) == 2
def test_remove_operation_on_unknown_field_validates():
"""Test remove operation on unknown field validates successfully."""
patch_op = PatchOp[User].model_validate(
{
"operations": [
{"op": "remove", "path": "unknownField"},
]
},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
assert len(patch_op.operations) == 1
assert patch_op.operations[0].path == "unknownField"
def test_remove_operation_on_non_required_field_allowed():
"""Test remove operation on non-required field is allowed."""
# nickName is not required, so remove should be allowed
PatchOp[User].model_validate(
{
"operations": [
{"op": "remove", "path": "nickName"},
]
},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
def test_patch_operations_with_none_path_skipped():
"""Test that patch operations with None path are skipped during validation."""
# Create a patch operation with None path (bypassing normal validation)
patch_op = PatchOp[User](
operations=[
PatchOperation.model_construct(
op=PatchOperation.Op.add, path=None, value="test"
)
]
)
# The validate_operations method should skip operations with None path
# This should not raise an error
user = User(user_name="test")
result = patch_op.patch(user)
assert result is False # Should return False because operation was skipped
def test_patch_operation_with_schema_only_urn_path():
"""Test patch operation with URN path that contains only schema."""
# Test edge case where extract_field_name returns None for schema-only URNs
user = User(user_name="test")
# This URN resolves to just the schema without an attribute name
patch = PatchOp[User](
operations=[
PatchOperation[User](
op=PatchOperation.Op.add,
path="urn:ietf:params:scim:schemas:core:2.0:User",
value="test",
)
]
)
# This should trigger the path where extract_field_name returns None
with pytest.raises(InvalidPathException):
patch.patch(user)
def test_add_remove_operations_on_group_members_allowed():
"""Test that add/remove operations work on group collections."""
# Test operations on group collection (not the immutable value field)
patch_op = PatchOp[User].model_validate(
{
"operations": [
{"op": "add", "path": "emails", "value": {"value": "test@example.com"}},
{
"op": "remove",
"path": "emails",
"value": {"value": "test@example.com"},
},
]
},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
assert len(patch_op.operations) == 2
def test_patch_error_handling_no_operations():
"""Test patch behavior with no operations (using model_construct to bypass validation)."""
user = User(user_name="test")
# Use model_construct to bypass Pydantic validation that requires at least 1 operation
patch = PatchOp[User].model_construct(operations=[])
result = patch.patch(user)
assert result is False
def test_patch_error_handling_type_mismatch():
"""Test error handling when patch value type doesn't match field type."""
user = User(user_name="test")
# Try to set active (boolean) to a string
patch = PatchOp[User](
operations=[
PatchOperation[User](
op=PatchOperation.Op.replace_, path="active", value="not_a_boolean"
)
]
)
with pytest.raises(ValidationError):
patch.patch(user)
T = TypeVar("T", bound=Resource)
UserT = TypeVar("UserT", bound=User)
UnboundT = TypeVar("UnboundT")
def test_patch_op_with_typevar_bound_to_resource():
"""Test that PatchOp accepts TypeVar bound to Resource."""
# Should not raise any exception
patch_type = PatchOp[T]
assert patch_type is not None
def test_patch_op_with_typevar_bound_to_resource_subclass():
"""Test that PatchOp accepts TypeVar bound to Resource subclass."""
# Should not raise any exception
patch_type = PatchOp[UserT]
assert patch_type is not None
def test_patch_op_with_unbound_typevar():
"""Test that PatchOp rejects unbound TypeVar."""
with pytest.raises(
TypeError,
match="PatchOp TypeVar must be bound to Resource or its subclass, got ~UnboundT",
):
PatchOp[UnboundT]
def test_patch_op_with_typevar_bound_to_non_resource():
"""Test that PatchOp rejects TypeVar bound to non-Resource class."""
NonResourceT = TypeVar("NonResourceT", bound=str)
with pytest.raises(
TypeError,
match="PatchOp TypeVar must be bound to Resource or its subclass, got ~NonResourceT",
):
PatchOp[NonResourceT]
def test_create_parent_object_return_none():
"""Test _create_parent_object returns None when type resolution fails."""
user = User()
# Create a patch that will trigger _create_parent_object with complex path
patch = PatchOp[User](
operations=[
PatchOperation[User](
op=PatchOperation.Op.add,
path="complexField.subField", # Non-existent complex field
value="test",
)
]
)
# Non-existent field returns invalidPath error
with pytest.raises(InvalidPathException):
patch.patch(user)
def test_validate_required_field_removal():
"""Test that removing required fields raises validation error."""
# Test removing schemas (required field) should raise validation error
with pytest.raises(ValidationError, match="required attribute cannot be removed"):
PatchOp[User].model_validate(
{"operations": [{"op": "remove", "path": "schemas"}]},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
def test_patch_error_handling_invalid_operation():
"""Test error handling when patch operation has invalid operation type."""
user = User(user_name="test")
patch = PatchOp[User](
operations=[
PatchOperation[User](
op=PatchOperation.Op.add, path="nickName", value="test"
)
]
)
# Force invalid operation type to test error handling
object.__setattr__(patch.operations[0], "op", "invalid_operation")
with pytest.raises(InvalidValueException):
patch.patch(user)
def test_remove_value_at_path_invalid_field():
"""Test removing value at path with invalid parent field name."""
user = User(name={"familyName": "Test"})
# Create patch that attempts to remove from invalid parent field
patch = PatchOp[User](
operations=[
PatchOperation[User](
op=PatchOperation.Op.remove, path="invalidParent.subField"
)
]
)
# Non-existent field returns invalidPath error
with pytest.raises(InvalidPathException):
patch.patch(user)
def test_remove_specific_value_invalid_field():
"""Test removing specific value from invalid field name."""
user = User()
# Create patch that attempts to remove specific value from invalid field
patch = PatchOp[User](
operations=[
PatchOperation[User](
op=PatchOperation.Op.remove,
path="invalidField",
value={"some": "value"},
)
]
)
# Non-existent field returns invalidPath error
with pytest.raises(InvalidPathException):
patch.patch(user)
def test_patch_op_operations_attribute_required_in_patch_context():
"""Test that Operations attribute is required in PATCH request context per RFC 7644."""
# Operations attribute must be present in PATCH request context
with pytest.raises(ValidationError, match="operations attribute is required"):
PatchOp[User].model_validate(
{"schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"]},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
# Operations can be None when not in PATCH request context
patch_op = PatchOp[User].model_validate(
{"schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"]}
)
assert patch_op.operations is None
# Operations with at least one operation is valid in PATCH request context
patch_op = PatchOp[User].model_validate(
{
"schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
"operations": [{"op": "add", "path": "userName", "value": "test"}],
},
context={"scim": Context.RESOURCE_PATCH_REQUEST},
)
assert len(patch_op.operations) == 1