我正在使用GoogleTest与 bazel 一起运行时 bazel test :tokens_test
(下面定义的规则)我有一个失败的测试,但是当我运行编译的测试时,我看到了预期的结果。由于测试无法打开测试数据文件,因此失败。我正在运行的测试的目录布局和构建规则如下所示:
tokens/
BUILD
tokens_test.cpp
test_data/
test_input1.txt
cc_test(
name = "tokens_test",
srcs = ["tokens_test.cpp"],
deps = [
'@gtest//:gtest'
'@gtest//:gtest_main',
],
data = ["//tokens/test_data:test_input1.txt"]
)
此时,测试只是一个包装器,用于打开文件并读取测试数据,这是失败的部分。
TEST(Tokenizer, OpenFileTest) {
auto fin = std::ifstream("test_data/test_input1.txt");
std::cout << a.get(); // Outputs -1.
}
当我导航到 bazel-out
时位置并找到 token 运行文件目录,我可以看到编译后的测试可执行文件。
[jibberish]/__main__/tokens>ls
test_data/
test_input1.txt
tokens_test
当我运行可执行文件时:
[jibberish]/__main__/tokens>./tokens_test
...normal test output...
The correct output!
...more test output...
我不知道从哪里开始寻找问题。我尝试在 test_data 目录中包含一个包含 exports_files
的 BUILD规则,在 BUILD 文件和我的源代码中使用各种相对路径以及这些相对路径的大量排列。
最佳答案
将您的数据定义为
data = ["test_data/test_input1.txt"]
使用绝对路径:./tokens/test_data/test_input1.txt
要找到它,请使用 bazel test --sandbox_debug -s 运行测试。最后一个命令看起来像这样:
SUBCOMMAND: # //:hello_test [action 'Testing //:hello_test', configuration: faff19e6fd939f490ac11578d94024c6b7a032836cde039fd5edd28b838194e8, execution platform: @local_config_platform//:host]
(cd /home/s/.cache/bazel/_bazel_s/fa4c7c7c7db2888182e4f15990b55d58/execroot/com_google_absl_hello_world && \
exec env - \
EXPERIMENTAL_SPLIT_XML_GENERATION=1 \
RUNFILES_DIR=bazel-out/k8-fastbuild/bin/hello_test.runfiles \
RUN_UNDER_RUNFILES=1 \
TEST_BINARY=./hello_test \
TEST_INFRASTRUCTURE_FAILURE_FILE=bazel-out/k8-fastbuild/testlogs/hello_test/test.infrastructure_failure \
TEST_LOGSPLITTER_OUTPUT_FILE=bazel-out/k8-fastbuild/testlogs/hello_test/test.raw_splitlogs/test.splitlogs \
TEST_PREMATURE_EXIT_FILE=bazel-out/k8-fastbuild/testlogs/hello_test/test.exited_prematurely \
TEST_SIZE=medium \
TEST_SRCDIR=bazel-out/k8-fastbuild/bin/hello_test.runfiles \
TZ=UTC \
XML_OUTPUT_FILE=bazel-out/k8-fastbuild/testlogs/hello_test/test.xml \
external/bazel_tools/tools/test/test-setup.sh ./hello_test)
然后,您可以粘贴整个 (cd ...)
单行代码,以重现 bazel 测试
运行期间的确切沙箱环境。例如,您可以用这种方式替换最后一行:
(cd /home/s/.cache/bazel/_bazel_s/fa4c7c7c7db2888182e4f15990b55d58/execroot/com_google_absl_hello_world && \
exec env - \
EXPERIMENTAL_SPLIT_XML_GENERATION=1 \
RUNFILES_DIR=bazel-out/k8-fastbuild/bin/hello_test.runfiles \
RUN_UNDER_RUNFILES=1 \
TEST_BINARY=./hello_test \
TEST_INFRASTRUCTURE_FAILURE_FILE=bazel-out/k8-fastbuild/testlogs/hello_test/test.infrastructure_failure \
TEST_LOGSPLITTER_OUTPUT_FILE=bazel-out/k8-fastbuild/testlogs/hello_test/test.raw_splitlogs/test.splitlogs \
TEST_PREMATURE_EXIT_FILE=bazel-out/k8-fastbuild/testlogs/hello_test/test.exited_prematurely \
TEST_SIZE=medium \
TEST_SRCDIR=bazel-out/k8-fastbuild/bin/hello_test.runfiles \
TZ=UTC \
XML_OUTPUT_FILE=bazel-out/k8-fastbuild/testlogs/hello_test/test.xml \
bash -c 'pwd && ls')
因此bash -c 'pwd && ls'
将显示当前目录路径和内容。
关于c++ - bazel 测试与直接执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66701840/