-
Notifications
You must be signed in to change notification settings - Fork 6
Re-implement casting of HFIDs to a list if the rel peer schema has hf… #746
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
0597033
Re-implement casting of HFIDs to a list if the rel peer schema has hf…
FragmentedPacket a66abc1
Fix linting issue with minor refactoring.
FragmentedPacket e96c799
Fixed other linting issue.
FragmentedPacket 4330c06
Moved peer_has_hfid to a property. Updated tests to properly test the…
FragmentedPacket 61cc694
Remove overly mocked tests to migrate to Infrahub repo for functional…
FragmentedPacket bb46a8f
Fix linting
FragmentedPacket File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,14 +1,23 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from typing import TYPE_CHECKING | ||
| from dataclasses import dataclass | ||
| from typing import TYPE_CHECKING, Any | ||
| from unittest.mock import AsyncMock, MagicMock, patch | ||
|
|
||
| import pytest | ||
|
|
||
| from infrahub_sdk.exceptions import ValidationError | ||
| from infrahub_sdk.spec.object import ObjectFile, RelationshipDataFormat, get_relationship_info | ||
| from infrahub_sdk.node.related_node import RelatedNode | ||
| from infrahub_sdk.spec.object import ( | ||
| ObjectFile, | ||
| RelationshipDataFormat, | ||
| get_relationship_info, | ||
| normalize_hfid_reference, | ||
| ) | ||
|
|
||
| if TYPE_CHECKING: | ||
| from infrahub_sdk.client import InfrahubClient | ||
| from infrahub_sdk.node import InfrahubNode | ||
|
|
||
|
|
||
| @pytest.fixture | ||
|
|
@@ -263,3 +272,256 @@ async def test_parameters_non_dict(client_with_schema_01: InfrahubClient, locati | |
| obj = ObjectFile(location="some/path", content=location_with_non_dict_parameters) | ||
| with pytest.raises(ValidationError): | ||
| await obj.validate_format(client=client_with_schema_01) | ||
|
|
||
|
|
||
| @dataclass | ||
| class HfidLoadTestCase: | ||
| """Test case for HFID normalization in object loading.""" | ||
|
|
||
| name: str | ||
| data: list[dict[str, Any]] | ||
| expected_primary_tag: str | list[str] | None | ||
| expected_tags: list[str] | list[list[str]] | None | ||
|
|
||
|
|
||
| HFID_NORMALIZATION_TEST_CASES = [ | ||
| HfidLoadTestCase( | ||
| name="cardinality_one_string_hfid_normalized", | ||
| data=[{"name": "Mexico", "type": "Country", "primary_tag": "Important"}], | ||
| expected_primary_tag=["Important"], | ||
| expected_tags=None, | ||
| ), | ||
| HfidLoadTestCase( | ||
| name="cardinality_one_list_hfid_unchanged", | ||
| data=[{"name": "Mexico", "type": "Country", "primary_tag": ["Important"]}], | ||
| expected_primary_tag=["Important"], | ||
| expected_tags=None, | ||
| ), | ||
| HfidLoadTestCase( | ||
| name="cardinality_one_uuid_unchanged", | ||
| data=[{"name": "Mexico", "type": "Country", "primary_tag": "550e8400-e29b-41d4-a716-446655440000"}], | ||
| expected_primary_tag="550e8400-e29b-41d4-a716-446655440000", | ||
| expected_tags=None, | ||
| ), | ||
| HfidLoadTestCase( | ||
| name="cardinality_many_string_hfids_normalized", | ||
| data=[{"name": "Mexico", "type": "Country", "tags": ["Important", "Active"]}], | ||
| expected_primary_tag=None, | ||
| expected_tags=[["Important"], ["Active"]], | ||
| ), | ||
| HfidLoadTestCase( | ||
| name="cardinality_many_list_hfids_unchanged", | ||
| data=[{"name": "Mexico", "type": "Country", "tags": [["Important"], ["Active"]]}], | ||
| expected_primary_tag=None, | ||
| expected_tags=[["Important"], ["Active"]], | ||
| ), | ||
| HfidLoadTestCase( | ||
| name="cardinality_many_mixed_hfids_normalized", | ||
| data=[{"name": "Mexico", "type": "Country", "tags": ["Important", ["namespace", "name"]]}], | ||
| expected_primary_tag=None, | ||
| expected_tags=[["Important"], ["namespace", "name"]], | ||
| ), | ||
| HfidLoadTestCase( | ||
| name="cardinality_many_uuids_unchanged", | ||
| data=[ | ||
| { | ||
| "name": "Mexico", | ||
| "type": "Country", | ||
| "tags": ["550e8400-e29b-41d4-a716-446655440000", "6ba7b810-9dad-11d1-80b4-00c04fd430c8"], | ||
| } | ||
| ], | ||
| expected_primary_tag=None, | ||
| expected_tags=["550e8400-e29b-41d4-a716-446655440000", "6ba7b810-9dad-11d1-80b4-00c04fd430c8"], | ||
| ), | ||
| ] | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("test_case", HFID_NORMALIZATION_TEST_CASES, ids=lambda tc: tc.name) | ||
| async def test_hfid_normalization_in_object_loading( | ||
| client_with_schema_01: InfrahubClient, test_case: HfidLoadTestCase | ||
| ) -> None: | ||
| """Test that HFIDs are normalized correctly based on cardinality and format.""" | ||
|
|
||
| root_location = {"apiVersion": "infrahub.app/v1", "kind": "Object", "spec": {"kind": "BuiltinLocation", "data": []}} | ||
| location = { | ||
| "apiVersion": root_location["apiVersion"], | ||
| "kind": root_location["kind"], | ||
| "spec": {"kind": root_location["spec"]["kind"], "data": test_case.data}, | ||
| } | ||
|
|
||
| obj = ObjectFile(location="some/path", content=location) | ||
| await obj.validate_format(client=client_with_schema_01) | ||
|
|
||
| create_calls: list[dict[str, Any]] = [] | ||
|
|
||
| async def mock_create( | ||
| kind: str, | ||
| branch: str | None = None, | ||
| data: dict | None = None, | ||
| **kwargs: Any, # noqa: ANN401 | ||
| ) -> InfrahubNode: | ||
| create_calls.append({"kind": kind, "data": data}) | ||
| original_create = client_with_schema_01.__class__.create | ||
| return await original_create(client_with_schema_01, kind=kind, branch=branch, data=data, **kwargs) | ||
|
|
||
| client_with_schema_01.create = mock_create | ||
|
|
||
| with patch("infrahub_sdk.node.InfrahubNode.save", new_callable=AsyncMock): | ||
| await obj.process(client=client_with_schema_01) | ||
|
|
||
| assert len(create_calls) == 1 | ||
| if test_case.expected_primary_tag is not None: | ||
| assert create_calls[0]["data"]["primary_tag"] == test_case.expected_primary_tag | ||
| if test_case.expected_tags is not None: | ||
| assert create_calls[0]["data"]["tags"] == test_case.expected_tags | ||
|
|
||
|
|
||
| @dataclass | ||
| class GraphQLPayloadTestCase: | ||
| """Test case for verifying data format that leads to correct GraphQL payload. | ||
|
|
||
| The RelatedNode interprets data as follows: | ||
| - list → stored as hfid → GraphQL: {"hfid": [...]} | ||
| - string → stored as id → GraphQL: {"id": "..."} | ||
| """ | ||
|
|
||
| name: str | ||
| peer_has_hfid: bool | ||
| input_value: str | list[str] | ||
| expected_output_type: str # "list" for hfid, "string" for id | ||
| expected_output_value: str | list[str] | ||
|
|
||
|
|
||
| GRAPHQL_PAYLOAD_TEST_CASES = [ | ||
| # Peer HAS HFID - non-UUID string should become list (hfid) | ||
| GraphQLPayloadTestCase( | ||
| name="hfid_defined_string_becomes_list", | ||
| peer_has_hfid=True, | ||
| input_value="Important", | ||
| expected_output_type="list", | ||
| expected_output_value=["Important"], | ||
| ), | ||
| # Peer HAS HFID - UUID string should stay as string (id) | ||
| GraphQLPayloadTestCase( | ||
| name="hfid_defined_uuid_stays_string", | ||
| peer_has_hfid=True, | ||
| input_value="550e8400-e29b-41d4-a716-446655440000", | ||
| expected_output_type="string", | ||
| expected_output_value="550e8400-e29b-41d4-a716-446655440000", | ||
| ), | ||
| # Peer HAS HFID - list stays as list (hfid) | ||
| GraphQLPayloadTestCase( | ||
| name="hfid_defined_list_stays_list", | ||
| peer_has_hfid=True, | ||
| input_value=["namespace", "name"], | ||
| expected_output_type="list", | ||
| expected_output_value=["namespace", "name"], | ||
| ), | ||
| # Peer has NO HFID - non-UUID string stays as string (id lookup) | ||
| GraphQLPayloadTestCase( | ||
| name="no_hfid_string_stays_string", | ||
| peer_has_hfid=False, | ||
| input_value="some-string-value", | ||
| expected_output_type="string", | ||
| expected_output_value="some-string-value", | ||
| ), | ||
| # Peer has NO HFID - UUID stays as string (id) | ||
| GraphQLPayloadTestCase( | ||
| name="no_hfid_uuid_stays_string", | ||
| peer_has_hfid=False, | ||
| input_value="550e8400-e29b-41d4-a716-446655440000", | ||
| expected_output_type="string", | ||
| expected_output_value="550e8400-e29b-41d4-a716-446655440000", | ||
| ), | ||
| ] | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("test_case", GRAPHQL_PAYLOAD_TEST_CASES, ids=lambda tc: tc.name) | ||
| def test_graphql_payload_format(test_case: GraphQLPayloadTestCase) -> None: | ||
| """Test that relationship data is formatted correctly for GraphQL payload. | ||
|
|
||
| The RelatedNode class interprets: | ||
| - list input → {"hfid": [...]} in GraphQL | ||
| - string input → {"id": "..."} in GraphQL | ||
|
|
||
| This test verifies the normalization produces the correct format. | ||
| """ | ||
| if test_case.peer_has_hfid: | ||
| # When peer has HFID, use normalization | ||
| processed_value = normalize_hfid_reference(test_case.input_value) | ||
| else: | ||
| # When peer has no HFID, pass value as-is (no normalization) | ||
| processed_value = test_case.input_value | ||
|
||
|
|
||
| # Verify the output type matches expected | ||
| if test_case.expected_output_type == "list": | ||
| assert isinstance(processed_value, list), ( | ||
| f"Expected list output for hfid, got {type(processed_value).__name__}: {processed_value}" | ||
| ) | ||
| else: | ||
| assert isinstance(processed_value, str), ( | ||
| f"Expected string output for id, got {type(processed_value).__name__}: {processed_value}" | ||
| ) | ||
|
|
||
| # Verify the actual value | ||
| assert processed_value == test_case.expected_output_value, ( | ||
| f"Expected {test_case.expected_output_value}, got {processed_value}" | ||
| ) | ||
|
|
||
|
|
||
| @dataclass | ||
| class RelatedNodePayloadTestCase: | ||
| """Test case for verifying the actual GraphQL payload structure from RelatedNode.""" | ||
|
|
||
| name: str | ||
| input_data: str | list[str] | ||
| expected_payload: dict[str, Any] | ||
|
|
||
|
|
||
| RELATED_NODE_PAYLOAD_TEST_CASES = [ | ||
| # String (UUID) → {"id": "uuid"} | ||
| RelatedNodePayloadTestCase( | ||
| name="uuid_string_becomes_id_payload", | ||
| input_data="550e8400-e29b-41d4-a716-446655440000", | ||
| expected_payload={"id": "550e8400-e29b-41d4-a716-446655440000"}, | ||
| ), | ||
| # List (HFID) → {"hfid": [...]} | ||
| RelatedNodePayloadTestCase( | ||
| name="list_becomes_hfid_payload", | ||
| input_data=["Important"], | ||
| expected_payload={"hfid": ["Important"]}, | ||
| ), | ||
| # Multi-component HFID list → {"hfid": [...]} | ||
| RelatedNodePayloadTestCase( | ||
| name="multi_component_hfid_payload", | ||
| input_data=["namespace", "name"], | ||
| expected_payload={"hfid": ["namespace", "name"]}, | ||
| ), | ||
| ] | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("test_case", RELATED_NODE_PAYLOAD_TEST_CASES, ids=lambda tc: tc.name) | ||
| def test_related_node_graphql_payload(test_case: RelatedNodePayloadTestCase) -> None: | ||
| """Test that RelatedNode produces the correct GraphQL payload structure. | ||
|
|
||
| This test verifies the actual {"id": ...} or {"hfid": ...} payload | ||
| that gets sent in GraphQL mutations. | ||
| """ | ||
| # Create mock dependencies | ||
| mock_client = MagicMock() | ||
| mock_schema = MagicMock() | ||
|
|
||
| # Create RelatedNode with the input data | ||
| related_node = RelatedNode( | ||
| schema=mock_schema, | ||
| name="test_rel", | ||
| branch="main", | ||
| client=mock_client, | ||
| data=test_case.input_data, | ||
| ) | ||
|
|
||
| # Generate the input data that would go into GraphQL mutation | ||
| payload = related_node._generate_input_data() | ||
|
|
||
| # Verify the payload structure | ||
| assert payload == test_case.expected_payload, f"Expected payload {test_case.expected_payload}, got {payload}" | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.