Debian Codegraph @

tests/validation/test_validation.py

raw
1 from pytest import raises
2
3 from graphql.error import GraphQLError
4 from graphql.language import parse
5 from graphql.utilities import TypeInfo, build_schema
6 from graphql.validation import ValidationRule, validate
7
8 from .harness import test_schema
9
10
11 def describe_validate_supports_full_validation():
12 def rejects_invalid_documents():
13 with raises(TypeError) as exc_info:
14 # noinspection PyTypeChecker
15 assert validate(test_schema, None) # type: ignore
16 assert str(exc_info.value) == "Must provide document."
17
18 def rejects_invalid_type_info():
19 with raises(TypeError) as exc_info:
20 # noinspection PyTypeChecker
21 assert validate(
22 test_schema, parse("query { name }"), type_info={} # type: ignore
23 )
24 assert str(exc_info.value) == "Not a TypeInfo object: {}."
25
26 def rejects_invalid_rules():
27 with raises(TypeError) as exc_info:
28 # noinspection PyTypeChecker
29 assert validate(
30 test_schema, parse("query { name }"), rules=[None] # type: ignore
31 )
32 assert (
33 str(exc_info.value) == "Rules must be specified as a collection"
34 " of ASTValidationRule subclasses."
35 )
36
37 def rejects_invalid_max_errors():
38 with raises(TypeError) as exc_info:
39 # noinspection PyTypeChecker
40 assert validate(
41 test_schema, parse("query { name }"), max_errors=2.5 # type: ignore
42 )
43 assert (
44 str(exc_info.value)
45 == "The maximum number of errors must be passed as an int."
46 )
47
48 def validates_queries():
49 doc = parse("""
50 query {
51 human {
52 pets {
53 ... on Cat {
54 meowsVolume
55 }
56 ... on Dog {
57 barkVolume
58 }
59 }
60 }
61 }
62 """)
63
64 errors = validate(test_schema, doc)
65 assert errors == []
66
67 def detects_unknown_fields():
68 doc = parse("""
69 {
70 unknown
71 }
72 """)
73
74 errors = validate(test_schema, doc)
75 assert errors == [
76 {"message": "Cannot query field 'unknown' on type 'QueryRoot'."}
77 ]
78
79 def deprecated_validates_using_a_custom_type_info():
80 # This TypeInfo will never return a valid field.
81 type_info = TypeInfo(test_schema, None, lambda *args: None)
82
83 doc = parse("""
84 query {
85 human {
86 pets {
87 ... on Cat {
88 meowsVolume
89 }
90 ... on Dog {
91 barkVolume
92 }
93 }
94 }
95 }
96 """)
97
98 errors = validate(test_schema, doc, None, None, type_info)
99
100 assert [error.message for error in errors] == [
101 "Cannot query field 'human' on type 'QueryRoot'. Did you mean 'human'?",
102 "Cannot query field 'meowsVolume' on type 'Cat'."
103 " Did you mean 'meowsVolume'?",
104 "Cannot query field 'barkVolume' on type 'Dog'."
105 " Did you mean 'barkVolume'?",
106 ]
107
108 def validates_using_a_custom_rule():
109 schema = build_schema("""
110 directive @custom(arg: String) on FIELD
111
112 type Query {
113 foo: String
114 }
115 """)
116
117 doc = parse("""
118 query {
119 name @custom
120 }
121 """)
122
123 class CustomRule(ValidationRule):
124 def enter_directive(self, node, *_args):
125 directive_def = self.context.get_directive()
126 error = GraphQLError("Reporting directive: " + str(directive_def), node)
127 self.context.report_error(error)
128
129 errors = validate(schema, doc, [CustomRule])
130 assert errors == [
131 {"message": "Reporting directive: @custom", "locations": [(3, 20)]}
132 ]
133
134
135 def describe_validate_limit_maximum_number_of_validation_errors():
136 query = """
137 {
138 firstUnknownField
139 secondUnknownField
140 thirdUnknownField
141 }
142 """
143 doc = parse(query, no_location=True)
144
145 def _validate_document(max_errors=None):
146 return validate(test_schema, doc, max_errors=max_errors)
147
148 def _invalid_field_error(field_name: str):
149 return {
150 "message": f"Cannot query field '{field_name}' on type 'QueryRoot'.",
151 }
152
153 def when_max_errors_is_equal_to_number_of_errors():
154 errors = _validate_document(max_errors=3)
155 assert errors == [
156 _invalid_field_error("firstUnknownField"),
157 _invalid_field_error("secondUnknownField"),
158 _invalid_field_error("thirdUnknownField"),
159 ]
160
161 def when_max_errors_is_less_than_number_of_errors():
162 errors = _validate_document(max_errors=2)
163 assert errors == [
164 _invalid_field_error("firstUnknownField"),
165 _invalid_field_error("secondUnknownField"),
166 {
167 "message": "Too many validation errors, error limit reached."
168 " Validation aborted."
169 },
170 ]
171
172 def limits_to_100_when_max_errors_is_not_passed():
173 errors = validate(
174 test_schema,
175 parse(
176 "{" + " ".join(f"unknownField{n}" for n in range(120)) + "}",
177 no_location=True,
178 ),
179 )
180 assert len(errors) == 101
181 assert errors[0] == _invalid_field_error("unknownField0")
182 assert errors[-2] == _invalid_field_error("unknownField99")
183 assert errors[-1] == {
184 "message": "Too many validation errors, error limit reached."
185 " Validation aborted."
186 }
187
188 def pass_through_exceptions_from_rules():
189 class CustomRule(ValidationRule):
190 def enter_field(self, *_args):
191 raise RuntimeError("Error from custom rule!")
192
193 with raises(RuntimeError, match="^Error from custom rule!$"):
194 validate(test_schema, doc, [CustomRule], max_errors=1)
195
196
197 def describe_operation_and_variable_definition_descriptions():
198 def validates_operation_with_description_and_variable_descriptions():
199 schema = build_schema("type Query { field(a: Int, b: String): String }")
200 query = '''
201 "Operation description"
202 query myQuery(
203 "Variable a description"
204 $a: Int,
205 """Variable b\nmultiline description"""
206 $b: String
207 ) {
208 field(a: $a, b: $b)
209 }
210 '''
211 ast = parse(query)
212 errors = validate(schema, ast)
213 assert errors == []