77# The creation of API keys requires a feature flag to be enabled.
88
99
10+ def test_create_api_key_success (admin_client ):
11+ # Create a test API key
12+ key_name = f"Test Key { uuid .uuid4 ()} "
13+ user_email = admin_client .get_user ().email
14+
15+ assert (
16+ admin_client .get_user ().org_role ().name == "Admin"
17+ ), "User must be an admin to create API keys"
18+
19+ # Get available roles and use the first one
20+ available_roles = ApiKey ._get_available_api_key_roles (admin_client )
21+ assert (
22+ len (available_roles ) > 0
23+ ), "No available roles found for API key creation"
24+
25+ # Create the API key with a short validity period
26+ api_key_result = admin_client .create_api_key (
27+ name = key_name ,
28+ user = user_email ,
29+ role = available_roles [0 ],
30+ validity = 5 ,
31+ time_unit = TimeUnit .MINUTE ,
32+ )
33+
34+ # Verify the response format
35+ assert isinstance (
36+ api_key_result , dict
37+ ), "API key result should be a dictionary"
38+ assert "id" in api_key_result , "API key result should contain an 'id' field"
39+ assert (
40+ "jwt" in api_key_result
41+ ), "API key result should contain a 'jwt' field"
42+
43+ # Verify the JWT token format (should be a JWT string)
44+ jwt = api_key_result ["jwt" ]
45+ assert isinstance (jwt , str ), "JWT should be a string"
46+ assert jwt .count ("." ) == 2 , "JWT should have three parts separated by dots"
47+
48+
1049def test_create_api_key_failed (client ):
1150 # Test with invalid role
1251 with pytest .raises (ValueError ) as excinfo :
@@ -132,7 +171,7 @@ def test_create_api_key_invalid_validity_values(client):
132171 validity = 0 ,
133172 time_unit = TimeUnit .MINUTE ,
134173 )
135- assert "validity must be a positive integer " in str (excinfo .value ).lower ()
174+ assert "minimum validity period is 1 minute " in str (excinfo .value ).lower ()
136175
137176 # Days (exceeding 6 months)
138177 with pytest .raises (ValueError ) as excinfo :
@@ -189,6 +228,8 @@ def test_create_api_key_insufficient_permissions(client):
189228 """Test that creating an API key fails when the user has insufficient permissions."""
190229 user_email = client .get_user ().email
191230
231+ assert client .get_user ().org_role ().name == "Admin"
232+
192233 # Attempt to create another API key using the limited permissions client
193234 # This should fail due to insufficient permissions
194235 with pytest .raises (LabelboxError ) as excinfo :
@@ -200,5 +241,4 @@ def test_create_api_key_insufficient_permissions(client):
200241 time_unit = TimeUnit .MINUTE ,
201242 )
202243
203- # Check for the exact "Permission denied" error message
204- assert "Permission denied" in str (excinfo .value )
244+ assert "192" in str (excinfo .value )
0 commit comments