diff --git a/changelog/+extract-fields-nested-inline-fragment.fixed.md b/changelog/+extract-fields-nested-inline-fragment.fixed.md new file mode 100644 index 000000000..9c45ec45f --- /dev/null +++ b/changelog/+extract-fields-nested-inline-fragment.fixed.md @@ -0,0 +1 @@ +Fixed `extract_fields` raising `AttributeError: 'InlineFragmentNode' object has no attribute 'name'` for a query that writes an inline fragment inside another inline fragment, such as `query { ... on Query { ... { TestPerson { id } } } }`. `GraphQLQueryAnalyzer.get_fields`, `calculate_depth` and `calculate_height` raised the same error for such a query. The fields of a nested inline fragment are now reported at the level of the enclosing fragment. A fragment spread inside an inline fragment is no longer reported as a field named after the fragment. diff --git a/changelog/+extract-fields-repeated-field.fixed.md b/changelog/+extract-fields-repeated-field.fixed.md new file mode 100644 index 000000000..49f9eb0af --- /dev/null +++ b/changelog/+extract-fields-repeated-field.fixed.md @@ -0,0 +1 @@ +Fixed `extract_fields` dropping sub-fields of a field that a query selects more than once. For `cars { edges { node { id } } } cars { edges { node { name { value } } } }`, only `name` was reported under `node`; both `id` and `name` are now reported. A field selected once without sub-fields and once with them now reports the sub-fields. `GraphQLQueryAnalyzer.get_fields`, `calculate_depth` and `calculate_height` read this result, so the depth and height of such a query can be higher than before. diff --git a/infrahub_sdk/utils.py b/infrahub_sdk/utils.py index 95da7504d..71857a05b 100644 --- a/infrahub_sdk/utils.py +++ b/infrahub_sdk/utils.py @@ -286,28 +286,26 @@ async def extract_fields(selection_set: SelectionSetNode | None) -> dict[str, di if not selection_set: return None - fields = {} + fields: dict[str, Any] = {} for node in selection_set.selections: - sub_selection_set = getattr(node, "selection_set", None) if isinstance(node, FieldNode): - value = await extract_fields(sub_selection_set) - if node.name.value not in fields: - fields[node.name.value] = value - elif isinstance(fields[node.name.value], dict) and isinstance(value, dict): - fields[node.name.value].update(value) - + _merge_extracted_field(fields=fields, name=node.name.value, value=await extract_fields(node.selection_set)) elif isinstance(node, InlineFragmentNode): - for sub_node in node.selection_set.selections: - sub_sub_selection_set = getattr(sub_node, "selection_set", None) - value = await extract_fields(sub_sub_selection_set) - if sub_node.name.value not in fields: - fields[sub_node.name.value] = await extract_fields(sub_sub_selection_set) - elif isinstance(fields[sub_node.name.value], dict) and isinstance(value, dict): - fields[sub_node.name.value].update(value) + # The fields of an inline fragment, and of any inline fragment nested in it, belong to the enclosing level. + for name, value in (await extract_fields(node.selection_set) or {}).items(): + _merge_extracted_field(fields=fields, name=name, value=value) return fields +def _merge_extracted_field(fields: dict[str, Any], name: str, value: dict | None) -> None: + """Record one selection of a field, keeping the sub-fields of every earlier selection of the same field.""" + if fields.get(name) is None: + fields[name] = value + elif value is not None: + deep_merge_dict(fields[name], value) + + async def extract_fields_first_node(info: GraphQLResolveInfo) -> dict[str, dict]: fields = None if info.field_nodes: diff --git a/tests/unit/sdk/test_query_analyzer.py b/tests/unit/sdk/test_query_analyzer.py index c078b3b3d..214b99db2 100644 --- a/tests/unit/sdk/test_query_analyzer.py +++ b/tests/unit/sdk/test_query_analyzer.py @@ -283,3 +283,13 @@ def test_operations_do_not_repeat_a_diamond_fragment() -> None: ) assert gqa.operations == [MUTATION_OPERATION] + + +async def test_depth_and_height_of_nested_inline_fragments() -> None: + """A query measures the same whether its fields are written plainly or inside nested inline fragments.""" + plain = GraphQLQueryAnalyzer(query="query { TestPerson { name { value } } }") + nested = GraphQLQueryAnalyzer(query="query { ... on Query { ... { TestPerson { name { value } } } } }") + + assert await nested.get_fields() == await plain.get_fields() + assert await nested.calculate_depth() == await plain.calculate_depth() + assert await nested.calculate_height() == await plain.calculate_height() diff --git a/tests/unit/sdk/test_utils.py b/tests/unit/sdk/test_utils.py index 97ea6d27d..f0eb2ae30 100644 --- a/tests/unit/sdk/test_utils.py +++ b/tests/unit/sdk/test_utils.py @@ -226,6 +226,101 @@ async def test_extract_fields_fragment(query_02: str) -> None: assert await extract_fields(definition.selection_set) == expected_response +@dataclass +class NestedInlineFragmentCase: + name: str + query: str + expected_fields: dict[str, Any] + + +NESTED_INLINE_FRAGMENT_CASES = [ + NestedInlineFragmentCase( + name="at_the_operation_root", + query="query { ... on Query { ... { TestPerson { name { value } } } } }", + expected_fields={"TestPerson": {"name": {"value": None}}}, + ), + NestedInlineFragmentCase( + name="below_a_field", + query="query { TestCar { ... on TestElectricCar { ... on TestCar { name { value } } nbr_engine { value } } } }", + expected_fields={"TestCar": {"name": {"value": None}, "nbr_engine": {"value": None}}}, + ), + NestedInlineFragmentCase( + name="three_levels", + query="query { ... { ... { ... { TestPerson { id } } } } }", + expected_fields={"TestPerson": {"id": None}}, + ), + NestedInlineFragmentCase( + name="merged_with_the_same_field_of_the_enclosing_fragment", + query="query { ... { TestPerson { id } ... { TestPerson { name { value } } } } }", + expected_fields={"TestPerson": {"id": None, "name": {"value": None}}}, + ), +] + + +@pytest.mark.parametrize("case", NESTED_INLINE_FRAGMENT_CASES, ids=lambda case: case.name) +async def test_extract_fields_nested_inline_fragment(case: NestedInlineFragmentCase) -> None: + """An inline fragment written inside another inline fragment contributes its fields like its parent.""" + definition = parse(case.query).definitions[0] + assert isinstance(definition, OperationDefinitionNode) + assert await extract_fields(definition.selection_set) == case.expected_fields + + +async def test_extract_fields_ignores_fragment_spread_in_inline_fragment() -> None: + """A fragment spread is not a field: inside an inline fragment it is skipped, as it is anywhere else.""" + document = parse( + "query { TestPerson { ... on TestPerson { id ...Names } } } fragment Names on TestPerson { name { value } }" + ) + definition = document.definitions[0] + assert isinstance(definition, OperationDefinitionNode) + assert await extract_fields(definition.selection_set) == {"TestPerson": {"id": None}} + + +@dataclass +class RepeatedFieldCase: + name: str + query: str + expected_fields: dict[str, Any] + + +REPEATED_FIELD_CASES = [ + RepeatedFieldCase( + name="two_plain_selections", + query="query { TestPerson { cars { edges { node { id } } } cars { edges { node { name { value } } } } } }", + expected_fields={"TestPerson": {"cars": {"edges": {"node": {"id": None, "name": {"value": None}}}}}}, + ), + RepeatedFieldCase( + name="inline_fragment_then_plain_selection", + query="query { TestPerson { ... on TestPerson { cars { edges { node { id } } } }" + " cars { edges { node { name { value } } } } } }", + expected_fields={"TestPerson": {"cars": {"edges": {"node": {"id": None, "name": {"value": None}}}}}}, + ), + RepeatedFieldCase( + name="two_inline_fragments", + query="query { TestCar { ... on TestElectricCar { owner { node { id } } }" + " ... on TestGazCar { owner { node { name { value } } } } } }", + expected_fields={"TestCar": {"owner": {"node": {"id": None, "name": {"value": None}}}}}, + ), + RepeatedFieldCase( + name="without_then_with_sub_fields", + query="query { TestPerson { cars cars { id } } }", + expected_fields={"TestPerson": {"cars": {"id": None}}}, + ), + RepeatedFieldCase( + name="with_then_without_sub_fields", + query="query { TestPerson { cars { id } cars } }", + expected_fields={"TestPerson": {"cars": {"id": None}}}, + ), +] + + +@pytest.mark.parametrize("case", REPEATED_FIELD_CASES, ids=lambda case: case.name) +async def test_extract_fields_merges_a_field_selected_twice(case: RepeatedFieldCase) -> None: + """A field selected twice reports the sub-fields of both selections, at every level.""" + definition = parse(case.query).definitions[0] + assert isinstance(definition, OperationDefinitionNode) + assert await extract_fields(definition.selection_set) == case.expected_fields + + def test_write_to_file() -> None: tmp_dir = tempfile.TemporaryDirectory() directory = Path(tmp_dir.name)