Skip to content

Commit

Permalink
feat: add HasSuffix and HasPrefix
Browse files Browse the repository at this point in the history
I am manually doing this  a lot in a very janky way: `assert.True(t,
strings.HasPrefix(...))`
  • Loading branch information
alecthomas committed May 1, 2024
1 parent a1597e0 commit fe12b41
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
20 changes: 20 additions & 0 deletions assert.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
18 changes: 18 additions & 0 deletions assert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit fe12b41

Please sign in to comment.