Add nil OldValue test coverage for union doc_tests

Add tests for Union, DiscriminatedUnion, and ZeroOrOneOfUnion
validating that nil oldObj (new map entry or newly-set pointer
field during update) does not skip validation via ratcheting.
This commit is contained in:
yongruilin
2026-03-18 22:26:00 +00:00
committed by Lalit Chauhan
parent 9a39e5c49f
commit 863ed56ac0
3 changed files with 20 additions and 0 deletions

View File

@@ -41,4 +41,10 @@ func Test(t *testing.T) {
// Test validation ratcheting
st.Value(&Struct{D: DM2, M1: &M1{}, M2: &M2{}}).OldValue(&Struct{D: DM2, M1: &M1{}, M2: &M2{}}).ExpectValid()
st.Value(&Struct{D: DM1}).OldValue(&Struct{D: DM1}).ExpectValid()
// Test update with nil old value (simulates newly-set pointer field during update).
// Discriminated union validation should still detect mismatches even though oldObj is nil.
st.Value(&Struct{D: DM1}).OldValue(nil).ExpectMatches(field.ErrorMatcher{}.ByType().ByField().ByDetailSubstring().ByOrigin(), field.ErrorList{
field.Invalid(field.NewPath("m1"), nil, "must be specified when"),
}.WithOrigin("union"))
}

View File

@@ -52,4 +52,10 @@ func Test(t *testing.T) {
st.Value(&Struct{}).OldValue(&Struct{}).ExpectValid()
st.Value(&Struct{M1: &M1{}, M2: &M2{}}).OldValue(&Struct{M1: &M1{}, M2: &M2{}}).ExpectValid()
st.Value(&Struct{M3: "a string", M2: &M2{}}).OldValue(&Struct{M3: "different string", M2: &M2{}}).ExpectValid()
// Test update with nil old value (simulates new map entry or newly-set pointer field during update).
// Union validation should still detect the empty union even though oldObj is nil.
st.Value(&Struct{}).OldValue(nil).ExpectMatches(field.ErrorMatcher{}.ByType().ByField().ByDetailSubstring().ByOrigin(), field.ErrorList{
field.Invalid(nil, nil, "must specify one of").WithOrigin("union"),
})
}

View File

@@ -51,4 +51,12 @@ func Test(t *testing.T) {
st.Value(&Struct{}).OldValue(&Struct{}).ExpectValid()
st.Value(&Struct{M1: &M1{}, M2: &M2{}}).OldValue(&Struct{M1: &M1{}, M2: &M2{}}).ExpectValid()
st.Value(&Struct{M3: "a string", M2: &M2{}}).OldValue(&Struct{M3: "different string", M2: &M2{}}).ExpectValid()
// Test update with nil old value (simulates new map entry added during update).
// Empty union is still valid for zeroOrOneOf, even with nil old value.
st.Value(&Struct{}).OldValue((*Struct)(nil)).ExpectValid()
// Multiple members set should still be caught even with nil old value.
st.Value(&Struct{M1: &M1{}, M2: &M2{}}).OldValue((*Struct)(nil)).ExpectMatches(field.ErrorMatcher{}.ByType().ByField().ByDetailSubstring().ByOrigin(), field.ErrorList{
field.Invalid(nil, nil, "must specify at most one of").WithOrigin("zeroOrOneOf"),
})
}