From 2d10236a218874fe0e790bb38b028fb9ecd30467 Mon Sep 17 00:00:00 2001 From: Oleksandr Redko Date: Fri, 24 May 2024 09:10:25 +0300 Subject: [PATCH] refactor: UnmarshalID implementation --- graphql/id.go | 8 ++--- graphql/id_test.go | 78 +++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 76 insertions(+), 10 deletions(-) diff --git a/graphql/id.go b/graphql/id.go index f13f7d9858..2a946dfa74 100644 --- a/graphql/id.go +++ b/graphql/id.go @@ -22,13 +22,9 @@ func UnmarshalID(v any) (string, error) { case int64: return strconv.FormatInt(v, 10), nil case float64: - return fmt.Sprintf("%f", v), nil + return strconv.FormatFloat(v, 'f', 6, 64), nil case bool: - if v { - return "true", nil - } else { - return "false", nil - } + return strconv.FormatBool(v), nil case nil: return "null", nil default: diff --git a/graphql/id_test.go b/graphql/id_test.go index a70ad4fa9f..b0dc2318a8 100644 --- a/graphql/id_test.go +++ b/graphql/id_test.go @@ -2,6 +2,7 @@ package graphql import ( "bytes" + "encoding/json" "math" "testing" @@ -35,10 +36,19 @@ func TestUnmarshalID(t *testing.T) { ShouldError bool }{ { - Name: "int64", - Input: int64(12), - Expected: "12", - ShouldError: false, + Name: "string", + Input: "str", + Expected: "str", + }, + { + Name: "json.Number float64", + Input: json.Number("1.2"), + Expected: "1.2", + }, + { + Name: "int64", + Input: int64(12), + Expected: "12", }, { Name: "int64 max", @@ -50,6 +60,66 @@ func TestUnmarshalID(t *testing.T) { Input: math.MinInt64, Expected: "-9223372036854775808", }, + { + Name: "bool true", + Input: true, + Expected: "true", + }, + { + Name: "bool false", + Input: false, + Expected: "false", + }, + { + Name: "nil", + Input: nil, + Expected: "null", + }, + { + Name: "float64", + Input: 1.234567, + Expected: "1.234567", + }, + { + Name: "float64 0", + Input: 0.0, + Expected: "0.000000", + }, + { + Name: "float64 loss of precision", + Input: 0.0000005, + Expected: "0.000000", + }, + { + Name: "float64 rounding up", + Input: 0.0000006, + Expected: "0.000001", + }, + { + Name: "float64 negative", + Input: -1.234560, + Expected: "-1.234560", + }, + { + Name: "float64 math.Inf(0)", + Input: math.Inf(0), + Expected: "+Inf", + }, + { + Name: "float64 math.Inf(-1)", + Input: math.Inf(-1), + Expected: "-Inf", + }, + { + Name: "float64 -math.Inf(0)", + Input: -math.Inf(0), + Expected: "-Inf", + }, + { + Name: "not a string", + Input: struct{}{}, + ShouldError: true, + }, } for _, tt := range tests {