MCPcopy Create free account
hub / github.com/stretchr/testify / Subset

Function Subset

assert/assertions.go:972–1022  ·  view source on GitHub ↗

Subset asserts that the specified list(array, slice...) or map contains all elements given in the specified subset list(array, slice...) or map. assert.Subset(t, [1, 2, 3], [1, 2]) assert.Subset(t, {"x": 1, "y": 2}, {"x": 1})

(t TestingT, list, subset interface{}, msgAndArgs ...interface{})

Source from the content-addressed store, hash-verified

970// assert.Subset(t, [1, 2, 3], [1, 2])
971// assert.Subset(t, {"x": 1, "y": 2}, {"x": 1})
972func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) {
973 if h, ok := t.(tHelper); ok {
974 h.Helper()
975 }
976 if subset == nil {
977 return true // we consider nil to be equal to the nil set
978 }
979
980 listKind := reflect.TypeOf(list).Kind()
981 if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map {
982 return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
983 }
984
985 subsetKind := reflect.TypeOf(subset).Kind()
986 if subsetKind != reflect.Array && subsetKind != reflect.Slice && listKind != reflect.Map {
987 return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
988 }
989
990 if subsetKind == reflect.Map && listKind == reflect.Map {
991 subsetMap := reflect.ValueOf(subset)
992 actualMap := reflect.ValueOf(list)
993
994 for _, k := range subsetMap.MapKeys() {
995 ev := subsetMap.MapIndex(k)
996 av := actualMap.MapIndex(k)
997
998 if !av.IsValid() {
999 return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, subset), msgAndArgs...)
1000 }
1001 if !ObjectsAreEqual(ev.Interface(), av.Interface()) {
1002 return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, subset), msgAndArgs...)
1003 }
1004 }
1005
1006 return true
1007 }
1008
1009 subsetList := reflect.ValueOf(subset)
1010 for i := 0; i < subsetList.Len(); i++ {
1011 element := subsetList.Index(i).Interface()
1012 ok, found := containsElement(list, element)
1013 if !ok {
1014 return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", list), msgAndArgs...)
1015 }
1016 if !found {
1017 return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, element), msgAndArgs...)
1018 }
1019 }
1020
1021 return true
1022}
1023
1024// NotSubset asserts that the specified list(array, slice...) or map does NOT
1025// contain all elements given in the specified subset list(array, slice...) or

Callers 4

SubsetFunction · 0.92
SubsetfFunction · 0.70
TestSubsetNotSubsetFunction · 0.70
SubsetMethod · 0.70

Calls 5

ObjectsAreEqualFunction · 0.85
containsElementFunction · 0.85
FailFunction · 0.70
HelperMethod · 0.65
LenMethod · 0.45

Tested by 1

TestSubsetNotSubsetFunction · 0.56