Build excluding test modules

9.2k Views Asked by At

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 its 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.

2

There are 2 best solutions below

0
On BEST ANSWER

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

0
On

When you run go build, it will:

  • Examine the package being built for import statements
  • Examine each of the imported packages for import statements
  • ... and so on, until it finds all transitive dependencies.
  • For each package to be built, it then examines the build constraints, and builds the files that are not excluded. *_test.go files are excluded by default, go test explicitly includes them when building tests.

This means that:

  • 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.