Skip to content

Commit 917d43b

Browse files
committed
Fix duplicate in api_key and imports in test_api_keys
1 parent 26f032d commit 917d43b

File tree

3 files changed

+50
-62
lines changed

3 files changed

+50
-62
lines changed

libs/labelbox/src/labelbox/client.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2466,7 +2466,7 @@ def create_api_key(
24662466
role: Union[Role, str],
24672467
validity: int = 0,
24682468
time_unit: TimeUnit = TimeUnit.SECOND,
2469-
) -> Dict[str, Any]:
2469+
) -> Dict[str, str]:
24702470
"""Creates a new API key.
24712471
24722472
Args:
@@ -2477,7 +2477,7 @@ def create_api_key(
24772477
time_unit (TimeUnit, optional): The time unit for the validity period. Defaults to TimeUnit.SECOND.
24782478
24792479
Returns:
2480-
Dict[str, Any]: A dictionary containing the created API key information.
2480+
Dict[str, str]: A dictionary containing the created API key information.
24812481
"""
24822482
warnings.warn(
24832483
"The creation of API keys is currently in alpha and its behavior may change in future releases.",

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

Lines changed: 36 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from datetime import datetime, timezone
2-
from typing import Any, Dict, List, Optional, Union
2+
from typing import Any, Dict, List, Optional, Union, TYPE_CHECKING
33
import logging
44

55
from labelbox.orm.db_object import DbObject
@@ -10,6 +10,9 @@
1010
from labelbox.schema.user import User
1111
from labelbox.schema.role import Role
1212

13+
if TYPE_CHECKING:
14+
from labelbox import Client
15+
1316
logger = logging.getLogger(__name__)
1417

1518

@@ -115,8 +118,15 @@ def revoke(self) -> Dict[str, Any]:
115118
return result
116119

117120
@staticmethod
118-
def _get_current_user_permissions(client) -> List[str]:
119-
"""Retrieve current user permissions from the client's organization role with caching."""
121+
def _get_current_user_permissions(client: "Client") -> List[str]:
122+
"""Retrieve current user permissions from the client's organization role with caching.
123+
124+
Args:
125+
client: The Labelbox client instance.
126+
127+
Returns:
128+
List[str]: A list of permission strings associated with the current user's role.
129+
"""
120130
if hasattr(client, "_cached_current_user_permissions"):
121131
return client._cached_current_user_permissions
122132

@@ -135,53 +145,9 @@ def _get_current_user_permissions(client) -> List[str]:
135145
return perms
136146

137147
@staticmethod
138-
def get_api_key(client, api_key_id: str) -> Optional["ApiKey"]:
139-
"""Retrieves a single API key by its ID.
140-
141-
Args:
142-
client: The Labelbox client instance.
143-
api_key_id (str): The unique ID of the API key.
144-
145-
Returns:
146-
Optional[ApiKey]: The corresponding ApiKey object if found, otherwise None.
147-
"""
148-
query = """
149-
query GetApiKeyPyApi($id: ID!) {
150-
apiKey(where: {id: $id}) {
151-
id
152-
name
153-
key
154-
createdAt
155-
expiresAt
156-
revoked
157-
user {
158-
id
159-
email
160-
}
161-
role {
162-
id
163-
name
164-
permissions
165-
}
166-
}
167-
}
168-
"""
169-
170-
try:
171-
result = client.execute(query, {"id": api_key_id})
172-
173-
if not result or "apiKey" not in result or not result["apiKey"]:
174-
return None
175-
176-
api_key_data = result["apiKey"]
177-
return ApiKey(client, api_key_data)
178-
179-
except Exception as e:
180-
raise LabelboxError(f"Failed to retrieve API key: {str(e)}")
181-
return None
182-
183-
@staticmethod
184-
def get_api_keys(client, include_expired: bool = False) -> List["ApiKey"]:
148+
def get_api_keys(
149+
client: "Client", include_expired: bool = False
150+
) -> List["ApiKey"]:
185151
"""Retrieves all API keys accessible to the current user using the provided client.
186152
187153
Args:
@@ -244,8 +210,22 @@ def get_api_keys(client, include_expired: bool = False) -> List["ApiKey"]:
244210
return all_keys
245211

246212
@staticmethod
247-
def _get_available_api_key_roles(client) -> List[str]:
248-
"""Get the list of built-in roles available for API key creation with caching."""
213+
def _get_available_api_key_roles(client: "Client") -> List[str]:
214+
"""Get the list of built-in roles available for API key creation with caching.
215+
216+
This method retrieves all roles available in the organization and filters them
217+
based on the current user's permissions. The results are cached on the client
218+
to avoid redundant API calls.
219+
220+
Args:
221+
client: The Labelbox client instance.
222+
223+
Returns:
224+
List[str]: A list of role names that can be assigned to API keys.
225+
226+
Raises:
227+
LabelboxError: If there's an error retrieving the user permissions.
228+
"""
249229
if hasattr(client, "_cached_available_api_key_roles"):
250230
return client._cached_available_api_key_roles
251231
try:
@@ -275,7 +255,7 @@ def _get_available_api_key_roles(client) -> List[str]:
275255
return available_roles
276256

277257
@staticmethod
278-
def _get_user(client, email: str) -> Optional[str]:
258+
def _get_user(client: "Client", email: str) -> Optional[str]:
279259
"""Checks if a user with the given email exists in the organization.
280260
281261
Args:
@@ -301,7 +281,7 @@ def _get_user(client, email: str) -> Optional[str]:
301281

302282
@staticmethod
303283
def create_api_key(
304-
client,
284+
client: "Client",
305285
name: str,
306286
user: Union["User", str],
307287
role: Union["Role", str],
@@ -319,7 +299,7 @@ def create_api_key(
319299
time_unit (TimeUnit, optional): Time unit for validity period. Defaults to TimeUnit.SECOND.
320300
321301
Returns:
322-
Dict[str, Any]: Dictionary containing the created API key details including id and jwt
302+
Dict[str, str]: Dictionary containing the created API key details including id and jwt
323303
324304
Raises:
325305
ValueError: If invalid parameters are provided
@@ -412,7 +392,7 @@ def create_api_key(
412392
raise LabelboxError(error_message) from e
413393

414394
@staticmethod
415-
def get_api_key(client, api_key_id: str) -> Optional["ApiKey"]:
395+
def get_api_key(client: "Client", api_key_id: str) -> Optional["ApiKey"]:
416396
"""Retrieves a single API key by its ID using the provided client.
417397
418398
Args:

libs/labelbox/tests/integration/test_api_keys.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,9 @@
11
import uuid
22
import pytest
3-
from datetime import datetime, timezone
43

5-
from labelbox.schema.role import Role
64
from labelbox.schema.timeunit import TimeUnit
75
from labelbox.schema.api_key import ApiKey
86
from lbox.exceptions import LabelboxError
9-
107
# The creation of API keys requires a feature flag to be enabled.
118

129

@@ -135,7 +132,7 @@ def test_create_api_key_invalid_validity_values(client):
135132
validity=0,
136133
time_unit=TimeUnit.MINUTE,
137134
)
138-
assert "validity" in str(excinfo.value).lower()
135+
assert "validity must be a positive integer" in str(excinfo.value).lower()
139136

140137
# Days (exceeding 6 months)
141138
with pytest.raises(ValueError) as excinfo:
@@ -148,6 +145,17 @@ def test_create_api_key_invalid_validity_values(client):
148145
)
149146
assert "maximum validity" in str(excinfo.value).lower()
150147

148+
# Test with validity period less than 1 minute
149+
with pytest.raises(ValueError) as excinfo:
150+
client.create_api_key(
151+
name=f"Test Key {uuid.uuid4()}",
152+
user=user_email,
153+
role="Admin",
154+
validity=30, # 30 seconds
155+
time_unit=TimeUnit.SECOND,
156+
)
157+
assert "Minimum validity period is 1 minute" in str(excinfo.value)
158+
151159

152160
def test_create_api_key_invalid_time_unit(client):
153161
"""Test that providing invalid time unit causes failure."""

0 commit comments

Comments
 (0)