File: test_build_client_schema.py

package info (click to toggle)
graphql-core 3.2.6-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,384 kB
  • sloc: python: 45,812; makefile: 26; sh: 13
file content (1106 lines) | stat: -rw-r--r-- 35,286 bytes parent folder | download | duplicates (2)
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
from typing import cast

from graphql import graphql_sync
from graphql.type import (
    GraphQLArgument,
    GraphQLBoolean,
    GraphQLEnumType,
    GraphQLEnumValue,
    GraphQLField,
    GraphQLFloat,
    GraphQLID,
    GraphQLInt,
    GraphQLObjectType,
    GraphQLSchema,
    GraphQLString,
    assert_enum_type,
)
from graphql.utilities import (
    build_client_schema,
    build_schema,
    introspection_from_schema,
    print_schema,
)
from graphql.utilities.get_introspection_query import (
    IntrospectionEnumType,
    IntrospectionInputObjectType,
    IntrospectionInterfaceType,
    IntrospectionObjectType,
    IntrospectionType,
    IntrospectionUnionType,
)
from pytest import raises

from ..utils import dedent


def cycle_introspection(sdl_string: str):
    """Test that the client side introspection gives the same result.

    This function does a full cycle of going from a string with the contents of the SDL,
    build in-memory GraphQLSchema from it, produce a client-side representation of the
    schema by using "build_client_schema" and then return that schema printed as SDL.
    """
    server_schema = build_schema(sdl_string)
    initial_introspection = introspection_from_schema(server_schema)
    client_schema = build_client_schema(initial_introspection)
    # If the client then runs the introspection query against the client-side schema,
    # it should get a result identical to what was returned by the server
    second_introspection = introspection_from_schema(client_schema)

    # If the client then runs the introspection query against the client-side
    # schema, it should get a result identical to what was returned by the server.
    assert initial_introspection == second_introspection
    return print_schema(client_schema)


def describe_type_system_build_schema_from_introspection():
    def builds_a_simple_schema():
        sdl = dedent(
            '''
            """Simple schema"""
            schema {
              query: Simple
            }

            """This is a simple type"""
            type Simple {
              """This is a string field"""
              string: String
            }
            '''
        )

        assert cycle_introspection(sdl) == sdl

    def builds_a_schema_without_the_query_type():
        sdl = dedent(
            """
            type Query {
              foo: String
            }
            """
        )

        schema = build_schema(sdl)
        introspection = introspection_from_schema(schema)
        del introspection["__schema"]["queryType"]  # type: ignore

        client_schema = build_client_schema(introspection)
        assert client_schema.query_type is None
        assert print_schema(client_schema) == sdl

    def builds_a_simple_schema_with_all_operation_types():
        sdl = dedent(
            '''
            schema {
              query: QueryType
              mutation: MutationType
              subscription: SubscriptionType
            }

            """This is a simple mutation type"""
            type MutationType {
              """Set the string field"""
              string: String
            }

            """This is a simple query type"""
            type QueryType {
              """This is a string field"""
              string: String
            }

            """This is a simple subscription type"""
            type SubscriptionType {
              """This is a string field"""
              string: String
            }
            '''
        )

        assert cycle_introspection(sdl) == sdl

    def uses_built_in_scalars_when_possible():
        sdl = dedent(
            """
            scalar CustomScalar

            type Query {
              int: Int
              float: Float
              string: String
              boolean: Boolean
              id: ID
              custom: CustomScalar
            }
            """
        )

        assert cycle_introspection(sdl) == sdl

        schema = build_schema(sdl)
        introspection = introspection_from_schema(schema)
        client_schema = build_client_schema(introspection)

        # Built-ins are used
        assert client_schema.get_type("Int") is GraphQLInt
        assert client_schema.get_type("Float") is GraphQLFloat
        assert client_schema.get_type("String") is GraphQLString
        assert client_schema.get_type("Boolean") is GraphQLBoolean
        assert client_schema.get_type("ID") is GraphQLID

        # Custom are built
        custom_scalar = schema.get_type("CustomScalar")
        assert client_schema.get_type("CustomScalar") is not custom_scalar

    def includes_standard_types_only_if_they_are_used():
        schema = build_schema(
            """
            type Query {
              foo: String
            }
            """
        )
        introspection = introspection_from_schema(schema)
        client_schema = build_client_schema(introspection)

        assert client_schema.get_type("Int") is None
        assert client_schema.get_type("Float") is None
        assert client_schema.get_type("ID") is None

    def builds_a_schema_with_a_recursive_type_reference():
        sdl = dedent(
            """
            schema {
              query: Recur
            }

            type Recur {
              recur: Recur
            }
            """
        )

        assert cycle_introspection(sdl) == sdl

    def builds_a_schema_with_a_circular_type_reference():
        sdl = dedent(
            """
            type Dog {
              bestFriend: Human
            }

            type Human {
              bestFriend: Dog
            }

            type Query {
              dog: Dog
              human: Human
            }
            """
        )

        assert cycle_introspection(sdl) == sdl

    def builds_a_schema_with_an_interface():
        sdl = dedent(
            '''
            type Dog implements Friendly {
              bestFriend: Friendly
            }

            interface Friendly {
              """The best friend of this friendly thing"""
              bestFriend: Friendly
            }

            type Human implements Friendly {
              bestFriend: Friendly
            }

            type Query {
              friendly: Friendly
            }
            '''
        )

        assert cycle_introspection(sdl) == sdl

    def builds_a_schema_with_an_interface_hierarchy():
        sdl = dedent(
            '''
            type Dog implements Friendly & Named {
              bestFriend: Friendly
              name: String
            }

            interface Friendly implements Named {
              """The best friend of this friendly thing"""
              bestFriend: Friendly
              name: String
            }

            type Human implements Friendly & Named {
              bestFriend: Friendly
              name: String
            }

            interface Named {
              name: String
            }

            type Query {
              friendly: Friendly
            }
            '''
        )

        assert cycle_introspection(sdl) == sdl

    def builds_a_schema_with_an_implicit_interface():
        sdl = dedent(
            '''
            type Dog implements Friendly {
              bestFriend: Friendly
            }

            interface Friendly {
              """The best friend of this friendly thing"""
              bestFriend: Friendly
            }

            type Query {
              dog: Dog
            }
            '''
        )

        assert cycle_introspection(sdl) == sdl

    def builds_a_schema_with_a_union():
        sdl = dedent(
            """
            type Dog {
              bestFriend: Friendly
            }

            union Friendly = Dog | Human

            type Human {
              bestFriend: Friendly
            }

            type Query {
              friendly: Friendly
            }
            """
        )

        assert cycle_introspection(sdl) == sdl

    def builds_a_schema_with_complex_field_values():
        sdl = dedent(
            """
            type Query {
              string: String
              listOfString: [String]
              nonNullString: String!
              nonNullListOfString: [String]!
              nonNullListOfNonNullString: [String!]!
            }
            """
        )

        assert cycle_introspection(sdl) == sdl

    def builds_a_schema_with_field_arguments():
        sdl = dedent(
            '''
            type Query {
              """A field with a single arg"""
              one(
                """This is an int arg"""
                intArg: Int
              ): String

              """A field with a two args"""
              two(
                """This is an list of int arg"""
                listArg: [Int]

                """This is a required arg"""
                requiredArg: Boolean!
              ): String
            }
            '''
        )

        assert cycle_introspection(sdl) == sdl

    def builds_a_schema_with_default_value_on_custom_scalar_field():
        sdl = dedent(
            """
            scalar CustomScalar

            type Query {
              testField(testArg: CustomScalar = "default"): String
            }
            """
        )

        assert cycle_introspection(sdl) == sdl

    def builds_a_schema_with_an_enum():
        food_enum = GraphQLEnumType(
            "Food",
            {
                "VEGETABLES": GraphQLEnumValue(
                    1, description="Foods that are vegetables."
                ),
                "FRUITS": GraphQLEnumValue(2),
                "OILS": GraphQLEnumValue(3, deprecation_reason="Too fatty."),
            },
            description="Varieties of food stuffs",
        )

        schema = GraphQLSchema(
            GraphQLObjectType(
                "EnumFields",
                {
                    "food": GraphQLField(
                        food_enum,
                        args={
                            "kind": GraphQLArgument(
                                food_enum, description="what kind of food?"
                            )
                        },
                        description="Repeats the arg you give it",
                    )
                },
            )
        )

        introspection = introspection_from_schema(schema)
        client_schema = build_client_schema(introspection)

        second_introspection = introspection_from_schema(client_schema)
        assert second_introspection == introspection

        # It's also an Enum type on the client.
        client_food_enum = assert_enum_type(client_schema.get_type("Food"))

        # Client types do not get server-only values, so the values mirror the names,
        # rather than using the integers defined in the "server" schema.
        values = {
            name: value.to_kwargs() for name, value in client_food_enum.values.items()
        }
        assert values == {
            "VEGETABLES": {
                "value": "VEGETABLES",
                "description": "Foods that are vegetables.",
                "deprecation_reason": None,
                "extensions": {},
                "ast_node": None,
            },
            "FRUITS": {
                "value": "FRUITS",
                "description": None,
                "deprecation_reason": None,
                "extensions": {},
                "ast_node": None,
            },
            "OILS": {
                "value": "OILS",
                "description": None,
                "deprecation_reason": "Too fatty.",
                "extensions": {},
                "ast_node": None,
            },
        }

    def builds_a_schema_with_an_input_object():
        sdl = dedent(
            '''
            """An input address"""
            input Address {
              """What street is this address?"""
              street: String!

              """The city the address is within?"""
              city: String!

              """The country (blank will assume USA)."""
              country: String = "USA"
            }

            type Query {
              """Get a geocode from an address"""
              geocode(
                """The address to lookup"""
                address: Address
              ): String
            }
            '''
        )

        assert cycle_introspection(sdl) == sdl

    def builds_a_schema_with_field_arguments_with_default_values():
        sdl = dedent(
            """
            input Geo {
              lat: Float
              lon: Float
            }

            type Query {
              defaultInt(intArg: Int = 30): String
              defaultList(listArg: [Int] = [1, 2, 3]): String
              defaultObject(objArg: Geo = {lat: 37.485, lon: -122.148}): String
              defaultNull(intArg: Int = null): String
              noDefault(intArg: Int): String
            }
            """
        )

        assert cycle_introspection(sdl) == sdl

    def builds_a_schema_with_custom_directives():
        sdl = dedent(
            '''
            """This is a custom directive"""
            directive @customDirective repeatable on FIELD

            type Query {
              string: String
            }
            '''
        )

        assert cycle_introspection(sdl) == sdl

    def builds_a_schema_without_directives():
        sdl = dedent(
            """
            type Query {
              foo: String
            }
            """
        )

        schema = build_schema(sdl)
        introspection = introspection_from_schema(schema)
        del introspection["__schema"]["directives"]  # type: ignore

        client_schema = build_client_schema(introspection)

        assert schema.directives
        assert client_schema.directives == ()
        assert print_schema(client_schema) == sdl

    def builds_a_schema_aware_of_deprecation():
        sdl = dedent(
            '''
            directive @someDirective(
              """This is a shiny new argument"""
              shinyArg: SomeInputObject

              """This was our design mistake :("""
              oldArg: String @deprecated(reason: "Use shinyArg")
            ) on QUERY

            enum Color {
              """So rosy"""
              RED

              """So grassy"""
              GREEN

              """So calming"""
              BLUE

              """So sickening"""
              MAUVE @deprecated(reason: "No longer in fashion")
            }

            input SomeInputObject {
              """Nothing special about it, just deprecated for some unknown reason"""
              oldField: String @deprecated(reason: "Don't use it, use newField instead!")

              """Same field but with a new name"""
              newField: String
            }

            type Query {
              """This is a shiny string field"""
              shinyString: String

              """This is a deprecated string field"""
              deprecatedString: String @deprecated(reason: "Use shinyString")

              """Color of a week"""
              color: Color

              """Some random field"""
              someField(
                """This is a shiny new argument"""
                shinyArg: SomeInputObject

                """This was our design mistake :("""
                oldArg: String @deprecated(reason: "Use shinyArg")
              ): String
            }
            '''  # noqa: E501
        )

        assert cycle_introspection(sdl) == sdl

    def builds_a_schema_with_empty_deprecation_reasons():
        sdl = dedent(
            """
            directive @someDirective(someArg: SomeInputObject @deprecated(reason: "")) on QUERY

            type Query {
              someField(someArg: SomeInputObject @deprecated(reason: "")): SomeEnum @deprecated(reason: "")
            }

            input SomeInputObject {
              someInputField: String @deprecated(reason: "")
            }

            enum SomeEnum {
              SOME_VALUE @deprecated(reason: "")
            }
            """  # noqa: E501
        )

        assert cycle_introspection(sdl) == sdl

    def builds_a_schema_with_specified_by_url():
        sdl = dedent(
            """
            scalar Foo @specifiedBy(url: "https://example.com/foo_spec")

            type Query {
              foo: Foo
            }
            """
        )

        assert cycle_introspection(sdl) == sdl

    def can_use_client_schema_for_limited_execution():
        schema = build_schema(
            """
            scalar CustomScalar

            type Query {
              foo(custom1: CustomScalar, custom2: CustomScalar): String
            }
            """
        )

        introspection = introspection_from_schema(schema)
        client_schema = build_client_schema(introspection)

        class Data:
            foo = "bar"
            unused = "value"

        result = graphql_sync(
            client_schema,
            "query Limited($v: CustomScalar) { foo(custom1: 123, custom2: $v) }",
            root_value=Data(),
            variable_values={"v": "baz"},
        )

        assert result.data == {"foo": "bar"}

    def can_build_invalid_schema():
        schema = build_schema("type Query", assume_valid=True)

        introspection = introspection_from_schema(schema)
        client_schema = build_client_schema(introspection, assume_valid=True)

        assert client_schema.to_kwargs()["assume_valid"] is True

    def describe_throws_when_given_invalid_introspection():
        dummy_schema = build_schema(
            """
            type Query {
              foo(bar: String): String
            }

            interface SomeInterface {
              foo: String
            }

            union SomeUnion = Query

            enum SomeEnum { FOO }

            input SomeInputObject {
              foo: String
            }

            directive @SomeDirective on QUERY
            """
        )

        def throws_when_introspection_is_missing_schema_property():
            with raises(TypeError) as exc_info:
                # noinspection PyTypeChecker
                build_client_schema(None)  # type: ignore

            assert str(exc_info.value) == (
                "Invalid or incomplete introspection result. Ensure that you"
                " are passing the 'data' attribute of an introspection response"
                " and no 'errors' were returned alongside: None."
            )

            with raises(TypeError) as exc_info:
                # noinspection PyTypeChecker
                build_client_schema({})  # type: ignore

            assert str(exc_info.value) == (
                "Invalid or incomplete introspection result. Ensure that you"
                " are passing the 'data' attribute of an introspection response"
                " and no 'errors' were returned alongside: {}."
            )

        def throws_when_referenced_unknown_type():
            introspection = introspection_from_schema(dummy_schema)

            introspection["__schema"]["types"] = [
                type_
                for type_ in introspection["__schema"]["types"]
                if type_["name"] != "Query"
            ]

            with raises(TypeError) as exc_info:
                build_client_schema(introspection)

            assert str(exc_info.value) == (
                "Invalid or incomplete schema, unknown type: Query."
                " Ensure that a full introspection query is used"
                " in order to build a client schema."
            )

        def throws_when_missing_definition_for_one_of_the_standard_scalars():
            schema = build_schema(
                """
                type Query {
                  foo: Float
                }
                """
            )
            introspection = introspection_from_schema(schema)
            introspection["__schema"]["types"] = [
                type_
                for type_ in introspection["__schema"]["types"]
                if type_["name"] != "Float"
            ]

            with raises(TypeError) as exc_info:
                build_client_schema(introspection)

            assert str(exc_info.value).endswith(
                "Invalid or incomplete schema, unknown type: Float."
                " Ensure that a full introspection query is used"
                " in order to build a client schema."
            )

        def throws_when_type_reference_is_missing_name():
            introspection = introspection_from_schema(dummy_schema)
            query_type = cast(IntrospectionType, introspection["__schema"]["queryType"])
            assert query_type["name"] == "Query"
            del query_type["name"]  # type: ignore

            with raises(TypeError) as exc_info:
                build_client_schema(introspection)

            assert str(exc_info.value) == "Unknown type reference: {}."

        def throws_when_missing_kind():
            introspection = introspection_from_schema(dummy_schema)
            query_type_introspection = next(
                type_
                for type_ in introspection["__schema"]["types"]
                if type_["name"] == "Query"
            )
            assert query_type_introspection["kind"] == "OBJECT"
            del query_type_introspection["kind"]

            with raises(
                TypeError,
                match=r"^Invalid or incomplete introspection result\."
                " Ensure that a full introspection query is used"
                r" in order to build a client schema: {'name': 'Query', .*}\.$",
            ):
                build_client_schema(introspection)

        def throws_when_missing_interfaces():
            introspection = introspection_from_schema(dummy_schema)
            query_type_introspection = cast(
                IntrospectionObjectType,
                next(
                    type_
                    for type_ in introspection["__schema"]["types"]
                    if type_["name"] == "Query"
                ),
            )

            assert query_type_introspection["interfaces"] == []
            del query_type_introspection["interfaces"]  # type: ignore

            with raises(
                TypeError,
                match="^Query interfaces cannot be resolved."
                " Introspection result missing interfaces:"
                r" {'kind': 'OBJECT', 'name': 'Query', .*}\.$",
            ):
                build_client_schema(introspection)

        def legacy_support_for_interfaces_with_null_as_interfaces_field():
            introspection = introspection_from_schema(dummy_schema)
            some_interface_introspection = cast(
                IntrospectionInterfaceType,
                next(
                    type_
                    for type_ in introspection["__schema"]["types"]
                    if type_["name"] == "SomeInterface"
                ),
            )

            assert some_interface_introspection["interfaces"] == []
            some_interface_introspection["interfaces"] = None  # type: ignore

            client_schema = build_client_schema(introspection)
            assert print_schema(client_schema) == print_schema(dummy_schema)

        def throws_when_missing_fields():
            introspection = introspection_from_schema(dummy_schema)
            query_type_introspection = cast(
                IntrospectionObjectType,
                next(
                    type_
                    for type_ in introspection["__schema"]["types"]
                    if type_["name"] == "Query"
                ),
            )

            assert query_type_introspection["fields"]
            del query_type_introspection["fields"]  # type: ignore

            with raises(
                TypeError,
                match="^Query fields cannot be resolved."
                " Introspection result missing fields:"
                r" {'kind': 'OBJECT', 'name': 'Query', .*}\.$",
            ):
                build_client_schema(introspection)

        def throws_when_missing_field_args():
            introspection = introspection_from_schema(dummy_schema)
            query_type_introspection = cast(
                IntrospectionObjectType,
                next(
                    type_
                    for type_ in introspection["__schema"]["types"]
                    if type_["name"] == "Query"
                ),
            )

            field = query_type_introspection["fields"][0]
            assert field["args"]
            del field["args"]  # type: ignore

            with raises(
                TypeError,
                match="^Query fields cannot be resolved."
                r" Introspection result missing field args: {'name': 'foo', .*}\.$",
            ):
                build_client_schema(introspection)

        def throws_when_output_type_is_used_as_an_arg_type():
            introspection = introspection_from_schema(dummy_schema)
            query_type_introspection = cast(
                IntrospectionObjectType,
                next(
                    type_
                    for type_ in introspection["__schema"]["types"]
                    if type_["name"] == "Query"
                ),
            )

            arg = query_type_introspection["fields"][0]["args"][0]
            assert arg["type"]["name"] == "String"
            arg["type"]["name"] = "SomeUnion"

            with raises(TypeError) as exc_info:
                build_client_schema(introspection)

            assert str(exc_info.value).startswith(
                "Query fields cannot be resolved."
                " Introspection must provide input type for arguments,"
                " but received: SomeUnion."
            )

        def throws_when_output_type_is_used_as_an_input_value_type():
            introspection = introspection_from_schema(dummy_schema)
            input_object_type_introspection = cast(
                IntrospectionInputObjectType,
                next(
                    type_
                    for type_ in introspection["__schema"]["types"]
                    if type_["name"] == "SomeInputObject"
                ),
            )

            input_field = input_object_type_introspection["inputFields"][0]
            assert input_field["type"]["name"] == "String"
            input_field["type"]["name"] = "SomeUnion"

            with raises(TypeError) as exc_info:
                build_client_schema(introspection)

            assert str(exc_info.value).startswith(
                "SomeInputObject fields cannot be resolved."
                " Introspection must provide input type for input fields,"
                " but received: SomeUnion."
            )

        def throws_when_input_type_is_used_as_a_field_type():
            introspection = introspection_from_schema(dummy_schema)
            query_type_introspection = cast(
                IntrospectionObjectType,
                next(
                    type_
                    for type_ in introspection["__schema"]["types"]
                    if type_["name"] == "Query"
                ),
            )

            field = query_type_introspection["fields"][0]
            assert field["type"]["name"] == "String"
            field["type"]["name"] = "SomeInputObject"

            with raises(TypeError) as exc_info:
                build_client_schema(introspection)

            assert str(exc_info.value).startswith(
                "Query fields cannot be resolved."
                " Introspection must provide output type for fields,"
                " but received: SomeInputObject."
            )

        def throws_when_missing_possible_types():
            introspection = introspection_from_schema(dummy_schema)
            some_union_introspection = cast(
                IntrospectionUnionType,
                next(
                    type_
                    for type_ in introspection["__schema"]["types"]
                    if type_["name"] == "SomeUnion"
                ),
            )

            assert some_union_introspection["possibleTypes"]
            del some_union_introspection["possibleTypes"]  # type: ignore

            with raises(
                TypeError,
                match="^Introspection result missing possibleTypes:"
                r" {'kind': 'UNION', 'name': 'SomeUnion', .*}\.$",
            ):
                build_client_schema(introspection)

        def throws_when_missing_enum_values():
            introspection = introspection_from_schema(dummy_schema)
            some_enum_introspection = cast(
                IntrospectionEnumType,
                next(
                    type_
                    for type_ in introspection["__schema"]["types"]
                    if type_["name"] == "SomeEnum"
                ),
            )

            assert some_enum_introspection["enumValues"]
            del some_enum_introspection["enumValues"]  # type: ignore

            with raises(
                TypeError,
                match="^Introspection result missing enumValues:"
                r" {'kind': 'ENUM', 'name': 'SomeEnum', .*}\.$",
            ):
                build_client_schema(introspection)

        def throws_when_missing_input_fields():
            introspection = introspection_from_schema(dummy_schema)
            some_input_object_introspection = cast(
                IntrospectionInputObjectType,
                next(
                    type_
                    for type_ in introspection["__schema"]["types"]
                    if type_["name"] == "SomeInputObject"
                ),
            )

            assert some_input_object_introspection["inputFields"]
            del some_input_object_introspection["inputFields"]  # type: ignore

            with raises(
                TypeError,
                match="^Introspection result missing inputFields:"
                r" {'kind': 'INPUT_OBJECT', 'name': 'SomeInputObject', .*}\.$",
            ):
                build_client_schema(introspection)

        def throws_when_missing_directive_locations():
            introspection = introspection_from_schema(dummy_schema)
            some_directive_introspection = introspection["__schema"]["directives"][0]

            assert some_directive_introspection["name"] == "SomeDirective"
            assert some_directive_introspection["locations"] == ["QUERY"]
            del some_directive_introspection["locations"]  # type: ignore

            with raises(
                TypeError,
                match="^Introspection result missing directive locations:"
                r" {'name': 'SomeDirective', .*}\.$",
            ):
                build_client_schema(introspection)

        def throws_when_missing_directive_args():
            introspection = introspection_from_schema(dummy_schema)
            some_directive_introspection = introspection["__schema"]["directives"][0]

            assert some_directive_introspection["name"] == "SomeDirective"
            assert some_directive_introspection["args"] == []
            del some_directive_introspection["args"]  # type: ignore

            with raises(
                TypeError,
                match="^Introspection result missing directive args:"
                r" {'name': 'SomeDirective', .*}\.$",
            ):
                build_client_schema(introspection)

    def describe_very_deep_decorators_are_not_supported():
        def fails_on_very_deep_lists_more_than_8_levels():
            schema = build_schema(
                """
                type Query {
                  foo: [[[[[[[[[[String]]]]]]]]]]
                }
                """
            )

            introspection = introspection_from_schema(schema)

            with raises(TypeError) as exc_info:
                build_client_schema(introspection)

            assert str(exc_info.value) == (
                "Query fields cannot be resolved."
                " Decorated type deeper than introspection query."
            )

        def fails_on_a_very_deep_non_null_more_than_8_levels():
            schema = build_schema(
                """
                type Query {
                  foo: [[[[[String!]!]!]!]!]
                }
                """
            )

            introspection = introspection_from_schema(schema)

            with raises(TypeError) as exc_info:
                build_client_schema(introspection)

            assert str(exc_info.value) == (
                "Query fields cannot be resolved."
                " Decorated type deeper than introspection query."
            )

        def succeeds_on_deep_types_less_or_equal_8_levels():
            # e.g., fully non-null 4D matrix
            sdl = dedent(
                """
                type Query {
                  foo: [[[[String!]!]!]!]!
                }
                """
            )

            assert cycle_introspection(sdl) == sdl

    def describe_prevents_infinite_recursion_on_invalid_introspection():
        def recursive_interfaces():
            sdl = """
                type Query {
                  foo: Foo
                }

                type Foo {
                  foo: String
                }
                """
            schema = build_schema(sdl, assume_valid=True)
            introspection = introspection_from_schema(schema)
            foo_introspection = cast(
                IntrospectionObjectType,
                next(
                    type_
                    for type_ in introspection["__schema"]["types"]
                    if type_["name"] == "Foo"
                ),
            )

            assert foo_introspection["interfaces"] == []
            # we need to patch here since invalid interfaces cannot be built with Python
            foo_introspection["interfaces"] = [
                {"kind": "OBJECT", "name": "Foo", "ofType": None}
            ]

            with raises(TypeError) as exc_info:
                build_client_schema(introspection)
            assert str(exc_info.value) == (
                "Foo interfaces cannot be resolved."
                " Expected Foo to be a GraphQL Interface type."
            )

        def recursive_union():
            sdl = """
                type Query {
                  foo: Foo
                }

                union Foo
                """
            schema = build_schema(sdl, assume_valid=True)
            introspection = introspection_from_schema(schema)
            foo_introspection = next(
                type_
                for type_ in introspection["__schema"]["types"]
                if type_["name"] == "Foo"
            )

            assert foo_introspection["kind"] == "UNION"
            assert foo_introspection["possibleTypes"] == []
            # we need to patch here since invalid unions cannot be built with Python
            foo_introspection["possibleTypes"] = [
                {"kind": "UNION", "name": "Foo", "ofType": None}
            ]

            with raises(TypeError) as exc_info:
                build_client_schema(introspection)
            assert str(exc_info.value) == (
                "Foo types cannot be resolved."
                " Expected Foo to be a GraphQL Object type."
            )