只在测试文件中引用的测试代码会被编译进二进制文件吗?

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

Will go test code only referenced in test files be compiled into the binary?

问题

如果使用go build ./...编译二进制文件,其中的代码将会被编译进Go二进制文件中。这将生成一个包含CLI程序的二进制文件。对于这个CLI程序,我有测试代码和非测试代码。目前我有几种测试代码的形式:

  • foo_test.go,位于foo_test包中
  • foo_internal_test.go,位于foo包中
  • testutil.go,提供测试工具函数的testutil

非测试代码中实际上没有引用任何测试代码。测试工具函数只在测试文件中被导入。

如果测试代码实际上被编译进二进制文件中,这会带来多大的问题?

英文:

I am wondering what code will be compiled into the go binary if you compile a binary using go build ./... . This will compile a binary that has a cli program. For this cli program, I have test code and non test code. I currently have several flavours of test code:

  • foo_test.go in package foo_test
  • foo_internal_test.go in package foo
  • testutil.go in package testutil that provides test utility functions

No test code is actually referenced in the non test code. The testutil functions are only imported in the test files.

If the test code is infact compiled into the binary , how much of a problem is this?

答案1

得分: 13

一个 Go 二进制文件只包含从其 main() 入口点可访问的代码。对于测试二进制文件,main() 是测试运行器。

至于如果它被包含进去会有多大问题,实际上没有问题。这会稍微增加二进制文件的大小和编译时间,但除此之外没有任何影响 - 按定义而言,未执行的代码什么也不做。

英文:

A go binary only includes code reachable from its main() entry point. For test binaries main() is the test runner.

As to "how much of a problem" it is if it were included... none. It would increase the binary size and compilation time somewhat but otherwise have no impact - code that isn't executed, by definition, does nothing.

答案2

得分: 6

我相信,如果在一个无法访问的文件中有一个init()函数,它仍然会被链接到可执行文件中。

_test.go文件仍然会被排除。

当我们有一些测试辅助代码不在_test文件中时,这个问题就出现了。其中一个文件有一个init()函数,在可执行文件启动时运行。

英文:

I believe that if you have an init() function in an otherwise unreachable file, it will still be linked into the executable.

_test.go files would be still excluded.

This bit us when we had some test helper code that was not in _test files. One had an init() function which ran on the executable startup.

huangapple
  • 本文由 发表于 2017年6月22日 03:56:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/44685206.html
匿名

发表评论

匿名网友

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

确定