Skip to content

Commit

Permalink
refactor: UnmarshalID implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
alexandear committed May 24, 2024
1 parent a9965fb commit 2d10236
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 10 deletions.
8 changes: 2 additions & 6 deletions graphql/id.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
78 changes: 74 additions & 4 deletions graphql/id_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package graphql

import (
"bytes"
"encoding/json"
"math"
"testing"

Expand Down Expand Up @@ -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",
Expand All @@ -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 {
Expand Down

0 comments on commit 2d10236

Please sign in to comment.