Build excluding test modules

Issue

My project has the following structure:

├── api
│   ├── api.go
│   ├── api_test.go
│   ├── other_files...
├── cmd
│   └── main.go

Under cmd/main.go I have the entrypoint of my Go project.

Since I am also creating some test files, I have other classes used for test purposes.

My go.mod is like:

require (
    github.com/gorilla/mux v1.8.0
    github.com/stretchr/testify v1.6.1          <-used for test
    gotest.tools v2.2.0+incompatible            <-used for test 
    k8s.io/api v0.19.0
    k8s.io/apimachinery v0.19.0
    k8s.io/client-go v0.19.0
)

My doubt is related to the build phase:
When doing go build ./cmd/main.go, am I selecting only the correct modules used from main.go and all his references across the code, excluding the unused modules listed in go.mod used for test classes?

Is there any ldd command to be sure I am linking only the required modules?
I assume that Go is optimized to do that, but I would like to be sure about that.

Solution

When go builds a package normally (go build or go install) it will ignore any files with the name pattern *_test.go. This means that object code for any packages that are only imported from those test files will not be linked into your executable.

So if you’re just careful not to import the test packages from your non-test code you’re good.

If you’re not sure, you can check the "build list" by running:

go list -m all

From the root of your module. This will list the set of modules providing packages for the build.

Ref: go – The main module and the build list

Answered By – Ezequiel Muns

Answer Checked By – Katrina (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.