pytest - 沙箱中的 Bazel 和 py_test - 任何定义输出的方法?

标签 pytest bazel

我正在运行多个 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/并将在之后删除。
  • 我想以 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_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/

    相关文章:

    python - 如何修复 "PT006 wrong name(s) type in @pytest.mark.parametrize, expected tuple"?

    python-2.7 - pytest-timeit或pytest-benchmark在精度s上哪个更好?

    python-2.7 - 在函数装饰器中使用 pytest 固定装置

    bazel - 获取给定 bazel 目标的特定属性的值

    python-3.x - 如何检查哪个pytest标记是运行的测试

    python - 如果 pytest 是从另一个模块以编程方式运行的,如何将参数传递给 pytest?

    bazel - Bazel 可以显示所有分析错误吗?

    bazel - 如何知道genrule中的编译模式

    googletest - 为什么我的 Bazel 测试在所有单独测试都通过时报告失败?

    java - 无法使用 Bazel 获取 Maven 依赖项 javadoc