c++ Bazel从给定目录运行测试二进制文件

h6my8fg2  于 2023-04-08  发布在  其他
关注(0)|答案(1)|浏览(117)

Bazel test runner从我项目的基目录在其沙箱中运行我的测试二进制文件。我如何指定它从哪里运行我的测试二进制文件?
我想这样做的原因是,我的测试从一个文本文件中读取了一些数据,这些数据是我从data属性传递给cc_test的。所以如果Bazel从我的项目的基目录运行我的测试二进制文件,它就找不到文本文件,所有测试都失败了。
有没有一种方法可以在Bazel文件中修复它,而不更改我的代码?

lmvvr0a8

lmvvr0a81#

我有一个破解方法:
Skylib作为依赖项添加到项目中,即添加到WORKSPACE文件中:

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

http_archive(
    name = "bazel_skylib",
    sha256 = "b8a1527901774180afc798aeb28c4634bdccf19c4d98e7bdd1ce79d1fe9aaad7",
    urls = [
        "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.4.1/bazel-skylib-1.4.1.tar.gz",
        "https://github.com/bazelbuild/bazel-skylib/releases/download/1.4.1/bazel-skylib-1.4.1.tar.gz",
    ],
)

load("@bazel_skylib//:workspace.bzl", "bazel_skylib_workspace")

bazel_skylib_workspace()

现在误用expand_template(Bazel规则形式的Skylib)将文件名从相对文件名更改为工作区相对文件名:

expand_template(
 name = "fix_filename",
 out = "some_file.modified.cpp",
 substitutions = {
 "my_file.txt":"my_project/package/subpackage/my_file.txt",
 },
 template = "some_file.cpp",
)

将您的cc_test

cc_test(
    name = "test1"
    srcs = ["some_file.cpp"]
)

expand_template(
 name = "fix_filename",
 out = "some_file.modified.cpp",
 substitutions = {
 "my_file.txt":"my_project/package/subpackage/my_file.txt",
 },
 template = "some_file.cpp",
)

cc_test(
    name = "test1"
    srcs = ["some_file.modified.cpp"]
)

当主构建系统不是Bazel(例如make或CMake)并且我不想破坏旧的构建系统时,我会使用这个技巧。

相关问题