Skip to content

Commit

Permalink
fix(BeElementOf): consistently flatten expected values
Browse files Browse the repository at this point in the history
  • Loading branch information
blgm committed Feb 2, 2021
1 parent dc1188a commit 1fa9468
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 21 deletions.
22 changes: 4 additions & 18 deletions matchers/be_element_of_matcher.go
Expand Up @@ -18,23 +18,9 @@ func (matcher *BeElementOfMatcher) Match(actual interface{}) (success bool, err
return false, fmt.Errorf("BeElement matcher expects actual to be typed")
}

length := len(matcher.Elements)
valueAt := func(i int) interface{} {
return matcher.Elements[i]
}
// Special handling of a single element of type Array or Slice
if length == 1 && isArrayOrSlice(valueAt(0)) {
element := valueAt(0)
value := reflect.ValueOf(element)
length = value.Len()
valueAt = func(i int) interface{} {
return value.Index(i).Interface()
}
}

var lastError error
for i := 0; i < length; i++ {
matcher := &EqualMatcher{Expected: valueAt(i)}
for _, m := range flatten(matcher.Elements) {
matcher := &EqualMatcher{Expected: m}
success, err := matcher.Match(actual)
if err != nil {
lastError = err
Expand All @@ -49,9 +35,9 @@ func (matcher *BeElementOfMatcher) Match(actual interface{}) (success bool, err
}

func (matcher *BeElementOfMatcher) FailureMessage(actual interface{}) (message string) {
return format.Message(actual, "to be an element of", matcher.Elements)
return format.Message(actual, "to be an element of", presentable(matcher.Elements))
}

func (matcher *BeElementOfMatcher) NegatedFailureMessage(actual interface{}) (message string) {
return format.Message(actual, "not to be an element of", matcher.Elements)
return format.Message(actual, "not to be an element of", presentable(matcher.Elements))
}
6 changes: 3 additions & 3 deletions matchers/be_element_of_matcher_test.go
Expand Up @@ -33,7 +33,7 @@ var _ = Describe("BeElementOf", func() {
})

When("passed a correctly typed nil", func() {
It("should operate succesfully on the passed in value", func() {
It("should operate successfully on the passed in value", func() {
var nilSlice []int
Expect(1).ShouldNot(BeElementOf(nilSlice))

Expand All @@ -56,11 +56,11 @@ var _ = Describe("BeElementOf", func() {

It("builds failure message", func() {
actual := BeElementOf(1, 2).FailureMessage(123)
Expect(actual).To(Equal("Expected\n <int>: 123\nto be an element of\n <[]interface {} | len:2, cap:2>: [1, 2]"))
Expect(actual).To(Equal("Expected\n <int>: 123\nto be an element of\n <[]int | len:2, cap:2>: [1, 2]"))
})

It("builds negated failure message", func() {
actual := BeElementOf(1, 2).NegatedFailureMessage(123)
Expect(actual).To(Equal("Expected\n <int>: 123\nnot to be an element of\n <[]interface {} | len:2, cap:2>: [1, 2]"))
Expect(actual).To(Equal("Expected\n <int>: 123\nnot to be an element of\n <[]int | len:2, cap:2>: [1, 2]"))
})
})

0 comments on commit 1fa9468

Please sign in to comment.