报告测试失败时,为什么golang测试包会用下划线替换空格?

报告测试失败时,为什么golang测试包会用下划线替换空格?

问题描述:

When I run this test and it fails:

func TestCaseA(t *testing.T){
    t.Run("my name with spaces", func (t *testing.T){
        t.Error("some error message")
    })
}

then the name of the test is modified (spaces are changed to underscores) in the output:

--- FAIL: TestCaseA (0.00s)
    --- FAIL: TestCaseA/my_name_with_spaces (0.00s)
        main.go:10: some error message
FAIL

Why does it do this?

Here's a working example: https://play.golang.org/p/viZjC60Dazg

当我运行此测试并失败时: p>

  func  TestCaseA(t * testing.T){
 t.Run(“我的名字带空格”,func(t * testing.T){
 t.Error(“某些错误消息”)
})
}  
  code>  pre> 
 
 

,然后在输出中修改测试名称(空格更改为下划线): p>

   ---失败:TestCaseA(0.00s)
 ---失败:TestCaseA / my_name_with_spaces(0.00s)
 main.go:10:一些错误消息
FAIL 
  code>  pre> 
 \  n 

为什么要这样做? p>

这是一个有效的示例: https://play.golang.org/p/viZjC60Dazg p> div>

It's explained in this blog post: https://blog.golang.org/subtests

The full name of a subtest or sub-benchmark is a slash-separated list of its name and the names of all of its parents, starting with the top-level. The name is the corresponding function name for top-level tests and benchmarks, and the first argument to Run otherwise. To avoid display and parsing issues, a name is sanitized by replacing spaces with underscores and escaping non-printable characters. The same sanitizing is applied to the regular expressions passed to the -run or -bench flags.

Some examples could be to make it simpler for automated tools to process the test output, to avoid issues with the shell making regex arguments containing spaces appearing as multiple arguments etc. I'd rather avoid using spaces than deal with this magic renaming.

I found the most definitive answer I could, in the code itself, of course. The rewrite function comment reads

rewrite rewrites a subname to having only printable characters and no white space.

https://golang.org/src/testing/match.go#L133

As to why? I'm guessing JimB hit the nail on the head with his comment:

As for why, maybe because it's easier to reference names without spaces in the cli?

White spaces are bad for cli.