Subset asserts that the list (array, slice, or map) contains all elements given in the subset (array, slice, or map). Map elements are key-value pairs unless compared with an array or slice where only the map key is evaluated. assert.Subset(t, [1, 2, 3], [1, 2]) assert.Subset(t, {"x": 1, "y": 2},
(t TestingT, list, subset interface{}, msgAndArgs ...interface{})
| 1005 | // assert.Subset(t, [1, 2, 3], {1: "one", 2: "two"}) |
| 1006 | // assert.Subset(t, {"x": 1, "y": 2}, ["x"]) |
| 1007 | func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) { |
| 1008 | if h, ok := t.(tHelper); ok { |
| 1009 | h.Helper() |
| 1010 | } |
| 1011 | if subset == nil { |
| 1012 | return true // we consider nil to be equal to the nil set |
| 1013 | } |
| 1014 | |
| 1015 | listKind := reflect.TypeOf(list).Kind() |
| 1016 | if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map { |
| 1017 | return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...) |
| 1018 | } |
| 1019 | |
| 1020 | subsetKind := reflect.TypeOf(subset).Kind() |
| 1021 | if subsetKind != reflect.Array && subsetKind != reflect.Slice && subsetKind != reflect.Map { |
| 1022 | return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...) |
| 1023 | } |
| 1024 | |
| 1025 | if subsetKind == reflect.Map && listKind == reflect.Map { |
| 1026 | subsetMap := reflect.ValueOf(subset) |
| 1027 | actualMap := reflect.ValueOf(list) |
| 1028 | |
| 1029 | for _, k := range subsetMap.MapKeys() { |
| 1030 | ev := subsetMap.MapIndex(k) |
| 1031 | av := actualMap.MapIndex(k) |
| 1032 | |
| 1033 | if !av.IsValid() { |
| 1034 | return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, subset), msgAndArgs...) |
| 1035 | } |
| 1036 | if !ObjectsAreEqual(ev.Interface(), av.Interface()) { |
| 1037 | return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, subset), msgAndArgs...) |
| 1038 | } |
| 1039 | } |
| 1040 | |
| 1041 | return true |
| 1042 | } |
| 1043 | |
| 1044 | subsetList := reflect.ValueOf(subset) |
| 1045 | if subsetKind == reflect.Map { |
| 1046 | keys := make([]interface{}, subsetList.Len()) |
| 1047 | for idx, key := range subsetList.MapKeys() { |
| 1048 | keys[idx] = key.Interface() |
| 1049 | } |
| 1050 | subsetList = reflect.ValueOf(keys) |
| 1051 | } |
| 1052 | for i := 0; i < subsetList.Len(); i++ { |
| 1053 | element := subsetList.Index(i).Interface() |
| 1054 | ok, found := containsElement(list, element) |
| 1055 | if !ok { |
| 1056 | return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", list), msgAndArgs...) |
| 1057 | } |
| 1058 | if !found { |
| 1059 | return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, element), msgAndArgs...) |
| 1060 | } |
| 1061 | } |
| 1062 | |
| 1063 | return true |
| 1064 | } |