我正在运行多个 py_test()
项目数量的配置。由于有很多,默认的沙箱机制似乎很方便——测试不会相互干扰,并且免费并行运行。
但是,这需要付出代价,据我所知,沙箱会导致 bazel 在临时目录中运行测试。结合py_test
规则未定义任何输出参数( https://docs.bazel.build/versions/master/be/python.html ),这可能意味着测试后不会保留生成的文件。
我想要达到的目标有两件事:
capsys
并显式写入一个与测试名称相似的文件来使其工作)。这里的问题是,该文件最终会出现在沙盒目录中,即:/home/user/.cache/bazel/_bazel_user/12342134213421342134/sandbox/linux-sandbox/1/execroot/project_name/bazel-out/k8-fastbuild/bin/test_suite.runfiles/
并将在之后删除。 --junitxml=path
( https://docs.pytest.org/en/latest/usage.html#creating-junitxml-format-files ) 可以工作,但同样 - 在临时沙盒目录中生成一个文件。 bazel 中的其他规则将 outs 定义为它们将生成的文件,即 https://docs.bazel.build/versions/master/be/make-variables.html#predefined_genrule_variables :
genrule
包含一个 outs 参数。所以问题归结为: bazel 有什么方法可以重复使用(或环绕)
py_test
规则并定义一些它将生成的输出文件?
最佳答案
在对 Bazel 进行了一些试验后,我得出结论,没有简单的方法可以扩展 py_test
向其添加输出。从头开始创建我自己的规则也相当困难。
然而,事实证明 Bazel 中的所有测试都定义了一些可以使用的环境变量。事实上,另一个类似的问题被问到使用它们解决了这个问题:bazel - writable archivable path for test runtime
在我的测试中,我从 Python 中运行 pytest,因此很容易以编程方式扩展启动参数:
def _get_log_file_args():
# Prepare the path to the log file, based on environmental
# variables defined by Bazel.
#
# As per docs, tests should not rely on these variables
# defined, so the framework will omit logging to file
# if necessary variables are undefined.
# See: https://docs.bazel.build/versions/master/test-encyclopedia.html#initial-conditions
LOG_DIR_ENV_VARIABLE = "TEST_UNDECLARED_OUTPUTS_DIR"
log_dir = os.environ.get(LOG_DIR_ENV_VARIABLE)
if log_dir:
file_log_path = os.path.join(log_dir, "test_output.log")
return [f"--log-file={file_log_path}"]
logger.warning(f"Environment variable '{LOG_DIR_ENV_VARIABLE}' used as the logging directory is not set. "
"Logging to file will be disabled.")
return [] # no file logging
然后是在
./bazel-out/darwin-fastbuild/testlogs/<package-name>/<target-name>/test.outputs/outputs.zip
处处理最终 .zip 存档的问题。 (根据链接的问题)。
关于pytest - 沙箱中的 Bazel 和 py_test - 任何定义输出的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54417450/