本文介绍了通过 pytest 使用多进程处理时如何测量覆盖率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过 pytest 运行我的单元测试.对于覆盖范围,我使用 coverage.py.

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

In one of my unit tests, I run a function via multirpocessing and the coverage does not reflect the functions running via multirpocessing, but the asserts work. That's the problem I am trying to solve.

测试看起来像这样:

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 中使用以下命令:

To run the tests and see the coverage I use the following command in Ubuntu:

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

在文档中给出了如何做的指导,以便覆盖率正确地解释多处理(这里).所以我设置了一个 .coveragerc 像这样:

In docs give guidance on what to do in order for coverage to account for multiprocessing correctly (here). So I have set up a .coveragerc like so:

[run]
concurrency = multiprocessing

[report]
show_missing = true

还有 sitecustomize.py 看起来像这样:

and also sitecustomize.py looks like so:

import coverage
coverage.process_startup()

尽管如此,上述通过 multiprocessing 运行的函数仍然没有考虑到覆盖范围.

Despite this, the above function running through multiprocessing is still not accounted for in coverage.

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

What am I doing wrong or missing?

附言似乎是一个类似的问题,但它并没有再次解决我的问题:(

P.S. This seems like a similar question, however it does not fix my problem again : (

推荐答案

我通过以下两个方法修复"了这个问题:

I "fixed" this issue by doing two this:

  1. coverage.pypytest-cov.
  2. 将此代码添加到 process 上方,如通过其 文档.
  1. Switching the coverage package from coverage.py to pytest-cov.
  2. Adding this code above the process as described via their docs.

代码:

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

然后我只需运行 pytest --cov=my_proj my_proj/

这篇关于通过 pytest 使用多进程处理时如何测量覆盖率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-13 07:55