登录
首页 >  Golang >  Go问答

防止在Go中导出测试依赖项的最佳实践

来源:stackoverflow

时间:2024-03-20 22:09:33 326浏览 收藏

在 Go 中开发可供他人使用的公共库时,防止导出测试依赖项非常重要。通常情况下,使用 `go mod graph` 会显示测试依赖项的传递依赖关系,并且 `go mod tidy` 或 `go mod download` 会从库中下载所有测试依赖项。本文介绍了防止导出测试依赖项的最佳实践,包括使用 `exinclude`、将测试拆分到单独的包中,以及利用 Go 1.17 中的模块图修剪功能。

问题内容

给定 golang (1.14+) 中的一个项目,该项目使用测试依赖项(如 github.com/stretchr/testify),现在假设该项目是一个可供其他人使用的公共库。

通常当我现在使用 go mod graph 时,我总是会看到这样的依赖关系:

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 tidygo mod download 似乎也从使用的库下载所有测试依赖项。但不是告诉每个人在他们的 go.mod 文件中使用 exinclude 有没有办法甚至阻止它被导出?


解决方案


go mod tidy 旨在提供运行 go 测试 all 所需的所有依赖项。请注意,在 Go 1.16 中,go 测试 all 对于测试的传递依赖性会稍微不那么激进 (https://tip.golang.org/doc/go1.16#all-pattern)。

但是,如果您自己的测试本身使用 testify,那么您的软件包的用户需要下载 testify 才能在自己的模块中运行 go 测试 all

(正如 colm.anseo 所指出的,如果您愿意,您可以将较重的测试拆分到单独的包中,这样当您的用户运行 go test all 时,他们将不会运行这些测试,并且不需要下载源代码这些依赖项。)

请注意,Go 1.17 添加了对 module graph pruning 的支持:如果您的模块指定 go 1.17 或更高版本,并且您的模块的使用者不在自己的模块中使用您的测试依赖项,则他们不需要下载源代码或 go。该依赖项的 mod 文件。 (一旦实现了https://golang.org/issue/44435,当他们运行go mod download时,它也不会下载不相关的依赖项。)

理论要掌握,实操不能落!以上关于《防止在Go中导出测试依赖项的最佳实践》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>