Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 581
snorberhuis Avatar asked Jun 21 '17 19:06

snorberhuis


People also ask

Where does Golang store test files?

By convention, Go testing files are always located in the same folder, or package, where the code they are testing resides. These files are not built by the compiler when you run the go build command, so you needn't worry about them ending up in deployments.

Does go build ignore test files?

Test files won't be included in a non-test build unless you explicitly include them. Unreferenced packages won't be included at all. What's in go. mod is irrelevant to the build: it's used only for dependency management, not compilation.

Should tests be in the same package Golang?

Test Files and Test PackagesWithin a single folder, all Go files must be in the same package. The one exception is test files: those with a _test.go suffix. There is a really good reason for that: your test files should always be in a different package.

How do you do a go test?

At the command line in the greetings directory, run the go test command to execute the test. The go test command executes test functions (whose names begin with Test ) in test files (whose names end with _test.go). You can add the -v flag to get verbose output that lists all of the tests and their results.


2 Answers

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.

like image 63
Adrian Avatar answered Sep 20 '22 17:09

Adrian


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.

like image 45
user3014416 Avatar answered Sep 23 '22 17:09

user3014416