Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmp/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -431,7 +431,7 @@ func AllowUnexported(types ...any) Option {
m := make(map[reflect.Type]bool)
for _, typ := range types {
t := reflect.TypeOf(typ)
if t.Kind() != reflect.Struct {
if t == nil || t.Kind() != reflect.Struct {
panic(fmt.Sprintf("invalid struct type: %T", typ))
}
m[t] = true
Expand Down
16 changes: 16 additions & 0 deletions cmp/options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -214,3 +214,19 @@ func TestOptionPanic(t *testing.T) {
})
}
}

// TestAllowUnexportedNilPanic asserts that AllowUnexported(nil) panics with
// the same descriptive message as other invalid inputs rather than crashing
// with a nil pointer dereference. TestOptionPanic cannot cover this case
// because it invokes the option functions through reflection, which cannot
// represent a bare nil argument.
func TestAllowUnexportedNilPanic(t *testing.T) {
var gotPanic any
func() {
defer func() { gotPanic = recover() }()
AllowUnexported(nil)
}()
if s, ok := gotPanic.(string); !ok || !strings.Contains(s, "invalid struct type") {
t.Fatalf("panic = %v (type %T), want string containing %q", gotPanic, gotPanic, "invalid struct type")
}
}