graphql-typed-python 0.1.2__tar.gz → 0.1.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/PKG-INFO +28 -2
  2. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/README.md +27 -1
  3. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/graphql_typed/generator/client.py +54 -35
  4. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/graphql_typed/generator/operations.py +21 -4
  5. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/graphql_typed/generator/types.py +13 -6
  6. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/pyproject.toml +1 -1
  7. graphql_typed_python-0.1.3/tests/contract/interfaces/operations.py +28 -0
  8. graphql_typed_python-0.1.3/tests/contract/interfaces/schema.graphql +8 -0
  9. graphql_typed_python-0.1.3/tests/contract/interfaces/usage.py +34 -0
  10. graphql_typed_python-0.1.3/tests/ide/test_interfaces.py +33 -0
  11. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/tests/test_contracts.py +9 -1
  12. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/tests/test_generation.py +52 -1
  13. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/uv.lock +1 -1
  14. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/.github/workflows/qa.yml +0 -0
  15. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/.github/workflows/release.yml +0 -0
  16. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/.gitignore +0 -0
  17. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/.pre-commit-config.yaml +0 -0
  18. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/.python-version +0 -0
  19. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/.vscode/settings.json +0 -0
  20. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/Justfile +0 -0
  21. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/LICENSE +0 -0
  22. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/graphql_typed/__init__.py +0 -0
  23. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/graphql_typed/cli.py +0 -0
  24. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/graphql_typed/generator/__init__.py +0 -0
  25. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/graphql_typed/generator/api.py +0 -0
  26. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/graphql_typed/generator/factory.py +0 -0
  27. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/graphql_typed/generator/loader.py +0 -0
  28. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/graphql_typed/generator/write.py +0 -0
  29. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/graphql_typed/py.typed +0 -0
  30. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/graphql_typed/templates/transport.py +0 -0
  31. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/scripts/benchmark_generate.py +0 -0
  32. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/scripts/release.py +0 -0
  33. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/tests/__init__.py +0 -0
  34. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/tests/conftest.py +0 -0
  35. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/tests/contract/devices/operations.py +0 -0
  36. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/tests/contract/devices/schema.graphql +0 -0
  37. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/tests/contract/devices/standalone.py +0 -0
  38. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/tests/contract/devices/usage.py +0 -0
  39. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/tests/contract/mutations/execute.py +0 -0
  40. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/tests/contract/mutations/operations.py +0 -0
  41. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/tests/contract/mutations/schema.graphql +0 -0
  42. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/tests/contract/mutations/usage.py +0 -0
  43. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/tests/contract/recursive/operations.py +0 -0
  44. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/tests/contract/recursive/schema.graphql +0 -0
  45. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/tests/contract/recursive/usage.py +0 -0
  46. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/tests/ide/__init__.py +0 -0
  47. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/tests/ide/conftest.py +0 -0
  48. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/tests/ide/test_completions.py +0 -0
  49. {graphql_typed_python-0.1.2 → graphql_typed_python-0.1.3}/tests/test_execution.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: graphql-typed-python
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Summary: Generate typed GraphQL selections, variables, and response dictionaries for Python.
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -87,7 +87,33 @@ Construct a client with `AsyncClient("https://example.test/graphql")`. The sync
87
87
  - Use `var("name")` at an argument, input object field, or list item. The first use determines its GraphQL type. Further uses must have exactly the same type, including nullability and list markers. Custom scalars retain their GraphQL names and use Python `Any`.
88
88
  - Input objects are dictionaries and enum values are string literals. Nullable variables can be omitted or set to `None`. A selected nullable response field has a required key whose value can be `None`.
89
89
  - Use `schema.mutation(...)` and `client.mutation("Name")(...)` for mutations. Operations without variables are called as `client.query("Name")()`.
90
- - V1 supports queries and mutations over concrete objects. Subscriptions, directives on selections, and type-specific selections on unions and interfaces are outside its scope.
90
+ - Queries and mutations support object and interface results. Union results, subscriptions, and directives on selections are outside the current scope.
91
+
92
+ ### Interface selections
93
+
94
+ Select shared fields directly. Add a key such as `"... on InterfaceVirtual"` for fields specific to a concrete implementation. The generated selection type provides completions for each fragment key and for the fields inside it.
95
+
96
+ ```python
97
+ peers: schema.InterfaceFields = {
98
+ "name": True,
99
+ "__typename": True,
100
+ "... on InterfaceVirtual": {
101
+ "parent_interface": {"select": {"name": True}},
102
+ },
103
+ }
104
+ ```
105
+
106
+ Use `peers` as the `select` value of an interface-valued field. Given an item from that result, `ty` can narrow on the selected `__typename`:
107
+
108
+ ```python
109
+ label = peer["name"]
110
+ if peer["__typename"] == "InterfaceVirtual":
111
+ parent = peer["parent_interface"]
112
+ if parent is not None:
113
+ label = parent["name"]
114
+ ```
115
+
116
+ The physical branch has only `name` and `__typename`. Selecting `__typename` is optional. If you alias it, use the alias for narrowing. Nested relationships retain their selected fields and schema nullability.
91
117
 
92
118
  ## Schema sources and output
93
119
 
@@ -75,7 +75,33 @@ Construct a client with `AsyncClient("https://example.test/graphql")`. The sync
75
75
  - Use `var("name")` at an argument, input object field, or list item. The first use determines its GraphQL type. Further uses must have exactly the same type, including nullability and list markers. Custom scalars retain their GraphQL names and use Python `Any`.
76
76
  - Input objects are dictionaries and enum values are string literals. Nullable variables can be omitted or set to `None`. A selected nullable response field has a required key whose value can be `None`.
77
77
  - Use `schema.mutation(...)` and `client.mutation("Name")(...)` for mutations. Operations without variables are called as `client.query("Name")()`.
78
- - V1 supports queries and mutations over concrete objects. Subscriptions, directives on selections, and type-specific selections on unions and interfaces are outside its scope.
78
+ - Queries and mutations support object and interface results. Union results, subscriptions, and directives on selections are outside the current scope.
79
+
80
+ ### Interface selections
81
+
82
+ Select shared fields directly. Add a key such as `"... on InterfaceVirtual"` for fields specific to a concrete implementation. The generated selection type provides completions for each fragment key and for the fields inside it.
83
+
84
+ ```python
85
+ peers: schema.InterfaceFields = {
86
+ "name": True,
87
+ "__typename": True,
88
+ "... on InterfaceVirtual": {
89
+ "parent_interface": {"select": {"name": True}},
90
+ },
91
+ }
92
+ ```
93
+
94
+ Use `peers` as the `select` value of an interface-valued field. Given an item from that result, `ty` can narrow on the selected `__typename`:
95
+
96
+ ```python
97
+ label = peer["name"]
98
+ if peer["__typename"] == "InterfaceVirtual":
99
+ parent = peer["parent_interface"]
100
+ if parent is not None:
101
+ label = parent["name"]
102
+ ```
103
+
104
+ The physical branch has only `name` and `__typename`. Selecting `__typename` is optional. If you alias it, use the alias for narrowing. Nested relationships retain their selected fields and schema nullability.
79
105
 
80
106
  ## Schema sources and output
81
107
 
@@ -1,14 +1,16 @@
1
- from collections import defaultdict
2
1
  from collections.abc import Iterable
2
+ from functools import cache
3
3
 
4
4
  from graphql import (
5
5
  FieldNode,
6
+ GraphQLInterfaceType,
6
7
  GraphQLNonNull,
7
8
  GraphQLObjectType,
8
9
  GraphQLSchema,
9
- SelectionNode,
10
+ SelectionSetNode,
10
11
  get_named_type,
11
12
  )
13
+ from graphql.execution.collect_fields import collect_fields
12
14
 
13
15
  from graphql_typed import Operation
14
16
  from graphql_typed.generator.operations import Document
@@ -17,42 +19,59 @@ from graphql_typed.generator.types import Inputs, Names, annotation, dictionary,
17
19
 
18
20
  def response(
19
21
  name: str,
20
- parent: GraphQLObjectType,
21
- selections: Iterable[SelectionNode],
22
+ schema: GraphQLSchema,
23
+ parent: GraphQLObjectType | GraphQLInterfaceType,
24
+ selection_set: SelectionSetNode,
22
25
  names: Names,
23
26
  definitions: list[str],
24
27
  ) -> None:
25
- groups: dict[str, list[FieldNode]] = defaultdict(list)
26
- for field in selections:
27
- assert isinstance(field, FieldNode)
28
- groups[(field.alias or field.name).value].append(field)
29
- items = []
30
- for key, nodes in groups.items():
31
- field_name = nodes[0].name.value
32
- if field_name == "__typename":
33
- item_type = f"t.Literal[{parent.name!r}]"
34
- else:
35
- field_type = parent.fields[field_name].type
36
- target = get_named_type(field_type)
37
- if isinstance(target, GraphQLObjectType):
38
- nested = names.take(f"{name}_{key}")
39
- response(
40
- nested,
41
- target,
42
- (
43
- child
44
- for node in nodes
45
- if node.selection_set
46
- for child in node.selection_set.selections
47
- ),
48
- names,
49
- definitions,
50
- )
51
- item_type = annotation(field_type, nested)
28
+ # A shared relationship has the same selected children in multiple variants.
29
+ @cache
30
+ def nested_type(
31
+ key: str,
32
+ target: GraphQLObjectType | GraphQLInterfaceType,
33
+ nodes: tuple[FieldNode, ...],
34
+ ) -> str:
35
+ nested = names.take(f"{name}_{key}")
36
+ children = tuple(
37
+ child
38
+ for node in nodes
39
+ if node.selection_set
40
+ for child in node.selection_set.selections
41
+ )
42
+ response(
43
+ nested,
44
+ schema,
45
+ target,
46
+ SelectionSetNode(selections=children),
47
+ names,
48
+ definitions,
49
+ )
50
+ return nested
51
+
52
+ abstract = isinstance(parent, GraphQLInterfaceType)
53
+ implementations = schema.get_possible_types(parent) if abstract else (parent,)
54
+ variants = []
55
+ for obj in implementations:
56
+ variant = names.take(f"{name}_{obj.name}") if abstract else name
57
+ variants.append(variant)
58
+ items = []
59
+ for key, nodes in collect_fields(schema, {}, {}, obj, selection_set).items():
60
+ field_name = nodes[0].name.value
61
+ if field_name == "__typename":
62
+ item_type = f"t.Literal[{obj.name!r}]"
52
63
  else:
53
- item_type = annotation(field_type, scalar(target, input_=False))
54
- items.append((key, item_type, True))
55
- definitions.append(dictionary(name, items))
64
+ field_type = obj.fields[field_name].type
65
+ target = get_named_type(field_type)
66
+ if isinstance(target, (GraphQLObjectType, GraphQLInterfaceType)):
67
+ leaf = nested_type(key, target, tuple(nodes))
68
+ else:
69
+ leaf = scalar(target, input_=False)
70
+ item_type = annotation(field_type, leaf)
71
+ items.append((key, item_type, True))
72
+ definitions.append(dictionary(variant, items))
73
+ if abstract:
74
+ definitions.append(f"{name} = {' | '.join(variants) or 't.Never'}")
56
75
 
57
76
 
58
77
  def render_client(
@@ -79,7 +98,7 @@ def render_client(
79
98
  documents[op.kind][op.name] = doc.text
80
99
  data = names.take(op.name + "Data")
81
100
  assert doc.root is not None
82
- response(data, doc.root, doc.fields, names, types)
101
+ response(data, schema, doc.root, doc.selection_set, names, types)
83
102
  params = ""
84
103
  if doc.variables:
85
104
  variables = names.take(op.name + "Variables")
@@ -6,6 +6,7 @@ from typing import Any
6
6
  from graphql import (
7
7
  GraphQLEnumType,
8
8
  GraphQLInputObjectType,
9
+ GraphQLInterfaceType,
9
10
  GraphQLList,
10
11
  GraphQLNonNull,
11
12
  GraphQLObjectType,
@@ -45,6 +46,7 @@ def literal(value: Any) -> str:
45
46
  class Document:
46
47
  def __init__(self, schema: GraphQLSchema, op: Operation):
47
48
  assert_name(op.name)
49
+ self.schema = schema
48
50
  self.variables: dict[str, GraphQLType] = {}
49
51
  self.locations: dict[str, str] = {}
50
52
  self.root = {"query": schema.query_type, "mutation": schema.mutation_type}[
@@ -64,7 +66,7 @@ class Document:
64
66
  self.text = print_ast(ast)
65
67
  definition = ast.definitions[0]
66
68
  assert isinstance(definition, OperationDefinitionNode)
67
- self.fields = definition.selection_set.selections
69
+ self.selection_set = definition.selection_set
68
70
 
69
71
  def value(self, value: Any, type_: GraphQLType, path: str) -> str:
70
72
  if isinstance(value, Variable):
@@ -101,9 +103,21 @@ class Document:
101
103
  return assert_name(value)
102
104
  return literal(value)
103
105
 
104
- def selection(self, parent: GraphQLObjectType, value: object) -> str:
106
+ def selection(
107
+ self, parent: GraphQLObjectType | GraphQLInterfaceType, value: object
108
+ ) -> str:
105
109
  parts = []
106
110
  for key, selections in object_value(value, parent.name).items():
111
+ if isinstance(parent, GraphQLInterfaceType) and key.startswith("... on "):
112
+ target = self.schema.get_type(key.removeprefix("... on "))
113
+ if not isinstance(
114
+ target, GraphQLObjectType
115
+ ) or not self.schema.is_sub_type(parent, target):
116
+ raise ValueError(
117
+ f"{parent.name}: invalid fragment condition {key!r}"
118
+ )
119
+ parts.append(f"{key} {self.selection(target, selections)}")
120
+ continue
107
121
  if selections == []:
108
122
  raise ValueError(f"{parent.name}.{key}: empty selection list")
109
123
  for item in selections if isinstance(selections, list) else [selections]:
@@ -116,7 +130,10 @@ class Document:
116
130
  return "{ " + " ".join(parts) + " }"
117
131
 
118
132
  def field(
119
- self, parent: GraphQLObjectType, key: str, options: dict[str, Any]
133
+ self,
134
+ parent: GraphQLObjectType | GraphQLInterfaceType,
135
+ key: str,
136
+ options: dict[str, Any],
120
137
  ) -> str:
121
138
  path = f"{parent.name}.{key}"
122
139
  if extra := options.keys() - {"alias", "args", "select"}:
@@ -135,7 +152,7 @@ class Document:
135
152
  args.append(f"{name}: {self.value(value, arg.type, f'{path}({name})')}")
136
153
  call = "(" + ", ".join(args) + ")" if args else ""
137
154
  target = get_named_type(field.type)
138
- if isinstance(target, GraphQLObjectType):
155
+ if isinstance(target, (GraphQLObjectType, GraphQLInterfaceType)):
139
156
  child = " " + self.selection(target, options.get("select"))
140
157
  elif is_leaf_type(target):
141
158
  if "select" in options:
@@ -7,15 +7,16 @@ from graphql import (
7
7
  GraphQLEnumType,
8
8
  GraphQLInputField,
9
9
  GraphQLInputObjectType,
10
+ GraphQLInterfaceType,
10
11
  GraphQLList,
11
12
  GraphQLNamedType,
12
13
  GraphQLNonNull,
13
14
  GraphQLObjectType,
14
15
  GraphQLSchema,
15
16
  GraphQLType,
17
+ GraphQLUnionType,
16
18
  Undefined,
17
19
  get_named_type,
18
- is_abstract_type,
19
20
  )
20
21
 
21
22
 
@@ -109,7 +110,8 @@ def render_schema(schema: GraphQLSchema) -> str:
109
110
  objects = [
110
111
  obj
111
112
  for obj in schema.type_map.values()
112
- if isinstance(obj, GraphQLObjectType) and not obj.name.startswith("__")
113
+ if isinstance(obj, (GraphQLObjectType, GraphQLInterfaceType))
114
+ and not obj.name.startswith("__")
113
115
  ]
114
116
  fields = {obj.name: names.take(f"{obj.name}Fields") for obj in objects}
115
117
  definitions = [
@@ -122,11 +124,16 @@ def render_schema(schema: GraphQLSchema) -> str:
122
124
  leaves = f"{leaf} | list[{leaf}]"
123
125
  for obj in objects:
124
126
  items = [("__typename", leaves, False)]
127
+ if isinstance(obj, GraphQLInterfaceType):
128
+ items.extend(
129
+ (f"... on {impl.name}", fields[impl.name], False)
130
+ for impl in schema.get_possible_types(obj)
131
+ )
125
132
  for key, field in obj.fields.items():
126
133
  target = get_named_type(field.type)
127
- if is_abstract_type(target):
134
+ if isinstance(target, GraphQLUnionType):
128
135
  continue
129
- if not field.args and not isinstance(target, GraphQLObjectType):
136
+ if not field.args and target.name not in fields:
130
137
  items.append((key, leaves, False))
131
138
  continue
132
139
  options = [("alias", "str", False)]
@@ -137,12 +144,12 @@ def render_schema(schema: GraphQLSchema) -> str:
137
144
  definitions.append(dictionary(args, members))
138
145
  required_args = any(required for _, _, required in members)
139
146
  options.append(("args", args, required_args))
140
- if isinstance(target, GraphQLObjectType):
147
+ if target.name in fields:
141
148
  options.append(("select", fields[target.name], True))
142
149
  selection = names.take(f"{obj.name}_{key}Selection")
143
150
  definitions.append(dictionary(selection, options))
144
151
  single = selection
145
- if not required_args and not isinstance(target, GraphQLObjectType):
152
+ if not required_args and target.name not in fields:
146
153
  single = f"t.Literal[True] | {single}"
147
154
  items.append((key, f"{single} | list[{single}]", False))
148
155
  definitions.append(dictionary(fields[obj.name], items))
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "graphql-typed-python"
7
- version = "0.1.2"
7
+ version = "0.1.3"
8
8
  description = "Generate typed GraphQL selections, variables, and response dictionaries for Python."
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -0,0 +1,28 @@
1
+ from generated import schema
2
+
3
+ peers: schema.InterfaceFields = {
4
+ "name": True,
5
+ "__typename": True,
6
+ "... on InterfaceVirtual": {
7
+ "parent_interface": {"select": {"name": True, "__typename": {"alias": "kind"}}}
8
+ },
9
+ }
10
+
11
+
12
+ def operations():
13
+ return [
14
+ schema.query(
15
+ "Peers",
16
+ select={
17
+ "device": {
18
+ "select": {
19
+ "peer": {"select": {"interfaces": {"select": peers}}},
20
+ }
21
+ }
22
+ },
23
+ ),
24
+ schema.query(
25
+ "Names",
26
+ select={"device": {"select": {"interfaces": {"select": {"name": True}}}}},
27
+ ),
28
+ ]
@@ -0,0 +1,8 @@
1
+ type Query { device: Device! }
2
+ type Device { peer: Device, interfaces: [Interface] }
3
+ interface Interface { name: String! }
4
+ type InterfacePhysical implements Interface { name: String! }
5
+ type InterfaceVirtual implements Interface {
6
+ name: String!
7
+ parent_interface: Interface
8
+ }
@@ -0,0 +1,34 @@
1
+ from typing import Literal, assert_type
2
+
3
+ from generated.client import Client
4
+ from generated.types import PeersData_device_peer_interfaces as Peer
5
+ from generated.types import PeersData_device_peer_interfaces_parent_interface as Parent
6
+
7
+
8
+ def check(client: Client):
9
+ device = client.query("Peers")()["device"]["peer"]
10
+ if device is None:
11
+ return
12
+ peers = assert_type(device["interfaces"], list[Peer | None] | None)
13
+ if peers is None:
14
+ return
15
+ for peer in peers:
16
+ if peer is None:
17
+ continue
18
+ assert_type(peer["name"], str)
19
+ if peer["__typename"] == "InterfaceVirtual":
20
+ parent = assert_type(peer["parent_interface"], Parent | None)
21
+ if parent is not None:
22
+ assert_type(parent["name"], str)
23
+ assert_type(
24
+ parent["kind"], Literal["InterfacePhysical", "InterfaceVirtual"]
25
+ )
26
+ parent["parent_interface"] # ty: ignore[invalid-typed-dict-key]
27
+ else:
28
+ assert_type(peer["__typename"], Literal["InterfacePhysical"])
29
+ peer["parent_interface"] # ty: ignore[invalid-typed-dict-key]
30
+
31
+ for item in client.query("Names")()["device"]["interfaces"] or []:
32
+ if item is not None:
33
+ assert_type(item["name"], str)
34
+ item["__typename"] # ty: ignore[invalid-typed-dict-key]
@@ -0,0 +1,33 @@
1
+ from pathlib import Path
2
+
3
+ import pytest
4
+
5
+ from tests.conftest import build_contract
6
+
7
+
8
+ @pytest.fixture(scope="module")
9
+ def ide_workspace(tmp_path_factory: pytest.TempPathFactory) -> Path:
10
+ return build_contract(tmp_path_factory.mktemp("interfaces"), "interfaces")
11
+
12
+
13
+ def test_fragment_completions(ty_server):
14
+ def complete(selection):
15
+ return ty_server.completion_labels(
16
+ "from generated import schema\n"
17
+ "schema.query('Q', select={'device': {'select': {'interfaces': {'select': {"
18
+ + selection
19
+ + "}}}}})"
20
+ )
21
+
22
+ keys = complete("'<CURSOR>'")
23
+ assert {
24
+ "... on InterfaceVirtual",
25
+ "... on InterfacePhysical",
26
+ "__typename",
27
+ "name",
28
+ } <= keys
29
+ assert "parent_interface" not in keys
30
+ assert "parent_interface" in complete("'... on InterfaceVirtual': {'<CURSOR>'}")
31
+ assert "parent_interface" not in complete(
32
+ "'... on InterfacePhysical': {'<CURSOR>'}"
33
+ )
@@ -12,7 +12,15 @@ from tests.conftest import CONTRACTS, build_contract
12
12
  def test_generated_and_usage_types(tmp_path: Path, case: str):
13
13
  build_contract(tmp_path, case)
14
14
  run = subprocess.run(
15
- ["ty", "check", ".", "--python-version", "3.12"],
15
+ [
16
+ "ty",
17
+ "check",
18
+ ".",
19
+ "--python-version",
20
+ "3.12",
21
+ "--error",
22
+ "unused-ignore-comment",
23
+ ],
16
24
  check=False,
17
25
  cwd=tmp_path,
18
26
  text=True,
@@ -2,11 +2,12 @@ import json
2
2
  from pathlib import Path
3
3
 
4
4
  import pytest
5
- from graphql import GraphQLError, build_schema, introspection_from_schema
5
+ from graphql import GraphQLError, build_schema, graphql_sync, introspection_from_schema
6
6
 
7
7
  from graphql_typed import Operation, var
8
8
  from graphql_typed.generator import generate
9
9
  from graphql_typed.generator.client import render_client
10
+ from graphql_typed.generator.operations import Document
10
11
  from tests.conftest import CONTRACTS
11
12
 
12
13
  SMALL = """
@@ -42,6 +43,56 @@ def test_invalid_operations(select, message):
42
43
  render_client(build_schema(SMALL), [Operation("query", "Q", select)])
43
44
 
44
45
 
46
+ @pytest.mark.parametrize(
47
+ ("selection", "message"),
48
+ [
49
+ ({"parent_interface": True}, "Unknown field Interface.parent_interface"),
50
+ ({"... on Device": {"name": True}}, "invalid fragment condition"),
51
+ ({"... on Unknown": {"name": True}}, "invalid fragment condition"),
52
+ ({"... on InterfaceVirtual": {}}, "select at least one field"),
53
+ ],
54
+ )
55
+ def test_invalid_interface_selections(selection, message):
56
+ schema = build_schema((CONTRACTS / "interfaces/schema.graphql").read_text())
57
+ op = Operation(
58
+ "query", "Q", {"device": {"select": {"interfaces": {"select": selection}}}}
59
+ )
60
+ with pytest.raises(ValueError, match=message):
61
+ Document(schema, op)
62
+
63
+
64
+ def test_execute_interface_fragment_without_typename():
65
+ schema = build_schema((CONTRACTS / "interfaces/schema.graphql").read_text())
66
+ fields = {
67
+ "name": True,
68
+ "... on InterfaceVirtual": {"parent_interface": {"select": {"name": True}}},
69
+ }
70
+ op = Operation(
71
+ "query", "Q", {"device": {"select": {"interfaces": {"select": fields}}}}
72
+ )
73
+ physical = {"__typename": "InterfacePhysical", "name": "eth0"}
74
+ virtual = {
75
+ "__typename": "InterfaceVirtual",
76
+ "name": "vlan5",
77
+ "parent_interface": physical,
78
+ }
79
+ result = graphql_sync(
80
+ schema,
81
+ Document(schema, op).text,
82
+ root_value={"device": {"interfaces": [physical, virtual, None]}},
83
+ )
84
+ assert result.errors is None
85
+ assert result.data == {
86
+ "device": {
87
+ "interfaces": [
88
+ {"name": "eth0"},
89
+ {"name": "vlan5", "parent_interface": {"name": "eth0"}},
90
+ None,
91
+ ]
92
+ }
93
+ }
94
+
95
+
45
96
  def test_unique_operations():
46
97
  op = Operation("query", "Same", {"foo": {"args": {"b": "a"}}})
47
98
  with pytest.raises(ValueError, match="Duplicate operation name 'Same'"):
@@ -283,7 +283,7 @@ wheels = [
283
283
 
284
284
  [[package]]
285
285
  name = "graphql-typed-python"
286
- version = "0.1.2"
286
+ version = "0.1.3"
287
287
  source = { editable = "." }
288
288
  dependencies = [
289
289
  { name = "graphql-core" },