Debian Codegraph @

tests/execution/test_union_interface.py

raw
1 from typing import Optional, Union, List
2
3 from pytest import mark
4
5 from graphql.execution import execute, execute_sync, ExecutionResult
6 from graphql.language import parse
7 from graphql.type import (
8 GraphQLBoolean,
9 GraphQLField,
10 GraphQLInterfaceType,
11 GraphQLList,
12 GraphQLObjectType,
13 GraphQLSchema,
14 GraphQLString,
15 GraphQLUnionType,
16 )
17
18
19 class Dog:
20
21 name: str
22 barks: bool
23 mother: Optional["Dog"]
24 father: Optional["Dog"]
25 progeny: List["Dog"]
26
27 def __init__(self, name: str, barks: bool):
28 self.name = name
29 self.barks = barks
30 self.mother = None
31 self.father = None
32 self.progeny = []
33
34
35 class Cat:
36
37 name: str
38 meows: bool
39 mother: Optional["Cat"]
40 father: Optional["Cat"]
41 progeny: List["Cat"]
42
43 def __init__(self, name: str, meows: bool):
44 self.name = name
45 self.meows = meows
46 self.mother = None
47 self.father = None
48 self.progeny = []
49
50
51 class Plant:
52
53 name: str
54
55 def __init__(self, name: str):
56 self.name = name
57
58
59 class Person:
60
61 name: str
62 pets: Optional[List[Union[Dog, Cat]]]
63 friends: Optional[List[Union[Dog, Cat, "Person"]]]
64 responsibilities: Optional[List[Union[Dog, Cat, Plant]]]
65
66 def __init__(
67 self,
68 name: str,
69 pets: Optional[List[Union[Dog, Cat]]] = None,
70 friends: Optional[List[Union[Dog, Cat, "Person"]]] = None,
71 responsibilities: Optional[List[Union[Dog, Cat, Plant]]] = None,
72 ):
73 self.name = name
74 self.pets = pets
75 self.friends = friends
76 self.responsibilities = responsibilities
77
78
79 NamedType = GraphQLInterfaceType("Named", {"name": GraphQLField(GraphQLString)})
80
81 LifeType = GraphQLInterfaceType(
82 "Life", lambda: {"progeny": GraphQLField(GraphQLList(LifeType))} # type: ignore
83 )
84
85 MammalType = GraphQLInterfaceType(
86 "Mammal",
87 lambda: {
88 "progeny": GraphQLField(GraphQLList(MammalType)), # type: ignore
89 "mother": GraphQLField(MammalType), # type: ignore
90 "father": GraphQLField(MammalType), # type: ignore
91 },
92 interfaces=[LifeType],
93 )
94
95 DogType = GraphQLObjectType(
96 "Dog",
97 lambda: {
98 "name": GraphQLField(GraphQLString),
99 "barks": GraphQLField(GraphQLBoolean),
100 "progeny": GraphQLField(GraphQLList(DogType)), # type: ignore
101 "mother": GraphQLField(DogType), # type: ignore
102 "father": GraphQLField(DogType), # type: ignore
103 },
104 interfaces=[MammalType, LifeType, NamedType],
105 is_type_of=lambda value, info: isinstance(value, Dog),
106 )
107
108 CatType = GraphQLObjectType(
109 "Cat",
110 lambda: {
111 "name": GraphQLField(GraphQLString),
112 "meows": GraphQLField(GraphQLBoolean),
113 "progeny": GraphQLField(GraphQLList(CatType)), # type: ignore
114 "mother": GraphQLField(CatType), # type: ignore
115 "father": GraphQLField(CatType), # type: ignore
116 },
117 interfaces=[MammalType, LifeType, NamedType],
118 is_type_of=lambda value, info: isinstance(value, Cat),
119 )
120
121
122 async def resolve_plant_type(_value, _info):
123 raise RuntimeError("Not sure if this is a plant")
124
125
126 PlantType = GraphQLObjectType(
127 "Plant",
128 lambda: {"name": GraphQLField(GraphQLString)},
129 interfaces=[NamedType],
130 is_type_of=resolve_plant_type,
131 )
132
133
134 def resolve_pet_type(value, _info, _type):
135 if isinstance(value, Dog):
136 return DogType.name
137 if isinstance(value, Cat):
138 return CatType.name
139
140 # Not reachable. All possible types have been considered.
141 assert False, "Unexpected pet type"
142
143
144 PetType = GraphQLUnionType("Pet", [DogType, CatType], resolve_type=resolve_pet_type)
145
146 PetOrPlantType = GraphQLUnionType("PetOrPlantType", [PlantType, DogType, CatType])
147
148 PersonType = GraphQLObjectType(
149 "Person",
150 lambda: {
151 "name": GraphQLField(GraphQLString),
152 "pets": GraphQLField(GraphQLList(PetType)),
153 "friends": GraphQLField(GraphQLList(NamedType)),
154 "responsibilities": GraphQLField(GraphQLList(PetOrPlantType)),
155 "progeny": GraphQLField(GraphQLList(PersonType)), # type: ignore
156 "mother": GraphQLField(PersonType), # type: ignore
157 "father": GraphQLField(PersonType), # type: ignore
158 },
159 interfaces=[NamedType, MammalType, LifeType],
160 is_type_of=lambda value, _info: isinstance(value, Person),
161 )
162
163 schema = GraphQLSchema(PersonType, types=[PetType])
164
165 garfield = Cat("Garfield", False)
166 garfield.mother = Cat("Garfield's Mom", False)
167 garfield.mother.progeny = [garfield]
168
169 odie = Dog("Odie", True)
170 odie.mother = Dog("Odie's Mom", True)
171 odie.mother.progeny = [odie]
172
173 fern = Plant("Fern")
174 liz = Person("Liz", [], [])
175 john = Person("John", [garfield, odie], [liz, odie], [garfield, fern])
176
177
178 def describe_execute_union_and_intersection_types():
179 def can_introspect_on_union_and_intersection_types():
180 document = parse("""
181 {
182 Named: __type(name: "Named") {
183 kind
184 name
185 fields { name }
186 interfaces { name }
187 possibleTypes { name }
188 enumValues { name }
189 inputFields { name }
190 }
191 Mammal: __type(name: "Mammal") {
192 kind
193 name
194 fields { name }
195 interfaces { name }
196 possibleTypes { name }
197 enumValues { name }
198 inputFields { name }
199 }
200 Pet: __type(name: "Pet") {
201 kind
202 name
203 fields { name }
204 interfaces { name }
205 possibleTypes { name }
206 enumValues { name }
207 inputFields { name }
208 }
209 }
210 """)
211
212 assert execute_sync(schema=schema, document=document) == (
213 {
214 "Named": {
215 "kind": "INTERFACE",
216 "name": "Named",
217 "fields": [{"name": "name"}],
218 "interfaces": [],
219 "possibleTypes": [
220 {"name": "Dog"},
221 {"name": "Cat"},
222 {"name": "Person"},
223 {"name": "Plant"},
224 ],
225 "enumValues": None,
226 "inputFields": None,
227 },
228 "Mammal": {
229 "kind": "INTERFACE",
230 "name": "Mammal",
231 "fields": [
232 {"name": "progeny"},
233 {"name": "mother"},
234 {"name": "father"},
235 ],
236 "interfaces": [{"name": "Life"}],
237 "possibleTypes": [
238 {"name": "Dog"},
239 {"name": "Cat"},
240 {"name": "Person"},
241 ],
242 "enumValues": None,
243 "inputFields": None,
244 },
245 "Pet": {
246 "kind": "UNION",
247 "name": "Pet",
248 "fields": None,
249 "interfaces": None,
250 "possibleTypes": [{"name": "Dog"}, {"name": "Cat"}],
251 "enumValues": None,
252 "inputFields": None,
253 },
254 },
255 None,
256 )
257
258 def executes_using_union_types():
259 # NOTE: This is an *invalid* query, but it should be *executable*.
260 document = parse("""
261 {
262 __typename
263 name
264 pets {
265 __typename
266 name
267 barks
268 meows
269 }
270 }
271 """)
272
273 assert execute_sync(schema=schema, document=document, root_value=john) == (
274 {
275 "__typename": "Person",
276 "name": "John",
277 "pets": [
278 {"__typename": "Cat", "name": "Garfield", "meows": False},
279 {"__typename": "Dog", "name": "Odie", "barks": True},
280 ],
281 },
282 None,
283 )
284
285 def executes_union_types_with_inline_fragment():
286 # This is the valid version of the query in the above test.
287 document = parse("""
288 {
289 __typename
290 name
291 pets {
292 __typename
293 ... on Dog {
294 name
295 barks
296 }
297 ... on Cat {
298 name
299 meows
300 }
301 }
302 }
303 """)
304
305 assert execute_sync(schema=schema, document=document, root_value=john) == (
306 {
307 "__typename": "Person",
308 "name": "John",
309 "pets": [
310 {"__typename": "Cat", "name": "Garfield", "meows": False},
311 {"__typename": "Dog", "name": "Odie", "barks": True},
312 ],
313 },
314 None,
315 )
316
317 def executes_using_interface_types():
318 # NOTE: This is an *invalid* query, but it should be a *executable*.
319 document = parse("""
320 {
321 __typename
322 name
323 friends {
324 __typename
325 name
326 barks
327 meows
328 }
329 }
330 """)
331
332 assert execute_sync(schema=schema, document=document, root_value=john) == (
333 {
334 "__typename": "Person",
335 "name": "John",
336 "friends": [
337 {"__typename": "Person", "name": "Liz"},
338 {"__typename": "Dog", "name": "Odie", "barks": True},
339 ],
340 },
341 None,
342 )
343
344 def executes_interface_types_with_inline_fragment():
345 # This is the valid version of the query in the above test.
346 document = parse("""
347 {
348 __typename
349 name
350 friends {
351 __typename
352 name
353 ... on Dog {
354 barks
355 }
356 ... on Cat {
357 meows
358 }
359
360 ... on Mammal {
361 mother {
362 __typename
363 ... on Dog {
364 name
365 barks
366 }
367 ... on Cat {
368 name
369 meows
370 }
371 }
372 }
373 }
374 }
375 """)
376
377 assert execute_sync(schema=schema, document=document, root_value=john) == (
378 {
379 "__typename": "Person",
380 "name": "John",
381 "friends": [
382 {"__typename": "Person", "name": "Liz", "mother": None},
383 {
384 "__typename": "Dog",
385 "name": "Odie",
386 "barks": True,
387 "mother": {
388 "__typename": "Dog",
389 "name": "Odie's Mom",
390 "barks": True,
391 },
392 },
393 ],
394 },
395 None,
396 )
397
398 def executes_interface_types_with_named_fragments():
399 document = parse("""
400 {
401 __typename
402 name
403 friends {
404 __typename
405 name
406 ...DogBarks
407 ...CatMeows
408 }
409 }
410
411 fragment DogBarks on Dog {
412 barks
413 }
414
415 fragment CatMeows on Cat {
416 meows
417 }
418 """)
419
420 assert execute_sync(schema=schema, document=document, root_value=john) == (
421 {
422 "__typename": "Person",
423 "name": "John",
424 "friends": [
425 {"__typename": "Person", "name": "Liz"},
426 {"__typename": "Dog", "name": "Odie", "barks": True},
427 ],
428 },
429 None,
430 )
431
432 def allows_fragment_conditions_to_be_abstract_types():
433 document = parse("""
434 {
435 __typename
436 name
437 pets {
438 ...PetFields,
439 ...on Mammal {
440 mother {
441 ...ProgenyFields
442 }
443 }
444 }
445 friends { ...FriendFields }
446 }
447
448 fragment PetFields on Pet {
449 __typename
450 ... on Dog {
451 name
452 barks
453 }
454 ... on Cat {
455 name
456 meows
457 }
458 }
459
460 fragment FriendFields on Named {
461 __typename
462 name
463 ... on Dog {
464 barks
465 }
466 ... on Cat {
467 meows
468 }
469 }
470
471 fragment ProgenyFields on Life {
472 progeny {
473 __typename
474 }
475 }
476 """)
477
478 assert execute_sync(schema=schema, document=document, root_value=john) == (
479 {
480 "__typename": "Person",
481 "name": "John",
482 "pets": [
483 {
484 "__typename": "Cat",
485 "name": "Garfield",
486 "meows": False,
487 "mother": {"progeny": [{"__typename": "Cat"}]},
488 },
489 {
490 "__typename": "Dog",
491 "name": "Odie",
492 "barks": True,
493 "mother": {"progeny": [{"__typename": "Dog"}]},
494 },
495 ],
496 "friends": [
497 {"__typename": "Person", "name": "Liz"},
498 {"__typename": "Dog", "name": "Odie", "barks": True},
499 ],
500 },
501 None,
502 )
503
504 # noinspection PyPep8Naming
505 def gets_execution_info_in_resolver():
506 encountered = {}
507
508 def resolve_type(_source, info, _type):
509 encountered["context"] = info.context
510 encountered["schema"] = info.schema
511 encountered["root_value"] = info.root_value
512 return PersonType2.name
513
514 NamedType2 = GraphQLInterfaceType(
515 "Named", {"name": GraphQLField(GraphQLString)}, resolve_type=resolve_type
516 )
517
518 PersonType2 = GraphQLObjectType(
519 "Person",
520 {
521 "name": GraphQLField(GraphQLString),
522 "friends": GraphQLField(GraphQLList(NamedType2)),
523 },
524 interfaces=[NamedType2],
525 )
526
527 schema2 = GraphQLSchema(PersonType2)
528 document = parse("{ name, friends { name } }")
529 root_value = Person("John", [], [liz])
530 context_value = {"authToken": "123abc"}
531
532 assert execute_sync(
533 schema=schema2,
534 document=document,
535 root_value=root_value,
536 context_value=context_value,
537 ) == (
538 {"name": "John", "friends": [{"name": "Liz"}]},
539 None,
540 )
541
542 assert encountered == {
543 "schema": schema2,
544 "root_value": root_value,
545 "context": context_value,
546 }
547
548 @mark.asyncio
549 @mark.filterwarnings("error:.*was never awaited:RuntimeWarning")
550 async def handles_rejections_from_is_type_of_after_an_is_type_of_returns_true():
551 document = parse("""
552 {
553 responsibilities {
554 __typename
555 ... on Dog {
556 name
557 barks
558 }
559 ... on Cat {
560 name
561 meows
562 }
563 }
564 }
565 """)
566
567 root_value = Person("John", [], [liz], [garfield])
568 context_value = {"authToken": "123abc"}
569
570 result = execute(schema, document, root_value, context_value)
571 assert not isinstance(result, ExecutionResult)
572 result = await result
573 assert isinstance(result, ExecutionResult)
574
575 assert result == (
576 {
577 "responsibilities": [
578 {"__typename": "Cat", "name": "Garfield", "meows": False},
579 ],
580 },
581 None,
582 )