Bazel Go测试中跨目录访问测试文件变量的可行性咨询
Bazel Go测试中跨目录访问测试文件变量的可行性咨询
嘿,我来帮你梳理这个问题!能不能访问到variables_test.go里的变量,得从Go语言本身的包规则和Bazel的构建配置两方面来看,下面给你拆解清楚:
一、先看Go语言层面的限制
Go的包访问规则是核心前提:
- 如果
variables_test.go里的变量是小写开头(未导出):不管你怎么配置Bazel,都没法在其他包的文件里访问到——这是Go的包级私有特性,没商量。 - 如果变量是大写开头(导出):还要看两个文件的包声明:
- 情况1:
endpoint_1目录下的文件包名和上层module_name一致(比如都声明package module_name)。这种跨目录同包的写法虽然技术上可行,但不符合Go的常规项目结构,容易引发编译混乱,非常不推荐。 - 情况2:
endpoint_1用独立包名(比如package endpoint_1)。这是更规范的写法,你只需要在module_test.go里导入endpoint_1的包,就能通过包名访问它的导出变量。
- 情况1:
二、再看Bazel构建配置的要求
假设你用的是更规范的“独立包名”方案,我们来调整Bazel配置:
1. 先确保endpoint_1目录有正确的go_library配置
如果endpoint_1/logic.go是业务代码,那它的BUILD.bazel需要定义一个可被上层测试访问的库:
load("@io_bazel_rules_go//go:def.bzl", "go_library") go_library( name = "endpoint_1", srcs = ["logic.go"], importpath = "github.com/path/service/internal/module_name/endpoint_1", visibility = ["//internal/module_name:__pkg__"], # 允许上层测试目标访问 )
2. 修改module_name下的go_test配置
把注释掉的endpoint_1/variables_test.go加入srcs,同时修正你笔误的embed字段(应该是:module_name而不是:pagination),并补充依赖:
load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") go_library( name = "module_name", srcs = ["module_logic.go"], importpath = "github.com/path/service/internal/module_name", visibility = ["//visibility:public"], deps = [ "//proto/path:go", "@org_golang_google_grpc//codes", "@org_golang_google_grpc//status", ], ) go_test( name = "module_test", srcs = [ "module_test.go", "endpoint_1/variables_test.go", # 取消注释,加入测试文件 ], embed = [":module_name"], # 修正笔误,嵌入当前的go_library deps = [ ":endpoint_1", # 加入endpoint_1的库依赖 "@com_github_stretchr_testify//assert", "@com_github_stretchr_testify//require", ], )
3. 在module_test.go中导入并访问变量
最后在测试代码里导入endpoint_1包,就能访问它的导出变量了:
import ( "github.com/path/service/internal/module_name/endpoint_1" "testing" ) func TestYourLogic(t *testing.T) { // 访问endpoint_1中导出的变量 testVar := endpoint_1.MyExportedTestVariable // 接下来写你的测试逻辑 }
额外提醒
如果variables_test.go里只有测试用的变量,完全不依赖endpoint_1的业务代码,那你可以不用加":endpoint_1"的依赖,直接把文件加入srcs即可——但前提是它的包声明和导入逻辑没问题。
总的来说,只要满足Go的导出规则+正确配置Bazel的测试目标,是完全可以实现跨目录访问测试变量的!
备注:内容来源于stack exchange,提问作者nimgwfc
相关产品推荐
相关产品推荐

