From 8c327fc4ed98ddf7fae0a67c48f3de24c530a06d Mon Sep 17 00:00:00 2001 From: Paul Bailey Date: Fri, 28 Aug 2020 10:55:46 -0500 Subject: [PATCH] add BigInt type (#1261) * add BigInt type * formatting * more Int tests --- graphene/types/scalars.py | 27 +++++++++++++++++++++++++++ graphene/types/tests/test_scalar.py | 22 +++++++++++++++++++++- 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/graphene/types/scalars.py b/graphene/types/scalars.py index 245fa570..472f2d41 100644 --- a/graphene/types/scalars.py +++ b/graphene/types/scalars.py @@ -82,6 +82,33 @@ class Int(Scalar): return num +class BigInt(Scalar): + """ + The `BigInt` scalar type represents non-fractional whole numeric values. + `BigInt` is not constrained to 32-bit like the `Int` type and thus is a less + compatible type. + """ + + @staticmethod + def coerce_int(value): + try: + num = int(value) + except ValueError: + try: + num = int(float(value)) + except ValueError: + return None + return num + + serialize = coerce_int + parse_value = coerce_int + + @staticmethod + def parse_literal(ast): + if isinstance(ast, IntValueNode): + return int(ast.value) + + class Float(Scalar): """ The `Float` scalar type represents signed double-precision fractional diff --git a/graphene/types/tests/test_scalar.py b/graphene/types/tests/test_scalar.py index 559c0ce6..2ff67208 100644 --- a/graphene/types/tests/test_scalar.py +++ b/graphene/types/tests/test_scalar.py @@ -1,4 +1,5 @@ -from ..scalars import Scalar +from ..scalars import Scalar, Int, BigInt +from graphql.language.ast import IntValueNode def test_scalar(): @@ -7,3 +8,22 @@ def test_scalar(): assert JSONScalar._meta.name == "JSONScalar" assert JSONScalar._meta.description == "Documentation" + + +def test_ints(): + assert Int.parse_value(2 ** 31 - 1) is not None + assert Int.parse_value("2.0") is not None + assert Int.parse_value(2 ** 31) is None + + assert Int.parse_literal(IntValueNode(value=str(2 ** 31 - 1))) == 2 ** 31 - 1 + assert Int.parse_literal(IntValueNode(value=str(2 ** 31))) is None + + assert Int.parse_value(-(2 ** 31)) is not None + assert Int.parse_value(-(2 ** 31) - 1) is None + + assert BigInt.parse_value(2 ** 31) is not None + assert BigInt.parse_value("2.0") is not None + assert BigInt.parse_value(-(2 ** 31) - 1) is not None + + assert BigInt.parse_literal(IntValueNode(value=str(2 ** 31 - 1))) == 2 ** 31 - 1 + assert BigInt.parse_literal(IntValueNode(value=str(2 ** 31))) == 2 ** 31