massert: implement HasKey

This commit is contained in:
Brian Picciano 2018-07-16 00:08:23 +00:00
parent 69e3019fbf
commit d3a81f9613
2 changed files with 33 additions and 0 deletions

View File

@ -375,3 +375,21 @@ func Has(set, elem interface{}) Assertion {
return errors.New("value not in set")
}, toStr(set)+" has value "+toStr(elem), 0)
}
// HasKey asserts that the given set (which must be a map type) has the given
// element as a key in it.
func HasKey(set, elem interface{}) Assertion {
return newAssertion(func() error {
v := reflect.ValueOf(set)
if v.Kind() != reflect.Map {
return fmt.Errorf("type %s is not a map", v.Type())
}
for _, key := range v.MapKeys() {
if reflect.DeepEqual(key.Interface(), elem) {
return nil
}
}
return errors.New("value not a key in the map")
}, toStr(set)+" has key "+toStr(elem), 0)
}

View File

@ -157,3 +157,18 @@ func TestHas(t *T) {
Has(map[int]int{1: 2, 2: 1}, 3),
))
}
func TestHasKey(t *T) {
Fatal(t, All(
HasKey(map[int]int{1: 1}, 1),
HasKey(map[int]int{1: 1, 2: 2}, 1),
HasKey(map[int]int{1: 1, 2: 2}, 2),
))
Fatal(t, None(
HasKey([]int{}, 1),
HasKey([]int{1}, 1),
HasKey(map[int]int{}, 1),
HasKey(map[int]int{2: 2}, 1),
))
}