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