@@ -124,3 +124,65 @@ def test_full_user(load_sample):
124124 obj .meta .location
125125 == "https://example.com/v2/Users/2819c223-7f76-453a-919d-413861904646"
126126 )
127+
128+
129+ def test_primary_attribute_validation_valid_cases ():
130+ """Test primary attribute validation for valid cases (0 or 1 primary)."""
131+ from scim2_models .context import Context
132+
133+ # Case 1: No primary attributes
134+ user_data = {
135+ "schemas" : ["urn:ietf:params:scim:schemas:core:2.0:User" ],
136+ "userName" : "testuser" ,
137+ "emails" : [
138+ {
"value" :
"[email protected] " ,
"type" :
"work" },
139+ {
"value" :
"[email protected] " ,
"type" :
"home" },
140+ ],
141+ }
142+ user = User .model_validate (
143+ user_data , context = {"scim" : Context .RESOURCE_CREATION_REQUEST }
144+ )
145+ assert user .user_name == "testuser"
146+
147+ # Case 2: Exactly one primary attribute
148+ user_data_with_primary = {
149+ "schemas" : ["urn:ietf:params:scim:schemas:core:2.0:User" ],
150+ "userName" : "testuser2" ,
151+ "emails" : [
152+ {
"value" :
"[email protected] " ,
"type" :
"work" ,
"primary" :
True },
153+ {
"value" :
"[email protected] " ,
"type" :
"home" ,
"primary" :
False },
154+ ],
155+ }
156+ user_with_primary = User .model_validate (
157+ user_data_with_primary , context = {"scim" : Context .RESOURCE_CREATION_REQUEST }
158+ )
159+ assert user_with_primary .emails [0 ].primary is True
160+ assert user_with_primary .emails [1 ].primary is False
161+
162+
163+ def test_primary_attribute_validation_invalid_case ():
164+ """Test primary attribute validation for invalid case (multiple primary)."""
165+ import pytest
166+ from pydantic import ValidationError
167+
168+ from scim2_models .context import Context
169+
170+ # Case: Multiple primary attributes (should fail)
171+ user_data_invalid = {
172+ "schemas" : ["urn:ietf:params:scim:schemas:core:2.0:User" ],
173+ "userName" : "testuser3" ,
174+ "emails" : [
175+ {
"value" :
"[email protected] " ,
"type" :
"work" ,
"primary" :
True },
176+ {
"value" :
"[email protected] " ,
"type" :
"home" ,
"primary" :
True },
177+ ],
178+ }
179+
180+ with pytest .raises (ValidationError ) as exc_info :
181+ User .model_validate (
182+ user_data_invalid , context = {"scim" : Context .RESOURCE_CREATION_REQUEST }
183+ )
184+
185+ error = exc_info .value .errors ()[0 ]
186+ assert error ["type" ] == "primary_uniqueness_error"
187+ assert "emails" in error ["ctx" ]["field_name" ]
188+ assert error ["ctx" ]["count" ] == 2
0 commit comments