diff --git a/assert.go b/assert.go index 1e4fccf..9dce84e 100644 --- a/assert.go +++ b/assert.go @@ -57,6 +57,26 @@ func extractCompareOptions(msgAndArgs ...any) ([]any, []CompareOption) { return out, compareOptions } +// HasPrefix asserts that the string s starts with prefix. +func HasPrefix(t testing.TB, s, prefix string, msgAndArgs ...any) { + if strings.HasPrefix(s, prefix) { + return + } + t.Helper() + msg := formatMsgAndArgs("Expected string to have prefix:", msgAndArgs...) + t.Fatalf("%s\nPrefix: %q\nString: %q\n", msg, prefix, s) +} + +// HasSuffix asserts that the string s ends with suffix. +func HasSuffix(t testing.TB, s, suffix string, msgAndArgs ...any) { + if strings.HasSuffix(s, suffix) { + return + } + t.Helper() + msg := formatMsgAndArgs("Expected string to have suffix:", msgAndArgs...) + t.Fatalf("%s\nSuffix: %q\nString: %q\n", msg, suffix, s) +} + // Equal asserts that "expected" and "actual" are equal. // // If they are not, a diff of the Go representation of the values will be displayed. diff --git a/assert_test.go b/assert_test.go index 3d1fe9f..cc49c8e 100644 --- a/assert_test.go +++ b/assert_test.go @@ -176,6 +176,24 @@ func TestDiff(t *testing.T) { Equal(t, "-before\n+after\n", diff("before", "after")) } +func TestHasSuffix(t *testing.T) { + assertOk(t, "Suffix", func(t testing.TB) { + HasSuffix(t, "hello", "lo") + }) + assertFail(t, "NoSuffix", func(t testing.TB) { + HasSuffix(t, "hello", "world") + }) +} + +func TestHasPrefix(t *testing.T) { + assertOk(t, "Prefix", func(t testing.TB) { + HasPrefix(t, "hello", "he") + }) + assertFail(t, "NoPrefix", func(t testing.TB) { + HasPrefix(t, "hello", "world") + }) +} + type testTester struct { *testing.T failed string