Skip to content

Commit

Permalink
assert: simplify Contains logic for byte slice
Browse files Browse the repository at this point in the history
  • Loading branch information
nickajacks1 committed Mar 7, 2024
1 parent e148db5 commit ee6de9c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 9 deletions.
11 changes: 5 additions & 6 deletions assert/assertions.go
Expand Up @@ -906,12 +906,11 @@ func containsElement(list interface{}, element interface{}) (ok, found bool) {
}
return true, false
case reflect.Slice:
// Special case: use bytes.Contains if both element and list are []byte.
elementValue := reflect.ValueOf(element)
if elementValue.Kind() == reflect.Slice &&
elementValue.Type().Elem().Kind() == reflect.Uint8 &&
listType.Elem().Kind() == reflect.Uint8 {
return true, bytes.Contains(listValue.Bytes(), elementValue.Bytes())
switch element := element.(type) {
case []byte:
if list, ok := list.([]byte); ok {
return true, bytes.Contains(list, element)
}
}
}

Expand Down
12 changes: 9 additions & 3 deletions assert/assertions_test.go
Expand Up @@ -922,15 +922,18 @@ func TestContainsNotContains(t *testing.T) {
}
list := []string{"Hello", "World"}

byteSliceList := [][]byte{
[]byte("Hello"), []byte("World"),
}

complexList := []*A{
{"b", "c"},
{"d", "e"},
{"g", "h"},
{"j", "k"},
}
byteSliceList := [][]byte{
[]byte("Hello"), []byte("World"),
}

interfaceList := []interface{}{"Hello World", 5, 2, []byte("Goodbye")}

simpleMap := map[interface{}]interface{}{"Hello": "World"}
var zeroMap map[interface{}]interface{}
Expand All @@ -950,6 +953,9 @@ func TestContainsNotContains(t *testing.T) {
{byteSliceList, []byte("Earth"), false},
{complexList, &A{"g", "h"}, true},
{complexList, &A{"g", "e"}, false},
{interfaceList, 5, true},
{interfaceList, []byte("Goodbye"), true},
{interfaceList, "World", false},
{simpleMap, "Hello", true},
{simpleMap, "Earth", false},
{zeroMap, "Bar", false},
Expand Down

0 comments on commit ee6de9c

Please sign in to comment.