Debian Codegraph @

tests/utilities/test_coerce_input_value.py

raw
1 from math import nan
2 from typing import Any, List, NamedTuple, Union
3
4 from pytest import raises
5
6 from graphql.error import GraphQLError
7 from graphql.pyutils import Undefined
8 from graphql.type import (
9 GraphQLEnumType,
10 GraphQLFloat,
11 GraphQLInputField,
12 GraphQLInputObjectType,
13 GraphQLInputType,
14 GraphQLInt,
15 GraphQLList,
16 GraphQLNonNull,
17 GraphQLScalarType,
18 )
19 from graphql.utilities import coerce_input_value
20
21
22 class CoercedValueError(NamedTuple):
23 error: str
24 path: List[Union[str, int]]
25 value: Any
26
27
28 class CoercedValue(NamedTuple):
29 errors: List[CoercedValueError]
30 value: Any
31
32
33 def expect_value(result: CoercedValue) -> Any:
34 assert result.errors == []
35 return result.value
36
37
38 def expect_errors(result: CoercedValue) -> List[CoercedValueError]:
39 return result.errors
40
41
42 def describe_coerce_input_value():
43 def _coerce_value(input_value: Any, type_: GraphQLInputType):
44 errors: List[CoercedValueError] = []
45 append = errors.append
46
47 def on_error(path, invalid_value, error):
48 append(CoercedValueError(error.message, path, invalid_value))
49
50 value = coerce_input_value(input_value, type_, on_error)
51 return CoercedValue(errors, value)
52
53 def describe_for_graphql_non_null():
54 TestNonNull = GraphQLNonNull(GraphQLInt)
55
56 def returns_non_error_for_non_null_value():
57 result = _coerce_value(1, TestNonNull)
58 assert expect_value(result) == 1
59
60 def returns_an_error_for_undefined_value():
61 result = _coerce_value(Undefined, TestNonNull)
62 assert expect_errors(result) == [
63 ("Expected non-nullable type 'Int!' not to be None.", [], Undefined)
64 ]
65
66 def returns_an_error_for_null_value():
67 result = _coerce_value(None, TestNonNull)
68 assert expect_errors(result) == [
69 ("Expected non-nullable type 'Int!' not to be None.", [], None)
70 ]
71
72 def describe_for_graphql_scalar():
73 def _parse_value(input_dict):
74 assert isinstance(input_dict, dict)
75 error = input_dict.get("error")
76 if error:
77 raise ValueError(error)
78 return input_dict.get("value")
79
80 TestScalar = GraphQLScalarType("TestScalar", parse_value=_parse_value)
81
82 def returns_no_error_for_valid_input():
83 result = _coerce_value({"value": 1}, TestScalar)
84 assert expect_value(result) == 1
85
86 def returns_no_error_for_null_result():
87 result = _coerce_value({"value": None}, TestScalar)
88 assert expect_value(result) is None
89
90 def returns_no_error_for_nan_result():
91 result = _coerce_value({"value": nan}, TestScalar)
92 assert expect_value(result) is nan
93
94 def returns_an_error_for_undefined_result():
95 result = _coerce_value({"value": Undefined}, TestScalar)
96 assert expect_errors(result) == [
97 ("Expected type 'TestScalar'.", [], {"value": Undefined})
98 ]
99
100 def returns_an_error_for_undefined_result_with_some_error_message():
101 input_value = {"error": "Some error message"}
102 result = _coerce_value(input_value, TestScalar)
103 assert expect_errors(result) == [
104 (
105 "Expected type 'TestScalar'. Some error message",
106 [],
107 {"error": "Some error message"},
108 )
109 ]
110
111 def describe_for_graphql_enum():
112 TestEnum = GraphQLEnumType(
113 "TestEnum", {"FOO": "InternalFoo", "BAR": 123_456_789}
114 )
115
116 def returns_no_error_for_a_known_enum_name():
117 foo_result = _coerce_value("FOO", TestEnum)
118 assert expect_value(foo_result) == "InternalFoo"
119
120 bar_result = _coerce_value("BAR", TestEnum)
121 assert expect_value(bar_result) == 123_456_789
122
123 def returns_an_error_for_misspelled_enum_value():
124 result = _coerce_value("foo", TestEnum)
125 assert expect_errors(result) == [
126 (
127 "Value 'foo' does not exist in 'TestEnum' enum."
128 " Did you mean the enum value 'FOO'?",
129 [],
130 "foo",
131 )
132 ]
133
134 def returns_an_error_for_incorrect_value_type():
135 result1 = _coerce_value(123, TestEnum)
136 assert expect_errors(result1) == [
137 ("Enum 'TestEnum' cannot represent non-string value: 123.", [], 123)
138 ]
139
140 result2 = _coerce_value({"field": "value"}, TestEnum)
141 assert expect_errors(result2) == [
142 (
143 "Enum 'TestEnum' cannot represent non-string value:"
144 " {'field': 'value'}.",
145 [],
146 {"field": "value"},
147 )
148 ]
149
150 def describe_for_graphql_input_object():
151 DeepObject = GraphQLInputObjectType(
152 "DeepObject",
153 {
154 "foo": GraphQLInputField(GraphQLNonNull(GraphQLInt)),
155 "bar": GraphQLInputField(GraphQLInt),
156 },
157 )
158 TestInputObject = GraphQLInputObjectType(
159 "TestInputObject",
160 {
161 "foo": GraphQLInputField(GraphQLNonNull(GraphQLInt)),
162 "bar": GraphQLInputField(GraphQLInt),
163 "deepObject": GraphQLInputField(DeepObject),
164 },
165 )
166
167 def returns_no_error_for_a_valid_input():
168 result = _coerce_value({"foo": 123}, TestInputObject)
169 assert expect_value(result) == {"foo": 123}
170
171 def returns_an_error_for_a_non_dict_value():
172 result = _coerce_value(123, TestInputObject)
173 assert expect_errors(result) == [
174 ("Expected type 'TestInputObject' to be a mapping.", [], 123)
175 ]
176
177 def returns_an_error_for_an_invalid_field():
178 result = _coerce_value({"foo": nan}, TestInputObject)
179 assert expect_errors(result) == [
180 (
181 "Int cannot represent non-integer value: nan",
182 ["foo"],
183 nan,
184 )
185 ]
186
187 def returns_multiple_errors_for_multiple_invalid_fields():
188 result = _coerce_value({"foo": "abc", "bar": "def"}, TestInputObject)
189 assert expect_errors(result) == [
190 (
191 "Int cannot represent non-integer value: 'abc'",
192 ["foo"],
193 "abc",
194 ),
195 (
196 "Int cannot represent non-integer value: 'def'",
197 ["bar"],
198 "def",
199 ),
200 ]
201
202 def returns_error_for_a_missing_required_field():
203 result = _coerce_value({"bar": 123}, TestInputObject)
204 assert expect_errors(result) == [
205 (
206 "Field 'foo' of required type 'Int!' was not provided.",
207 [],
208 {"bar": 123},
209 )
210 ]
211
212 def returns_error_for_an_unknown_field():
213 result = _coerce_value({"foo": 123, "unknownField": 123}, TestInputObject)
214 assert expect_errors(result) == [
215 (
216 "Field 'unknownField' is not defined by type 'TestInputObject'.",
217 [],
218 {"foo": 123, "unknownField": 123},
219 )
220 ]
221
222 def returns_error_for_a_misspelled_field():
223 result = _coerce_value({"foo": 123, "bart": 123}, TestInputObject)
224 assert expect_errors(result) == [
225 (
226 "Field 'bart' is not defined by type 'TestInputObject'."
227 " Did you mean 'bar'?",
228 [],
229 {"foo": 123, "bart": 123},
230 )
231 ]
232
233 def returns_an_error_for_an_array_type():
234 result = _coerce_value([{"foo": 1}, {"bar": 1}], TestInputObject)
235 assert expect_errors(result) == [
236 (
237 "Expected type 'TestInputObject' to be a mapping.",
238 [],
239 [{"foo": 1}, {"bar": 1}],
240 )
241 ]
242
243 def returns_an_error_for_an_array_type_on_a_nested_field():
244 result = _coerce_value({"foo": 1, "deepObject": [1, 2, 3]}, TestInputObject)
245 assert expect_errors(result) == [
246 (
247 "Expected type 'DeepObject' to be a mapping.",
248 ["deepObject"],
249 [1, 2, 3],
250 )
251 ]
252
253 def transforms_names_using_out_name():
254 # This is an extension of GraphQL.js.
255 ComplexInputObject = GraphQLInputObjectType(
256 "Complex",
257 {
258 "realPart": GraphQLInputField(GraphQLFloat, out_name="real_part"),
259 "imagPart": GraphQLInputField(
260 GraphQLFloat, default_value=0, out_name="imag_part"
261 ),
262 },
263 )
264 result = _coerce_value({"realPart": 1}, ComplexInputObject)
265 assert expect_value(result) == {"real_part": 1, "imag_part": 0}
266
267 def transforms_values_with_out_type():
268 # This is an extension of GraphQL.js.
269 ComplexInputObject = GraphQLInputObjectType(
270 "Complex",
271 {
272 "real": GraphQLInputField(GraphQLFloat),
273 "imag": GraphQLInputField(GraphQLFloat),
274 },
275 out_type=lambda value: complex(value["real"], value["imag"]),
276 )
277 result = _coerce_value({"real": 1, "imag": 2}, ComplexInputObject)
278 assert expect_value(result) == 1 + 2j
279
280 def describe_for_graphql_input_object_that_is_one_of():
281 TestInputObject = GraphQLInputObjectType(
282 "TestInputObject",
283 {
284 "foo": GraphQLInputField(GraphQLInt),
285 "bar": GraphQLInputField(GraphQLInt),
286 },
287 is_one_of=True,
288 )
289
290 def returns_no_error_for_a_valid_input():
291 result = _coerce_value({"foo": 123}, TestInputObject)
292 assert expect_value(result) == {"foo": 123}
293
294 def returns_an_error_if_more_than_one_field_is_specified():
295 result = _coerce_value({"foo": 123, "bar": None}, TestInputObject)
296 assert expect_errors(result) == [
297 (
298 "Exactly one key must be specified"
299 " for OneOf type 'TestInputObject'.",
300 [],
301 {"foo": 123, "bar": None},
302 )
303 ]
304
305 def returns_an_error_if_the_one_field_is_null():
306 result = _coerce_value({"bar": None}, TestInputObject)
307 assert expect_errors(result) == [
308 (
309 "Field 'bar' must be non-null.",
310 ["bar"],
311 None,
312 )
313 ]
314
315 def returns_an_error_for_an_invalid_field():
316 result = _coerce_value({"foo": nan}, TestInputObject)
317 assert expect_errors(result) == [
318 (
319 "Int cannot represent non-integer value: nan",
320 ["foo"],
321 nan,
322 )
323 ]
324
325 def returns_multiple_errors_for_multiple_invalid_fields():
326 result = _coerce_value({"foo": "abc", "bar": "def"}, TestInputObject)
327 assert expect_errors(result) == [
328 (
329 "Int cannot represent non-integer value: 'abc'",
330 ["foo"],
331 "abc",
332 ),
333 (
334 "Int cannot represent non-integer value: 'def'",
335 ["bar"],
336 "def",
337 ),
338 (
339 "Exactly one key must be specified"
340 " for OneOf type 'TestInputObject'.",
341 [],
342 {"foo": "abc", "bar": "def"},
343 ),
344 ]
345
346 def returns_an_error_for_an_unknown_field():
347 result = _coerce_value({"foo": 123, "unknownField": 123}, TestInputObject)
348 assert expect_errors(result) == [
349 (
350 "Field 'unknownField' is not defined by type 'TestInputObject'.",
351 [],
352 {"foo": 123, "unknownField": 123},
353 )
354 ]
355
356 def returns_an_error_for_a_misspelled_field():
357 result = _coerce_value({"bart": 123}, TestInputObject)
358 assert expect_errors(result) == [
359 (
360 "Field 'bart' is not defined by type 'TestInputObject'."
361 " Did you mean 'bar'?",
362 [],
363 {"bart": 123},
364 ),
365 (
366 "Exactly one key must be specified"
367 " for OneOf type 'TestInputObject'.",
368 [],
369 {"bart": 123},
370 ),
371 ]
372
373 def describe_for_graphql_input_object_with_default_value():
374 def _get_test_input_object(default_value):
375 return GraphQLInputObjectType(
376 "TestInputObject",
377 {
378 "foo": GraphQLInputField(
379 GraphQLScalarType("TestScalar"), default_value=default_value
380 )
381 },
382 )
383
384 def returns_no_errors_for_valid_input_value():
385 result = _coerce_value({"foo": 5}, _get_test_input_object(7))
386 assert expect_value(result) == {"foo": 5}
387
388 def returns_object_with_default_value():
389 result = _coerce_value({}, _get_test_input_object(7))
390 assert expect_value(result) == {"foo": 7}
391
392 def returns_null_as_value():
393 result = _coerce_value({}, _get_test_input_object(None))
394 assert expect_value(result) == {"foo": None}
395
396 def returns_nan_as_value():
397 result = _coerce_value({}, _get_test_input_object(nan))
398 result_value = expect_value(result)
399 assert "foo" in result_value
400 assert result_value["foo"] is nan
401
402 def describe_for_graphql_list():
403 TestList = GraphQLList(GraphQLInt)
404
405 def returns_no_error_for_a_valid_input():
406 result = _coerce_value([1, 2, 3], TestList)
407 assert expect_value(result) == [1, 2, 3]
408
409 def returns_no_error_for_a_valid_iterable_input():
410 def list_generator():
411 yield 1
412 yield 2
413 yield 3
414
415 result = _coerce_value(list_generator(), TestList)
416 assert expect_value(result) == [1, 2, 3]
417
418 def returns_an_error_for_an_invalid_input():
419 result = _coerce_value([1, "b", True, 4], TestList)
420 assert expect_errors(result) == [
421 (
422 "Int cannot represent non-integer value: 'b'",
423 [1],
424 "b",
425 ),
426 (
427 "Int cannot represent non-integer value: True",
428 [2],
429 True,
430 ),
431 ]
432
433 def returns_a_list_for_a_non_list_value():
434 result = _coerce_value(42, TestList)
435 assert expect_value(result) == [42]
436
437 def returns_a_list_for_a_dictionary():
438 test_list_of_objects = GraphQLList(
439 GraphQLInputObjectType(
440 "TestObject", {"length": GraphQLInputField(GraphQLInt)}
441 )
442 )
443
444 result = _coerce_value({"length": 100500}, test_list_of_objects)
445 assert expect_value(result) == [{"length": 100500}]
446
447 def returns_a_list_for_a_non_list_invalid_value():
448 result = _coerce_value("Undefined", TestList)
449 assert expect_errors(result) == [
450 (
451 "Int cannot represent non-integer value: 'Undefined'",
452 [],
453 "Undefined",
454 )
455 ]
456
457 def returns_null_for_a_null_value():
458 result = _coerce_value(None, TestList)
459 assert expect_value(result) is None
460
461 def describe_for_nested_graphql_list():
462 TestNestedList = GraphQLList(GraphQLList(GraphQLInt))
463
464 def returns_no_error_for_a_valid_input():
465 result = _coerce_value([[1], [2], [3]], TestNestedList)
466 assert expect_value(result) == [[1], [2], [3]]
467
468 def returns_a_list_for_a_non_list_value():
469 result = _coerce_value(42, TestNestedList)
470 assert expect_value(result) == [[42]]
471
472 def returns_null_for_a_null_value():
473 result = _coerce_value(None, TestNestedList)
474 assert expect_value(result) is None
475
476 def returns_nested_list_for_nested_non_list_values():
477 result = _coerce_value([1, 2, 3], TestNestedList)
478 assert expect_value(result) == [[1], [2], [3]]
479
480 def returns_nested_null_for_nested_null_values():
481 result = _coerce_value([42, [None], None], TestNestedList)
482 assert expect_value(result) == [[42], [None], None]
483
484 def describe_with_default_on_error():
485 def throw_error_without_path():
486 with raises(GraphQLError) as exc_info:
487 assert coerce_input_value(None, GraphQLNonNull(GraphQLInt))
488 assert exc_info.value.message == (
489 "Invalid value None: Expected non-nullable type 'Int!' not to be None."
490 )
491
492 def throw_error_with_path():
493 with raises(GraphQLError) as exc_info:
494 assert coerce_input_value(
495 [None], GraphQLList(GraphQLNonNull(GraphQLInt))
496 )
497 assert exc_info.value.message == (
498 "Invalid value None at 'value[0]':"
499 " Expected non-nullable type 'Int!' not to be None."
500 )