Skip to content
This repository has been archived by the owner on May 2, 2020. It is now read-only.

Commit

Permalink
Add Len()
Browse files Browse the repository at this point in the history
  • Loading branch information
tylerb committed Apr 11, 2016
1 parent f974651 commit 7fb88d3
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
18 changes: 18 additions & 0 deletions is.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"io"
"log"
"os"
"reflect"
"testing"
)

Expand Down Expand Up @@ -221,6 +222,23 @@ func (is *Is) NotZero(o interface{}) {
}
}

// Len checks the provided object to determine if it is the same length as the
// provided length argument.
//
// If the object is not one of type array, slice or map, it will fail.
func (is *Is) Len(o interface{}, l int) {
t := reflect.TypeOf(o)
if t.Kind() != reflect.Array &&
t.Kind() != reflect.Slice &&
t.Kind() != reflect.Map {
fail(is, "expected object '%s' to be of length '%d', but the object is not one of array, slice or map", objectTypeName(o), l)
}

if reflect.ValueOf(o).Len() != l {
fail(is, "expected object '%s' to be of length '%d'", objectTypeName(o), l)
}
}

// SetOutput changes the message output Writer from the default (os.Stdout).
// This may be useful if the application under test takes over the console, or
// if logging to a file is desired.
Expand Down
9 changes: 9 additions & 0 deletions is_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,15 @@ func TestIs(t *testing.T) {
is.OneOf(1, 2, 3, 1)
is.NotOneOf(1, 2, 3)

lens := []interface{}{
[]int{1, 2, 3},
[3]int{1, 2, 3},
map[int]int{1: 1, 2: 2, 3: 3},
}
for _, l := range lens {
is.Len(l, 3)
}

fail = func(is *Is, format string, args ...interface{}) {}
is.Equal((*testStruct)(nil), &testStruct{})
is.Equal(&testStruct{}, (*testStruct)(nil))
Expand Down

0 comments on commit 7fb88d3

Please sign in to comment.