Skip to content

Commit 5a31ff5

Browse files
committed
Move functions into SDK
1 parent 4088fdc commit 5a31ff5

File tree

11 files changed

+174
-125
lines changed

11 files changed

+174
-125
lines changed

infrahub_sdk/client.py

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,13 @@
4646
)
4747
from .object_store import ObjectStore, ObjectStoreSync
4848
from .protocols_base import CoreNode, CoreNodeSync
49-
from .queries import get_commit_update_mutation
49+
from .queries import QUERY_USER, get_commit_update_mutation
5050
from .query_groups import InfrahubGroupContext, InfrahubGroupContextSync
5151
from .schema import InfrahubSchema, InfrahubSchemaSync, NodeSchemaAPI
5252
from .store import NodeStore, NodeStoreSync
5353
from .timestamp import Timestamp
5454
from .types import AsyncRequester, HTTPMethod, SyncRequester
55-
from .utils import decode_json, is_valid_uuid
55+
from .utils import decode_json, get_user_permissions, is_valid_uuid
5656

5757
if TYPE_CHECKING:
5858
from types import TracebackType
@@ -274,6 +274,22 @@ def _initialize(self) -> None:
274274
self._request_method: AsyncRequester = self.config.requester or self._default_request_method
275275
self.group_context = InfrahubGroupContext(self)
276276

277+
async def get_version(self) -> str:
278+
"""Return the Infrahub version."""
279+
response = await self.execute_graphql(query="query { InfrahubInfo { version }}")
280+
version = response.get("InfrahubInfo", {}).get("version", "")
281+
return version
282+
283+
async def get_user(self) -> dict:
284+
"""Return user information"""
285+
user_info = await self.execute_graphql(query=QUERY_USER)
286+
return user_info
287+
288+
async def get_user_permissions(self) -> dict:
289+
"""Return user permissions"""
290+
user_info = await self.get_user()
291+
return get_user_permissions(user_info["AccountProfile"]["member_of_groups"]["edges"])
292+
277293
@overload
278294
async def create(
279295
self,
@@ -1427,6 +1443,22 @@ def _initialize(self) -> None:
14271443
self._request_method: SyncRequester = self.config.sync_requester or self._default_request_method
14281444
self.group_context = InfrahubGroupContextSync(self)
14291445

1446+
def get_version(self) -> str:
1447+
"""Return the Infrahub version."""
1448+
response = self.execute_graphql(query="query { InfrahubInfo { version }}")
1449+
version = response.get("InfrahubInfo", {}).get("version", "")
1450+
return version
1451+
1452+
def get_user(self) -> dict:
1453+
"""Return user information"""
1454+
user_info = self.execute_graphql(query=QUERY_USER)
1455+
return user_info
1456+
1457+
def get_user_permissions(self) -> dict:
1458+
"""Return user permissions"""
1459+
user_info = self.get_user()
1460+
return get_user_permissions(user_info["AccountProfile"]["member_of_groups"]["edges"])
1461+
14301462
@overload
14311463
def create(
14321464
self,

infrahub_sdk/ctl/cli_commands.py

Lines changed: 5 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@
3939
from ..ctl.utils import (
4040
catch_exception,
4141
execute_graphql_query,
42-
get_user_permissions,
4342
load_yamlfile_from_disk_and_exit,
4443
parse_cli_vars,
4544
)
@@ -409,75 +408,6 @@ def version() -> None:
409408
def info(detail: bool = typer.Option(False, help="Display detailed information."), _: str = CONFIG_PARAM) -> None: # noqa: PLR0915
410409
"""Display the status of the Python SDK."""
411410

412-
query = """
413-
query GET_PROFILE_DETAILS {
414-
AccountProfile {
415-
id
416-
display_label
417-
account_type {
418-
value
419-
__typename
420-
updated_at
421-
}
422-
status {
423-
label
424-
value
425-
updated_at
426-
__typename
427-
}
428-
description {
429-
value
430-
updated_at
431-
__typename
432-
}
433-
label {
434-
value
435-
updated_at
436-
__typename
437-
}
438-
member_of_groups {
439-
count
440-
edges {
441-
node {
442-
display_label
443-
group_type {
444-
value
445-
}
446-
... on CoreAccountGroup {
447-
id
448-
roles {
449-
count
450-
edges {
451-
node {
452-
permissions {
453-
count
454-
edges {
455-
node {
456-
display_label
457-
identifier {
458-
value
459-
}
460-
}
461-
}
462-
}
463-
}
464-
}
465-
}
466-
display_label
467-
}
468-
}
469-
}
470-
}
471-
__typename
472-
name {
473-
value
474-
updated_at
475-
__typename
476-
}
477-
}
478-
}
479-
"""
480-
481411
info: dict[str, Any] = {
482412
"error": None,
483413
"status": ":x:",
@@ -487,11 +417,10 @@ def info(detail: bool = typer.Option(False, help="Display detailed information."
487417
}
488418
try:
489419
client = initialize_client_sync()
490-
version_response = client.execute_graphql(query="query { InfrahubInfo { version }}")
491-
info["infrahub_version"] = version_response["InfrahubInfo"]["version"]
492-
info["user_info"] = client.execute_graphql(query=query)
420+
info["infrahub_version"] = client.get_version()
421+
info["user_info"] = client.get_user()
493422
info["status"] = ":white_heavy_check_mark:"
494-
info["groups"] = get_user_permissions(info["user_info"]["AccountProfile"]["member_of_groups"]["edges"])
423+
info["groups"] = client.get_user_permissions()
495424
except Exception as e:
496425
info["error"] = f"{e!s} ({e.__class__.__name__})"
497426

@@ -550,8 +479,8 @@ def info(detail: bool = typer.Option(False, help="Display detailed information."
550479

551480
if groups := info["groups"]:
552481
infrahub_info.add_row("Groups:", "")
553-
for k, v in groups.items():
554-
infrahub_info.add_row("", k, v)
482+
for group, roles in groups.items():
483+
infrahub_info.add_row("", group, ", ".join(roles))
555484

556485
layout["infrahub_info"].update(Panel(infrahub_info, title="Infrahub Info"))
557486

infrahub_sdk/ctl/utils.py

Lines changed: 0 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -214,21 +214,3 @@ def load_yamlfile_from_disk_and_exit(
214214
raise typer.Exit(1)
215215

216216
return data_files
217-
218-
219-
def get_user_permissions(data: list[dict]) -> dict:
220-
groups = {}
221-
for group in data:
222-
group_name = group["node"]["display_label"]
223-
permissions = []
224-
225-
roles = group["node"].get("roles", {}).get("edges", [])
226-
for role in roles:
227-
role_permissions = role["node"].get("permissions", {}).get("edges", [])
228-
for permission in role_permissions:
229-
permissions.append(permission["node"]["identifier"]["value"])
230-
231-
permissions_str = ", ".join(permissions)
232-
groups[group_name] = permissions_str
233-
234-
return groups

infrahub_sdk/queries.py

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,72 @@ def get_commit_update_mutation(is_read_only: bool = False) -> str:
4242
}
4343
}
4444
"""
45+
46+
QUERY_USER = """
47+
query GET_PROFILE_DETAILS {
48+
AccountProfile {
49+
id
50+
display_label
51+
account_type {
52+
value
53+
__typename
54+
updated_at
55+
}
56+
status {
57+
label
58+
value
59+
updated_at
60+
__typename
61+
}
62+
description {
63+
value
64+
updated_at
65+
__typename
66+
}
67+
label {
68+
value
69+
updated_at
70+
__typename
71+
}
72+
member_of_groups {
73+
count
74+
edges {
75+
node {
76+
display_label
77+
group_type {
78+
value
79+
}
80+
... on CoreAccountGroup {
81+
id
82+
roles {
83+
count
84+
edges {
85+
node {
86+
permissions {
87+
count
88+
edges {
89+
node {
90+
display_label
91+
identifier {
92+
value
93+
}
94+
}
95+
}
96+
}
97+
}
98+
}
99+
}
100+
display_label
101+
}
102+
}
103+
}
104+
}
105+
__typename
106+
name {
107+
value
108+
updated_at
109+
__typename
110+
}
111+
}
112+
}
113+
"""

infrahub_sdk/utils.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,3 +335,20 @@ def write_to_file(path: Path, value: Any) -> bool:
335335
written = path.write_text(to_write)
336336

337337
return written is not None
338+
339+
340+
def get_user_permissions(data: list[dict]) -> dict:
341+
groups = {}
342+
for group in data:
343+
group_name = group["node"]["display_label"]
344+
permissions = []
345+
346+
roles = group["node"].get("roles", {}).get("edges", [])
347+
for role in roles:
348+
role_permissions = role["node"].get("permissions", {}).get("edges", [])
349+
for permission in role_permissions:
350+
permissions.append(permission["node"]["identifier"]["value"])
351+
352+
groups[group_name] = permissions
353+
354+
return groups

tests/fixtures/integration/test_infrahubctl/info_cmd/infrahub_info.json

Lines changed: 0 additions & 7 deletions
This file was deleted.

tests/unit/ctl/conftest.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import pytest
22
from pytest_httpx import HTTPXMock
33

4+
from tests.unit.sdk.conftest import mock_query_infrahub_user, mock_query_infrahub_version # noqa: F401
5+
46

57
@pytest.fixture
68
async def mock_branches_list_query(httpx_mock: HTTPXMock) -> HTTPXMock:

tests/unit/ctl/test_cli.py

Lines changed: 2 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,10 @@
1-
import json
21
import sys
32

43
import pytest
5-
from pytest_httpx._httpx_mock import HTTPXMock
64
from typer.testing import CliRunner
75

86
from infrahub_sdk.ctl.cli import app
97

10-
from .test_transform_app import read_fixture
11-
128
runner = CliRunner()
139

1410
requires_python_310 = pytest.mark.skipif(sys.version_info < (3, 10), reason="Requires Python 3.10 or higher")
@@ -40,23 +36,8 @@ def test_version_command():
4036
assert "Python SDK: v" in result.stdout
4137

4238

43-
def mock_common_responses(httpx_mock: HTTPXMock):
44-
httpx_mock.add_response(
45-
method="POST",
46-
url="http://mock/graphql/main",
47-
json=json.loads(read_fixture("infrahub_info.json", "info_cmd")),
48-
)
49-
httpx_mock.add_response(
50-
method="POST",
51-
url="http://mock/graphql/main",
52-
json=json.loads(read_fixture("account_profile.json", "info_cmd")),
53-
)
54-
55-
5639
@requires_python_310
57-
def test_info_command_success(httpx_mock: HTTPXMock):
58-
mock_common_responses(httpx_mock)
59-
40+
def test_info_command_success(mock_query_infrahub_version, mock_query_infrahub_user):
6041
result = runner.invoke(app, ["info"])
6142
assert result.exit_code == 0
6243
for expected in ["Connection Status", "Python Version", "SDK Version", "Infrahub Version"]:
@@ -71,8 +52,7 @@ def test_info_command_failure():
7152

7253

7354
@requires_python_310
74-
def test_info_detail_command_success(httpx_mock: HTTPXMock):
75-
mock_common_responses(httpx_mock)
55+
def test_info_detail_command_success(mock_query_infrahub_version, mock_query_infrahub_user):
7656
result = runner.invoke(app, ["info", "--detail"])
7757
assert result.exit_code == 0
7858
for expected in [

tests/unit/sdk/conftest.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2031,6 +2031,19 @@ async def mock_query_mutation_location_create_failed(httpx_mock: HTTPXMock) -> H
20312031
return httpx_mock
20322032

20332033

2034+
@pytest.fixture
2035+
async def mock_query_infrahub_version(httpx_mock: HTTPXMock) -> HTTPXMock:
2036+
httpx_mock.add_response(method="POST", json={"data": {"InfrahubInfo": {"version": "1.1.0"}}})
2037+
return httpx_mock
2038+
2039+
2040+
@pytest.fixture
2041+
async def mock_query_infrahub_user(httpx_mock: HTTPXMock) -> HTTPXMock:
2042+
response_text = (get_fixtures_dir() / "account_profile.json").read_text(encoding="UTF-8")
2043+
httpx_mock.add_response(method="POST", json=ujson.loads(response_text))
2044+
return httpx_mock
2045+
2046+
20342047
@pytest.fixture
20352048
def query_01() -> str:
20362049
"""Simple query with one document"""

0 commit comments

Comments
 (0)