Skip to content

Commit e93501d

Browse files
Jamie Tannajamietanna
authored andcommitted
chore(examples): add tests for preferskipoptionalpointer
As part of a future change, we're adding the Output Option `prefer-skip-optional-pointer-with-omitzero`. As part of this, we want to make sure that the existing behaviour, with the `omitempty` default, works as expected.
1 parent 739f502 commit e93501d

1 file changed

Lines changed: 65 additions & 0 deletions

File tree

  • examples/output-options/preferskipoptionalpointer
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package preferskipoptionalpointer
2+
3+
import (
4+
"encoding/json"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
"github.com/stretchr/testify/require"
9+
)
10+
11+
func TestClient(t *testing.T) {
12+
t.Run("zero value (empty string) on Name is not omitted", func(t *testing.T) {
13+
client := Client{
14+
Name: "",
15+
}
16+
17+
b, err := json.Marshal(client)
18+
require.NoError(t, err)
19+
20+
assert.True(t, jsonContainsKey(b, "name"))
21+
})
22+
23+
t.Run("value on Name is not omitted", func(t *testing.T) {
24+
client := Client{
25+
Name: "some value",
26+
}
27+
28+
b, err := json.Marshal(client)
29+
require.NoError(t, err)
30+
31+
assert.True(t, jsonContainsKey(b, "name"))
32+
})
33+
34+
t.Run("zero value (0.0) on Id is omitted (as `omitempty` flags it as empty)", func(t *testing.T) {
35+
client := Client{
36+
Id: 0.0,
37+
}
38+
39+
b, err := json.Marshal(client)
40+
require.NoError(t, err)
41+
42+
assert.False(t, jsonContainsKey(b, "id"))
43+
})
44+
45+
t.Run("value on Id is not omitted", func(t *testing.T) {
46+
client := Client{
47+
Id: 3.142,
48+
}
49+
50+
b, err := json.Marshal(client)
51+
require.NoError(t, err)
52+
53+
assert.True(t, jsonContainsKey(b, "id"))
54+
})
55+
}
56+
57+
// jsonContainsKey checks if the given JSON object contains the specified key at the top level.
58+
func jsonContainsKey(b []byte, key string) bool {
59+
var m map[string]any
60+
if err := json.Unmarshal(b, &m); err != nil {
61+
return false
62+
}
63+
_, ok := m[key]
64+
return ok
65+
}

0 commit comments

Comments
 (0)