test: non-shallow copy of OverrideCLISetValues in DeepCopy + test
Signed-off-by: Vojta Polak <vojta.polak@gmail.com>
This commit is contained in:
parent
bca4e96bf0
commit
7b79578d20
|
|
@ -30,7 +30,17 @@ func (o LoadOpts) DeepCopy() LoadOpts {
|
|||
panic(err)
|
||||
}
|
||||
|
||||
new.Environment.OverrideCLISetValues = o.Environment.OverrideCLISetValues
|
||||
if src := o.Environment.OverrideCLISetValues; src != nil {
|
||||
b, err := yaml.Marshal(src)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
var dst []any
|
||||
if err := yaml.Unmarshal(b, &dst); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
new.Environment.OverrideCLISetValues = dst
|
||||
}
|
||||
|
||||
return new
|
||||
}
|
||||
|
|
|
|||
|
|
@ -34,3 +34,20 @@ func TestLoadOptsDeepCopyPreservesOverrideCLISetValues(t *testing.T) {
|
|||
|
||||
require.Equal(t, lOld.Environment.OverrideCLISetValues, lNew.Environment.OverrideCLISetValues, "DeepCopy should preserve OverrideCLISetValues field")
|
||||
}
|
||||
|
||||
// TestLoadOptsDeepCopyOverrideCLISetValuesIsNotShallow verifies that mutating a
|
||||
// map nested inside OverrideCLISetValues on the copy does not affect the
|
||||
// original.
|
||||
func TestLoadOptsDeepCopyOverrideCLISetValuesIsNotShallow(t *testing.T) {
|
||||
lOld := LoadOpts{}
|
||||
lOld.Environment.OverrideCLISetValues = []any{map[string]any{"key": "original"}}
|
||||
|
||||
lNew := lOld.DeepCopy()
|
||||
|
||||
// Mutate the map inside the copy.
|
||||
lNew.Environment.OverrideCLISetValues[0].(map[string]any)["key"] = "mutated"
|
||||
|
||||
// The original must be unaffected; this fails with a shallow copy.
|
||||
require.Equal(t, "original", lOld.Environment.OverrideCLISetValues[0].(map[string]any)["key"],
|
||||
"mutating the copy's OverrideCLISetValues map must not affect the original (aliasing bug)")
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue