Skip to content

Commit

Permalink
Merge branch 'main' into merge_release/2.162.2
Browse files Browse the repository at this point in the history
  • Loading branch information
baptiste-olivier committed Nov 18, 2024
2 parents 781c3d9 + 51a231b commit 5370473
Show file tree
Hide file tree
Showing 6 changed files with 96 additions and 2 deletions.
9 changes: 8 additions & 1 deletion src/kili/adapters/kili_api_gateway/tag/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Mixin extending Kili API Gateway class with Tags related operations."""

from typing import Dict, List
from typing import Dict, List, Optional

from kili.adapters.kili_api_gateway.base import BaseOperationMixin
from kili.adapters.kili_api_gateway.helpers.queries import fragment_builder
Expand All @@ -10,6 +10,7 @@

from .operations import (
GQL_CHECK_TAG,
GQL_CREATE_TAG,
GQL_DELETE_TAG,
GQL_UNCHECK_TAG,
GQL_UPDATE_TAG,
Expand Down Expand Up @@ -67,3 +68,9 @@ def delete_tag(self, tag_id: TagId) -> bool:
variables = {"tagId": tag_id}
result = self.graphql_client.execute(GQL_DELETE_TAG, variables)
return result["data"]

def create_tag(self, label: str, color: Optional[str] = None) -> Dict:
"""Send a GraphQL request calling createTag resolver."""
variables = {"data": {"label": label, "color": color}}
result = self.graphql_client.execute(GQL_CREATE_TAG, variables)
return result["createTag"]
10 changes: 10 additions & 0 deletions src/kili/adapters/kili_api_gateway/tag/operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,16 @@
}
"""

GQL_CREATE_TAG = """
mutation createTag($data: TagData!) {
createTag(data: $data) {
id
color
label
}
}
"""


def get_list_tags_by_org_query(fragment: str) -> str:
"""Return the GraphQL query to list tags by organization."""
Expand Down
11 changes: 10 additions & 1 deletion src/kili/core/graphql/graphql_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import logging
import os
import threading
import time
from pathlib import Path
from typing import Any, Dict, Optional, Union
from urllib.parse import urlparse
Expand Down Expand Up @@ -80,6 +81,8 @@ def __init__(
self.http_client = http_client
self.verify = verify
self.enable_schema_caching = enable_schema_caching
self.created_at = time.time()
self.complexity_consumed = 0
self.graphql_schema_cache_dir = (
Path(graphql_schema_cache_dir) if graphql_schema_cache_dir else None
)
Expand Down Expand Up @@ -309,7 +312,7 @@ def _raw_execute(
) -> Dict[str, Any]:
_limiter.try_acquire("GraphQLClient.execute")
with _execute_lock:
return self._gql_client.execute(
res = self._gql_client.execute(
document=document,
variable_values=variables,
extra_args={
Expand All @@ -320,3 +323,9 @@ def _raw_execute(
},
**kwargs,
)
transport = self._gql_client.transport
if transport:
headers = transport.response_headers # pyright: ignore[reportGeneralTypeIssues]
returned_complexity = int(headers.get("x-complexity", 0)) if headers else 0
self.complexity_consumed += returned_complexity
return res
16 changes: 16 additions & 0 deletions src/kili/presentation/client/tag.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,3 +176,19 @@ def delete_tag(self, tag_name: Optional[str] = None, tag_id: Optional[str] = Non
raise ValueError("Either `tag_name` or `tag_id` must be provided.")
tag_id = tag_use_cases.get_tag_ids_from_labels(labels=(tag_name,))[0]
return tag_use_cases.delete_tag(tag_id=TagId(tag_id))

def create_tag(self, name: str, color: Optional[str] = None) -> Dict[Literal["id"], str]:
"""Create a tag.
This operation is organization-wide.
The tag will be proposed for projects of the organization.
Args:
name: Name of the tag to create.
color: Color of the tag to create. If not providen a default color will be used.
Returns:
The id of the created tag.
"""
tag_use_cases = TagUseCases(self.kili_api_gateway)
return tag_use_cases.create_tag(name, color)
4 changes: 4 additions & 0 deletions src/kili/use_cases/tag/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,7 @@ def delete_tag(self, tag_id: TagId) -> bool:
Whether the tag was successfully removed.
"""
return self._kili_api_gateway.delete_tag(tag_id=tag_id)

def create_tag(self, name: str, color: Optional[str]) -> Dict:
"""Create a tag."""
return self._kili_api_gateway.create_tag(label=name, color=color)
48 changes: 48 additions & 0 deletions tests/integration/entrypoints/client/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,51 @@ def test_given_an_api_key_away_to_expiration_when_I_check_expiry_of_key_is_not_c
warnings.simplefilter("error") # checks that no warning is raised
# When
_ = Kili()


@patch.dict(os.environ, {"KILI_API_KEY": "fake_key"})
def test_complexity_increases_with_calls(
mocker: pytest_mock.MockerFixture,
):
graphql_mock = mocker.MagicMock()
graphql_mock.execute.return_value = {"data": 1}
graphql_mock.transport.response_headers = {"x-complexity": "125"}

# Given
mocker.patch("kili.client.is_api_key_valid", return_value=True)
mocker.patch.object(ApiKeyUseCases, "check_expiry_of_key_is_close")
mocker.patch(
"kili.core.graphql.graphql_client.GraphQLClient._initizalize_graphql_client",
return_value=graphql_mock,
)
kili = Kili()

assert kili.graphql_client.complexity_consumed == 0
initialized_date = kili.graphql_client.created_at

kili.count_projects()
assert kili.graphql_client.complexity_consumed == 125
assert kili.graphql_client.created_at == initialized_date


@patch.dict(os.environ, {"KILI_API_KEY": "fake_key"})
def test_complexity_compatibility_with_legacy(
mocker: pytest_mock.MockerFixture,
):
graphql_mock = mocker.MagicMock()
graphql_mock.execute.return_value = {"data": 1}
graphql_mock.transport.response_headers = {}

# Given
mocker.patch("kili.client.is_api_key_valid", return_value=True)
mocker.patch.object(ApiKeyUseCases, "check_expiry_of_key_is_close")
mocker.patch(
"kili.core.graphql.graphql_client.GraphQLClient._initizalize_graphql_client",
return_value=graphql_mock,
)
kili = Kili()

assert kili.graphql_client.complexity_consumed == 0

kili.count_projects()
assert kili.graphql_client.complexity_consumed == 0

0 comments on commit 5370473

Please sign in to comment.