-
Notifications
You must be signed in to change notification settings - Fork 8
/
have_key.go
38 lines (31 loc) · 859 Bytes
/
have_key.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package matchers
import (
"fmt"
"reflect"
)
// HaveKeyMatcher accepts map types and will succeed if the map contains the
// specified key.
type HaveKeyMatcher struct {
key any
}
// HaveKey returns a HaveKeyMatcher with the specified key.
func HaveKey(key any) HaveKeyMatcher {
return HaveKeyMatcher{
key: key,
}
}
func (m HaveKeyMatcher) Match(actual any) (any, error) {
t := reflect.TypeOf(actual)
if t.Kind() != reflect.Map {
return nil, fmt.Errorf("'%v' (%T) is not a Map", actual, actual)
}
if t.Key() != reflect.TypeOf(m.key) {
return nil, fmt.Errorf("'%v' (%T) has a Key type of %v not %T", actual, actual, t.Key(), m.key)
}
v := reflect.ValueOf(actual)
value := v.MapIndex(reflect.ValueOf(m.key))
if !value.IsValid() {
return nil, fmt.Errorf("unable to find key %v in %v", m.key, actual)
}
return value.Interface(), nil
}