Skip to content

Commit

Permalink
test: add SliceNotContainsFunc assertion (#115)
Browse files Browse the repository at this point in the history
Fixes: #110
  • Loading branch information
shoenig authored Mar 20, 2023
1 parent 63e356f commit f7cac66
Show file tree
Hide file tree
Showing 5 changed files with 56 additions and 0 deletions.
8 changes: 8 additions & 0 deletions internal/assertions/assertions.go
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,14 @@ func SliceNotContains[A any](slice []A, item A, opts ...cmp.Option) (s string) {
return
}

func SliceNotContainsFunc[A, B any](slice []A, item B, eq func(a A, b B) bool) (s string) {
if containsFunc(slice, item, eq) {
s = "expected slice to not contain item but it does\n"
s += bullet("unwanted item %#v\n", item)
}
return
}

func SliceContainsAll[A any](slice, items []A) (s string) {
if len(slice) != len(items) {
s = "expected slice and items to contain same number of elements\n"
Expand Down
7 changes: 7 additions & 0 deletions must/must.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 17 additions & 0 deletions must/must_test.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions test.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,13 @@ func SliceNotContains[A any](t T, slice []A, item A, settings ...Setting) {
invoke(t, assertions.SliceNotContains(slice, item), settings...)
}

// SliceNotContainsFunc asserts item does not exist inslice, using eq to compare
// elements.
func SliceNotContainsFunc[A, B any](t T, slice []A, item B, eq func(a A, b B) bool, settings ...Setting) {
t.Helper()
invoke(t, assertions.SliceNotContainsFunc(slice, item, eq), settings...)
}

// SliceContainsAll asserts slice and items contain the same elements, but in
// no particular order. The number of elements in slice and items must be the
// same.
Expand Down
17 changes: 17 additions & 0 deletions test_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -649,6 +649,23 @@ func TestSliceNotContains(t *testing.T) {
SliceNotContains(tc, s, &Person{ID: 101, Name: "Bob"})
}

func TestSliceNotContainsFunc(t *testing.T) {
tc := newCase(t, `expected slice to not contain item but it does`)
t.Cleanup(tc.assert)

s := []*Person{
{ID: 100, Name: "Alice"},
{ID: 101, Name: "Bob"},
{ID: 102, Name: "Carla"},
}

f := func(a, b *Person) bool {
return a.Name == b.Name && a.ID == b.ID
}

SliceNotContainsFunc(tc, s, &Person{ID: 101, Name: "Bob"}, f)
}

func TestSliceContainsAll(t *testing.T) {
t.Run("wrong element", func(t *testing.T) {
tc := newCase(t, `expected slice to contain missing item`)
Expand Down

0 comments on commit f7cac66

Please sign in to comment.