-
Notifications
You must be signed in to change notification settings - Fork 180
/
Copy pathtest_executor.py
795 lines (657 loc) · 20.5 KB
/
test_executor.py
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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
# type: ignore
import json
from pytest import raises
from graphql.error import GraphQLError
from graphql.execution import execute
from graphql.language.ast import ObjectTypeDefinition
from graphql.language.parser import parse
from graphql.type import (
GraphQLArgument,
GraphQLBoolean,
GraphQLField,
GraphQLInt,
GraphQLList,
GraphQLObjectType,
GraphQLSchema,
GraphQLString,
GraphQLNonNull,
GraphQLID,
)
from promise import Promise
def test_executes_arbitary_code():
# type: () -> None
class Data(object):
a = "Apple"
b = "Banana"
c = "Cookie"
d = "Donut"
e = "Egg"
f = "Fish"
def pic(self, size=50):
# type: (int) -> str
return "Pic of size: {}".format(size)
def deep(self):
# type: () -> DeepData
return DeepData()
def promise(self):
# type: () -> Data
# FIXME: promise is unsupported
return Data()
class DeepData(object):
a = "Already Been Done"
b = "Boring"
c = ["Contrived", None, "Confusing"]
def deeper(self):
# type: () -> List[Optional[Data]]
return [Data(), None, Data()]
doc = """
query Example($size: Int) {
a,
b,
x: c
...c
f
...on DataType {
pic(size: $size)
promise {
a
}
}
deep {
a
b
c
deeper {
a
b
}
}
}
fragment c on DataType {
d
e
}
"""
ast = parse(doc)
expected = {
"a": "Apple",
"b": "Banana",
"x": "Cookie",
"d": "Donut",
"e": "Egg",
"f": "Fish",
"pic": "Pic of size: 100",
"promise": {"a": "Apple"},
"deep": {
"a": "Already Been Done",
"b": "Boring",
"c": ["Contrived", None, "Confusing"],
"deeper": [
{"a": "Apple", "b": "Banana"},
None,
{"a": "Apple", "b": "Banana"},
],
},
}
DataType = GraphQLObjectType(
"DataType",
lambda: {
"a": GraphQLField(GraphQLString),
"b": GraphQLField(GraphQLString),
"c": GraphQLField(GraphQLString),
"d": GraphQLField(GraphQLString),
"e": GraphQLField(GraphQLString),
"f": GraphQLField(GraphQLString),
"pic": GraphQLField(
args={"size": GraphQLArgument(GraphQLInt)},
type_=GraphQLString,
resolver=lambda obj, info, size: obj.pic(size),
),
"deep": GraphQLField(DeepDataType),
"promise": GraphQLField(DataType),
},
)
DeepDataType = GraphQLObjectType(
"DeepDataType",
{
"a": GraphQLField(GraphQLString),
"b": GraphQLField(GraphQLString),
"c": GraphQLField(GraphQLList(GraphQLString)),
"deeper": GraphQLField(GraphQLList(DataType)),
},
)
schema = GraphQLSchema(query=DataType)
result = execute(
schema, ast, Data(), operation_name="Example", variable_values={"size": 100}
)
assert not result.errors
assert result.data == expected
def test_merges_parallel_fragments():
# type: () -> None
ast = parse(
"""
{ a, deep {...FragOne, ...FragTwo} }
fragment FragOne on Type {
b
deep { b, deeper: deep { b } }
}
fragment FragTwo on Type {
c
deep { c, deeper: deep { c } }
}
"""
)
Type = GraphQLObjectType(
"Type",
lambda: {
"a": GraphQLField(GraphQLString, resolver=lambda *_: "Apple"),
"b": GraphQLField(GraphQLString, resolver=lambda *_: "Banana"),
"c": GraphQLField(GraphQLString, resolver=lambda *_: "Cherry"),
"deep": GraphQLField(Type, resolver=lambda *_: {}),
},
)
schema = GraphQLSchema(query=Type)
result = execute(schema, ast)
assert not result.errors
assert result.data == {
"a": "Apple",
"deep": {
"b": "Banana",
"c": "Cherry",
"deep": {
"b": "Banana",
"c": "Cherry",
"deeper": {"b": "Banana", "c": "Cherry"},
},
},
}
def test_threads_root_value_context_correctly():
# type: () -> None
doc = "query Example { a }"
class Data(object):
context_thing = "thing"
ast = parse(doc)
def resolver(root_value, *_):
# type: (Data, *ResolveInfo) -> None
assert root_value.context_thing == "thing"
resolver.got_here = True
resolver.got_here = False
Type = GraphQLObjectType(
"Type", {"a": GraphQLField(GraphQLString, resolver=resolver)}
)
result = execute(GraphQLSchema(Type), ast, Data(), operation_name="Example")
assert not result.errors
assert resolver.got_here
def test_correctly_threads_arguments():
# type: () -> None
doc = """
query Example {
b(numArg: 123, stringArg: "foo")
}
"""
def resolver(source, info, numArg, stringArg):
# type: (Optional[Any], ResolveInfo, int, str) -> None
assert numArg == 123
assert stringArg == "foo"
resolver.got_here = True
resolver.got_here = False
doc_ast = parse(doc)
Type = GraphQLObjectType(
"Type",
{
"b": GraphQLField(
GraphQLString,
args={
"numArg": GraphQLArgument(GraphQLInt),
"stringArg": GraphQLArgument(GraphQLString),
},
resolver=resolver,
)
},
)
result = execute(GraphQLSchema(Type), doc_ast, None, operation_name="Example")
assert not result.errors
assert resolver.got_here
def test_nulls_out_error_subtrees():
# type: () -> None
doc = """{
ok,
error
}"""
class Data(object):
def ok(self):
# type: () -> str
return "ok"
def error(self):
# type: () -> NoReturn
raise GraphQLError("Error getting error")
doc_ast = parse(doc)
Type = GraphQLObjectType(
"Type",
{"ok": GraphQLField(GraphQLString), "error": GraphQLField(GraphQLString)},
)
result = execute(GraphQLSchema(Type), doc_ast, Data())
assert result.data == {"ok": "ok", "error": None}
assert len(result.errors) == 1
assert result.errors[0].message == "Error getting error"
# TODO: check error location
def test_uses_the_inline_operation_if_no_operation_name_is_provided():
# type: () -> None
doc = "{ a }"
class Data(object):
a = "b"
ast = parse(doc)
Type = GraphQLObjectType("Type", {"a": GraphQLField(GraphQLString)})
result = execute(GraphQLSchema(Type), ast, Data())
assert not result.errors
assert result.data == {"a": "b"}
def test_uses_the_only_operation_if_no_operation_name_is_provided():
# type: () -> None
doc = "query Example { a }"
class Data(object):
a = "b"
ast = parse(doc)
Type = GraphQLObjectType("Type", {"a": GraphQLField(GraphQLString)})
result = execute(GraphQLSchema(Type), ast, Data())
assert not result.errors
assert result.data == {"a": "b"}
def test_uses_the_named_operation_if_operation_name_is_provided():
# type: () -> None
doc = "query Example { first: a } query OtherExample { second: a }"
class Data(object):
a = "b"
ast = parse(doc)
Type = GraphQLObjectType("Type", {"a": GraphQLField(GraphQLString)})
result = execute(GraphQLSchema(Type), ast, Data(), operation_name="OtherExample")
assert not result.errors
assert result.data == {"second": "b"}
def test_raises_if_no_operation_is_provided():
# type: () -> None
doc = "fragment Example on Type { a }"
class Data(object):
a = "b"
ast = parse(doc)
Type = GraphQLObjectType("Type", {"a": GraphQLField(GraphQLString)})
with raises(GraphQLError) as excinfo:
execute(GraphQLSchema(Type), ast, Data())
assert "Must provide an operation." == str(excinfo.value)
def test_raises_if_no_operation_name_is_provided_with_multiple_operations():
# type: () -> None
doc = "query Example { a } query OtherExample { a }"
class Data(object):
a = "b"
ast = parse(doc)
Type = GraphQLObjectType("Type", {"a": GraphQLField(GraphQLString)})
with raises(GraphQLError) as excinfo:
execute(GraphQLSchema(Type), ast, Data(), operation_name="UnknownExample")
assert 'Unknown operation named "UnknownExample".' == str(excinfo.value)
def test_raises_if_unknown_operation_name_is_provided():
# type: () -> None
doc = "query Example { a } query OtherExample { a }"
class Data(object):
a = "b"
ast = parse(doc)
Type = GraphQLObjectType("Type", {"a": GraphQLField(GraphQLString)})
with raises(GraphQLError) as excinfo:
execute(GraphQLSchema(Type), ast, Data())
assert "Must provide operation name if query contains multiple operations." == str(
excinfo.value
)
def test_uses_the_query_schema_for_queries():
# type: () -> None
doc = "query Q { a } mutation M { c } subscription S { a }"
class Data(object):
a = "b"
c = "d"
ast = parse(doc)
Q = GraphQLObjectType("Q", {"a": GraphQLField(GraphQLString)})
M = GraphQLObjectType("M", {"c": GraphQLField(GraphQLString)})
S = GraphQLObjectType("S", {"a": GraphQLField(GraphQLString)})
result = execute(GraphQLSchema(Q, M, S), ast, Data(), operation_name="Q")
assert not result.errors
assert result.data == {"a": "b"}
def test_uses_the_mutation_schema_for_queries():
# type: () -> None
doc = "query Q { a } mutation M { c }"
class Data(object):
a = "b"
c = "d"
ast = parse(doc)
Q = GraphQLObjectType("Q", {"a": GraphQLField(GraphQLString)})
M = GraphQLObjectType("M", {"c": GraphQLField(GraphQLString)})
result = execute(GraphQLSchema(Q, M), ast, Data(), operation_name="M")
assert not result.errors
assert result.data == {"c": "d"}
def test_uses_the_subscription_schema_for_subscriptions():
# type: () -> None
from rx import Observable
doc = "query Q { a } subscription S { a }"
class Data(object):
a = "b"
c = "d"
ast = parse(doc)
Q = GraphQLObjectType("Q", {"a": GraphQLField(GraphQLString)})
S = GraphQLObjectType(
"S",
{
"a": GraphQLField(
GraphQLString, resolver=lambda root, info: Observable.from_(["b"])
)
},
)
result = execute(
GraphQLSchema(Q, subscription=S),
ast,
Data(),
operation_name="S",
allow_subscriptions=True,
)
assert isinstance(result, Observable)
l = []
result.subscribe(l.append)
result = l[0]
assert not result.errors
assert result.data == {"a": "b"}
def test_avoids_recursion():
# type: () -> None
doc = """
query Q {
a
...Frag
...Frag
}
fragment Frag on Type {
a,
...Frag
}
"""
class Data(object):
a = "b"
ast = parse(doc)
Type = GraphQLObjectType("Type", {"a": GraphQLField(GraphQLString)})
result = execute(GraphQLSchema(Type), ast, Data(), operation_name="Q")
assert not result.errors
assert result.data == {"a": "b"}
def test_does_not_include_illegal_fields_in_output():
# type: () -> None
doc = "mutation M { thisIsIllegalDontIncludeMe }"
ast = parse(doc)
Q = GraphQLObjectType("Q", {"a": GraphQLField(GraphQLString)})
M = GraphQLObjectType("M", {"c": GraphQLField(GraphQLString)})
result = execute(GraphQLSchema(Q, M), ast)
assert not result.errors
assert result.data == {}
def test_does_not_include_arguments_that_were_not_set():
# type: () -> None
schema = GraphQLSchema(
GraphQLObjectType(
"Type",
{
"field": GraphQLField(
GraphQLString,
resolver=lambda source, info, **args: args
and json.dumps(args, sort_keys=True, separators=(",", ":")),
args={
"a": GraphQLArgument(GraphQLBoolean),
"b": GraphQLArgument(GraphQLBoolean),
"c": GraphQLArgument(GraphQLBoolean),
"d": GraphQLArgument(GraphQLInt),
"e": GraphQLArgument(GraphQLInt),
},
)
},
)
)
ast = parse("{ field(a: true, c: false, e: 0) }")
result = execute(schema, ast)
assert result.data == {"field": '{"a":true,"c":false,"e":0}'}
def test_fails_when_an_is_type_of_check_is_not_met():
# type: () -> None
class Special(object):
def __init__(self, value):
# type: (str) -> None
self.value = value
class NotSpecial(object):
def __init__(self, value):
# type: (str) -> None
self.value = value
SpecialType = GraphQLObjectType(
"SpecialType",
fields={"value": GraphQLField(GraphQLString)},
is_type_of=lambda obj, info: isinstance(obj, Special),
)
schema = GraphQLSchema(
GraphQLObjectType(
name="Query",
fields={
"specials": GraphQLField(
GraphQLList(SpecialType), resolver=lambda root, *_: root["specials"]
)
},
)
)
query = parse("{ specials { value } }")
value = {"specials": [Special("foo"), NotSpecial("bar")]}
result = execute(schema, query, value)
assert result.data == {"specials": [{"value": "foo"}, None]}
assert 'Expected value of type "SpecialType" but got: NotSpecial.' in [
str(e) for e in result.errors
]
def test_fails_to_execute_a_query_containing_a_type_definition():
# type: () -> None
query = parse(
"""
{ foo }
type Query { foo: String }
"""
)
schema = GraphQLSchema(
GraphQLObjectType(name="Query", fields={"foo": GraphQLField(GraphQLString)})
)
with raises(GraphQLError) as excinfo:
execute(schema, query)
error = excinfo.value
assert (
error.message
== "GraphQL cannot execute a request containing a ObjectTypeDefinition."
)
nodes = error.nodes
assert type(nodes) is list
assert len(nodes) == 1
assert isinstance(nodes[0], ObjectTypeDefinition)
def test_exceptions_are_reraised():
# type: () -> None
query = parse(
"""
{ foo }
"""
)
class Error(Exception):
pass
def resolver(*_):
# type: (*Any) -> NoReturn
raise Error("UH OH!")
schema = GraphQLSchema(
GraphQLObjectType(
name="Query", fields={"foo": GraphQLField(GraphQLString, resolver=resolver)}
)
)
with raises(Error):
execute(schema, query)
def test_exceptions_are_reraised_promise():
# type: () -> None
query = parse(
"""
{ foo }
"""
)
class Error(Exception):
pass
@Promise.promisify
def resolver(*_):
# type: (*Any) -> NoReturn
raise Error("UH OH!")
schema = GraphQLSchema(
GraphQLObjectType(
name="Query", fields={"foo": GraphQLField(GraphQLString, resolver=resolver)}
)
)
with raises(Error):
execute(schema, query)
def test_executor_properly_propogates_path_data(mocker):
# type: (MockFixture) -> None
time_mock = mocker.patch("time.time")
time_mock.side_effect = range(0, 10000)
BlogImage = GraphQLObjectType(
"BlogImage",
{
"url": GraphQLField(GraphQLString),
"width": GraphQLField(GraphQLInt),
"height": GraphQLField(GraphQLInt),
},
)
BlogAuthor = GraphQLObjectType(
"Author",
lambda: {
"id": GraphQLField(GraphQLString),
"name": GraphQLField(GraphQLString),
"pic": GraphQLField(
BlogImage,
args={
"width": GraphQLArgument(GraphQLInt),
"height": GraphQLArgument(GraphQLInt),
},
resolver=lambda obj, info, **args: obj.pic(
args["width"], args["height"]
),
),
"recentArticle": GraphQLField(BlogArticle),
},
)
BlogArticle = GraphQLObjectType(
"Article",
{
"id": GraphQLField(GraphQLNonNull(GraphQLString)),
"isPublished": GraphQLField(GraphQLBoolean),
"author": GraphQLField(BlogAuthor),
"title": GraphQLField(GraphQLString),
"body": GraphQLField(GraphQLString),
"keywords": GraphQLField(GraphQLList(GraphQLString)),
},
)
BlogQuery = GraphQLObjectType(
"Query",
{
"article": GraphQLField(
BlogArticle,
args={"id": GraphQLArgument(GraphQLID)},
resolver=lambda obj, info, **args: Article(args["id"]),
),
"feed": GraphQLField(
GraphQLList(BlogArticle),
resolver=lambda *_: map(Article, range(1, 2 + 1)),
),
},
)
BlogSchema = GraphQLSchema(BlogQuery)
class Article(object):
def __init__(self, id):
# type: (int) -> None
self.id = id
self.isPublished = True
self.author = Author()
self.title = "My Article {}".format(id)
self.body = "This is a post"
self.hidden = "This data is not exposed in the schema"
self.keywords = ["foo", "bar", 1, True, None]
class Author(object):
id = 123
name = "John Smith"
def pic(self, width, height):
return Pic(123, width, height)
@property
def recentArticle(self):
return Article(1)
class Pic(object):
def __init__(self, uid, width, height):
self.url = "cdn://{}".format(uid)
self.width = str(width)
self.height = str(height)
class PathCollectorMiddleware(object):
def __init__(self):
# type: () -> None
self.paths = []
def resolve(
self,
_next, # type: Callable
root, # type: Optional[Article]
info, # type: ResolveInfo
*args, # type: Any
**kwargs # type: Any
):
# type: (...) -> Promise
self.paths.append(info.path)
return _next(root, info, *args, **kwargs)
request = """
{
feed {
id
...articleFields
author {
id
name
nameAlias: name
}
},
}
fragment articleFields on Article {
title,
body,
hidden,
}
"""
paths_middleware = PathCollectorMiddleware()
result = execute(BlogSchema, parse(request), middleware=(paths_middleware,))
assert not result.errors
assert result.data == {
"feed": [
{
"id": "1",
"title": "My Article 1",
"body": "This is a post",
"author": {
"id": "123",
"name": "John Smith",
"nameAlias": "John Smith",
},
},
{
"id": "2",
"title": "My Article 2",
"body": "This is a post",
"author": {
"id": "123",
"name": "John Smith",
"nameAlias": "John Smith",
},
},
]
}
traversed_paths = paths_middleware.paths
assert traversed_paths == [
["feed"],
["feed", 0, "id"],
["feed", 0, "title"],
["feed", 0, "body"],
["feed", 0, "author"],
["feed", 1, "id"],
["feed", 1, "title"],
["feed", 1, "body"],
["feed", 1, "author"],
["feed", 0, "author", "id"],
["feed", 0, "author", "name"],
["feed", 0, "author", "nameAlias"],
["feed", 1, "author", "id"],
["feed", 1, "author", "name"],
["feed", 1, "author", "nameAlias"],
]