Skip to content

Commit 8c327fc

Browse files
authored
add BigInt type (#1261)
* add BigInt type * formatting * more Int tests
1 parent b685e10 commit 8c327fc

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

graphene/types/scalars.py

+27
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,33 @@ def parse_literal(ast):
8282
return num
8383

8484

85+
class BigInt(Scalar):
86+
"""
87+
The `BigInt` scalar type represents non-fractional whole numeric values.
88+
`BigInt` is not constrained to 32-bit like the `Int` type and thus is a less
89+
compatible type.
90+
"""
91+
92+
@staticmethod
93+
def coerce_int(value):
94+
try:
95+
num = int(value)
96+
except ValueError:
97+
try:
98+
num = int(float(value))
99+
except ValueError:
100+
return None
101+
return num
102+
103+
serialize = coerce_int
104+
parse_value = coerce_int
105+
106+
@staticmethod
107+
def parse_literal(ast):
108+
if isinstance(ast, IntValueNode):
109+
return int(ast.value)
110+
111+
85112
class Float(Scalar):
86113
"""
87114
The `Float` scalar type represents signed double-precision fractional

graphene/types/tests/test_scalar.py

+21-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
from ..scalars import Scalar
1+
from ..scalars import Scalar, Int, BigInt
2+
from graphql.language.ast import IntValueNode
23

34

45
def test_scalar():
@@ -7,3 +8,22 @@ class JSONScalar(Scalar):
78

89
assert JSONScalar._meta.name == "JSONScalar"
910
assert JSONScalar._meta.description == "Documentation"
11+
12+
13+
def test_ints():
14+
assert Int.parse_value(2 ** 31 - 1) is not None
15+
assert Int.parse_value("2.0") is not None
16+
assert Int.parse_value(2 ** 31) is None
17+
18+
assert Int.parse_literal(IntValueNode(value=str(2 ** 31 - 1))) == 2 ** 31 - 1
19+
assert Int.parse_literal(IntValueNode(value=str(2 ** 31))) is None
20+
21+
assert Int.parse_value(-(2 ** 31)) is not None
22+
assert Int.parse_value(-(2 ** 31) - 1) is None
23+
24+
assert BigInt.parse_value(2 ** 31) is not None
25+
assert BigInt.parse_value("2.0") is not None
26+
assert BigInt.parse_value(-(2 ** 31) - 1) is not None
27+
28+
assert BigInt.parse_literal(IntValueNode(value=str(2 ** 31 - 1))) == 2 ** 31 - 1
29+
assert BigInt.parse_literal(IntValueNode(value=str(2 ** 31))) == 2 ** 31

0 commit comments

Comments
 (0)