Best way to use test dependencies in Go but prevent export them

13.7k views Asked by At

Given a project in Golang (1.14+) which is using test dependencies (like github.com/stretchr/testify) and now assume this project is a public library which can be used by others.

Usually when I now use go mod graph I'll always see this dependency like:

github.com/its-me/[email protected]
github.com/stretchr/[email protected] github.com/davecgh/[email protected]
github.com/stretchr/[email protected] github.com/pmezard/[email protected]
github.com/stretchr/[email protected] github.com/stretchr/[email protected]
github.com/stretchr/[email protected] gopkg.in/[email protected]
gopkg.in/[email protected] gopkg.in/[email protected]

go mod tidy or go mod download also seems to download all the test dependencies from the used lib. But instead of telling everybody to use exclude in their go.mod files is there a way to even prevent this been exported?

1

There are 1 answers

0
bcmills On

go mod tidy is intended to provide all of the dependencies needed to run go test all. Note that in Go 1.16, go test all will be somewhat less aggressive about transitive dependencies of tests (https://tip.golang.org/doc/go1.16#all-pattern).

However, if your own test itself is using testify, then users of your package will need to download testify in order to run go test all in their own module.

(As colm.anseo notes, if you want you can split out the heavier tests to a separate package, so that when your users run go test all they will not run those tests and will not need to download the source code for those dependencies.)

Note that Go 1.17 adds support for module graph pruning: if your module specifies go 1.17 or higher and a consumer of your module does not use your test dependency in their own module, they will not need to download the source code or go.mod file for that dependency. (And once https://golang.org/issue/44435 is implemented, when they run go mod download it will not download the irrelevant dependency either.)