Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

go - Build excluding test modules

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.

question from:https://stackoverflow.com/questions/65844499/build-excluding-test-modules

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...