代码之家  ›  专栏  ›  技术社区  ›  hauron

pytest结果junit样式XML文件测试用例计数

  •  0
  • hauron  · 技术社区  · 6 年前

    源库由几个相互分离的Python库/模块组成。对于每个测试,都有一组测试,即:

    • 模块调用: foo ,有几个文件,
    • 对应的测试文件 test_foo.py ,使用pytest编写两个测试。

    运行测试后,我会得到一个生成的XML文件,其内容类似于:

    <?xml version="1.0" encoding="UTF-8"?>
    <testsuites>
      <testsuite name="foo/test_foo" tests="1" failures="0" errors="0">
        <testcase name="foo/test_foo" status="run" duration="9" time="9"></testcase>
        <system-out><![CDATA[============================= test session starts ==============================
    platform linux -- Python 3.6.6, pytest-3.10.1, py-1.7.0, pluggy-0.8.0 -- /usr/bin/python3
    cachedir: .pytest_cache
    rootdir: ..., inifile: pytest.ini
    plugins: timeout-1.3.2, mock-1.10.0, cov-2.6.0
    timeout: 60.0s
    timeout method: thread
    timeout func_only: False
    collecting ... collected 2 items
    
    ::test_foo_test1
    -------------------------------- live log setup --------------------------------
    # ... some logging performed in the test...
    PASSED                                                                   [ 50%]
    ::test_foo_test2
    -------------------------------- live log call ---------------------------------
    # ... some logging performed in the test...
    PASSED                                                                   [100%]
    
    =========================== 2 passed in 6.63 seconds ===========================]]></system-out>
      </testsuite>
    </testsuites>
    

    ( 笔记 :未对齐的部分由 system-out 标记)

    我的 pytest.ini 文件相当简单,只包含有关日志记录的信息( log_cli* , log_file* ) timeout . 我使用bazel作为构建系统,它定义了 py_test 乔布斯,我的假设是它以某种方式隐式地添加了一个默认的输出设置。然而,即使直接运行,也应该类似地工作。

    现在,我想处理这些XML文件,并提取运行测试、错误等的总计数。示例中显示的问题是,XML文件声明测试计数为 tests="1" ,而日志中的stdout显示至少收集了两个项目。

    在我看来,格式计算整个 文件夹 作为 测试用例 而不是实际 测试用例 在文件中收集。

    在python中有什么简单的方法可以使testsuite包含 collected items ?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Okken    6 年前

    是否使用--junitxml=something.xml标志? https://docs.pytest.org/en/latest/usage.html#creating-junitxml-format-files

    当我使用--junitxml标志时,生成的输出包含正确数量的测试。 我的猜测是,bazel是生成XML输出的,而不是pytest,它将整个pytest运行视为一个测试。

    我认为这可能需要是一个带有bazel标签的问题,因为它实际上是“如何让bazel读取额外的XML文件?”,然后使用--junitxml生成自己的XML。

    还有一件事。如果XML文件在捕获的所有输出中变得很大,我建议执行以下操作:

    1. 使用-s运行以不捕获输出
    2. 如果需要会话日志,请运行整个过程,如“pytest-s--junitxml=out.xml[其他标志、测试目录、文件等]>out.txt”

    然后,您还需要将out.txt存档,但这样可以防止XML变得庞大。