|
| 1 | +package matcher |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + |
| 6 | + "github.com/getapid/apid/log" |
| 7 | +) |
| 8 | + |
| 9 | +type lenMatcher struct { |
| 10 | + value int |
| 11 | +} |
| 12 | + |
| 13 | +func LenMatcherWithOptions(params interface{}) Matcher { |
| 14 | + switch v := params.(type) { |
| 15 | + case float64: |
| 16 | + // check if value is int, json unmarshal puts |
| 17 | + // numbers in float64 |
| 18 | + if v == float64(int(v)) { |
| 19 | + return lenMatcher{int(v)} |
| 20 | + } |
| 21 | + log.L.Fatalf("invalid len matcher, got %v", params) |
| 22 | + default: |
| 23 | + log.L.Fatalf("invalid len matcher, got %v", params) |
| 24 | + } |
| 25 | + return nil |
| 26 | +} |
| 27 | + |
| 28 | +func (m lenMatcher) Match(data interface{}, location string) (bool, []string, []string) { |
| 29 | + switch val := data.(type) { |
| 30 | + case []interface{}: |
| 31 | + if len(val) == m.value { |
| 32 | + return true, []string{fmt.Sprintf("`%s` has length %d", location, m.value)}, nil |
| 33 | + } |
| 34 | + return true, nil, []string{fmt.Sprintf("`%s` of length %d wanted, got %d", location, m.value, len(val))} |
| 35 | + case map[string]interface{}: |
| 36 | + if len(val) == m.value { |
| 37 | + return true, []string{fmt.Sprintf("`%s` has length %d", location, m.value)}, nil |
| 38 | + } |
| 39 | + return true, nil, []string{fmt.Sprintf("`%s` of length %d wanted, got %d", location, m.value, len(val))} |
| 40 | + case string: |
| 41 | + if len(val) == m.value { |
| 42 | + return true, []string{fmt.Sprintf("`%s` has length %d", location, m.value)}, nil |
| 43 | + } |
| 44 | + return false, nil, []string{fmt.Sprintf("`%s` of length %d wanted, got %d", location, m.value, len(val))} |
| 45 | + default: |
| 46 | + return false, nil, []string{fmt.Sprintf("`%s` not a map, array or string", location)} |
| 47 | + } |
| 48 | + |
| 49 | +} |
| 50 | + |
| 51 | +func (m lenMatcher) String() string { |
| 52 | + return fmt.Sprintf("of lentgh %d", m.value) |
| 53 | +} |
0 commit comments