Skip to content

Commit fe12b41

Browse files
committed
feat: add HasSuffix and HasPrefix
I am manually doing this a lot in a very janky way: `assert.True(t, strings.HasPrefix(...))`
1 parent a1597e0 commit fe12b41

2 files changed

Lines changed: 38 additions & 0 deletions

File tree

assert.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,26 @@ func extractCompareOptions(msgAndArgs ...any) ([]any, []CompareOption) {
5757
return out, compareOptions
5858
}
5959

60+
// HasPrefix asserts that the string s starts with prefix.
61+
func HasPrefix(t testing.TB, s, prefix string, msgAndArgs ...any) {
62+
if strings.HasPrefix(s, prefix) {
63+
return
64+
}
65+
t.Helper()
66+
msg := formatMsgAndArgs("Expected string to have prefix:", msgAndArgs...)
67+
t.Fatalf("%s\nPrefix: %q\nString: %q\n", msg, prefix, s)
68+
}
69+
70+
// HasSuffix asserts that the string s ends with suffix.
71+
func HasSuffix(t testing.TB, s, suffix string, msgAndArgs ...any) {
72+
if strings.HasSuffix(s, suffix) {
73+
return
74+
}
75+
t.Helper()
76+
msg := formatMsgAndArgs("Expected string to have suffix:", msgAndArgs...)
77+
t.Fatalf("%s\nSuffix: %q\nString: %q\n", msg, suffix, s)
78+
}
79+
6080
// Equal asserts that "expected" and "actual" are equal.
6181
//
6282
// If they are not, a diff of the Go representation of the values will be displayed.

assert_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,24 @@ func TestDiff(t *testing.T) {
176176
Equal(t, "-before\n+after\n", diff("before", "after"))
177177
}
178178

179+
func TestHasSuffix(t *testing.T) {
180+
assertOk(t, "Suffix", func(t testing.TB) {
181+
HasSuffix(t, "hello", "lo")
182+
})
183+
assertFail(t, "NoSuffix", func(t testing.TB) {
184+
HasSuffix(t, "hello", "world")
185+
})
186+
}
187+
188+
func TestHasPrefix(t *testing.T) {
189+
assertOk(t, "Prefix", func(t testing.TB) {
190+
HasPrefix(t, "hello", "he")
191+
})
192+
assertFail(t, "NoPrefix", func(t testing.TB) {
193+
HasPrefix(t, "hello", "world")
194+
})
195+
}
196+
179197
type testTester struct {
180198
*testing.T
181199
failed string

0 commit comments

Comments
 (0)