Skip to content

Commit 20ccb96

Browse files
Fix conversion helpers
1 parent d727995 commit 20ccb96

2 files changed

Lines changed: 65 additions & 0 deletions

File tree

v2/pkg/genruntime/conversion_helpers.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,13 @@ func GetFloatFromInt(i int) float64 {
114114

115115
// ConvertJSONToString returns the string value of the given v1.JSON.
116116
func ConvertJSONToString(json v1.JSON) string {
117+
// An empty v1.JSON marshals to the literal "null" (see (v1.JSON).MarshalJSON), but the value we want to
118+
// round trip is the empty string. v1.JSON.UnmarshalJSON treats both "" and "null" as an empty Raw, so
119+
// treating an empty Raw as the empty string here makes ConvertJSONToString(ConvertStringToJSON("")) lossless.
120+
if len(json.Raw) == 0 {
121+
return ""
122+
}
123+
117124
// Ignoring error here, its always nil
118125
marshalJSON, _ := json.MarshalJSON()
119126
return string(marshalJSON)
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/*
2+
* Copyright (c) Microsoft Corporation.
3+
* Licensed under the MIT license.
4+
*/
5+
6+
package genruntime_test
7+
8+
import (
9+
"testing"
10+
11+
. "github.com/onsi/gomega"
12+
v1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
13+
14+
"github.com/Azure/azure-service-operator/v2/pkg/genruntime"
15+
)
16+
17+
func TestConvertStringToJSON_RoundTripsThroughConvertJSONToString(t *testing.T) {
18+
t.Parallel()
19+
20+
cases := map[string]struct {
21+
value string
22+
}{
23+
"empty string": {
24+
value: "",
25+
},
26+
"simple string": {
27+
value: "value",
28+
},
29+
"numeric string": {
30+
value: "123",
31+
},
32+
"boolean string": {
33+
value: "true",
34+
},
35+
"json object string": {
36+
value: `{"key":"value"}`,
37+
},
38+
}
39+
40+
for name, c := range cases {
41+
name, c := name, c
42+
t.Run(name, func(t *testing.T) {
43+
t.Parallel()
44+
g := NewGomegaWithT(t)
45+
46+
j := genruntime.ConvertStringToJSON(c.value)
47+
actual := genruntime.ConvertJSONToString(j)
48+
g.Expect(actual).To(Equal(c.value))
49+
})
50+
}
51+
}
52+
53+
func TestConvertJSONToString_EmptyJSONReturnsEmptyString(t *testing.T) {
54+
t.Parallel()
55+
g := NewGomegaWithT(t)
56+
57+
g.Expect(genruntime.ConvertJSONToString(v1.JSON{})).To(Equal(""))
58+
}

0 commit comments

Comments
 (0)