Skip to content

Commit

Permalink
Add a ContainsItem func (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
tamj0rd2 authored Sep 17, 2024
1 parent a8be363 commit 9b12f17
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
15 changes: 15 additions & 0 deletions assert.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,21 @@ func Contains(t testing.TB, haystack string, needle string, msgAndArgs ...any) {
t.Fatalf("%s\nNeedle: %q\nHaystack: %q\n", msg, needle, haystack)
}

// ContainsItem asserts that "haystack" contains "needle".
func ContainsItem[T any](t testing.TB, haystack []T, needle T, msgAndArgs ...interface{}) {
t.Helper()
for _, item := range haystack {
if objectsAreEqual(item, needle) {
return
}
}

msg := formatMsgAndArgs("Haystack does not contain needle.", msgAndArgs...)
needleRepr := repr.String(needle, repr.Indent(" "))
haystackRepr := repr.String(haystack, repr.Indent(" "))
t.Fatalf("%s\nNeedle: %s\nHaystack: %s\n", msg, needleRepr, haystackRepr)
}

// NotContains asserts that "haystack" does not contain "needle".
func NotContains(t testing.TB, haystack string, needle string, msgAndArgs ...any) {
if !strings.Contains(haystack, needle) {
Expand Down
9 changes: 9 additions & 0 deletions assert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,15 @@ func TestContains(t *testing.T) {
})
}

func TestContainsItem(t *testing.T) {
assertOk(t, "Found", func(t testing.TB) {
ContainsItem(t, []string{"hello", "world"}, "hello")
})
assertFail(t, "NotFound", func(t testing.TB) {
ContainsItem(t, []string{"hello", "world"}, "goodbye")
})
}

func TestNotContains(t *testing.T) {
assertOk(t, "NotFound", func(t testing.TB) {
NotContains(t, "a haystack with a needle in it", "screw")
Expand Down

0 comments on commit 9b12f17

Please sign in to comment.