Skip to content

Commit

Permalink
add pointer support to HaveField matcher (#495)
Browse files Browse the repository at this point in the history
  • Loading branch information
schrej authored Jan 27, 2022
1 parent 8e0d16d commit 79e41a3
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
7 changes: 7 additions & 0 deletions matchers/have_field.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ func extractField(actual interface{}, field string) (interface{}, error) {
fields := strings.SplitN(field, ".", 2)
actualValue := reflect.ValueOf(actual)

if actualValue.Kind() == reflect.Ptr {
actualValue = actualValue.Elem()
}
if actualValue == (reflect.Value{}) {
return nil, fmt.Errorf("HaveField encountered nil while dereferencing a pointer of type %T.", actual)
}

if actualValue.Kind() != reflect.Struct {
return nil, fmt.Errorf("HaveField encountered:\n%s\nWhich is not a struct.", format.Object(actual, 1))
}
Expand Down
17 changes: 14 additions & 3 deletions matchers/have_field_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ import (
)

type Book struct {
Title string
Author person
Pages int
Title string
Author person
Pages int
Sequel *Book
Prequel *Book
}

func (book Book) AuthorName() string {
Expand Down Expand Up @@ -54,6 +56,9 @@ var _ = Describe("HaveField", func() {
DOB: time.Date(1802, 2, 26, 0, 0, 0, 0, time.UTC),
},
Pages: 2783,
Sequel: &Book{
Title: "Les Miserables 2",
},
}
})

Expand All @@ -67,6 +72,7 @@ var _ = Describe("HaveField", func() {
Entry("Top-level method", "AuthorName()", "Victor Hugo"),
Entry("Nested method", "Author.DOB.Year()", BeNumerically("<", 1900)),
Entry("Traversing past a method", "AbbreviatedAuthor().FirstName", Equal("Vic")),
Entry("Traversing a pointer", "Sequel.Title", "Les Miserables 2"),
)

DescribeTable("negation works",
Expand All @@ -78,6 +84,7 @@ var _ = Describe("HaveField", func() {
Entry("Nested field", "Author.FirstName", "Hugo"),
Entry("Top-level method", "AuthorName()", "Victor M. Hugo"),
Entry("Nested method", "Author.DOB.Year()", BeNumerically(">", 1900)),
Entry("Traversing a pointer", "Sequel.Title", "Les Mis 2"),
)

Describe("when field lookup fails", func() {
Expand Down Expand Up @@ -117,6 +124,10 @@ var _ = Describe("HaveField", func() {
success, err = HaveField("Author.Abbreviation", "Vic").Match(book)
Ω(success).Should(BeFalse())
Ω(err.Error()).Should(ContainSubstring("HaveField could not find field named '%s' in struct:", "Abbreviation"))

success, err = HaveField("Prequel.Title", "Les Miserables 0").Match(book)
Ω(success).Should(BeFalse())
Ω(err.Error()).Should(ContainSubstring("HaveField encountered nil while dereferencing a pointer of type *matchers_test.Book."))
})
})

Expand Down

0 comments on commit 79e41a3

Please sign in to comment.