Skip to content

Commit d7bd509

Browse files
authored
Merge pull request moby#51356 from robmry/compat-replace-nil-pointer
API compat: replace nil values when adding fields
2 parents 43b48f1 + 22c0379 commit d7bd509

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

daemon/internal/compat/compat.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ func appendFields(src, dst map[string]any) {
4646
continue
4747
}
4848
}
49-
if _, ok := dst[k]; !ok {
49+
if existing, ok := dst[k]; !ok || existing == nil {
5050
dst[k] = v
5151
}
5252
}

daemon/internal/compat/compat_test.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import (
77
"testing"
88

99
"github.com/moby/moby/v2/daemon/internal/compat"
10+
"gotest.tools/v3/assert"
11+
is "gotest.tools/v3/assert/cmp"
1012
)
1113

1214
type Info struct {
@@ -80,6 +82,49 @@ func TestWrap(t *testing.T) {
8082
}
8183
}
8284

85+
func TestWrapNilPtrField(t *testing.T) {
86+
type bStruct struct {
87+
StringField string `json:"stringfield"`
88+
}
89+
type aStruct struct {
90+
IntField *int `json:"intfield"`
91+
StructField *bStruct `json:"structfield"`
92+
}
93+
info := &aStruct{}
94+
95+
tests := []struct {
96+
name string
97+
options []compat.Option
98+
expected string
99+
}{
100+
{
101+
name: "none",
102+
expected: `{"intfield":null,"structfield":null}`,
103+
},
104+
{
105+
name: "replace nil int",
106+
options: []compat.Option{compat.WithExtraFields(map[string]any{"intfield": 42})},
107+
expected: `{"intfield":42,"structfield":null}`,
108+
},
109+
{
110+
name: "replace nil struct",
111+
options: []compat.Option{compat.WithExtraFields(map[string]any{
112+
"structfield": map[string]any{"stringfield": "hello"},
113+
})},
114+
expected: `{"intfield":null,"structfield":{"stringfield":"hello"}}`,
115+
},
116+
}
117+
for _, tc := range tests {
118+
t.Run(tc.name, func(t *testing.T) {
119+
resp := compat.Wrap(info, tc.options...)
120+
data, err := json.Marshal(resp)
121+
if assert.Check(t, err) {
122+
assert.Check(t, is.Equal(string(data), tc.expected))
123+
}
124+
})
125+
}
126+
}
127+
83128
func TestNestedCompat(t *testing.T) {
84129
info := &Info{
85130
Name: "daemon",

0 commit comments

Comments
 (0)