File: test_dsl.py

package info (click to toggle)
python-gql 4.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,900 kB
  • sloc: python: 21,677; makefile: 54
file content (1273 lines) | stat: -rw-r--r-- 31,880 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
import pytest
from graphql import (
    FloatValueNode,
    GraphQLError,
    GraphQLFloat,
    GraphQLID,
    GraphQLInputObjectType,
    GraphQLInt,
    GraphQLList,
    GraphQLNonNull,
    IntValueNode,
    ListTypeNode,
    NamedTypeNode,
    NameNode,
    NonNullTypeNode,
    NullValueNode,
    Undefined,
    build_ast_schema,
    parse,
    print_ast,
)
from graphql.utilities import get_introspection_query

from gql import Client, gql
from gql.dsl import (
    DSLFragment,
    DSLInlineFragment,
    DSLMetaField,
    DSLMutation,
    DSLQuery,
    DSLSchema,
    DSLSubscription,
    DSLVariable,
    DSLVariableDefinitions,
    ast_from_serialized_value_untyped,
    ast_from_value,
    dsl_gql,
)
from gql.utilities import get_introspection_query_ast, node_tree

from ..conftest import strip_braces_spaces
from .schema import StarWarsSchema


@pytest.fixture
def ds():
    return DSLSchema(StarWarsSchema)


@pytest.fixture
def client():
    return Client(schema=StarWarsSchema)


def test_ast_from_value_with_input_type_and_not_mapping_value():
    obj_type = StarWarsSchema.get_type("ReviewInput")
    assert isinstance(obj_type, GraphQLInputObjectType)
    assert ast_from_value(8, obj_type) is None


def test_ast_from_value_with_list_type_and_non_iterable_value():
    assert ast_from_value(5, GraphQLList(GraphQLInt)) == IntValueNode(value="5")


def test_ast_from_value_with_none():
    assert ast_from_value(None, GraphQLInt) == NullValueNode()


def test_ast_from_value_with_undefined():
    with pytest.raises(GraphQLError) as exc_info:
        ast_from_value(Undefined, GraphQLInt)

    assert "Received Undefined value for type Int." in str(exc_info.value)


def test_ast_from_value_with_graphqlid():

    assert ast_from_value("12345", GraphQLID) == IntValueNode(value="12345")


def test_ast_from_value_with_invalid_type():
    with pytest.raises(TypeError) as exc_info:
        ast_from_value(4, None)  # type: ignore

    assert "Unexpected input type: None." in str(exc_info.value)


def test_ast_from_value_with_non_null_type_and_none():
    typ = GraphQLNonNull(GraphQLInt)

    with pytest.raises(GraphQLError) as exc_info:
        ast_from_value(None, typ)

    assert "Received Null value for a Non-Null type Int." in str(exc_info.value)


def test_ast_from_value_float_precision():

    # Checking precision of float serialization
    # See https://github.com/graphql-python/graphql-core/pull/164

    assert ast_from_value(123456789.01234567, GraphQLFloat) == FloatValueNode(
        value="123456789.01234567"
    )

    assert ast_from_value(1.1, GraphQLFloat) == FloatValueNode(value="1.1")

    assert ast_from_value(123.0, GraphQLFloat) == FloatValueNode(value="123")


def test_ast_from_serialized_value_untyped_typeerror():
    with pytest.raises(TypeError) as exc_info:
        ast_from_serialized_value_untyped(GraphQLInt)

    assert "Cannot convert value to AST: Int." in str(exc_info.value)


def test_variable_to_ast_type_passing_wrapping_type():
    review_type = StarWarsSchema.get_type("ReviewInput")
    assert isinstance(review_type, GraphQLInputObjectType)

    wrapping_type = GraphQLNonNull(GraphQLList(review_type))
    variable = DSLVariable("review_input")
    ast = variable.to_ast_type(wrapping_type)
    assert ast == NonNullTypeNode(
        type=ListTypeNode(type=NamedTypeNode(name=NameNode(value="ReviewInput")))
    )


def test_use_variable_definition_multiple_times(ds):
    var = DSLVariableDefinitions()

    # `episode` variable is used in both fields
    op = DSLMutation(
        ds.Mutation.createReview.alias("badReview")
        .args(review=var.badReview, episode=var.episode)
        .select(ds.Review.stars, ds.Review.commentary),
        ds.Mutation.createReview.alias("goodReview")
        .args(review=var.goodReview, episode=var.episode)
        .select(ds.Review.stars, ds.Review.commentary),
    )
    op.variable_definitions = var
    query = dsl_gql(op)

    assert (
        print_ast(query.document)
        == """mutation \
($badReview: ReviewInput, $episode: Episode, $goodReview: ReviewInput) {
  badReview: createReview(review: $badReview, episode: $episode) {
    stars
    commentary
  }
  goodReview: createReview(review: $goodReview, episode: $episode) {
    stars
    commentary
  }
}"""
    )

    assert node_tree(query.document) == node_tree(
        gql(print_ast(query.document)).document
    )


def test_add_variable_definitions(ds):
    var = DSLVariableDefinitions()
    op = DSLMutation(
        ds.Mutation.createReview.args(review=var.review, episode=var.episode).select(
            ds.Review.stars, ds.Review.commentary
        )
    )
    op.variable_definitions = var
    query = dsl_gql(op)

    assert (
        print_ast(query.document)
        == """mutation ($review: ReviewInput, $episode: Episode) {
  createReview(review: $review, episode: $episode) {
    stars
    commentary
  }
}"""
    )

    assert node_tree(query.document) == node_tree(
        gql(print_ast(query.document)).document
    )


def test_add_variable_definitions_with_default_value_enum(ds):
    var = DSLVariableDefinitions()
    op = DSLMutation(
        ds.Mutation.createReview.args(
            review=var.review, episode=var.episode.default(4)
        ).select(ds.Review.stars, ds.Review.commentary)
    )
    op.variable_definitions = var
    query = dsl_gql(op)

    assert (
        print_ast(query.document)
        == """mutation ($review: ReviewInput, $episode: Episode = NEWHOPE) {
  createReview(review: $review, episode: $episode) {
    stars
    commentary
  }
}"""
    )


def test_add_variable_definitions_with_default_value_input_object(ds):
    var = DSLVariableDefinitions()
    op = DSLMutation(
        ds.Mutation.createReview.args(
            review=var.review.default({"stars": 5, "commentary": "Wow!"}),
            episode=var.episode,
        ).select(ds.Review.stars, ds.Review.commentary)
    )
    op.variable_definitions = var
    query = dsl_gql(op)

    assert (
        strip_braces_spaces(print_ast(query.document))
        == """
mutation ($review: ReviewInput = {stars: 5, commentary: "Wow!"}, $episode: Episode) {
  createReview(review: $review, episode: $episode) {
    stars
    commentary
  }
}""".strip()
    )

    assert node_tree(query.document) == node_tree(
        gql(print_ast(query.document)).document
    )


def test_add_variable_definitions_in_input_object(ds):
    var = DSLVariableDefinitions()
    op = DSLMutation(
        ds.Mutation.createReview.args(
            review={"stars": var.stars, "commentary": var.commentary},
            episode=var.episode,
        ).select(ds.Review.stars, ds.Review.commentary)
    )
    op.variable_definitions = var
    query = dsl_gql(op)

    assert (
        strip_braces_spaces(print_ast(query.document))
        == """mutation ($stars: Int, $commentary: String, $episode: Episode) {
  createReview(
    review: {stars: $stars, commentary: $commentary}
    episode: $episode
  ) {
    stars
    commentary
  }
}"""
    )

    assert node_tree(query.document) == node_tree(
        gql(print_ast(query.document)).document
    )


def test_invalid_field_on_type_query(ds):
    with pytest.raises(AttributeError) as exc_info:
        ds.Query.extras.select(ds.Character.name)
    assert "Field extras does not exist in type Query." in str(exc_info.value)


def test_incompatible_field(ds):
    with pytest.raises(TypeError) as exc_info:
        ds.Query.hero.select("not_a_DSL_FIELD")
    assert (
        "Fields should be instances of DSLSelectable. Received: <class 'str'>"
        in str(exc_info.value)
    )


def test_hero_name_query(ds):
    query = """
hero {
  name
}
    """.strip()
    query_dsl = ds.Query.hero.select(ds.Character.name)
    assert query == str(query_dsl)


def test_hero_name_and_friends_query(ds):
    query = """
hero {
  id
  name
  friends {
    name
  }
}
    """.strip()
    query_dsl = ds.Query.hero.select(
        ds.Character.id,
        ds.Character.name,
        ds.Character.friends.select(
            ds.Character.name,
        ),
    )
    assert query == str(query_dsl)

    # Should also work with a chain of selects
    query_dsl = (
        ds.Query.hero.select(ds.Character.id)
        .select(ds.Character.name)
        .select(
            ds.Character.friends.select(
                ds.Character.name,
            ),
        )
    )
    assert query == str(query_dsl)


def test_hero_id_and_name(ds):
    query = """
hero {
  id
  name
}
    """.strip()
    query_dsl = ds.Query.hero.select(ds.Character.id)
    query_dsl = query_dsl.select(ds.Character.name)
    assert query == str(query_dsl)


def test_nested_query(ds):
    query = """
hero {
  name
  friends {
    name
    appearsIn
    friends {
      name
    }
  }
}
    """.strip()
    query_dsl = ds.Query.hero.select(
        ds.Character.name,
        ds.Character.friends.select(
            ds.Character.name,
            ds.Character.appears_in,
            ds.Character.friends.select(ds.Character.name),
        ),
    )
    assert query == str(query_dsl)


def test_fetch_luke_query(ds):
    query = """
human(id: "1000") {
  name
}
    """.strip()
    query_dsl = ds.Query.human(id="1000").select(
        ds.Human.name,
    )

    assert query == str(query_dsl)


def test_fetch_luke_aliased(ds):
    query = """
luke: human(id: "1000") {
  name
}
    """.strip()
    query_dsl = (
        ds.Query.human.args(id=1000)
        .alias("luke")
        .select(
            ds.Character.name,
        )
    )
    assert query == str(query_dsl)

    # Should also work with select before alias
    query_dsl = (
        ds.Query.human.args(id=1000)
        .select(
            ds.Character.name,
        )
        .alias("luke")
    )
    assert query == str(query_dsl)


def test_fetch_name_aliased(ds: DSLSchema) -> None:
    query = """
human(id: "1000") {
  my_name: name
}
    """.strip()
    query_dsl = ds.Query.human.args(id=1000).select(ds.Character.name.alias("my_name"))
    print(str(query_dsl))
    assert query == str(query_dsl)


def test_fetch_name_aliased_as_kwargs(ds: DSLSchema) -> None:
    query = """
human(id: "1000") {
  my_name: name
}
    """.strip()
    query_dsl = ds.Query.human.args(id=1000).select(
        my_name=ds.Character.name,
    )
    assert query == str(query_dsl)


def test_hero_name_query_result(ds, client):
    query = dsl_gql(DSLQuery(ds.Query.hero.select(ds.Character.name)))
    result = client.execute(query)
    expected = {"hero": {"name": "R2-D2"}}
    assert result == expected
    assert node_tree(query.document) == node_tree(
        gql(print_ast(query.document)).document
    )


def test_arg_serializer_list(ds, client):
    query = dsl_gql(
        DSLQuery(
            ds.Query.characters.args(ids=[1000, 1001, 1003]).select(
                ds.Character.name,
            )
        )
    )
    result = client.execute(query)
    expected = {
        "characters": [
            {"name": "Luke Skywalker"},
            {"name": "Darth Vader"},
            {"name": "Leia Organa"},
        ]
    }
    assert result == expected
    assert node_tree(query.document) == node_tree(
        gql(print_ast(query.document)).document
    )


def test_arg_serializer_enum(ds, client):
    query = dsl_gql(DSLQuery(ds.Query.hero.args(episode=5).select(ds.Character.name)))
    result = client.execute(query)
    expected = {"hero": {"name": "Luke Skywalker"}}
    assert result == expected
    assert node_tree(query.document) == node_tree(
        gql(print_ast(query.document)).document
    )


def test_create_review_mutation_result(ds, client):

    query = dsl_gql(
        DSLMutation(
            ds.Mutation.createReview.args(
                episode=6, review={"stars": 5, "commentary": "This is a great movie!"}
            ).select(ds.Review.stars, ds.Review.commentary)
        )
    )
    result = client.execute(query)
    expected = {"createReview": {"stars": 5, "commentary": "This is a great movie!"}}
    assert result == expected
    assert node_tree(query.document) == node_tree(
        gql(print_ast(query.document)).document
    )


def test_subscription(ds):

    query = dsl_gql(
        DSLSubscription(
            ds.Subscription.reviewAdded(episode=6).select(
                ds.Review.stars, ds.Review.commentary
            )
        )
    )
    assert (
        print_ast(query.document)
        == """subscription {
  reviewAdded(episode: JEDI) {
    stars
    commentary
  }
}"""
    )

    assert node_tree(query.document) == node_tree(
        gql(print_ast(query.document)).document
    )


def test_field_does_not_exit_in_type(ds):
    with pytest.raises(
        GraphQLError,
        match="Invalid field for <DSLField Query::hero>: <DSLField Query::hero>",
    ):
        ds.Query.hero.select(ds.Query.hero)


def test_try_to_select_on_scalar_field(ds):
    with pytest.raises(
        GraphQLError,
        match="Invalid field for <DSLField Human::name>: <DSLField Query::hero>",
    ):
        ds.Human.name.select(ds.Query.hero)


def test_invalid_arg(ds):
    with pytest.raises(
        KeyError, match="Argument invalid_arg does not exist in Field: Character."
    ):
        ds.Query.hero.args(invalid_arg=5).select(ds.Character.name)


def test_multiple_root_fields(ds, client):
    query = dsl_gql(
        DSLQuery(
            ds.Query.hero.select(ds.Character.name),
            ds.Query.hero(episode=5)
            .alias("hero_of_episode_5")
            .select(ds.Character.name),
        )
    )
    result = client.execute(query)
    expected = {
        "hero": {"name": "R2-D2"},
        "hero_of_episode_5": {"name": "Luke Skywalker"},
    }
    assert result == expected
    assert node_tree(query.document) == node_tree(
        gql(print_ast(query.document)).document
    )


def test_root_fields_aliased(ds, client):
    query = dsl_gql(
        DSLQuery(
            ds.Query.hero.select(ds.Character.name),
            hero_of_episode_5=ds.Query.hero(episode=5).select(ds.Character.name),
        )
    )
    result = client.execute(query)
    expected = {
        "hero": {"name": "R2-D2"},
        "hero_of_episode_5": {"name": "Luke Skywalker"},
    }
    assert result == expected
    assert node_tree(query.document) == node_tree(
        gql(print_ast(query.document)).document
    )


def test_operation_name(ds):
    query = dsl_gql(
        GetHeroName=DSLQuery(
            ds.Query.hero.select(ds.Character.name),
        )
    )

    assert (
        print_ast(query.document)
        == """query GetHeroName {
  hero {
    name
  }
}"""
    )

    assert node_tree(query.document) == node_tree(
        gql(print_ast(query.document)).document
    )


def test_multiple_operations(ds):
    query = dsl_gql(
        GetHeroName=DSLQuery(ds.Query.hero.select(ds.Character.name)),
        CreateReviewMutation=DSLMutation(
            ds.Mutation.createReview.args(
                episode=6, review={"stars": 5, "commentary": "This is a great movie!"}
            ).select(ds.Review.stars, ds.Review.commentary)
        ),
    )

    assert (
        strip_braces_spaces(print_ast(query.document))
        == """query GetHeroName {
  hero {
    name
  }
}

mutation CreateReviewMutation {
  createReview(
    episode: JEDI
    review: {stars: 5, commentary: "This is a great movie!"}
  ) {
    stars
    commentary
  }
}"""
    )

    assert node_tree(query.document) == node_tree(
        gql(print_ast(query.document)).document
    )


def test_inline_fragments(ds):
    query = """hero(episode: JEDI) {
  name
  ... on Droid {
    primaryFunction
  }
  ... on Human {
    homePlanet
  }
}"""
    query_dsl = ds.Query.hero.args(episode=6).select(
        ds.Character.name,
        DSLInlineFragment().on(ds.Droid).select(ds.Droid.primaryFunction),
        DSLInlineFragment().on(ds.Human).select(ds.Human.homePlanet),
    )
    assert query == str(query_dsl)


def test_inline_fragments_nested(ds):
    query = """hero(episode: JEDI) {
  name
  ... on Human {
    ... on Human {
      homePlanet
    }
  }
}"""
    query_dsl = ds.Query.hero.args(episode=6).select(
        ds.Character.name,
        DSLInlineFragment()
        .on(ds.Human)
        .select(DSLInlineFragment().on(ds.Human).select(ds.Human.homePlanet)),
    )
    assert query == str(query_dsl)


def test_fragments_repr(ds):

    assert repr(DSLInlineFragment()) == "<DSLInlineFragment>"
    assert repr(DSLInlineFragment().on(ds.Droid)) == "<DSLInlineFragment on Droid>"
    assert repr(DSLFragment("fragment_1")) == "<DSLFragment fragment_1>"
    assert repr(DSLFragment("fragment_2").on(ds.Droid)) == "<DSLFragment fragment_2>"


def test_fragments(ds):
    query = """fragment NameAndAppearances on Character {
  name
  appearsIn
}

{
  hero {
    ...NameAndAppearances
  }
}"""

    name_and_appearances = (
        DSLFragment("NameAndAppearances")
        .on(ds.Character)
        .select(ds.Character.name, ds.Character.appearsIn)
    )

    query_dsl = DSLQuery(ds.Query.hero.select(name_and_appearances))

    request = dsl_gql(name_and_appearances, query_dsl)

    document = request.document

    print(print_ast(document))

    assert query == print_ast(document)
    assert node_tree(document) == node_tree(gql(print_ast(document)).document)


def test_fragment_without_type_condition_error(ds):

    # We create a fragment without using the .on(type_condition) method
    name_and_appearances = DSLFragment("NameAndAppearances")

    # If we try to use this fragment, gql generates an error
    with pytest.raises(
        AttributeError,
        match=r"Missing type condition. Please use .on\(type_condition\) method",
    ):
        dsl_gql(name_and_appearances)

    with pytest.raises(
        AttributeError,
        match=r"Missing type condition. Please use .on\(type_condition\) method",
    ):
        DSLFragment("NameAndAppearances").select(
            ds.Character.name, ds.Character.appearsIn
        )


def test_inline_fragment_in_dsl_gql(ds):

    inline_fragment = DSLInlineFragment()

    query = DSLQuery()

    with pytest.raises(
        GraphQLError,
        match=r"Invalid field for <DSLQuery>: <DSLInlineFragment>",
    ):
        query.select(inline_fragment)


def test_fragment_with_name_changed(ds):

    fragment = DSLFragment("ABC")

    assert str(fragment) == "...ABC"

    fragment.name = "DEF"

    assert str(fragment) == "...DEF"


def test_fragment_select_field_not_in_fragment(ds):

    fragment = DSLFragment("test").on(ds.Character)

    with pytest.raises(
        GraphQLError,
        match="Invalid field for <DSLFragment test>: <DSLField Droid::primaryFunction>",
    ):
        fragment.select(ds.Droid.primaryFunction)


def test_dsl_nested_query_with_fragment(ds):
    query = """fragment NameAndAppearances on Character {
  name
  appearsIn
}

query NestedQueryWithFragment {
  hero {
    ...NameAndAppearances
    friends {
      ...NameAndAppearances
      friends {
        ...NameAndAppearances
      }
    }
  }
}"""

    name_and_appearances = (
        DSLFragment("NameAndAppearances")
        .on(ds.Character)
        .select(ds.Character.name, ds.Character.appearsIn)
    )

    query_dsl = DSLQuery(
        ds.Query.hero.select(
            name_and_appearances,
            ds.Character.friends.select(
                name_and_appearances, ds.Character.friends.select(name_and_appearances)
            ),
        )
    )

    request = dsl_gql(name_and_appearances, NestedQueryWithFragment=query_dsl)

    document = request.document

    print(print_ast(document))

    assert query == print_ast(document)
    assert node_tree(document) == node_tree(gql(print_ast(document)).document)

    # Same thing, but incrementaly

    name_and_appearances = DSLFragment("NameAndAppearances")
    name_and_appearances.on(ds.Character)
    name_and_appearances.select(ds.Character.name)
    name_and_appearances.select(ds.Character.appearsIn)

    level_2 = ds.Character.friends
    level_2.select(name_and_appearances)
    level_1 = ds.Character.friends
    level_1.select(name_and_appearances)
    level_1.select(level_2)

    hero = ds.Query.hero
    hero.select(name_and_appearances)
    hero.select(level_1)

    query_dsl = DSLQuery(hero)

    request = dsl_gql(name_and_appearances, NestedQueryWithFragment=query_dsl)

    document = request.document

    print(print_ast(document))

    assert query == print_ast(document)
    assert node_tree(document) == node_tree(gql(print_ast(document)).document)


def test_dsl_query_all_fields_should_be_instances_of_DSLField():
    with pytest.raises(
        TypeError,
        match="Fields should be instances of DSLSelectable. Received: <class 'str'>",
    ):
        DSLQuery("I am a string")  # type: ignore


def test_dsl_query_all_fields_should_correspond_to_the_root_type(ds):
    with pytest.raises(GraphQLError) as excinfo:
        DSLQuery(ds.Character.name)

    assert ("Invalid field for <DSLQuery>: <DSLField Character::name>") in str(
        excinfo.value
    )


def test_dsl_root_type_not_default():

    schema_str = """
schema {
  query: QueryNotDefault
}

type QueryNotDefault {
  version: String
}
"""

    type_def_ast = parse(schema_str)
    schema = build_ast_schema(type_def_ast)

    ds = DSLSchema(schema)

    query = dsl_gql(DSLQuery(ds.QueryNotDefault.version))

    expected_query = """
{
  version
}
"""
    assert print_ast(query.document) == expected_query.strip()

    with pytest.raises(GraphQLError) as excinfo:
        DSLSubscription(ds.QueryNotDefault.version)

    assert (
        "Invalid field for <DSLSubscription>: <DSLField QueryNotDefault::version>"
    ) in str(excinfo.value)

    assert node_tree(query.document) == node_tree(
        gql(print_ast(query.document)).document
    )


def test_dsl_gql_all_arguments_should_be_operations_or_fragments():
    with pytest.raises(
        TypeError, match="Operations should be instances of DSLExecutable "
    ):
        dsl_gql("I am a string")  # type: ignore


def test_DSLSchema_requires_a_schema(client):
    with pytest.raises(TypeError, match="DSLSchema needs a schema as parameter"):
        DSLSchema(client)


def test_invalid_type(ds):
    with pytest.raises(
        AttributeError, match="Type 'invalid_type' not found in the schema!"
    ):
        ds.invalid_type


def test_invalid_type_union():
    schema_str = """
    type FloatValue {
        floatValue: Float!
    }

    type IntValue {
        intValue: Int!
    }

    union Value = FloatValue | IntValue

    type Entry {
        name: String!
        value: Value
    }

    type Query {
        values: [Entry!]!
    }
    """

    schema = build_ast_schema(parse(schema_str))
    ds = DSLSchema(schema)

    with pytest.raises(
        AttributeError,
        match=(
            "Type \"Value \\(<GraphQLUnionType 'Value'>\\)\" is not valid as an "
            "attribute of DSLSchema. Only Object types or Interface types are accepted."
        ),
    ):
        ds.Value


def test_hero_name_query_with_typename(ds):
    query = """
hero {
  name
  __typename
}
    """.strip()
    query_dsl = ds.Query.hero.select(ds.Character.name, DSLMetaField("__typename"))
    assert query == str(query_dsl)


def test_type_hero_query(ds):
    query = """{
  __type(name: "Hero") {
    kind
    name
    ofType {
      kind
      name
    }
  }
}"""

    type_hero = DSLMetaField("__type")(name="Hero")
    type_hero.select(
        ds.__Type.kind,
        ds.__Type.name,
        ds.__Type.ofType.select(ds.__Type.kind, ds.__Type.name),
    )
    query_dsl = DSLQuery(type_hero)

    assert query == str(print_ast(dsl_gql(query_dsl).document)).strip()


def test_invalid_meta_field_selection(ds):

    DSLQuery(DSLMetaField("__typename"))
    DSLQuery(DSLMetaField("__schema"))
    DSLQuery(DSLMetaField("__type"))

    metafield = DSLMetaField("__typename")
    assert metafield.name == "__typename"

    with pytest.raises(GraphQLError):
        DSLMetaField("__invalid_meta_field")

    DSLMutation(DSLMetaField("__typename"))

    with pytest.raises(GraphQLError):
        DSLMutation(DSLMetaField("__schema"))

    with pytest.raises(GraphQLError):
        DSLMutation(DSLMetaField("__type"))

    with pytest.raises(GraphQLError):
        DSLSubscription(DSLMetaField("__typename"))

    with pytest.raises(GraphQLError):
        DSLSubscription(DSLMetaField("__schema"))

    with pytest.raises(GraphQLError):
        DSLSubscription(DSLMetaField("__type"))

    fragment = DSLFragment("blah")

    with pytest.raises(AttributeError):
        fragment.select(DSLMetaField("__typename"))

    fragment.on(ds.Character)

    fragment.select(DSLMetaField("__typename"))

    with pytest.raises(GraphQLError):
        fragment.select(DSLMetaField("__schema"))

    with pytest.raises(GraphQLError):
        fragment.select(DSLMetaField("__type"))

    ds.Query.hero.select(DSLMetaField("__typename"))

    with pytest.raises(GraphQLError):
        ds.Query.hero.select(DSLMetaField("__schema"))

    with pytest.raises(GraphQLError):
        ds.Query.hero.select(DSLMetaField("__type"))


@pytest.mark.parametrize("option", [True, False])
def test_get_introspection_query_ast(option):

    introspection_query = get_introspection_query(
        descriptions=option,
        specified_by_url=option,
        directive_is_repeatable=option,
        schema_description=option,
        input_value_deprecation=option,
    )
    dsl_introspection_query = get_introspection_query_ast(
        descriptions=option,
        specified_by_url=option,
        directive_is_repeatable=option,
        schema_description=option,
        input_value_deprecation=option,
    )

    try:
        assert print_ast(gql(introspection_query).document) == print_ast(
            dsl_introspection_query
        )
        assert node_tree(dsl_introspection_query) == node_tree(
            gql(print_ast(dsl_introspection_query)).document
        )
    except AssertionError:

        # From graphql-core version 3.3.0a7, there is two more type recursion levels
        dsl_introspection_query = get_introspection_query_ast(
            descriptions=option,
            specified_by_url=option,
            directive_is_repeatable=option,
            schema_description=option,
            input_value_deprecation=option,
            type_recursion_level=9,
        )
        assert print_ast(gql(introspection_query).document) == print_ast(
            dsl_introspection_query
        )
        assert node_tree(dsl_introspection_query) == node_tree(
            gql(print_ast(dsl_introspection_query)).document
        )


def test_typename_aliased(ds):
    query = """
hero {
  name
  typenameField: __typename
}
""".strip()

    query_dsl = ds.Query.hero.select(
        ds.Character.name, typenameField=DSLMetaField("__typename")
    )
    assert query == str(query_dsl)

    query_dsl = ds.Query.hero.select(
        ds.Character.name, DSLMetaField("__typename").alias("typenameField")
    )
    assert query == str(query_dsl)


def test_node_tree_with_loc(ds):
    query = """query GetHeroName {
  hero {
    name
  }
}""".strip()

    document = gql(query).document

    node_tree_result = """
DocumentNode
  definitions:
    OperationDefinitionNode
      directives:
        empty tuple
      loc:
        Location
          <Location 0:43>
      name:
        NameNode
          loc:
            Location
              <Location 6:17>
          value:
            'GetHeroName'
      operation:
        <OperationType.QUERY: 'query'>
      selection_set:
        SelectionSetNode
          loc:
            Location
              <Location 18:43>
          selections:
            FieldNode
              alias:
                None
              arguments:
                empty tuple
              directives:
                empty tuple
              loc:
                Location
                  <Location 22:41>
              name:
                NameNode
                  loc:
                    Location
                      <Location 22:26>
                  value:
                    'hero'
              nullability_assertion:
                None
              selection_set:
                SelectionSetNode
                  loc:
                    Location
                      <Location 27:41>
                  selections:
                    FieldNode
                      alias:
                        None
                      arguments:
                        empty tuple
                      directives:
                        empty tuple
                      loc:
                        Location
                          <Location 33:37>
                      name:
                        NameNode
                          loc:
                            Location
                              <Location 33:37>
                          value:
                            'name'
                      nullability_assertion:
                        None
                      selection_set:
                        None
      variable_definitions:
        empty tuple
  loc:
    Location
      <Location 0:43>
""".strip()

    node_tree_result_stable = """
DocumentNode
  definitions:
    OperationDefinitionNode
      directives:
        empty tuple
      loc:
        Location
          <Location 0:43>
      name:
        NameNode
          loc:
            Location
              <Location 6:17>
          value:
            'GetHeroName'
      operation:
        <OperationType.QUERY: 'query'>
      selection_set:
        SelectionSetNode
          loc:
            Location
              <Location 18:43>
          selections:
            FieldNode
              alias:
                None
              arguments:
                empty tuple
              directives:
                empty tuple
              loc:
                Location
                  <Location 22:41>
              name:
                NameNode
                  loc:
                    Location
                      <Location 22:26>
                  value:
                    'hero'
              selection_set:
                SelectionSetNode
                  loc:
                    Location
                      <Location 27:41>
                  selections:
                    FieldNode
                      alias:
                        None
                      arguments:
                        empty tuple
                      directives:
                        empty tuple
                      loc:
                        Location
                          <Location 33:37>
                      name:
                        NameNode
                          loc:
                            Location
                              <Location 33:37>
                          value:
                            'name'
                      selection_set:
                        None
      variable_definitions:
        empty tuple
  loc:
    Location
      <Location 0:43>
""".strip()

    print(node_tree(document, ignore_loc=False))

    try:
        assert node_tree(document, ignore_loc=False) == node_tree_result
    except AssertionError:
        # graphql-core version 3.2.3
        assert node_tree(document, ignore_loc=False) == node_tree_result_stable


def test_legacy_fragment_with_variables(ds):
    var = DSLVariableDefinitions()

    hero_fragment = (
        DSLFragment("heroFragment")
        .on(ds.Query)
        .select(
            ds.Query.hero.args(episode=var.episode).select(ds.Character.name),
        )
    )

    print(hero_fragment)

    hero_fragment.variable_definitions = var

    query = dsl_gql(hero_fragment)

    expected = """
fragment heroFragment($episode: Episode) on Query {
  hero(episode: $episode) {
    name
  }
}
""".strip()
    assert print_ast(query.document) == expected