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 functionsNo 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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With