Skip to content

Commit

Permalink
Add SliceMatcher type to objmatcher package (#118)
Browse files Browse the repository at this point in the history
  • Loading branch information
nmiyake authored Nov 6, 2018
1 parent 05f3741 commit 55589af
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 0 deletions.
23 changes: 23 additions & 0 deletions objmatcher/matcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,29 @@ func (m RegExpMatcher) String() string {
return fmt.Sprintf("matchesRegexp(%s)", m.WantRegexp)
}

type SliceMatcher []Matcher

func (s SliceMatcher) Matches(in interface{}) error {
items := reflect.ValueOf(in)
switch items.Kind() {
case reflect.Slice, reflect.Array:
break
default:
return fmt.Errorf("kind of %v is not a slice or array", in)
}

if len(s) != items.Len() {
return fmt.Errorf("want: %+v\ngot: %+v\nsize %d != %d", s, in, len(s), items.Len())
}
for i := 0; i < items.Len(); i++ {
if err := s[i].Matches(items.Index(i).Interface()); err != nil {
indented := strings.Replace("\n"+err.Error(), "\n", "\n\t", -1)
return fmt.Errorf("want: %+v\ngot: %+v\nvalue for index %d did not match:%s", s, in, i, indented)
}
}
return nil
}

type MapMatcher map[string]Matcher

func (m MapMatcher) Matches(in interface{}) error {
Expand Down
63 changes: 63 additions & 0 deletions objmatcher/matcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,66 @@ func TestEqualsMatcher(t *testing.T) {
}
}
}

func TestMapMatcher(t *testing.T) {
for i, tc := range []struct {
name string
matcher objmatcher.MapMatcher
given interface{}
wantErr string
}{
{
name: "map matches",
matcher: objmatcher.MapMatcher(map[string]objmatcher.Matcher{
"key": objmatcher.NewEqualsMatcher("value"),
}),
given: map[string]interface{}{
"key": "value",
},
},
} {
gotErr := tc.matcher.Matches(tc.given)
if tc.wantErr == "" {
assert.NoError(t, gotErr, "Case %d: %v", i, tc.name)
} else {
assert.EqualError(t, gotErr, tc.wantErr, "Case %d: %v", i, tc.name)
}
}
}

func TestSliceMatcher(t *testing.T) {
for i, tc := range []struct {
name string
matcher objmatcher.SliceMatcher
given interface{}
wantErr string
}{
{
name: "strings slice matches",
matcher: objmatcher.SliceMatcher([]objmatcher.Matcher{
objmatcher.NewEqualsMatcher("hello"),
}),
given: []string{
"hello",
},
},
{
name: "unequal slice length fails",
matcher: objmatcher.SliceMatcher([]objmatcher.Matcher{
objmatcher.NewEqualsMatcher("hello"),
}),
given: []string{
"hello",
"goodbye",
},
wantErr: "want: [equals(string(hello))]\ngot: [hello goodbye]\nsize 1 != 2",
},
} {
gotErr := tc.matcher.Matches(tc.given)
if tc.wantErr == "" {
assert.NoError(t, gotErr, "Case %d: %v", i, tc.name)
} else {
assert.EqualError(t, gotErr, tc.wantErr, "Case %d: %v", i, tc.name)
}
}
}

0 comments on commit 55589af

Please sign in to comment.