Skip to content

Commit 0b190b8

Browse files
committed
Add test cases for immutable to verify pointers
The code was correct, but the test case was bad at proving it.
1 parent 855918f commit 0b190b8

File tree

3 files changed

+13
-9
lines changed

3 files changed

+13
-9
lines changed

staging/src/k8s.io/code-generator/cmd/validation-gen/output_tests/tags/immutable/doc_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,13 @@ func Test(t *testing.T) {
3838
ImmutableField: "fff",
3939
ImmutablePtrField: ptr.To(ImmutableType("fff")),
4040
}
41+
42+
structA2 := structA // dup of A but with different pointer values
43+
structA2.StringPtrField = ptr.To(*structA2.StringPtrField)
44+
structA2.StructPtrField = ptr.To(*structA2.StructPtrField)
45+
structA2.NonComparableStructPtrField = ptr.To(*structA2.NonComparableStructPtrField)
46+
structA2.ImmutablePtrField = ptr.To(*structA2.ImmutablePtrField)
47+
4148
structB := Struct{
4249
StringField: "uuu",
4350
StringPtrField: ptr.To("uuu"),
@@ -52,6 +59,8 @@ func Test(t *testing.T) {
5259
}
5360

5461
st.Value(&structA).OldValue(&structA).ExpectValid()
62+
st.Value(&structA).OldValue(&structA2).ExpectValid()
63+
st.Value(&structA2).OldValue(&structA).ExpectValid()
5564

5665
st.Value(&structA).OldValue(&structB).ExpectInvalid(
5766
field.Forbidden(field.NewPath("stringField"), "field is immutable"),

staging/src/k8s.io/code-generator/cmd/validation-gen/validators/common.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ func isNilableType(t *types.Type) bool {
5050
return false
5151
}
5252

53+
// realType returns the underlying type of a type, unwrapping aliases and
54+
// dropping pointerness.
5355
func realType(t *types.Type) *types.Type {
5456
for {
5557
if t.Kind == types.Alias {

staging/src/k8s.io/code-generator/cmd/validation-gen/validators/immutable.go

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -51,15 +51,8 @@ var (
5151
func (immutableTagValidator) GetValidations(context Context, _ []string, payload string) (Validations, error) {
5252
var result Validations
5353

54-
t := context.Type
55-
for t.Kind == types.Pointer || t.Kind == types.Alias {
56-
if t.Kind == types.Pointer {
57-
t = t.Elem
58-
} else if t.Kind == types.Alias {
59-
t = t.Underlying
60-
}
61-
}
62-
if t.IsComparable() {
54+
if realType(context.Type).IsComparable() {
55+
// Note: This compares the pointee, not the pointer itself.
6356
result.AddFunction(Function(immutableTagName, DefaultFlags, immutableValidator))
6457
} else {
6558
result.AddFunction(Function(immutableTagName, DefaultFlags, immutableNonComparableValidator))

0 commit comments

Comments
 (0)