测量Python线程中的覆盖率

问题描述 投票:0回答:2

我正在尝试使用使用 python

threading
模块创建的线程的代码来测量代码覆盖率。 我正在使用
coverage
来测量覆盖范围。 但是,我无法获取在线程内运行的代码来进行测量。我尝试按照覆盖文档中的建议来衡量子流程中的覆盖率,但是没有运气。

这是一个最小的示例文件

untitled.py

import time, threading
import numpy as np


def thread():
    print(f'{threading.get_ident()}: started thread')
    time.sleep(np.random.uniform(1, 10))
    print(f'{threading.get_ident()}: done')

    
def run_threads():
    threads = [threading.Thread(target=thread)]
    for t in threads:
        t.start()
        
    print('started all threads')
        
    for t in threads:
        t.join()
        
    print('all threads done')


if __name__ == '__main__':
    
    run_threads()
> coverage run untitled.py
139952541644544: started thread
started all threads
139952541644544: done
all threads done
> coverage combine
Combined data file .coverage.248973.677959
> coverage report -m
Name          Stmts   Miss  Cover   Missing
-------------------------------------------
untitled.py      14      3    79%   6-8
-------------------------------------------
TOTAL            14      3    79%
> 

如您所见,第 6-8 行(

thread()
函数)已执行但未测量。

对于上下文,我在 Linux 机器上运行,Python 3.9.0,

coverage
6.2。该目录包含以下
.coveragerc
文件:

# .coveragerc to control coverage.py
[run]
source = ./
parallel = True
concurrency = multiprocessing

[report]
# Regexes for lines to exclude from consideration
exclude_lines =
    # Have to re-enable the standard pragma
    pragma: no cover

    # Don't complain about missing debug-only code:
    def __repr__
    if self\.debug

    # Don't complain if tests don't hit defensive assertion code:
    raise AssertionError
    raise NotImplementedError

    # Don't complain if non-runnable code isn't run:
    if 0:
    if __name__ == .__main__.:

我非常感谢任何建议!!

python multithreading code-coverage
2个回答
5
投票

您需要指定“线程”作为并发设置的一部分:

concurrency = multiprocessing,thread

我不确定您是否需要多重处理。你的示例程序没有使用它,也许你的真实程序也没有。


0
投票

我在使用 Pyqt 线程时遇到同样的问题,并且 concurrency=thread 似乎不起作用。任何更新表示赞赏。

© www.soinside.com 2019 - 2024. All rights reserved.