【问题标题】:Bazel and py_test in sandbox - any way to define outputs?沙盒中的 Bazel 和 py_test - 有什么方法可以定义输出?
【发布时间】:2022-04-20 08:34:43
【问题描述】:

我在多个项目上运行多个 py_test() 配置。由于它们很多,默认的沙盒机制似乎很方便 - 测试不会相互干扰,并且免费并行运行。

不过,这是有代价的,据我了解,沙盒会导致 bazel 在临时目录中运行测试。结合 py_test 规则未定义任何 outs 参数 (https://docs.bazel.build/versions/master/be/python.html),这可能意味着测试后不会保留任何生成的文件。

我想要实现的,有两件事:

  1. 保留测试的输出,按测试用例分割(我想我可以使用capsys 并显式写入与测试名称类似的文件)。这里的问题是,该文件最终将位于沙盒目录中,即: /home/user/.cache/bazel/_bazel_user/12342134213421342134/sandbox/linux-sandbox/1/execroot/project_name/bazel-out/k8-fastbuild/bin/test_suite.runfiles/ 之后会被移除。
  2. 我想获得一份 XML 格式的运行测试摘要。 Bazel 本身会生成一个 JUnit 格式的 XML 文件,这很好,但不幸的是它不能正常工作 (https://github.com/bazelbuild/bazel/issues/3413)。最简单的解决方案是提供一个有效的参数--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_variablesgenrule 包含一个 outs 参数。

所以问题归结为:在 bazel 中是否有任何方法可以重用(或环绕)py_test 规则并定义它将生成的一些输出文件?

【问题讨论】:

  • 特别是对于junit输出,你应该使用环境变量XML_OUTPUT_FILE到pytest的--junitxml标志,然后bazel将使用那个文件而不是它自己的junit xml文件生成器。

标签: pytest bazel


【解决方案1】:

在对 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 存档(根据链接的问题)。

【讨论】:

    【解决方案2】:

    只需将 xml 输出写入 XML_OUTPUT_FILE env 变量中指定的位置。在这种情况下,文件不会被压缩。

    来自这里的源代码:

    https://github.com/bazelbuild/bazel/blob/master/tools/test/test-setup.sh#L188

     if [ -n "${XML_OUTPUT_FILE-}" -a ! -f "${XML_OUTPUT_FILE-}" ]; then
        # Create a default XML output file if the test runner hasn't generated 
    

    我非常讨厌 bazel 文档,它总是让我发疯。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-08
      • 2014-03-24
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多