Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent nil-dereference in format.Object for boxed nil error #681

Merged
merged 1 commit into from Jul 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion format/format.go
Expand Up @@ -259,7 +259,7 @@ func Object(object interface{}, indentation uint) string {
indent := strings.Repeat(Indent, int(indentation))
value := reflect.ValueOf(object)
commonRepresentation := ""
if err, ok := object.(error); ok {
if err, ok := object.(error); ok && !isNilValue(value) { // isNilValue check needed here to avoid nil deref due to boxed nil
Copy link
Contributor Author

@matthchr matthchr Jul 14, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Happy to remove this comment if you feel it's unneeded.

commonRepresentation += "\n" + IndentString(err.Error(), indentation) + "\n" + indent
}
return fmt.Sprintf("%s<%s>: %s%s", indent, formatType(value), commonRepresentation, formatValue(value, indentation))
Expand Down
16 changes: 16 additions & 0 deletions format/format_test.go
Expand Up @@ -7,6 +7,7 @@ import (
"time"

. "github.com/onsi/ginkgo/v2"

. "github.com/onsi/gomega"
. "github.com/onsi/gomega/format"
"github.com/onsi/gomega/types"
Expand Down Expand Up @@ -73,6 +74,16 @@ type NotCustomFormatted struct {
Count int
}

type CustomError struct {
Details string
}

var _ error = &CustomError{}

func (c *CustomError) Error() string {
return c.Details
}

func customFormatter(obj interface{}) (string, bool) {
cf, ok := obj.(CustomFormatted)
if !ok {
Expand Down Expand Up @@ -626,6 +637,11 @@ var _ = Describe("Format", func() {
\},
\}`))
})

It("should not panic if the error is a boxed nil", func() {
var err *CustomError
Expect(Object(err, 1)).Should(Equal(" <*format_test.CustomError | 0x0>: nil"))
})
})
})

Expand Down