12

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?

4
  • What binary are you referring to? If you're not building a test binary, you're not compiling *_test.go files, so they're not just eliminated during linking, they're never compiled at all.
    – JimB
    Jun 21, 2017 at 20:11
  • I hopefully clarified the question Jun 21, 2017 at 21:06
  • *_test.go files are only included by the go test command, in the named package. They are never even seen by the compiler otherwise.
    – JimB
    Jun 21, 2017 at 21:07
  • BTW, you can't compile a binary with go build ./..., that is building all the packages included in the wildcard, then discarding all the compiled objects.
    – JimB
    Jun 21, 2017 at 21:09

2 Answers 2

14

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.

1
  • 8
    Interesting edge case is when using helper functions for testing. These helpers can import additional packages. It might make significant difference to size of prod vs testing code when you have test only dependencies. I agree, Go should eliminate all dead code. But it would be nice to be explicit about this rather then rely on magic.
    – mikijov
    Jan 28, 2018 at 20:42
6

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.