From 22f46863f4f4658683ceb9daaaa0fa08a47373e4 Mon Sep 17 00:00:00 2001 From: Hanusz Leszek Date: Sun, 10 Apr 2022 16:12:20 +0200 Subject: [PATCH] Represent serialized floats to approximately python float precision --- gql/dsl.py | 7 +++++-- tests/starwars/test_dsl.py | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/gql/dsl.py b/gql/dsl.py index 634c10cb..26b9f426 100644 --- a/gql/dsl.py +++ b/gql/dsl.py @@ -106,10 +106,13 @@ def ast_from_serialized_value_untyped(serialized: Any) -> Optional[ValueNode]: return BooleanValueNode(value=serialized) if isinstance(serialized, int): - return IntValueNode(value=f"{serialized:d}") + return IntValueNode(value=str(serialized)) if isinstance(serialized, float) and isfinite(serialized): - return FloatValueNode(value=f"{serialized:g}") + value = str(serialized) + if value.endswith(".0"): + value = value[:-2] + return FloatValueNode(value=value) if isinstance(serialized, str): return StringValueNode(value=serialized) diff --git a/tests/starwars/test_dsl.py b/tests/starwars/test_dsl.py index 50f5449c..c0f2b441 100644 --- a/tests/starwars/test_dsl.py +++ b/tests/starwars/test_dsl.py @@ -1,6 +1,8 @@ import pytest from graphql import ( + FloatValueNode, GraphQLError, + GraphQLFloat, GraphQLID, GraphQLInt, GraphQLList, @@ -87,6 +89,20 @@ def test_ast_from_value_with_non_null_type_and_none(): assert "Received Null value for a Non-Null type Int." in str(exc_info.value) +def test_ast_from_value_float_precision(): + + # Checking precision of float serialization + # See https://github.com/graphql-python/graphql-core/pull/164 + + assert ast_from_value(123456789.01234567, GraphQLFloat) == FloatValueNode( + value="123456789.01234567" + ) + + assert ast_from_value(1.1, GraphQLFloat) == FloatValueNode(value="1.1") + + assert ast_from_value(123.0, GraphQLFloat) == FloatValueNode(value="123") + + def test_ast_from_serialized_value_untyped_typeerror(): with pytest.raises(TypeError) as exc_info: ast_from_serialized_value_untyped(GraphQLInt)