github.com/mook-as/cf-cli@v7.0.0-beta.28.0.20200120190804-b91c115fae48+incompatible/cf/util/testhelpers/matchers/contain_element_times.go (about) 1 package matchers 2 3 import ( 4 "errors" 5 "fmt" 6 "github.com/onsi/gomega" 7 "github.com/onsi/gomega/format" 8 "reflect" 9 ) 10 11 type ContainElementTimesMatcher struct { 12 Element interface{} 13 ExpectedCount int 14 ActualCount int 15 } 16 17 func ContainElementTimes(element interface{}, count int) gomega.OmegaMatcher { 18 return &ContainElementTimesMatcher{ 19 Element: element, 20 ExpectedCount: count, 21 } 22 } 23 24 func (matcher *ContainElementTimesMatcher) Match(actual interface{}) (success bool, err error) { 25 if !isArrayOrSlice(actual) { 26 return false, errors.New("expected an array") 27 } 28 29 actualValue := reflect.ValueOf(actual) 30 31 for i := 0; i < actualValue.Len(); i++ { 32 if reflect.DeepEqual(actualValue.Index(i).Interface(), matcher.Element) { 33 matcher.ActualCount++ 34 } 35 } 36 37 return matcher.ActualCount == matcher.ExpectedCount, nil 38 } 39 40 func (matcher *ContainElementTimesMatcher) FailureMessage(actual interface{}) (message string) { 41 return format.Message( 42 actual, 43 fmt.Sprintf( 44 "to contain element %v %d times, but found it %d times", 45 matcher.Element, 46 matcher.ExpectedCount, 47 matcher.ActualCount, 48 ), 49 ) 50 } 51 52 func (matcher *ContainElementTimesMatcher) NegatedFailureMessage(actual interface{}) (message string) { 53 return format.Message( 54 actual, 55 fmt.Sprintf( 56 "not to contain element %v %d times, but it did", 57 matcher.Element, 58 matcher.ExpectedCount, 59 ), 60 ) 61 }