Skip to content

Commit 5458071

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

File tree

3 files changed

+75
-29
lines changed

3 files changed

+75
-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: 52 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,56 @@
11
import uuid
22
import pytest
3+
import os
34

45
from labelbox.schema.timeunit import TimeUnit
56
from labelbox.schema.api_key import ApiKey
67
from lbox.exceptions import LabelboxError
78
# The creation of API keys requires a feature flag to be enabled.
89

910

11+
@pytest.mark.skipif(
12+
condition=os.environ["LABELBOX_TEST_ENVIRON"] != "prod",
13+
reason="Admin permissions are required to create API keys",
14+
)
15+
def test_create_api_key_success(client):
16+
# Create a test API key
17+
key_name = f"Test Key {uuid.uuid4()}"
18+
user_email = client.get_user().email
19+
20+
assert (
21+
client.get_user().org_role().name == "Admin"
22+
), "User must be an admin to create API keys"
23+
24+
# Get available roles and use the first one
25+
available_roles = ApiKey._get_available_api_key_roles(client)
26+
assert (
27+
len(available_roles) > 0
28+
), "No available roles found for API key creation"
29+
30+
# Create the API key with a short validity period
31+
api_key_result = client.create_api_key(
32+
name=key_name,
33+
user=user_email,
34+
role=available_roles[0],
35+
validity=5,
36+
time_unit=TimeUnit.MINUTE,
37+
)
38+
39+
# Verify the response format
40+
assert isinstance(
41+
api_key_result, dict
42+
), "API key result should be a dictionary"
43+
assert "id" in api_key_result, "API key result should contain an 'id' field"
44+
assert (
45+
"jwt" in api_key_result
46+
), "API key result should contain a 'jwt' field"
47+
48+
# Verify the JWT token format (should be a JWT string)
49+
jwt = api_key_result["jwt"]
50+
assert isinstance(jwt, str), "JWT should be a string"
51+
assert jwt.count(".") == 2, "JWT should have three parts separated by dots"
52+
53+
1054
def test_create_api_key_failed(client):
1155
# Test with invalid role
1256
with pytest.raises(ValueError) as excinfo:
@@ -132,7 +176,7 @@ def test_create_api_key_invalid_validity_values(client):
132176
validity=0,
133177
time_unit=TimeUnit.MINUTE,
134178
)
135-
assert "validity must be a positive integer" in str(excinfo.value).lower()
179+
assert "minimum validity period is 1 minute" in str(excinfo.value).lower()
136180

137181
# Days (exceeding 6 months)
138182
with pytest.raises(ValueError) as excinfo:
@@ -185,10 +229,16 @@ def test_create_api_key_invalid_time_unit(client):
185229
assert "valid TimeUnit" in str(excinfo.value)
186230

187231

232+
@pytest.mark.skipif(
233+
condition=os.environ["LABELBOX_TEST_ENVIRON"] == "prod",
234+
reason="Accounts with sdmin permission can create API keys",
235+
)
188236
def test_create_api_key_insufficient_permissions(client):
189237
"""Test that creating an API key fails when the user has insufficient permissions."""
190238
user_email = client.get_user().email
191239

240+
assert client.get_user().org_role().name == "Admin"
241+
192242
# Attempt to create another API key using the limited permissions client
193243
# This should fail due to insufficient permissions
194244
with pytest.raises(LabelboxError) as excinfo:
@@ -200,5 +250,4 @@ def test_create_api_key_insufficient_permissions(client):
200250
time_unit=TimeUnit.MINUTE,
201251
)
202252

203-
# Check for the exact "Permission denied" error message
204-
assert "Permission denied" in str(excinfo.value)
253+
assert "192" in str(excinfo.value)

0 commit comments

Comments
 (0)