-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
ParserTest.groovy
1167 lines (935 loc) · 39.8 KB
/
ParserTest.groovy
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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package graphql.parser
import graphql.ExecutionInput
import graphql.TestUtil
import graphql.language.Argument
import graphql.language.ArrayValue
import graphql.language.AstComparator
import graphql.language.BooleanValue
import graphql.language.Description
import graphql.language.Directive
import graphql.language.DirectiveDefinition
import graphql.language.Document
import graphql.language.EnumTypeDefinition
import graphql.language.Field
import graphql.language.FloatValue
import graphql.language.FragmentDefinition
import graphql.language.FragmentSpread
import graphql.language.IgnoredChar
import graphql.language.IgnoredChars
import graphql.language.InlineFragment
import graphql.language.InputObjectTypeDefinition
import graphql.language.IntValue
import graphql.language.InterfaceTypeDefinition
import graphql.language.ListType
import graphql.language.Node
import graphql.language.NodeBuilder
import graphql.language.NonNullType
import graphql.language.NullValue
import graphql.language.ObjectField
import graphql.language.ObjectTypeDefinition
import graphql.language.ObjectValue
import graphql.language.OperationDefinition
import graphql.language.ScalarTypeDefinition
import graphql.language.Selection
import graphql.language.SelectionSet
import graphql.language.SourceLocation
import graphql.language.StringValue
import graphql.language.Type
import graphql.language.TypeName
import graphql.language.UnionTypeDefinition
import graphql.language.VariableDefinition
import graphql.language.VariableReference
import org.antlr.v4.runtime.CommonTokenStream
import org.antlr.v4.runtime.ParserRuleContext
import spock.lang.Issue
import spock.lang.Specification
import spock.lang.Unroll
class ParserTest extends Specification {
def "parse anonymous simple query"() {
given:
def input = "{ me }"
when:
Document document = new Parser().parseDocument(input)
then:
document.definitions.size() == 1
document.definitions[0] instanceof OperationDefinition
document.definitions[0].operation == OperationDefinition.Operation.QUERY
assertField(document.definitions[0] as OperationDefinition, "me")
}
def assertField(OperationDefinition operationDefinition, String fieldName) {
Selection selection = operationDefinition.getSelectionSet().getSelections()[0]
assert selection instanceof Field
Field field = (Field) selection
assert field.name == fieldName
true
}
boolean isEqual(Node node1, Node node2) {
return AstComparator.isEqual(node1, node2)
}
boolean isEqual(List<Node> node1, List<Node> node2) {
return AstComparator.isEqual(node1, node2)
}
def "parse selectionSet for field"() {
given:
def input = "{ me { name } }"
def innerSelectionSet = new SelectionSet([new Field("name")])
def selectionSet = new SelectionSet([new Field("me", innerSelectionSet)])
def definition = OperationDefinition.newOperationDefinition().operation(OperationDefinition.Operation.QUERY).selectionSet(selectionSet).build()
def expectedResult = new Document([definition])
when:
Document document = new Parser().parseDocument(input)
then:
isEqual(document, expectedResult)
}
def "parse query with variable definition"() {
given:
def input = 'query getProfile($devicePicSize: Int){ me }'
def expectedResult = Document.newDocument()
def variableDefinition = new VariableDefinition("devicePicSize", new TypeName("Int"))
def selectionSet = new SelectionSet([new Field("me")])
def definition = OperationDefinition.newOperationDefinition().name("getProfile").operation(OperationDefinition.Operation.QUERY)
.variableDefinitions([variableDefinition])
.selectionSet(selectionSet).build()
expectedResult.definition(definition)
when:
Document document = new Parser().parseDocument(input)
then:
isEqual(document, expectedResult.build())
}
def "parse mutation"() {
given:
def input = 'mutation setName { setName(name: "Homer") { newName } }'
when:
Document document = new Parser().parseDocument(input)
then:
document.definitions[0].operation == OperationDefinition.Operation.MUTATION
}
def "parse subscription"() {
given:
def input = 'subscription setName { setName(name: "Homer") { newName } }'
when:
Document document = new Parser().parseDocument(input)
then:
document.definitions[0].operation == OperationDefinition.Operation.SUBSCRIPTION
}
def "parse field arguments"() {
given:
def input = '{ user(id: 10, name: "homer", admin:true, floatValue: 3.04) }'
def argument = new Argument("id", new IntValue(BigInteger.valueOf(10)))
def argument2 = new Argument("name", new StringValue("homer"))
def argument3 = new Argument("admin", new BooleanValue(true))
def argument4 = new Argument("floatValue", new FloatValue(3.04))
def field = new Field("user", [argument, argument2, argument3, argument4])
def selectionSet = new SelectionSet([field])
def operationDefinition = OperationDefinition.newOperationDefinition()
operationDefinition.operation(OperationDefinition.Operation.QUERY)
operationDefinition.selectionSet(selectionSet)
def expectedResult = Document.newDocument().definitions([operationDefinition.build()]).build()
when:
Document document = new Parser().parseDocument(input)
then:
isEqual(document, expectedResult)
}
def "parse fragment and query"() {
given:
def input = """query withFragments {
user(id: 4) {
friends(first: 10) { ...friendFields }
mutualFriends(first: 10) { ...friendFields }
}
}
fragment friendFields on User {
id
name
profilePic(size: 50)
}"""
and: "expected query"
def fragmentSpreadFriends = new FragmentSpread("friendFields")
def selectionSetFriends = new SelectionSet([fragmentSpreadFriends])
def friendsField = new Field("friends", [new Argument("first", new IntValue(BigInteger.valueOf(10)))], selectionSetFriends)
def fragmentSpreadMutalFriends = new FragmentSpread("friendFields")
def selectionSetMutalFriends = new SelectionSet([fragmentSpreadMutalFriends])
def mutalFriendsField = new Field("mutualFriends", [new Argument("first", new IntValue(BigInteger.valueOf(10)))], selectionSetMutalFriends)
def userField = new Field("user", [new Argument("id", new IntValue(BigInteger.valueOf(4)))], new SelectionSet([friendsField, mutalFriendsField]))
def queryDefinition = OperationDefinition.newOperationDefinition().name("withFragments").operation(OperationDefinition.Operation.QUERY).selectionSet(new SelectionSet([userField])).build()
and: "expected fragment definition"
def idField = new Field("id")
def nameField = new Field("name")
def profilePicField = new Field("profilePic", [new Argument("size", new IntValue(BigInteger.valueOf(50)))])
def selectionSet = SelectionSet.newSelectionSet().selections([idField, nameField, profilePicField]).build()
def fragmentDefinition = FragmentDefinition.newFragmentDefinition().name("friendFields").typeCondition(new TypeName("User")).selectionSet(selectionSet).build()
when:
Document document = new Parser().parseDocument(input)
then:
document.definitions.size() == 2
isEqual(document.definitions[0], queryDefinition)
isEqual(document.definitions[1], fragmentDefinition)
}
def "parse inline fragment"() {
given:
def input = """
query InlineFragmentTyping {
profiles(handles: ["zuck", "cocacola"]) {
handle
... on User {
friends { count }
}
... on Page {
likers { count }
}
}
}
"""
and: "expected query definition"
def handleField = new Field("handle")
def userSelectionSet = new SelectionSet([new Field("friends", new SelectionSet([new Field("count")]))])
def userFragment = new InlineFragment(new TypeName("User"), userSelectionSet)
def pageSelectionSet = new SelectionSet([new Field("likers", new SelectionSet([new Field("count")]))])
def pageFragment = new InlineFragment(new TypeName("Page"), pageSelectionSet)
def handlesArgument = new ArrayValue([new StringValue("zuck"), new StringValue("cocacola")])
def profilesField = new Field("profiles", [new Argument("handles", handlesArgument)], new SelectionSet([handleField, userFragment, pageFragment]))
def queryDefinition = OperationDefinition.newOperationDefinition()
.name("InlineFragmentTyping").operation(OperationDefinition.Operation.QUERY)
.selectionSet(new SelectionSet([profilesField])).build()
when:
def document = new Parser().parseDocument(input)
then:
document.definitions.size() == 1
isEqual(document.definitions[0], queryDefinition)
}
def "parse directives"() {
given:
def input = """
query myQuery(\$someTest: Boolean) {
experimentalField @skip(if: \$someTest),
controlField @include(if: \$someTest) }
"""
and: "expected query"
def skipDirective = new Directive("skip", [new Argument("if", new VariableReference("someTest"))])
def experimentalField = Field.newField().name("experimentalField").directives([skipDirective]).build()
def includeDirective = new Directive("include", [new Argument("if", new VariableReference("someTest"))])
def controlField = Field.newField().name("controlField").directives([includeDirective]).build()
def queryDefinition = OperationDefinition.newOperationDefinition()
.name("myQuery")
.operation(OperationDefinition.Operation.QUERY)
.variableDefinitions([new VariableDefinition("someTest", new TypeName("Boolean"))])
.selectionSet(new SelectionSet([experimentalField, controlField])).build()
when:
def document = new Parser().parseDocument(input)
then:
isEqual(document.definitions[0], queryDefinition)
}
@Unroll
def "parse variable definition for type #typeString"() {
given:
def input = """
query myQuery(\$someTest: $typeString) {
hello }
"""
and: "expected query"
def helloField = new Field("hello")
def variableDefinition = new VariableDefinition("someTest", getOutputType as Type)
def queryDefinition = OperationDefinition.newOperationDefinition().name("myQuery").operation(OperationDefinition.Operation.QUERY)
.variableDefinitions([variableDefinition]).selectionSet(new SelectionSet([helloField])).build()
when:
def document = new Parser().parseDocument(input)
then:
isEqual(document.definitions[0], queryDefinition)
where:
typeString | getOutputType
"String" | new TypeName("String")
"[String]" | new ListType(new TypeName("String"))
"Boolean!" | new NonNullType(new TypeName("Boolean"))
"[Int]!" | new NonNullType(new ListType(new TypeName("Int")))
"[[String!]]" | new ListType(new ListType(new NonNullType(new TypeName("String"))))
}
def "parse variable with default value"() {
given:
def input = """
query myQuery(\$variable: String = \"world\") {
hello }
"""
and: "expected query"
def helloField = new Field("hello")
def variableDefinition = new VariableDefinition("variable", new TypeName("String"), new StringValue("world"))
def queryDefinition = OperationDefinition.newOperationDefinition().name("myQuery").operation(OperationDefinition.Operation.QUERY)
.variableDefinitions([variableDefinition]).selectionSet(new SelectionSet([helloField])).build()
when:
def document = new Parser().parseDocument(input)
then:
isEqual(document.definitions[0], queryDefinition)
}
def "parse complex object values"() {
given:
def input = """
query myQuery {
hello(arg: {intKey:1, floatKey: 4.1, stringKey: \"world\", subObject: {subKey:true} } ) }
"""
and: "expected query"
def objectValue = ObjectValue.newObjectValue()
objectValue.objectField(new ObjectField("intKey", new IntValue(BigInteger.valueOf(1))))
objectValue.objectField(new ObjectField("floatKey", new FloatValue(4.1)))
objectValue.objectField(new ObjectField("stringKey", new StringValue("world")))
def subObject = ObjectValue.newObjectValue()
subObject.objectField(new ObjectField("subKey", new BooleanValue(true)))
objectValue.objectField(new ObjectField("subObject", subObject.build()))
def argument = new Argument("arg", objectValue.build())
def helloField = new Field("hello", [argument])
def queryDefinition = OperationDefinition.newOperationDefinition().name("myQuery")
.operation(OperationDefinition.Operation.QUERY)
.selectionSet(new SelectionSet([helloField])).build()
when:
def document = new Parser().parseDocument(input)
then:
isEqual(document.definitions[0], queryDefinition)
}
def "parse complex string value and comment"() {
given:
def input = """
{ # this is some comment, which should be captured
hello(arg: "hello, world" ) }
"""
when:
def document = new Parser().parseDocument(input)
Field helloField = (document.definitions[0] as OperationDefinition).selectionSet.selections[0] as Field
then:
isEqual(helloField, new Field("hello", [new Argument("arg", new StringValue("hello, world"))]))
helloField.comments.collect { c -> c.content } == [" this is some comment, which should be captured"]
}
@Issue("https://github.com/graphql-java/graphql-java/issues/2767")
def "parser does not transform comments to AST nodes when ParserOptions.captureLineComments(false)"() {
given:
def input = """
{ # this is some comment, which should be captured
hello(arg: "hello, world" ) # test
}
"""
def parserOptionsWithoutCaptureLineComments = ParserOptions.newParserOptions()
.captureLineComments(false)
.build()
when:
def document = new Parser().parseDocument(input, parserOptionsWithoutCaptureLineComments)
Field helloField = (document.definitions[0] as OperationDefinition).selectionSet.selections[0] as Field
then:
isEqual(helloField, new Field("hello", [new Argument("arg", new StringValue("hello, world"))]))
assert helloField.comments.isEmpty() // No single-line comments on lone fields
assert document.comments.isEmpty() // No single-line comments in entire document
}
@Unroll
def "parse floatValue #floatString"() {
given:
def input = """
{ hello(arg: ${floatString}) }
"""
when:
def document = new Parser().parseDocument(input)
Field helloField = (document.definitions[0] as OperationDefinition).selectionSet.selections[0] as Field
then:
isEqual(helloField, new Field("hello", [new Argument("arg", new FloatValue(floatValue))]))
where:
floatString | floatValue
'1.0' | 1.0
'-0.3' | -0.3
'-3.4' | -3.4
'-3.4e3' | -3.4e3
'3.4E3' | 3.4e3
'3e4' | 3e4
'123e-4' | 123e-4
}
def "#848 floats must have digits"() {
given:
def input = """
{ hello(arg: 4.) }
"""
when:
new Parser().parseDocument(input)
then:
thrown(InvalidSyntaxException)
}
def "extraneous input is an exception"() {
given:
def input = """
mutation event(\$var: SomeType[]!) { res: update(arg: \$var) {id} }
"""
when:
new Parser().parseDocument(input)
then:
thrown(InvalidSyntaxException)
}
def "invalid syntax is an error"() {
given:
def input = """
mutation event(() }
"""
when:
new Parser().parseDocument(input)
then:
thrown(InvalidSyntaxException)
}
def "mutation without a name"() {
given:
def input = """
mutation { m }
"""
when:
def document = new Parser().parseDocument(input)
then:
document.definitions[0].operation == OperationDefinition.Operation.MUTATION
}
def "subscription without a name"() {
given:
def input = """
subscription { s }
"""
when:
def document = new Parser().parseDocument(input)
then:
document.definitions[0].operation == OperationDefinition.Operation.SUBSCRIPTION
}
def "keywords can be used as field names"() {
given:
def input = "{ ${name} }"
when:
Document document = new Parser().parseDocument(input)
then:
document.definitions.size() == 1
document.definitions[0] instanceof OperationDefinition
document.definitions[0].operation == OperationDefinition.Operation.QUERY
assertField(document.definitions[0] as OperationDefinition, name)
where:
name | _
'fragment' | _
'query' | _
'mutation' | _
'subscription' | _
'schema' | _
'scalar' | _
'type' | _
'interface' | _
'implements' | _
'enum' | _
'union' | _
'input' | _
'extend' | _
'directive' | _
}
def "#352 - incorrect parentheses are detected"() {
given:
def input = "{profile(id:117) {firstNames, lastNames, frontDegree}}}"
when:
new Parser().parseDocument(input)
then:
def exception = thrown(InvalidSyntaxException)
exception != null
}
def "#352 - lots of incorrect parentheses are detected"() {
given:
def input = "{profile(id:117) {firstNames, lastNames, frontDegree}}}}}}}}"
when:
new Parser().parseDocument(input)
then:
def exception = thrown(InvalidSyntaxException)
exception != null
}
def "#352 - comments don't count as unused"() {
given:
def input = "{profile(id:117) {firstNames, lastNames, frontDegree}} #trailing comments don't count"
when:
new Parser().parseDocument(input)
then:
noExceptionThrown()
}
def "parses null values"() {
given:
def input = "{ foo(bar: null, bell : null) }"
when:
def document = new Parser().parseDocument(input)
def operation = document.definitions[0] as OperationDefinition
def selection = operation.selectionSet.selections[0] as Field
then:
selection.arguments[0].value instanceof NullValue
selection.arguments[1].value instanceof NullValue
selection.arguments[0].value.sourceLocation.toString() == "SourceLocation{line=1, column=12}"
selection.arguments[1].value.sourceLocation.toString() == "SourceLocation{line=1, column=25}"
}
def "whitespace_ignored"() {
given:
def BOM = "\ufeff"
def ws = "\t \n"
def comma = ","
def input = "{ " + BOM + ws + comma + "foo(bar: null) }"
when:
def document = new Parser().parseDocument(input)
def operation = document.definitions[0] as OperationDefinition
def selection = operation.selectionSet.selections[0] as Field
then:
selection.name == "foo"
}
def "four quotation marks is an illegal string"() {
given:
def input = '''{foo(arg:[""""])}'''
when:
Parser.parse(input)
then:
def e = thrown(InvalidSyntaxException)
e.message.contains("Invalid Syntax")
}
def "three quotation marks is an illegal string"() {
given:
def input = '''{foo(arg: ["""])}'''
when:
Parser.parse(input)
then:
def e = thrown(InvalidSyntaxException)
e.message.contains("Invalid Syntax")
}
def "escaped triple quote inside block string"() {
given:
def input = '''{foo(arg: """\\"""""")}'''
when:
Document document = Parser.parse(input)
OperationDefinition operationDefinition = document.definitions[0] as OperationDefinition
Selection selection = operationDefinition.getSelectionSet().getSelections()[0]
Field field = (Field) selection
then:
field.getArguments().size() == 1
argValue(field, 0) == '"""'
}
def "triple quoted strings"() {
given:
def input = '''{ field(triple : """triple
string""", single : "single") }'''
when:
Document document = new Parser().parseDocument(input)
then:
document.definitions.size() == 1
OperationDefinition operationDefinition = document.definitions[0] as OperationDefinition
Selection selection = operationDefinition.getSelectionSet().getSelections()[0]
Field field = (Field) selection
assert field.getArguments().size() == 2
assert argValue(field, 0) == 'triple\nstring'
assert argValue(field, 1) == 'single'
}
def "triple quoted strings with the one special escape character"() {
given:
def input = '''{ field(
triple : """triple
string that is \\""" escaped""",
triple2 : """another string with \\""" escaping""",
triple3 : """edge cases \\""" "" " \\"" \\" edge cases"""
) }'''
when:
Document document = new Parser().parseDocument(input)
then:
document.definitions.size() == 1
OperationDefinition operationDefinition = document.definitions[0] as OperationDefinition
Selection selection = operationDefinition.getSelectionSet().getSelections()[0]
Field field = (Field) selection
assert field.getArguments().size() == 3
assert argValue(field, 0) == 'triple\n\nstring that is """ escaped'
assert argValue(field, 1) == 'another string with """ escaping'
assert argValue(field, 2) == 'edge cases """ "" " \\"" \\" edge cases'
}
String argValue(Field field, Integer index) {
def value = (field.getArguments()[index].getValue() as StringValue).getValue()
value
}
def "parse IDL type definitions with doc string comments"() {
given:
def input = '''
"""object type"""
type Object {
"""object field"""
field : String
}
"""interface type"""
interface Interface {
"""interface field"""
field : String
}
"""union type"""
union Union = Foo | Bar
"""scalar type"""
scalar Scalar
"""enum type"""
enum Enum {
"""enum field"""
foo
}
"""input type"""
input Input {
"""input field"""
field : String
}
"""directive def"""
directive @ dname on scalar
'''
when:
Document document = new Parser().parseDocument(input)
then:
document.definitions.size() == 7
assertMultiDesc((document.definitions[0] as ObjectTypeDefinition).getDescription(), "object type")
assertMultiDesc((document.definitions[0] as ObjectTypeDefinition).getFieldDefinitions()[0].getDescription(), "object field")
assertMultiDesc((document.definitions[1] as InterfaceTypeDefinition).getDescription(), "interface type")
assertMultiDesc((document.definitions[1] as InterfaceTypeDefinition).getFieldDefinitions()[0].getDescription(), "interface field")
assertMultiDesc((document.definitions[2] as UnionTypeDefinition).getDescription(), "union type")
assertMultiDesc((document.definitions[3] as ScalarTypeDefinition).getDescription(), "scalar type")
assertMultiDesc((document.definitions[4] as EnumTypeDefinition).getDescription(), "enum type")
assertMultiDesc((document.definitions[4] as EnumTypeDefinition).getEnumValueDefinitions()[0].getDescription(), "enum field")
assertMultiDesc((document.definitions[5] as InputObjectTypeDefinition).getDescription(), "input type")
assertMultiDesc((document.definitions[5] as InputObjectTypeDefinition).getInputValueDefinitions()[0].getDescription(), "input field")
assertMultiDesc((document.definitions[6] as DirectiveDefinition).getDescription(), "directive def")
}
def assertMultiDesc(Description description, String expected) {
assertDesc(description, expected, true)
}
def assertDesc(Description description, String expected, boolean multiLine) {
if (description == null) {
assert expected == null
} else {
assert expected == description.getContent(), "content check"
assert multiLine == description.isMultiLine(), "multi line ==" + multiLine
}
true
}
def "parse ignored chars"() {
given:
def input = "{,\r me\n\t} ,\n"
when:
def captureIgnoredCharsTRUE = ParserOptions.newParserOptions().captureIgnoredChars(true).build()
Document document = new Parser().parseDocument(input, captureIgnoredCharsTRUE)
def field = (document.definitions[0] as OperationDefinition).selectionSet.selections[0]
then:
field.getIgnoredChars().getLeft().size() == 3
field.getIgnoredChars().getLeft()[0] == new IgnoredChar(",", IgnoredChar.IgnoredCharKind.COMMA, new SourceLocation(1, 2))
field.getIgnoredChars().getLeft()[1] == new IgnoredChar("\r", IgnoredChar.IgnoredCharKind.CR, new SourceLocation(1, 3))
field.getIgnoredChars().getLeft()[2] == new IgnoredChar(" ", IgnoredChar.IgnoredCharKind.SPACE, new SourceLocation(1, 4))
field.getIgnoredChars().getRight().size() == 2
field.getIgnoredChars().getRight()[0] == new IgnoredChar("\n", IgnoredChar.IgnoredCharKind.LF, new SourceLocation(1, 7))
field.getIgnoredChars().getRight()[1] == new IgnoredChar("\t", IgnoredChar.IgnoredCharKind.TAB, new SourceLocation(2, 1))
document.getIgnoredChars().getRight().size() == 3
document.getIgnoredChars().getRight()[0] == new IgnoredChar(" ", IgnoredChar.IgnoredCharKind.SPACE, new SourceLocation(2, 3))
document.getIgnoredChars().getRight()[1] == new IgnoredChar(",", IgnoredChar.IgnoredCharKind.COMMA, new SourceLocation(2, 4))
document.getIgnoredChars().getRight()[2] == new IgnoredChar("\n", IgnoredChar.IgnoredCharKind.LF, new SourceLocation(2, 5))
}
def "parsed float with positive exponent"() {
given:
def input = """
{
getEmployee (sal:1.7976931348155E+308){
sal
}
}
"""
when:
Document document = new Parser().parseDocument(input)
Field getEmployee = (document.definitions[0] as OperationDefinition).selectionSet.selections[0] as Field
def argumentValue = getEmployee.getArguments().get(0).getValue()
then:
argumentValue instanceof FloatValue
((FloatValue) argumentValue).value.toString() == "1.7976931348155E+308"
}
def "parse fragment definition"() {
given:
def input = """
fragment Foo on Bar {
hello
}
"""
when:
Document document = Parser.parse(input)
FragmentDefinition fragmentDefinition = (document.definitions[0] as FragmentDefinition)
then:
fragmentDefinition.name == "Foo"
}
def "parser should throw syntax errors"() {
given:
def input = """
type Foo {
name / String
}
"""
when:
def document = Parser.parse(input)
println document
then:
def e = thrown(InvalidSyntaxException)
e.message.contains("Invalid Syntax")
e.sourcePreview == input + "\n"
e.location.line == 3
e.location.column == 20
}
def "allow emoji in comments"() {
def input = '''
# Represents the 😕 emoji.
{
foo
}
'''
when:
Document document = Parser.parse(input)
OperationDefinition operationDefinition = (document.definitions[0] as OperationDefinition)
then:
operationDefinition.getComments()[0].content == " Represents the 😕 emoji."
}
def "can override antlr to ast"() {
def query = '''
query {
field
}
'''
when:
Parser parser = new Parser() {
@Override
protected GraphqlAntlrToLanguage getAntlrToLanguage(CommonTokenStream tokens, MultiSourceReader multiSourceReader) {
// this pattern is used in Nadel - its backdoor but needed
return new GraphqlAntlrToLanguage(tokens, multiSourceReader) {
@Override
protected void addCommonData(NodeBuilder nodeBuilder, ParserRuleContext parserRuleContext) {
super.addCommonData(nodeBuilder, parserRuleContext)
nodeBuilder.additionalData("key", "value")
}
}
}
}
def document = parser.parseDocument(query)
then:
document.getAdditionalData().get("key") == "value"
document.children[0].getAdditionalData().get("key") == "value"
when: "The new override method is used"
parser = new Parser() {
@Override
protected GraphqlAntlrToLanguage getAntlrToLanguage(CommonTokenStream tokens, MultiSourceReader multiSourceReader, ParserOptions parserOptions) {
return new GraphqlAntlrToLanguage(tokens, multiSourceReader, parserOptions) {
@Override
protected void addCommonData(NodeBuilder nodeBuilder, ParserRuleContext parserRuleContext) {
super.addCommonData(nodeBuilder, parserRuleContext)
nodeBuilder.additionalData("key", "value")
}
}
}
}
document = parser.parseDocument(query)
then:
document.getAdditionalData().get("key") == "value"
document.children[0].getAdditionalData().get("key") == "value"
}
def "parse integer"() {
given:
def input = '''{foo(arg: 11)}'''
when:
Document document = Parser.parse(input)
OperationDefinition operationDefinition = document.definitions[0] as OperationDefinition
Selection selection = operationDefinition.getSelectionSet().getSelections()[0]
Field field = (Field) selection
then:
field.getArguments().size() == 1
(field.getArguments()[0].getValue() as IntValue).getValue().intValueExact() == 11
}
@Unroll
def "invalid int #value is an error"() {
given:
def input = "{foo(arg: [$value])}"
when:
Parser.parse(input)
then:
def e = thrown(InvalidSyntaxException)
e.message.contains("Invalid Syntax")
where:
value | _
'00' | _
'01' | _
'123.' | _
'123e' | _
'123E' | _
}
@Unroll
def "invalid float #value is an error"() {
given:
def input = "{foo(arg: [$value])}"
when:
Parser.parse(input)
then:
def e = thrown(InvalidSyntaxException)
e.message.contains("Invalid Syntax")
where:
value | _
'01.23' | _
'1.2e3.4' | _
'1.23.4' | _
'1.2e3e' | _
}
@Unroll
def 'parse ast literals #valueLiteral'() {
expect:
Parser.parseValue(valueLiteral) in expectedValue
where:
valueLiteral | expectedValue
'"s"' | StringValue.class
'true' | BooleanValue.class
'666' | IntValue.class
'666.6' | FloatValue.class
'["A", "B", "C"]' | ArrayValue.class
'{string : "s", integer : 1, boolean : true}' | ObjectValue.class
}
def "ignored chars can be set on or off"() {
def s = '''
type X {
s : String
}
'''
def captureIgnoredCharsFALSE = ParserOptions.newParserOptions().captureIgnoredChars(false).build()
def captureIgnoredCharsTRUE = ParserOptions.newParserOptions().captureIgnoredChars(true).build()
when: "explicitly off"
def doc = new Parser().parseDocument(s, captureIgnoredCharsFALSE)
def type = doc.getDefinitionsOfType(ObjectTypeDefinition)[0]
then:
type.getIgnoredChars() == IgnoredChars.EMPTY
when: "implicitly off it uses the system default"
doc = new Parser().parseDocument(s)
type = doc.getDefinitionsOfType(ObjectTypeDefinition)[0]
then:
type.getIgnoredChars() == IgnoredChars.EMPTY
!ParserOptions.getDefaultParserOptions().isCaptureIgnoredChars()
when: "explicitly on"
doc = new Parser().parseDocument(s, captureIgnoredCharsTRUE)
type = doc.getDefinitionsOfType(ObjectTypeDefinition)[0]
then:
type.getIgnoredChars() != IgnoredChars.EMPTY
!type.getIgnoredChars().getLeft().isEmpty()
!type.getIgnoredChars().getRight().isEmpty()
when: "implicitly on if the static is set"