Skip to content

Commit 4bedd10

Browse files
committed
Changes tests and add refresh cache following review
1 parent 784487b commit 4bedd10

File tree

3 files changed

+66
-29
lines changed

3 files changed

+66
-29
lines changed

libs/labelbox/src/labelbox/client.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2466,6 +2466,7 @@ def create_api_key(
24662466
role: Union[Role, str],
24672467
validity: int = 0,
24682468
time_unit: TimeUnit = TimeUnit.SECOND,
2469+
refresh_cache: bool = False,
24692470
) -> Dict[str, str]:
24702471
"""Creates a new API key.
24712472
@@ -2475,13 +2476,21 @@ def create_api_key(
24752476
role (Union[Role, str]): The role object or role ID to assign to the API key.
24762477
validity (int, optional): The validity period of the API key. Defaults to 0 (no expiration).
24772478
time_unit (TimeUnit, optional): The time unit for the validity period. Defaults to TimeUnit.SECOND.
2479+
refresh_cache (bool, optional): Whether to refresh cached permissions and roles. Defaults to False.
24782480
24792481
Returns:
24802482
Dict[str, str]: A dictionary containing the created API key information.
24812483
"""
24822484
warnings.warn(
24832485
"The creation of API keys is currently in alpha and its behavior may change in future releases.",
24842486
)
2487+
if refresh_cache:
2488+
# Clear cached attributes if they exist
2489+
if hasattr(self, "_cached_current_user_permissions"):
2490+
delattr(self, "_cached_current_user_permissions")
2491+
if hasattr(self, "_cached_available_api_key_roles"):
2492+
delattr(self, "_cached_available_api_key_roles")
2493+
24852494
return ApiKey.create_api_key(
24862495
self, name, user, role, validity, time_unit
24872496
)

libs/labelbox/src/labelbox/schema/api_key.py

Lines changed: 14 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -330,24 +330,22 @@ def create_api_key(
330330
)
331331

332332
validity_seconds = 0
333-
if validity > 0:
334-
if not isinstance(time_unit, TimeUnit):
335-
raise ValueError(
336-
"time_unit must be a valid TimeUnit enum value"
337-
)
333+
if validity < 0:
334+
raise ValueError("validity must be a positive integer")
338335

339-
validity_seconds = validity * time_unit.value
336+
if not isinstance(time_unit, TimeUnit):
337+
raise ValueError("time_unit must be a valid TimeUnit enum value")
340338

341-
if validity_seconds < TimeUnit.MINUTE.value:
342-
raise ValueError("Minimum validity period is 1 minute")
339+
validity_seconds = validity * time_unit.value
343340

344-
max_seconds = 25 * TimeUnit.WEEK.value
345-
if validity_seconds > max_seconds:
346-
raise ValueError(
347-
"Maximum validity period is 6 months (or 25 weeks)"
348-
)
349-
else:
350-
raise ValueError("validity must be a positive integer")
341+
if validity_seconds < TimeUnit.MINUTE.value:
342+
raise ValueError("Minimum validity period is 1 minute")
343+
344+
max_seconds = 25 * TimeUnit.WEEK.value
345+
if validity_seconds > max_seconds:
346+
raise ValueError(
347+
"Maximum validity period is 6 months (or 25 weeks)"
348+
)
351349

352350
query_str = """
353351
mutation CreateUserApiKeyPyApi($name: String!, $userEmail: String!, $role: String, $validitySeconds: Int) {
@@ -379,17 +377,7 @@ def create_api_key(
379377
return api_key_result
380378

381379
except Exception as e:
382-
if (
383-
"permission" in str(e).lower()
384-
or "unauthorized" in str(e).lower()
385-
):
386-
raise LabelboxError(
387-
f"Permission denied: You don't have sufficient permissions to create API keys. Original error: {str(e)}"
388-
)
389-
else:
390-
error_message = f"Failed to create API key: {str(e)}"
391-
logger.error(error_message)
392-
raise LabelboxError(error_message) from e
380+
raise LabelboxError(str(e)) from e
393381

394382
@staticmethod
395383
def get_api_key(client: "Client", api_key_id: str) -> Optional["ApiKey"]:

libs/labelbox/tests/integration/test_api_keys.py

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,45 @@
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+
1049
def 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

Comments
 (0)