Debian Codegraph @

tests/utilities/test_print_schema.py

raw
1 from typing import Any, Dict, cast
2
3 from graphql.language import DirectiveLocation
4 from graphql.type import (
5 GraphQLArgument,
6 GraphQLBoolean,
7 GraphQLDirective,
8 GraphQLEnumType,
9 GraphQLField,
10 GraphQLFloat,
11 GraphQLInputField,
12 GraphQLInputObjectType,
13 GraphQLInt,
14 GraphQLInterfaceType,
15 GraphQLList,
16 GraphQLNonNull,
17 GraphQLObjectType,
18 GraphQLScalarType,
19 GraphQLSchema,
20 GraphQLString,
21 GraphQLUnionType,
22 )
23 from graphql.utilities import (
24 build_schema,
25 print_introspection_schema,
26 print_schema,
27 print_value,
28 )
29
30 from ..utils import dedent
31
32
33 def expect_printed_schema(schema: GraphQLSchema) -> str:
34 schema_text = print_schema(schema)
35 # keep print_schema and build_schema in sync
36 assert print_schema(build_schema(schema_text)) == schema_text
37 return schema_text
38
39
40 def build_single_field_schema(field: GraphQLField):
41 query = GraphQLObjectType(name="Query", fields={"singleField": field})
42 return GraphQLSchema(query=query)
43
44
45 def describe_type_system_printer():
46 def prints_string_field():
47 schema = build_single_field_schema(GraphQLField(GraphQLString))
48 assert expect_printed_schema(schema) == dedent("""
49 type Query {
50 singleField: String
51 }
52 """)
53
54 def prints_list_of_string_field():
55 schema = build_single_field_schema(GraphQLField(GraphQLList(GraphQLString)))
56 assert expect_printed_schema(schema) == dedent("""
57 type Query {
58 singleField: [String]
59 }
60 """)
61
62 def prints_non_null_string_field():
63 schema = build_single_field_schema(GraphQLField(GraphQLNonNull(GraphQLString)))
64 assert expect_printed_schema(schema) == dedent("""
65 type Query {
66 singleField: String!
67 }
68 """)
69
70 def prints_non_null_list_of_string_field():
71 schema = build_single_field_schema(
72 GraphQLField(GraphQLNonNull(GraphQLList(GraphQLString)))
73 )
74 assert expect_printed_schema(schema) == dedent("""
75 type Query {
76 singleField: [String]!
77 }
78 """)
79
80 def prints_list_of_non_null_string_field():
81 schema = build_single_field_schema(
82 GraphQLField((GraphQLList(GraphQLNonNull(GraphQLString))))
83 )
84 assert expect_printed_schema(schema) == dedent("""
85 type Query {
86 singleField: [String!]
87 }
88 """)
89
90 def prints_non_null_list_of_non_null_string_field():
91 schema = build_single_field_schema(
92 GraphQLField(GraphQLNonNull(GraphQLList(GraphQLNonNull(GraphQLString))))
93 )
94 assert expect_printed_schema(schema) == dedent("""
95 type Query {
96 singleField: [String!]!
97 }
98 """)
99
100 def prints_object_field():
101 foo_type = GraphQLObjectType(
102 name="Foo", fields={"str": GraphQLField(GraphQLString)}
103 )
104 schema = GraphQLSchema(types=[foo_type])
105
106 assert expect_printed_schema(schema) == dedent("""
107 type Foo {
108 str: String
109 }
110 """)
111
112 def prints_string_field_with_int_arg():
113 schema = build_single_field_schema(
114 GraphQLField(
115 type_=GraphQLString, args={"argOne": GraphQLArgument(GraphQLInt)}
116 )
117 )
118
119 assert expect_printed_schema(schema) == dedent("""
120 type Query {
121 singleField(argOne: Int): String
122 }
123 """)
124
125 def prints_string_field_with_int_arg_with_default():
126 schema = build_single_field_schema(
127 GraphQLField(
128 type_=GraphQLString,
129 args={"argOne": GraphQLArgument(GraphQLInt, default_value=2)},
130 )
131 )
132
133 assert expect_printed_schema(schema) == dedent("""
134 type Query {
135 singleField(argOne: Int = 2): String
136 }
137 """)
138
139 def prints_string_field_with_string_arg_with_default():
140 schema = build_single_field_schema(
141 GraphQLField(
142 type_=GraphQLString,
143 args={
144 "argOne": GraphQLArgument(
145 GraphQLString, default_value="tes\t de\fault"
146 )
147 },
148 )
149 )
150
151 assert expect_printed_schema(schema) == dedent(r"""
152 type Query {
153 singleField(argOne: String = "tes\t de\fault"): String
154 }
155 """)
156
157 def prints_string_field_with_int_arg_with_default_null():
158 schema = build_single_field_schema(
159 GraphQLField(
160 type_=GraphQLString,
161 args={"argOne": GraphQLArgument(GraphQLInt, default_value=None)},
162 )
163 )
164
165 assert expect_printed_schema(schema) == dedent("""
166 type Query {
167 singleField(argOne: Int = null): String
168 }
169 """)
170
171 def prints_string_field_with_non_null_int_arg():
172 schema = build_single_field_schema(
173 GraphQLField(
174 type_=GraphQLString,
175 args={"argOne": GraphQLArgument(GraphQLNonNull(GraphQLInt))},
176 )
177 )
178
179 assert expect_printed_schema(schema) == dedent("""
180 type Query {
181 singleField(argOne: Int!): String
182 }
183 """)
184
185 def prints_string_field_with_multiple_args():
186 schema = build_single_field_schema(
187 GraphQLField(
188 type_=GraphQLString,
189 args={
190 "argOne": GraphQLArgument(GraphQLInt),
191 "argTwo": GraphQLArgument(GraphQLString),
192 },
193 )
194 )
195
196 assert expect_printed_schema(schema) == dedent("""
197 type Query {
198 singleField(argOne: Int, argTwo: String): String
199 }
200 """)
201
202 def prints_string_field_with_multiple_args_first_is_default():
203 schema = build_single_field_schema(
204 GraphQLField(
205 type_=GraphQLString,
206 args={
207 "argOne": GraphQLArgument(GraphQLInt, default_value=1),
208 "argTwo": GraphQLArgument(GraphQLString),
209 "argThree": GraphQLArgument(GraphQLBoolean),
210 },
211 )
212 )
213
214 assert expect_printed_schema(schema) == dedent("""
215 type Query {
216 singleField(argOne: Int = 1, argTwo: String, argThree: Boolean): String
217 }
218 """)
219
220 def prints_string_field_with_multiple_args_second_is_default():
221 schema = build_single_field_schema(
222 GraphQLField(
223 type_=GraphQLString,
224 args={
225 "argOne": GraphQLArgument(GraphQLInt),
226 "argTwo": GraphQLArgument(GraphQLString, default_value="foo"),
227 "argThree": GraphQLArgument(GraphQLBoolean),
228 },
229 )
230 )
231
232 assert expect_printed_schema(schema) == dedent("""
233 type Query {
234 singleField(argOne: Int, argTwo: String = "foo", argThree: Boolean): String
235 }
236 """) # noqa: E501
237
238 def prints_string_field_with_multiple_args_last_is_default():
239 schema = build_single_field_schema(
240 GraphQLField(
241 type_=GraphQLString,
242 args={
243 "argOne": GraphQLArgument(GraphQLInt),
244 "argTwo": GraphQLArgument(GraphQLString),
245 "argThree": GraphQLArgument(GraphQLBoolean, default_value=False),
246 },
247 )
248 )
249
250 assert expect_printed_schema(schema) == dedent("""
251 type Query {
252 singleField(argOne: Int, argTwo: String, argThree: Boolean = false): String
253 }
254 """) # noqa: E501
255
256 def prints_schema_with_description():
257 schema = GraphQLSchema(
258 description="Schema description.", query=GraphQLObjectType("Query", {})
259 )
260
261 assert expect_printed_schema(schema) == dedent('''
262 """Schema description."""
263 schema {
264 query: Query
265 }
266
267 type Query
268 ''')
269
270 def omits_schema_of_common_names():
271 schema = GraphQLSchema(
272 query=GraphQLObjectType("Query", {}),
273 mutation=GraphQLObjectType("Mutation", {}),
274 subscription=GraphQLObjectType("Subscription", {}),
275 )
276
277 assert expect_printed_schema(schema) == dedent("""
278 type Query
279
280 type Mutation
281
282 type Subscription
283 """)
284
285 def prints_custom_query_root_types():
286 schema = GraphQLSchema(query=GraphQLObjectType("CustomType", {}))
287
288 assert expect_printed_schema(schema) == dedent("""
289 schema {
290 query: CustomType
291 }
292
293 type CustomType
294 """)
295
296 def prints_custom_mutation_root_types():
297 schema = GraphQLSchema(mutation=GraphQLObjectType("CustomType", {}))
298
299 assert expect_printed_schema(schema) == dedent("""
300 schema {
301 mutation: CustomType
302 }
303
304 type CustomType
305 """)
306
307 def prints_custom_subscription_root_types():
308 schema = GraphQLSchema(subscription=GraphQLObjectType("CustomType", {}))
309
310 assert expect_printed_schema(schema) == dedent("""
311 schema {
312 subscription: CustomType
313 }
314
315 type CustomType
316 """)
317
318 def prints_interface():
319 foo_type = GraphQLInterfaceType(
320 name="Foo", fields={"str": GraphQLField(GraphQLString)}
321 )
322
323 bar_type = GraphQLObjectType(
324 name="Bar",
325 fields={"str": GraphQLField(GraphQLString)},
326 interfaces=[foo_type],
327 )
328
329 schema = GraphQLSchema(types=[bar_type])
330 assert expect_printed_schema(schema) == dedent("""
331 type Bar implements Foo {
332 str: String
333 }
334
335 interface Foo {
336 str: String
337 }
338 """)
339
340 def prints_multiple_interfaces():
341 foo_type = GraphQLInterfaceType(
342 name="Foo", fields={"str": GraphQLField(GraphQLString)}
343 )
344
345 baz_type = GraphQLInterfaceType(
346 name="Baz", fields={"int": GraphQLField(GraphQLInt)}
347 )
348
349 bar_type = GraphQLObjectType(
350 name="Bar",
351 fields={
352 "str": GraphQLField(GraphQLString),
353 "int": GraphQLField(GraphQLInt),
354 },
355 interfaces=[foo_type, baz_type],
356 )
357
358 schema = GraphQLSchema(types=[bar_type])
359 assert expect_printed_schema(schema) == dedent("""
360 type Bar implements Foo & Baz {
361 str: String
362 int: Int
363 }
364
365 interface Foo {
366 str: String
367 }
368
369 interface Baz {
370 int: Int
371 }
372 """)
373
374 def prints_hierarchical_interface():
375 foo_type = GraphQLInterfaceType(
376 name="Foo", fields={"str": GraphQLField(GraphQLString)}
377 )
378
379 baz_type = GraphQLInterfaceType(
380 name="Baz",
381 interfaces=[foo_type],
382 fields={
383 "int": GraphQLField(GraphQLInt),
384 "str": GraphQLField(GraphQLString),
385 },
386 )
387
388 bar_type = GraphQLObjectType(
389 name="Bar",
390 fields={
391 "str": GraphQLField(GraphQLString),
392 "int": GraphQLField(GraphQLInt),
393 },
394 interfaces=[foo_type, baz_type],
395 )
396
397 query = GraphQLObjectType(name="Query", fields={"bar": GraphQLField(bar_type)})
398
399 schema = GraphQLSchema(query, types=[bar_type])
400 assert expect_printed_schema(schema) == dedent("""
401 type Bar implements Foo & Baz {
402 str: String
403 int: Int
404 }
405
406 interface Foo {
407 str: String
408 }
409
410 interface Baz implements Foo {
411 int: Int
412 str: String
413 }
414
415 type Query {
416 bar: Bar
417 }
418 """)
419
420 def prints_unions():
421 foo_type = GraphQLObjectType(
422 name="Foo", fields={"bool": GraphQLField(GraphQLBoolean)}
423 )
424
425 bar_type = GraphQLObjectType(
426 name="Bar", fields={"str": GraphQLField(GraphQLString)}
427 )
428
429 single_union = GraphQLUnionType(name="SingleUnion", types=[foo_type])
430
431 multiple_union = GraphQLUnionType(
432 name="MultipleUnion", types=[foo_type, bar_type]
433 )
434
435 schema = GraphQLSchema(types=[single_union, multiple_union])
436 assert expect_printed_schema(schema) == dedent("""
437 union SingleUnion = Foo
438
439 type Foo {
440 bool: Boolean
441 }
442
443 union MultipleUnion = Foo | Bar
444
445 type Bar {
446 str: String
447 }
448 """)
449
450 def prints_input_type():
451 input_type = GraphQLInputObjectType(
452 name="InputType", fields={"int": GraphQLInputField(GraphQLInt)}
453 )
454
455 schema = GraphQLSchema(types=[input_type])
456 assert expect_printed_schema(schema) == dedent("""
457 input InputType {
458 int: Int
459 }
460 """)
461
462 def prints_input_type_with_one_of_directive():
463 input_type = GraphQLInputObjectType(
464 name="InputType",
465 fields={"int": GraphQLInputField(GraphQLInt)},
466 is_one_of=True,
467 )
468
469 schema = GraphQLSchema(types=[input_type])
470 assert expect_printed_schema(schema) == dedent("""
471 input InputType @oneOf {
472 int: Int
473 }
474 """)
475
476 def prints_custom_scalar():
477 odd_type = GraphQLScalarType(name="Odd")
478
479 schema = GraphQLSchema(types=[odd_type])
480 assert expect_printed_schema(schema) == dedent("""
481 scalar Odd
482 """)
483
484 def prints_custom_scalar_with_specified_by_url():
485 foo_type = GraphQLScalarType(
486 name="Foo", specified_by_url="https://example.com/foo_spec"
487 )
488
489 schema = GraphQLSchema(types=[foo_type])
490 assert expect_printed_schema(schema) == dedent("""
491 scalar Foo @specifiedBy(url: "https://example.com/foo_spec")
492 """)
493
494 def prints_enum():
495 rgb_type = GraphQLEnumType(
496 name="RGB", values=dict.fromkeys(("RED", "GREEN", "BLUE"))
497 )
498
499 schema = GraphQLSchema(types=[rgb_type])
500 assert expect_printed_schema(schema) == dedent("""
501 enum RGB {
502 RED
503 GREEN
504 BLUE
505 }
506 """)
507
508 def prints_empty_types():
509 schema = GraphQLSchema(
510 types=[
511 GraphQLEnumType("SomeEnum", cast(Dict[str, Any], {})),
512 GraphQLInputObjectType("SomeInputObject", {}),
513 GraphQLInterfaceType("SomeInterface", {}),
514 GraphQLObjectType("SomeObject", {}),
515 GraphQLUnionType("SomeUnion", []),
516 ]
517 )
518
519 assert expect_printed_schema(schema) == dedent("""
520 enum SomeEnum
521
522 input SomeInputObject
523
524 interface SomeInterface
525
526 type SomeObject
527
528 union SomeUnion
529 """)
530
531 def prints_custom_directives():
532 simple_directive = GraphQLDirective(
533 "simpleDirective", [DirectiveLocation.FIELD]
534 )
535 complex_directive = GraphQLDirective(
536 "complexDirective",
537 [DirectiveLocation.FIELD, DirectiveLocation.QUERY],
538 description="Complex Directive",
539 args={
540 "stringArg": GraphQLArgument(GraphQLString),
541 "intArg": GraphQLArgument(GraphQLInt, default_value=-1),
542 },
543 is_repeatable=True,
544 )
545
546 schema = GraphQLSchema(directives=[simple_directive, complex_directive])
547 assert expect_printed_schema(schema) == dedent('''
548 directive @simpleDirective on FIELD
549
550 """Complex Directive"""
551 directive @complexDirective(stringArg: String, intArg: Int = -1) repeatable on FIELD | QUERY
552 ''') # noqa: E501
553
554 def prints_deprecated_directives():
555 schema = GraphQLSchema(
556 directives=[
557 GraphQLDirective(
558 name="deprecatedDirective",
559 locations=[DirectiveLocation.FIELD],
560 deprecation_reason="Use another directive",
561 ),
562 ],
563 )
564
565 assert print_schema(schema) == dedent("""
566 directive @deprecatedDirective @deprecated(reason: "Use another directive") on FIELD
567 """) # noqa: E501
568
569 def prints_an_empty_description():
570 schema = build_single_field_schema(GraphQLField(GraphQLString, description=""))
571
572 assert expect_printed_schema(schema) == dedent('''
573 type Query {
574 """"""
575 singleField: String
576 }
577 ''')
578
579 def prints_a_description_with_only_whitespace():
580 schema = build_single_field_schema(GraphQLField(GraphQLString, description=" "))
581
582 assert expect_printed_schema(schema) == dedent("""
583 type Query {
584 " "
585 singleField: String
586 }
587 """)
588
589 def one_line_prints_a_short_description():
590 schema = build_single_field_schema(
591 GraphQLField(GraphQLString, description="This field is awesome")
592 )
593
594 assert expect_printed_schema(schema) == dedent('''
595 type Query {
596 """This field is awesome"""
597 singleField: String
598 }
599 ''')
600
601 def prints_introspection_schema():
602 schema = GraphQLSchema()
603 output = print_introspection_schema(schema)
604
605 assert output == dedent('''
606 """
607 Directs the executor to include this field or fragment only when the `if` argument is true.
608 """
609 directive @include(
610 """Included when true."""
611 if: Boolean!
612 ) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT
613
614 """
615 Directs the executor to skip this field or fragment when the `if` argument is true.
616 """
617 directive @skip(
618 """Skipped when true."""
619 if: Boolean!
620 ) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT
621
622 """Marks an element of a GraphQL schema as no longer supported."""
623 directive @deprecated(
624 """
625 Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/).
626 """
627 reason: String = "No longer supported"
628 ) on FIELD_DEFINITION | ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION | ENUM_VALUE | DIRECTIVE_DEFINITION
629
630 """Exposes a URL that specifies the behavior of this scalar."""
631 directive @specifiedBy(
632 """The URL that specifies the behavior of this scalar."""
633 url: String!
634 ) on SCALAR
635
636 """Indicates an Input Object is a OneOf Input Object."""
637 directive @oneOf on INPUT_OBJECT
638
639 """
640 A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.
641 """
642 type __Schema {
643 description: String
644
645 """A list of all types supported by this server."""
646 types: [__Type!]!
647
648 """The type that query operations will be rooted at."""
649 queryType: __Type!
650
651 """
652 If this server supports mutation, the type that mutation operations will be rooted at.
653 """
654 mutationType: __Type
655
656 """
657 If this server supports subscription, the type that subscription operations will be rooted at.
658 """
659 subscriptionType: __Type
660
661 """A list of all directives supported by this server."""
662 directives(includeDeprecated: Boolean! = false): [__Directive!]!
663 }
664
665 """
666 The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.
667
668 Depending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name, description and optional `specifiedByURL`, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.
669 """
670 type __Type {
671 kind: __TypeKind!
672 name: String
673 description: String
674 specifiedByURL: String
675 fields(includeDeprecated: Boolean = false): [__Field!]
676 interfaces: [__Type!]
677 possibleTypes: [__Type!]
678 enumValues(includeDeprecated: Boolean = false): [__EnumValue!]
679 inputFields(includeDeprecated: Boolean = false): [__InputValue!]
680 ofType: __Type
681 isOneOf: Boolean
682 }
683
684 """An enum describing what kind of type a given `__Type` is."""
685 enum __TypeKind {
686 """Indicates this type is a scalar."""
687 SCALAR
688
689 """
690 Indicates this type is an object. `fields` and `interfaces` are valid fields.
691 """
692 OBJECT
693
694 """
695 Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields.
696 """
697 INTERFACE
698
699 """Indicates this type is a union. `possibleTypes` is a valid field."""
700 UNION
701
702 """Indicates this type is an enum. `enumValues` is a valid field."""
703 ENUM
704
705 """
706 Indicates this type is an input object. `inputFields` is a valid field.
707 """
708 INPUT_OBJECT
709
710 """Indicates this type is a list. `ofType` is a valid field."""
711 LIST
712
713 """Indicates this type is a non-null. `ofType` is a valid field."""
714 NON_NULL
715 }
716
717 """
718 Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.
719 """
720 type __Field {
721 name: String!
722 description: String
723 args(includeDeprecated: Boolean = false): [__InputValue!]!
724 type: __Type!
725 isDeprecated: Boolean!
726 deprecationReason: String
727 }
728
729 """
730 Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.
731 """
732 type __InputValue {
733 name: String!
734 description: String
735 type: __Type!
736
737 """
738 A GraphQL-formatted string representing the default value for this input value.
739 """
740 defaultValue: String
741 isDeprecated: Boolean!
742 deprecationReason: String
743 }
744
745 """
746 One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.
747 """
748 type __EnumValue {
749 name: String!
750 description: String
751 isDeprecated: Boolean!
752 deprecationReason: String
753 }
754
755 """
756 A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.
757
758 In some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.
759 """
760 type __Directive {
761 name: String!
762 description: String
763 isRepeatable: Boolean!
764 locations: [__DirectiveLocation!]!
765 args(includeDeprecated: Boolean = false): [__InputValue!]!
766 isDeprecated: Boolean!
767 deprecationReason: String
768 }
769
770 """
771 A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.
772 """
773 enum __DirectiveLocation {
774 """Location adjacent to a query operation."""
775 QUERY
776
777 """Location adjacent to a mutation operation."""
778 MUTATION
779
780 """Location adjacent to a subscription operation."""
781 SUBSCRIPTION
782
783 """Location adjacent to a field."""
784 FIELD
785
786 """Location adjacent to a fragment definition."""
787 FRAGMENT_DEFINITION
788
789 """Location adjacent to a fragment spread."""
790 FRAGMENT_SPREAD
791
792 """Location adjacent to an inline fragment."""
793 INLINE_FRAGMENT
794
795 """Location adjacent to a variable definition."""
796 VARIABLE_DEFINITION
797
798 """Location adjacent to a schema definition."""
799 SCHEMA
800
801 """Location adjacent to a scalar definition."""
802 SCALAR
803
804 """Location adjacent to an object type definition."""
805 OBJECT
806
807 """Location adjacent to a field definition."""
808 FIELD_DEFINITION
809
810 """Location adjacent to an argument definition."""
811 ARGUMENT_DEFINITION
812
813 """Location adjacent to an interface definition."""
814 INTERFACE
815
816 """Location adjacent to a union definition."""
817 UNION
818
819 """Location adjacent to an enum definition."""
820 ENUM
821
822 """Location adjacent to an enum value definition."""
823 ENUM_VALUE
824
825 """Location adjacent to an input object type definition."""
826 INPUT_OBJECT
827
828 """Location adjacent to an input object field definition."""
829 INPUT_FIELD_DEFINITION
830
831 """Location adjacent to a directive definition."""
832 DIRECTIVE_DEFINITION
833 }
834 ''') # noqa: E501
835
836
837 def describe_print_value():
838 def print_value_convenience_function():
839 assert print_value(1.5, GraphQLFloat) == "1.5"
840 assert print_value("foo", GraphQLString) == '"foo"'