massert: implement Len

This commit is contained in:
Brian Picciano 2018-07-16 00:38:00 +00:00
parent d3a81f9613
commit 0a4be2f8cd
2 changed files with 40 additions and 0 deletions

View File

@ -8,6 +8,7 @@ import (
"path/filepath" "path/filepath"
"reflect" "reflect"
"runtime" "runtime"
"strconv"
"strings" "strings"
"testing" "testing"
"text/tabwriter" "text/tabwriter"
@ -393,3 +394,18 @@ func HasKey(set, elem interface{}) Assertion {
return errors.New("value not a key in the map") return errors.New("value not a key in the map")
}, toStr(set)+" has key "+toStr(elem), 0) }, toStr(set)+" has key "+toStr(elem), 0)
} }
// Len asserts that the given set has the given number of elements in it. The
// set may be an array, a slice, or a map. A nil value'd set is considered to be
// a length of zero.
func Len(set interface{}, length int) Assertion {
return newAssertion(func() error {
setVV, err := toSet(set, false)
if err != nil {
return err
} else if len(setVV) != length {
return errors.New("set not correct length")
}
return nil
}, toStr(set)+" has length "+strconv.Itoa(length), 0)
}

View File

@ -172,3 +172,27 @@ func TestHasKey(t *T) {
HasKey(map[int]int{2: 2}, 1), HasKey(map[int]int{2: 2}, 1),
)) ))
} }
func TestLen(t *T) {
Fatal(t, All(
Len([]int(nil), 0),
Len([]int{}, 0),
Len([]int{1}, 1),
Len([]int{1, 2}, 2),
Len(map[int]int(nil), 0),
Len(map[int]int{}, 0),
Len(map[int]int{1: 1}, 1),
Len(map[int]int{1: 1, 2: 2}, 2),
))
Fatal(t, None(
Len([]int(nil), 1),
Len([]int{}, 1),
Len([]int{1}, 0),
Len([]int{1}, 2),
Len([]int{1, 2}, 1),
Len([]int{1, 2}, 3),
Len(map[int]int(nil), 1),
Len(map[int]int{}, 1),
))
}