Skip to content

coerce str #103

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/graphql/type/scalars.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from math import isfinite
from typing import Any
from typing import Any, Union

from ..error import GraphQLError
from ..pyutils import inspect, is_finite, is_integer, FrozenDict
Expand Down Expand Up @@ -60,8 +60,15 @@ def serialize_int(output_value: Any) -> int:
)
return num

def _try_convert_str_to_int(s: str) -> Union[str, int]:
try:
return int(s)
except (ValueError, TypeError):
return s

def coerce_int(input_value: Any) -> int:
if isinstance(input_value, str):
input_value = _try_convert_str_to_int(input_value)
if not is_integer(input_value):
raise GraphQLError(
"Int cannot represent non-integer value: " + inspect(input_value)
Expand Down
4 changes: 3 additions & 1 deletion tests/type/test_scalars.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
GraphQLBoolean,
GraphQLID,
)
from graphql.type.scalars import coerce_int


def describe_type_system_specified_scalar_types():
Expand All @@ -27,6 +28,7 @@ def _parse_value_raises(s, message):
assert _parse_value(1) == 1
assert _parse_value(0) == 0
assert _parse_value(-1) == -1
assert _parse_value("123") == 123

_parse_value_raises(
9876504321,
Expand All @@ -44,7 +46,7 @@ def _parse_value_raises(s, message):
)
_parse_value_raises(None, "Int cannot represent non-integer value: None")
_parse_value_raises("", "Int cannot represent non-integer value: ''")
_parse_value_raises("123", "Int cannot represent non-integer value: '123'")
_parse_value_raises("abc", "Int cannot represent non-integer value: 'abc'")
_parse_value_raises(False, "Int cannot represent non-integer value: False")
_parse_value_raises(True, "Int cannot represent non-integer value: True")
_parse_value_raises([1], "Int cannot represent non-integer value: [1]")
Expand Down