Skip to content

Commit

Permalink
fix incorrect handling of nil slices in HaveExactElements (fixes #771)
Browse files Browse the repository at this point in the history
  • Loading branch information
onsi committed Jul 25, 2024
1 parent f5bec80 commit 878940c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
7 changes: 6 additions & 1 deletion matchers/have_exact_elements.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,18 @@ func (matcher *HaveExactElementsMatcher) Match(actual interface{}) (success bool

lenMatchers := len(matchers)
lenValues := len(values)
success = true

for i := 0; i < lenMatchers || i < lenValues; i++ {
if i >= lenMatchers {
matcher.extraIndex = i
success = false
continue
}

if i >= lenValues {
matcher.missingIndex = i
success = false
return
}

Expand All @@ -49,15 +52,17 @@ func (matcher *HaveExactElementsMatcher) Match(actual interface{}) (success bool
index: i,
failure: err.Error(),
})
success = false
} else if !match {
matcher.mismatchFailures = append(matcher.mismatchFailures, mismatchFailure{
index: i,
failure: elemMatcher.FailureMessage(values[i]),
})
success = false
}
}

return matcher.missingIndex+matcher.extraIndex+len(matcher.mismatchFailures) == 0, nil
return success, nil
}

func (matcher *HaveExactElementsMatcher) FailureMessage(actual interface{}) (message string) {
Expand Down
10 changes: 10 additions & 0 deletions matchers/have_exact_elements_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,16 @@ var _ = Describe("HaveExactElements", func() {
})
})

When("passed nil", func() {
It("should fail correctly", func() {
failures := InterceptGomegaFailures(func() {
var expected []any
Expect([]string{"one"}).Should(HaveExactElements(expected...))
})
Expect(failures).Should(HaveLen(1))
})
})

Describe("Failure Message", func() {
When("actual contains extra elements", func() {
It("should print the starting index of the extra elements", func() {
Expand Down

0 comments on commit 878940c

Please sign in to comment.