Debian Codegraph @

tests/utilities/test_build_ast_schema.py

raw
1 import pickle
2 import sys
3 from collections import namedtuple
4 from copy import deepcopy
5 from typing import Union
6
7 from pytest import mark, raises
8
9 from graphql import graphql_sync
10 from graphql.language import DocumentNode, InterfaceTypeDefinitionNode, parse, print_ast
11 from graphql.type import (
12 GraphQLArgument,
13 GraphQLBoolean,
14 GraphQLDeprecatedDirective,
15 GraphQLEnumType,
16 GraphQLEnumValue,
17 GraphQLField,
18 GraphQLFloat,
19 GraphQLID,
20 GraphQLIncludeDirective,
21 GraphQLInputField,
22 GraphQLInt,
23 GraphQLNamedType,
24 GraphQLSchema,
25 GraphQLSkipDirective,
26 GraphQLSpecifiedByDirective,
27 GraphQLOneOfDirective,
28 GraphQLString,
29 assert_directive,
30 assert_enum_type,
31 assert_input_object_type,
32 assert_interface_type,
33 assert_object_type,
34 assert_scalar_type,
35 assert_union_type,
36 introspection_types,
37 validate_schema,
38 )
39 from graphql.utilities import build_ast_schema, build_schema, print_schema, print_type
40
41 from ..fixtures import big_schema_sdl # noqa: F401
42 from ..star_wars_schema import star_wars_schema
43 from ..utils import dedent, timeout_factor
44
45
46 def cycle_sdl(sdl: str) -> str:
47 """Full cycle test.
48
49 This function does a full cycle of going from a string with the contents of the SDL,
50 parsed in a schema AST, materializing that schema AST into an in-memory
51 GraphQLSchema, and then finally printing that GraphQL into the SDL.
52 """
53 ast = parse(sdl)
54 schema = build_ast_schema(ast)
55 return print_schema(schema)
56
57
58 TypeWithAstNode = Union[
59 GraphQLArgument, GraphQLEnumValue, GraphQLField, GraphQLInputField, GraphQLNamedType
60 ]
61
62 TypeWithExtensionAstNodes = GraphQLNamedType
63
64
65 def expect_ast_node(obj: TypeWithAstNode, expected: str) -> None:
66 assert obj is not None and obj.ast_node is not None
67 assert print_ast(obj.ast_node) == expected
68
69
70 def expect_extension_ast_nodes(obj: TypeWithExtensionAstNodes, expected: str) -> None:
71 assert obj is not None and obj.extension_ast_nodes is not None
72 assert "\n\n".join(print_ast(node) for node in obj.extension_ast_nodes) == expected
73
74
75 def describe_schema_builder():
76 def can_use_built_schema_for_limited_execution():
77 schema = build_ast_schema(parse("""
78 type Query {
79 str: String
80 }
81 """))
82
83 root_value = namedtuple("Data", "str")(123) # type: ignore
84
85 result = graphql_sync(schema=schema, source="{ str }", root_value=root_value)
86 assert result == ({"str": "123"}, None)
87
88 def can_build_a_schema_directly_from_the_source():
89 schema = build_schema("""
90 type Query {
91 add(x: Int, y: Int): Int
92 }
93 """)
94 source = "{ add(x: 34, y: 55) }"
95
96 # noinspection PyMethodMayBeStatic
97 class RootValue:
98 def add(self, _info, x, y):
99 return x + y
100
101 assert graphql_sync(schema=schema, source=source, root_value=RootValue()) == (
102 {"add": 89},
103 None,
104 )
105
106 def ignores_non_type_system_definitions():
107 sdl = """
108 type Query {
109 str: String
110 }
111
112 fragment SomeFragment on Query {
113 str
114 }
115 """
116 build_schema(sdl)
117
118 def match_order_of_default_types_and_directives():
119 schema = GraphQLSchema()
120 sdl_schema = build_ast_schema(DocumentNode(definitions=[]))
121
122 assert sdl_schema.directives == schema.directives
123 assert sdl_schema.type_map == schema.type_map
124
125 def empty_type():
126 sdl = dedent("""
127 type EmptyType
128 """)
129 assert cycle_sdl(sdl) == sdl
130
131 def simple_type():
132 sdl = dedent("""
133 type Query {
134 str: String
135 int: Int
136 float: Float
137 id: ID
138 bool: Boolean
139 }
140 """)
141 assert cycle_sdl(sdl) == sdl
142
143 schema = build_schema(sdl)
144 # Built-ins are used
145 assert schema.get_type("Int") is GraphQLInt
146 assert schema.get_type("Float") is GraphQLFloat
147 assert schema.get_type("String") is GraphQLString
148 assert schema.get_type("Boolean") is GraphQLBoolean
149 assert schema.get_type("ID") is GraphQLID
150
151 def include_standard_type_only_if_it_is_used():
152 schema = build_schema("type Query")
153
154 # Only String and Boolean are used by introspection types
155 assert schema.get_type("Int") is None
156 assert schema.get_type("Float") is None
157 assert schema.get_type("String") is GraphQLString
158 assert schema.get_type("Boolean") is GraphQLBoolean
159 assert schema.get_type("ID") is None
160
161 def with_directives():
162 sdl = dedent("""
163 directive @foo(arg: Int) on FIELD
164
165 directive @repeatableFoo(arg: Int) repeatable on FIELD
166 """)
167 assert cycle_sdl(sdl) == sdl
168
169 def supports_descriptions():
170 sdl = dedent('''
171 """Do you agree that this is the most creative schema ever?"""
172 schema {
173 query: Query
174 }
175
176 """This is a directive"""
177 directive @foo(
178 """It has an argument"""
179 arg: Int
180 ) on FIELD
181
182 """Who knows what's inside this scalar?"""
183 scalar MysteryScalar
184
185 """This is an input object type"""
186 input FooInput {
187 """It has a field"""
188 field: Int
189 }
190
191 """This is an interface type"""
192 interface Energy {
193 """It also has a field"""
194 str: String
195 }
196
197 """There is nothing inside!"""
198 union BlackHole
199
200 """With an enum"""
201 enum Color {
202 RED
203
204 """Not a creative color"""
205 GREEN
206 BLUE
207 }
208
209 """What a great type"""
210 type Query {
211 """And a field to boot"""
212 str: String
213 }
214 ''')
215 assert cycle_sdl(sdl) == sdl
216
217 def maintains_include_skip_and_specified_by_url_directives():
218 schema = build_schema("type Query")
219
220 assert len(schema.directives) == 5
221 assert schema.get_directive("skip") is GraphQLSkipDirective
222 assert schema.get_directive("include") is GraphQLIncludeDirective
223 assert schema.get_directive("deprecated") is GraphQLDeprecatedDirective
224 assert schema.get_directive("specifiedBy") is GraphQLSpecifiedByDirective
225 assert schema.get_directive("oneOf") is GraphQLOneOfDirective
226
227 def overriding_directives_excludes_specified():
228 schema = build_schema("""
229 directive @skip on FIELD
230 directive @include on FIELD
231 directive @deprecated on FIELD_DEFINITION
232 directive @specifiedBy on FIELD_DEFINITION
233 directive @oneOf on OBJECT
234 """)
235
236 assert len(schema.directives) == 5
237 get_directive = schema.get_directive
238 assert get_directive("skip") is not GraphQLSkipDirective
239 assert get_directive("skip") is not None
240 assert get_directive("include") is not GraphQLIncludeDirective
241 assert get_directive("include") is not None
242 assert get_directive("deprecated") is not GraphQLDeprecatedDirective
243 assert get_directive("deprecated") is not None
244 assert get_directive("specifiedBy") is not GraphQLSpecifiedByDirective
245 assert get_directive("specifiedBy") is not None
246 assert get_directive("oneOf") is not GraphQLOneOfDirective
247 assert get_directive("oneOf") is not None
248
249 def adding_directives_maintains_include_skip_and_three_other_directives():
250 schema = build_schema("""
251 directive @foo(arg: Int) on FIELD
252 """)
253
254 assert len(schema.directives) == 6
255 assert schema.get_directive("skip") is GraphQLSkipDirective
256 assert schema.get_directive("include") is GraphQLIncludeDirective
257 assert schema.get_directive("deprecated") is GraphQLDeprecatedDirective
258 assert schema.get_directive("specifiedBy") is GraphQLSpecifiedByDirective
259 assert schema.get_directive("oneOf") is GraphQLOneOfDirective
260 assert schema.get_directive("foo") is not None
261
262 def type_modifiers():
263 sdl = dedent("""
264 type Query {
265 nonNullStr: String!
266 listOfStrings: [String]
267 listOfNonNullStrings: [String!]
268 nonNullListOfStrings: [String]!
269 nonNullListOfNonNullStrings: [String!]!
270 }
271 """)
272 assert cycle_sdl(sdl) == sdl
273
274 def recursive_type():
275 sdl = dedent("""
276 type Query {
277 str: String
278 recurse: Query
279 }
280 """)
281 assert cycle_sdl(sdl) == sdl
282
283 def two_types_circular():
284 sdl = dedent("""
285 type TypeOne {
286 str: String
287 typeTwo: TypeTwo
288 }
289
290 type TypeTwo {
291 str: String
292 typeOne: TypeOne
293 }
294 """)
295 assert cycle_sdl(sdl) == sdl
296
297 def single_argument_field():
298 sdl = dedent("""
299 type Query {
300 str(int: Int): String
301 floatToStr(float: Float): String
302 idToStr(id: ID): String
303 booleanToStr(bool: Boolean): String
304 strToStr(bool: String): String
305 }
306 """)
307 assert cycle_sdl(sdl) == sdl
308
309 def simple_type_with_multiple_arguments():
310 sdl = dedent("""
311 type Query {
312 str(int: Int, bool: Boolean): String
313 }
314 """)
315 assert cycle_sdl(sdl) == sdl
316
317 def empty_interface():
318 sdl = dedent("""
319 interface EmptyInterface
320 """)
321
322 definition = parse(sdl).definitions[0]
323 assert isinstance(definition, InterfaceTypeDefinitionNode)
324 assert definition.interfaces == ()
325
326 assert cycle_sdl(sdl) == sdl
327
328 def simple_type_with_interface():
329 sdl = dedent("""
330 type Query implements WorldInterface {
331 str: String
332 }
333
334 interface WorldInterface {
335 str: String
336 }
337 """)
338 assert cycle_sdl(sdl) == sdl
339
340 def simple_interface_hierarchy():
341 sdl = dedent("""
342 schema {
343 query: Child
344 }
345
346 interface Child implements Parent {
347 str: String
348 }
349
350 type Hello implements Parent & Child {
351 str: String
352 }
353
354 interface Parent {
355 str: String
356 }
357 """)
358 assert cycle_sdl(sdl) == sdl
359
360 def empty_enum():
361 sdl = dedent("""
362 enum EmptyEnum
363 """)
364 assert cycle_sdl(sdl) == sdl
365
366 def simple_output_enum():
367 sdl = dedent("""
368 enum Hello {
369 WORLD
370 }
371
372 type Query {
373 hello: Hello
374 }
375 """)
376 assert cycle_sdl(sdl) == sdl
377
378 def simple_input_enum():
379 sdl = dedent("""
380 enum Hello {
381 WORLD
382 }
383
384 type Query {
385 str(hello: Hello): String
386 }
387 """)
388 assert cycle_sdl(sdl) == sdl
389
390 def multiple_value_enum():
391 sdl = dedent("""
392 enum Hello {
393 WO
394 RLD
395 }
396
397 type Query {
398 hello: Hello
399 }
400 """)
401 assert cycle_sdl(sdl) == sdl
402
403 # check that the internal values are the same as the names
404 schema = build_schema(sdl)
405 enum_type = schema.get_type("Hello")
406 assert isinstance(enum_type, GraphQLEnumType)
407 assert [value.value for value in enum_type.values.values()] == ["WO", "RLD"]
408
409 def empty_union():
410 sdl = dedent("""
411 union EmptyUnion
412 """)
413 assert cycle_sdl(sdl) == sdl
414
415 def simple_union():
416 sdl = dedent("""
417 union Hello = World
418
419 type Query {
420 hello: Hello
421 }
422
423 type World {
424 str: String
425 }
426 """)
427 assert cycle_sdl(sdl) == sdl
428
429 def multiple_union():
430 sdl = dedent("""
431 union Hello = WorldOne | WorldTwo
432
433 type Query {
434 hello: Hello
435 }
436
437 type WorldOne {
438 str: String
439 }
440
441 type WorldTwo {
442 str: String
443 }
444 """)
445 assert cycle_sdl(sdl) == sdl
446
447 def can_build_recursive_union():
448 # invalid schema cannot be built with Python
449 with raises(TypeError) as exc_info:
450 build_schema("""
451 union Hello = Hello
452
453 type Query {
454 hello: Hello
455 }
456 """)
457 assert (
458 str(exc_info.value) == "Hello types must be specified"
459 " as a collection of GraphQLObjectType instances."
460 )
461
462 def custom_scalar():
463 sdl = dedent("""
464 scalar CustomScalar
465
466 type Query {
467 customScalar: CustomScalar
468 }
469 """)
470 assert cycle_sdl(sdl) == sdl
471
472 def empty_input_object():
473 sdl = dedent("""
474 input EmptyInputObject
475 """)
476 assert cycle_sdl(sdl) == sdl
477
478 def simple_input_object():
479 sdl = dedent("""
480 input Input {
481 int: Int
482 }
483
484 type Query {
485 field(in: Input): String
486 }
487 """)
488 assert cycle_sdl(sdl) == sdl
489
490 def simple_argument_field_with_default():
491 sdl = dedent("""
492 type Query {
493 str(int: Int = 2): String
494 }
495 """)
496 assert cycle_sdl(sdl) == sdl
497
498 def custom_scalar_argument_field_with_default():
499 sdl = dedent("""
500 scalar CustomScalar
501
502 type Query {
503 str(int: CustomScalar = 2): String
504 }
505 """)
506 assert cycle_sdl(sdl) == sdl
507
508 def simple_type_with_mutation():
509 sdl = dedent("""
510 schema {
511 query: HelloScalars
512 mutation: Mutation
513 }
514
515 type HelloScalars {
516 str: String
517 int: Int
518 bool: Boolean
519 }
520
521 type Mutation {
522 addHelloScalars(str: String, int: Int, bool: Boolean): HelloScalars
523 }
524 """)
525 assert cycle_sdl(sdl) == sdl
526
527 def simple_type_with_subscription():
528 sdl = dedent("""
529 schema {
530 query: HelloScalars
531 subscription: Subscription
532 }
533
534 type HelloScalars {
535 str: String
536 int: Int
537 bool: Boolean
538 }
539
540 type Subscription {
541 subscribeHelloScalars(str: String, int: Int, bool: Boolean): HelloScalars
542 }
543 """)
544 assert cycle_sdl(sdl) == sdl
545
546 def unreferenced_type_implementing_referenced_interface():
547 sdl = dedent("""
548 type Concrete implements Interface {
549 key: String
550 }
551
552 interface Interface {
553 key: String
554 }
555
556 type Query {
557 interface: Interface
558 }
559 """)
560 assert cycle_sdl(sdl) == sdl
561
562 def unreferenced_interface_implementing_referenced_interface():
563 sdl = dedent("""
564 interface Child implements Parent {
565 key: String
566 }
567
568 interface Parent {
569 key: String
570 }
571
572 type Query {
573 interfaceField: Parent
574 }
575 """)
576 assert cycle_sdl(sdl) == sdl
577
578 def unreferenced_type_implementing_referenced_union():
579 sdl = dedent("""
580 type Concrete {
581 key: String
582 }
583
584 type Query {
585 union: Union
586 }
587
588 union Union = Concrete
589 """)
590 assert cycle_sdl(sdl) == sdl
591
592 def supports_deprecated_directive():
593 sdl = dedent("""
594 enum MyEnum {
595 VALUE
596 OLD_VALUE @deprecated
597 OTHER_VALUE @deprecated(reason: "Terrible reasons")
598 }
599
600 input MyInput {
601 oldInput: String @deprecated
602 otherInput: String @deprecated(reason: "Use newInput")
603 newInput: String
604 }
605
606 type Query {
607 field1: String @deprecated
608 field2: Int @deprecated(reason: "Because I said so")
609 enum: MyEnum
610 field3(oldArg: String @deprecated, arg: String): String
611 field4(oldArg: String @deprecated(reason: "Why not?"), arg: String): String
612 field5(arg: MyInput): String
613 }
614 """) # noqa: E501
615 assert cycle_sdl(sdl) == sdl
616
617 schema = build_schema(sdl)
618
619 my_enum = assert_enum_type(schema.get_type("MyEnum"))
620
621 value = my_enum.values["VALUE"]
622 assert value.deprecation_reason is None
623
624 old_value = my_enum.values["OLD_VALUE"]
625 assert old_value.deprecation_reason == "No longer supported"
626
627 other_value = my_enum.values["OTHER_VALUE"]
628 assert other_value.deprecation_reason == "Terrible reasons"
629
630 root_fields = assert_object_type(schema.get_type("Query")).fields
631 field1 = root_fields["field1"]
632 assert field1.deprecation_reason == "No longer supported"
633 field2 = root_fields["field2"]
634 assert field2.deprecation_reason == "Because I said so"
635
636 input_fields = assert_input_object_type(schema.get_type("MyInput")).fields
637
638 new_input = input_fields["newInput"]
639 assert new_input.deprecation_reason is None
640
641 old_input = input_fields["oldInput"]
642 assert old_input.deprecation_reason == "No longer supported"
643
644 other_input = input_fields["otherInput"]
645 assert other_input.deprecation_reason == "Use newInput"
646
647 field3_old_arg = root_fields["field3"].args["oldArg"]
648 assert field3_old_arg.deprecation_reason == "No longer supported"
649
650 field4_old_arg = root_fields["field4"].args["oldArg"]
651 assert field4_old_arg.deprecation_reason == "Why not?"
652
653 def supports_specified_by_directives():
654 sdl = dedent("""
655 scalar Foo @specifiedBy(url: "https://example.com/foo_spec")
656
657 type Query {
658 foo: Foo @deprecated
659 }
660 """)
661 assert cycle_sdl(sdl) == sdl
662
663 schema = build_schema(sdl)
664
665 foo_scalar = assert_scalar_type(schema.get_type("Foo"))
666 assert foo_scalar.specified_by_url == "https://example.com/foo_spec"
667
668 def correctly_extend_scalar_type():
669 schema = build_schema("""
670 scalar SomeScalar
671 extend scalar SomeScalar @foo
672 extend scalar SomeScalar @bar
673
674 directive @foo on SCALAR
675 directive @bar on SCALAR
676 """)
677
678 some_scalar = assert_scalar_type(schema.get_type("SomeScalar"))
679 assert print_type(some_scalar) == dedent("""
680 scalar SomeScalar
681 """)
682
683 expect_ast_node(some_scalar, "scalar SomeScalar")
684 expect_extension_ast_nodes(
685 some_scalar,
686 dedent("""
687 extend scalar SomeScalar @foo
688
689 extend scalar SomeScalar @bar
690 """),
691 )
692
693 def correctly_extend_object_type():
694 schema = build_schema("""
695 type SomeObject implements Foo {
696 first: String
697 }
698
699 extend type SomeObject implements Bar {
700 second: Int
701 }
702
703 extend type SomeObject implements Baz {
704 third: Float
705 }
706
707 interface Foo
708 interface Bar
709 interface Baz
710 """)
711
712 some_object = assert_object_type(schema.get_type("SomeObject"))
713 assert print_type(some_object) == dedent("""
714 type SomeObject implements Foo & Bar & Baz {
715 first: String
716 second: Int
717 third: Float
718 }
719 """)
720
721 expect_ast_node(
722 some_object,
723 dedent("""
724 type SomeObject implements Foo {
725 first: String
726 }
727 """),
728 )
729 expect_extension_ast_nodes(
730 some_object,
731 dedent("""
732 extend type SomeObject implements Bar {
733 second: Int
734 }
735
736 extend type SomeObject implements Baz {
737 third: Float
738 }
739 """),
740 )
741
742 def correctly_extend_interface_type():
743 schema = build_schema("""
744 interface SomeInterface {
745 first: String
746 }
747
748 extend interface SomeInterface {
749 second: Int
750 }
751
752 extend interface SomeInterface {
753 third: Float
754 }
755 """)
756
757 some_interface = assert_interface_type(schema.get_type("SomeInterface"))
758 assert print_type(some_interface) == dedent("""
759 interface SomeInterface {
760 first: String
761 second: Int
762 third: Float
763 }
764 """)
765
766 expect_ast_node(
767 some_interface,
768 dedent("""
769 interface SomeInterface {
770 first: String
771 }
772 """),
773 )
774 expect_extension_ast_nodes(
775 some_interface,
776 dedent("""
777 extend interface SomeInterface {
778 second: Int
779 }
780
781 extend interface SomeInterface {
782 third: Float
783 }
784 """),
785 )
786
787 def correctly_extend_union_type():
788 schema = build_schema("""
789 union SomeUnion = FirstType
790 extend union SomeUnion = SecondType
791 extend union SomeUnion = ThirdType
792
793 type FirstType
794 type SecondType
795 type ThirdType
796 """)
797
798 some_union = assert_union_type(schema.get_type("SomeUnion"))
799 assert print_type(some_union) == dedent("""
800 union SomeUnion = FirstType | SecondType | ThirdType
801 """)
802
803 expect_ast_node(some_union, "union SomeUnion = FirstType")
804 expect_extension_ast_nodes(
805 some_union,
806 dedent("""
807 extend union SomeUnion = SecondType
808
809 extend union SomeUnion = ThirdType
810 """),
811 )
812
813 def correctly_extend_enum_type():
814 schema = build_schema("""
815 enum SomeEnum {
816 FIRST
817 }
818
819 extend enum SomeEnum {
820 SECOND
821 }
822
823 extend enum SomeEnum {
824 THIRD
825 }
826 """)
827
828 some_enum = assert_enum_type(schema.get_type("SomeEnum"))
829 assert print_type(some_enum) == dedent("""
830 enum SomeEnum {
831 FIRST
832 SECOND
833 THIRD
834 }
835 """)
836
837 expect_ast_node(
838 some_enum,
839 dedent("""
840 enum SomeEnum {
841 FIRST
842 }
843 """),
844 )
845 expect_extension_ast_nodes(
846 some_enum,
847 dedent("""
848 extend enum SomeEnum {
849 SECOND
850 }
851
852 extend enum SomeEnum {
853 THIRD
854 }
855 """),
856 )
857
858 def correctly_extend_input_object_type():
859 schema = build_schema("""
860 input SomeInput {
861 first: String
862 }
863
864 extend input SomeInput {
865 second: Int
866 }
867
868 extend input SomeInput {
869 third: Float
870 }
871 """)
872
873 some_input = assert_input_object_type(schema.get_type("SomeInput"))
874 assert print_type(some_input) == dedent("""
875 input SomeInput {
876 first: String
877 second: Int
878 third: Float
879 }
880 """)
881
882 expect_ast_node(
883 some_input,
884 dedent("""
885 input SomeInput {
886 first: String
887 }
888 """),
889 )
890 expect_extension_ast_nodes(
891 some_input,
892 dedent("""
893 extend input SomeInput {
894 second: Int
895 }
896
897 extend input SomeInput {
898 third: Float
899 }
900 """),
901 )
902
903 def correctly_assign_ast_nodes():
904 sdl = dedent("""
905 schema {
906 query: Query
907 }
908
909 type Query {
910 testField(testArg: TestInput): TestUnion
911 }
912
913 input TestInput {
914 testInputField: TestEnum
915 }
916
917 enum TestEnum {
918 TEST_VALUE
919 }
920
921 union TestUnion = TestType
922
923 interface TestInterface {
924 interfaceField: String
925 }
926
927 type TestType implements TestInterface {
928 interfaceField: String
929 }
930
931 scalar TestScalar
932
933 directive @test(arg: TestScalar) on FIELD
934 """)
935 ast = parse(sdl, no_location=True)
936
937 schema = build_ast_schema(ast)
938 query = assert_object_type(schema.get_type("Query"))
939 test_input = assert_input_object_type(schema.get_type("TestInput"))
940 test_enum = assert_enum_type(schema.get_type("TestEnum"))
941 test_union = assert_union_type(schema.get_type("TestUnion"))
942 test_interface = assert_interface_type(schema.get_type("TestInterface"))
943 test_type = assert_object_type(schema.get_type("TestType"))
944 test_scalar = assert_scalar_type(schema.get_type("TestScalar"))
945 test_directive = assert_directive(schema.get_directive("test"))
946
947 assert (
948 schema.ast_node,
949 query.ast_node,
950 test_input.ast_node,
951 test_enum.ast_node,
952 test_union.ast_node,
953 test_interface.ast_node,
954 test_type.ast_node,
955 test_scalar.ast_node,
956 test_directive.ast_node,
957 ) == ast.definitions
958
959 test_field = query.fields["testField"]
960 expect_ast_node(test_field, "testField(testArg: TestInput): TestUnion")
961 expect_ast_node(test_field.args["testArg"], "testArg: TestInput")
962 expect_ast_node(test_input.fields["testInputField"], "testInputField: TestEnum")
963 test_enum_value = test_enum.values["TEST_VALUE"]
964 expect_ast_node(test_enum_value, "TEST_VALUE")
965 expect_ast_node(
966 test_interface.fields["interfaceField"], "interfaceField: String"
967 )
968 expect_ast_node(test_directive.args["arg"], "arg: TestScalar")
969
970 def root_operation_types_with_custom_names():
971 schema = build_schema("""
972 schema {
973 query: SomeQuery
974 mutation: SomeMutation
975 subscription: SomeSubscription
976 }
977 type SomeQuery
978 type SomeMutation
979 type SomeSubscription
980 """)
981
982 assert schema.query_type
983 assert schema.query_type.name == "SomeQuery"
984 assert schema.mutation_type
985 assert schema.mutation_type.name == "SomeMutation"
986 assert schema.subscription_type
987 assert schema.subscription_type.name == "SomeSubscription"
988
989 def default_root_operation_type_names():
990 schema = build_schema("""
991 type Query
992 type Mutation
993 type Subscription
994 """)
995
996 assert schema.query_type
997 assert schema.query_type.name == "Query"
998 assert schema.mutation_type
999 assert schema.mutation_type.name == "Mutation"
1000 assert schema.subscription_type
1001 assert schema.subscription_type.name == "Subscription"
1002
1003 def can_build_invalid_schema():
1004 # Invalid schema, because it is missing query root type
1005 schema = build_schema("type Mutation")
1006 errors = validate_schema(schema)
1007 assert errors
1008
1009 def do_not_override_standard_types():
1010 # Note: not sure it's desired behavior to just silently ignore override
1011 # attempts so just documenting it here.
1012
1013 schema = build_schema("""
1014 scalar ID
1015
1016 scalar __Schema
1017 """)
1018
1019 assert schema.get_type("ID") is GraphQLID
1020 assert schema.get_type("__Schema") is introspection_types["__Schema"]
1021
1022 def allows_to_reference_introspection_types():
1023 schema = build_schema("""
1024 type Query {
1025 introspectionField: __EnumValue
1026 }
1027 """)
1028
1029 query_type = assert_object_type(schema.get_type("Query"))
1030 __EnumValue = introspection_types["__EnumValue"]
1031 assert query_type.fields["introspectionField"].type is __EnumValue
1032 assert schema.get_type("__EnumValue") is introspection_types["__EnumValue"]
1033
1034 def rejects_invalid_sdl():
1035 sdl = """
1036 type Query {
1037 foo: String @unknown
1038 }
1039 """
1040 with raises(TypeError) as exc_info:
1041 build_schema(sdl)
1042 assert str(exc_info.value) == "Unknown directive '@unknown'."
1043
1044 def allows_to_disable_sdl_validation():
1045 sdl = """
1046 type Query {
1047 foo: String @unknown
1048 }
1049 """
1050 build_schema(sdl, assume_valid=True)
1051 build_schema(sdl, assume_valid_sdl=True)
1052
1053 def forwards_parser_options_to_build_schema():
1054 schema = build_schema(
1055 """
1056 type Query {
1057 foo: String
1058 }
1059
1060 directive @bar @deprecated(reason: "Use another directive") on FIELD_DEFINITION
1061 """,
1062 experimental_directives_on_directive_definitions=True,
1063 )
1064
1065 bar_directive = assert_directive(schema.get_directive("bar"))
1066 assert bar_directive.deprecation_reason == "Use another directive"
1067
1068 def throws_on_unknown_types():
1069 sdl = """
1070 type Query {
1071 unknown: UnknownType
1072 }
1073 """
1074 with raises(TypeError) as exc_info:
1075 build_schema(sdl, assume_valid_sdl=True)
1076 assert str(exc_info.value).endswith("Unknown type: 'UnknownType'.")
1077
1078 def rejects_invalid_ast():
1079 with raises(TypeError) as exc_info:
1080 build_ast_schema(None) # type: ignore
1081 assert str(exc_info.value) == "Must provide valid Document AST."
1082 with raises(TypeError) as exc_info:
1083 build_ast_schema({}) # type: ignore
1084 assert str(exc_info.value) == "Must provide valid Document AST."
1085
1086 def describe_deepcopy_and_pickle(): # pragma: no cover
1087 sdl = print_schema(star_wars_schema)
1088
1089 def can_deep_copy_schema():
1090 schema = build_schema(sdl, assume_valid_sdl=True)
1091 # create a deepcopy of the schema
1092 copied = deepcopy(schema)
1093 # check that printing the copied schema gives the same SDL
1094 assert print_schema(copied) == sdl
1095
1096 def can_pickle_and_unpickle_star_wars_schema():
1097 # create a schema from the star wars SDL
1098 schema = build_schema(sdl, assume_valid_sdl=True)
1099 # check that the schema can be pickled
1100 # (particularly, there should be no recursion error,
1101 # or errors because of trying to pickle lambdas or local functions)
1102 dumped = pickle.dumps(schema)
1103
1104 # check that the pickle size is reasonable
1105 assert len(dumped) < 25 * len(sdl)
1106 loaded = pickle.loads(dumped)
1107
1108 # check that printing the unpickled schema gives the same SDL
1109 assert print_schema(loaded) == sdl
1110
1111 # check that pickling again creates the same result
1112 dumped = pickle.dumps(schema)
1113 assert len(dumped) < 25 * len(sdl)
1114 loaded = pickle.loads(dumped)
1115 assert print_schema(loaded) == sdl
1116
1117 def can_deep_copy_pickled_schema():
1118 # create a schema from the star wars SDL
1119 schema = build_schema(sdl, assume_valid_sdl=True)
1120 # pickle and unpickle the schema
1121 loaded = pickle.loads(pickle.dumps(schema))
1122 # create a deepcopy of the unpickled schema
1123 copied = deepcopy(loaded)
1124 # check that printing the copied schema gives the same SDL
1125 assert print_schema(copied) == sdl
1126
1127 @mark.slow
1128 def describe_deepcopy_and_pickle_big(): # pragma: no cover
1129 @mark.timeout(20 * timeout_factor)
1130 def can_deep_copy_big_schema(big_schema_sdl): # noqa: F811
1131 # use our printing conventions
1132 big_schema_sdl = cycle_sdl(big_schema_sdl)
1133
1134 # create a schema from the big SDL
1135 schema = build_schema(big_schema_sdl, assume_valid_sdl=True)
1136 # create a deepcopy of the schema
1137 copied = deepcopy(schema)
1138 # check that printing the copied schema gives the same SDL
1139 assert print_schema(copied) == big_schema_sdl
1140
1141 @mark.timeout(60 * timeout_factor)
1142 def can_pickle_and_unpickle_big_schema(big_schema_sdl): # noqa: F811
1143 # use our printing conventions
1144 big_schema_sdl = cycle_sdl(big_schema_sdl)
1145
1146 limit = sys.getrecursionlimit()
1147 sys.setrecursionlimit(max(limit, 4000)) # needed for pickle
1148
1149 try:
1150 # create a schema from the big SDL
1151 schema = build_schema(big_schema_sdl, assume_valid_sdl=True)
1152 # check that the schema can be pickled
1153 # (particularly, there should be no recursion error,
1154 # or errors because of trying to pickle lambdas or local functions)
1155 dumped = pickle.dumps(schema)
1156
1157 # check that the pickle size is reasonable
1158 assert len(dumped) < 25 * len(big_schema_sdl)
1159 loaded = pickle.loads(dumped)
1160
1161 # check that printing the unpickled schema gives the same SDL
1162 assert print_schema(loaded) == big_schema_sdl
1163
1164 # check that pickling again creates the same result
1165 dumped = pickle.dumps(schema)
1166 assert len(dumped) < 25 * len(big_schema_sdl)
1167 loaded = pickle.loads(dumped)
1168 assert print_schema(loaded) == big_schema_sdl
1169
1170 finally:
1171 sys.setrecursionlimit(limit)
1172
1173 @mark.timeout(60 * timeout_factor)
1174 def can_deep_copy_pickled_big_schema(big_schema_sdl): # noqa: F811
1175 # use our printing conventions
1176 big_schema_sdl = cycle_sdl(big_schema_sdl)
1177
1178 limit = sys.getrecursionlimit()
1179 sys.setrecursionlimit(max(limit, 4000)) # needed for pickle
1180
1181 try:
1182 # create a schema from the big SDL
1183 schema = build_schema(big_schema_sdl, assume_valid_sdl=True)
1184 # pickle and unpickle the schema
1185 loaded = pickle.loads(pickle.dumps(schema))
1186 # create a deepcopy of the unpickled schema
1187 copied = deepcopy(loaded)
1188 # check that printing the copied schema gives the same SDL
1189 assert print_schema(copied) == big_schema_sdl
1190
1191 finally:
1192 sys.setrecursionlimit(limit)