通过pytest使用多处理时如何测量覆盖率?

How to measure coverage when using multirpocessing via pytest?

我 运行 我的单元测试通过 pytest. For coverage I use coverage.py

在我的一个单元测试中,我通过 multirpocessing 运行 一个函数并且覆盖率不反映通过 multirpocessing 的函数 运行ning,但是断言工作。这就是我要解决的问题。

测试看起来像这样:

import time
import multiprocessing

def test_a_while_loop():
    # Start through multiprocessing in order to have a timeout.
    p = multiprocessing.Process(
        target=foo
        name="Foo",
    )
    try:
        p.start()
        # my timeout
        time.sleep(10)
        p.terminate()
    finally:
        # Cleanup.
        p.join()

    # Asserts below
    ...

运行 测试并查看覆盖率我在 Ubuntu 中使用以下命令:

coverage run --concurrency=multiprocessing -m pytest my_project/
coverage combine
coverage report

在文档中提供有关如何使覆盖率正确说明多处理的指导 (here)。所以我设置了一个 .coveragerc 像这样:

[run]
concurrency = multiprocessing

[report]
show_missing = true

而且 sitecustomize.py 看起来像这样:

import coverage
coverage.process_startup()

尽管如此,上述函数 运行ning 到 multiprocessing 仍未包含在覆盖范围内。

我做错了什么或遗漏了什么?

P.S。 似乎是一个类似的问题,但它并没有再次解决我的问题:(

我"fixed"这个问题是通过做两个这样的:

  1. 正在从 coverage.py to pytest-cov 切换覆盖范围包。
  2. 按照他们的 docs.
  3. 所述,将此代码添加到 process 上方

代码:

try:
    from pytest_cov.embed import cleanup_on_sigterm
except ImportError:
    pass
else:
    cleanup_on_sigterm()

那我就运行pytest --cov=my_proj my_proj/