Home > Enterprise >  Function like assert.Contains by stretchr/testify but ignore case and whitespace
Function like assert.Contains by stretchr/testify but ignore case and whitespace

Time:09-02

For example, I have this test here

assert.Contains(t, "HELLO     WORLD", "hello world)

and I want this to return true. Obviously, I can clean up the string with strings.TrimSpace(), strings.ReplaceAll(), and strings.ToLower() beforehand. Although it gets cumbersome when I have dozens of these. Is there any cleaner way to achieve this? Or can I possibly modify or create a customized assert.NormalizedContains()? Thank you for the input!

CodePudding user response:

You could create a func normalize(s string) string and use that together with assert.Contains, for example:

func normalize(s string) string {
    return strings.ToLower(strings.Join(strings.Fields(s), ""))
}

func TestFoo(t *testing.T) {
    assert.Contains(t, normalize("HELLO     WORLD"), "hello world")
    // or you might want to normalize both:
    assert.Contains(t, normalize("HELLO     WORLD"), normalize("hello world"))
}

If you're really doing this a lot, you could create a custom func assertNormalizedContains(t *testing.T, haystack, needle string) and just use that instead of assert.Contains. Though I'd argue that's not as clear.

  • Related