类似于stretchr/testify中的assert.Contains函数,但忽略大小写和空白字符。

huangapple go评论72阅读模式
英文:

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

问题

例如,我有这个测试代码:

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

我希望这个测试返回 true。显然,我可以在测试之前使用 strings.TrimSpace()strings.ReplaceAll()strings.ToLower() 来清理字符串。但是当我有几十个这样的测试时,这样做会变得很繁琐。有没有更简洁的方法来实现这个?或者我是否可以修改或创建一个自定义的 assert.NormalizedContains()?谢谢你的建议!

英文:

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!

答案1

得分: 0

你可以创建一个名为 normalize 的函数,其参数为字符串类型,返回值也是字符串类型,并将其与 assert.Contains 一起使用,例如:

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")
    // 或者你可能想要同时规范化两个字符串:
    assert.Contains(t, normalize("HELLO     WORLD"), normalize("hello world"))
}

如果你确实经常这样做,你可以创建一个自定义的 assertNormalizedContains 函数,其参数为 t *testing.Thaystackneedle 两个字符串,并在使用时替代 assert.Contains。不过我认为这样做可能不够清晰。

英文:

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.

huangapple
  • 本文由 发表于 2022年9月1日 04:46:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/73561721.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定