使用Python线程测量覆盖率

3

我正在尝试使用由Python threading 模块创建的线程来测量代码覆盖率。 我正在使用coverage来测量覆盖率。 然而,我无法测量在线程内运行的代码。我尝试遵循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__.:

非常感谢任何建议!!


请注意此相关GitHub问题 - jayquintana
1个回答

5
您需要在并发设置中指定“线程”:
concurrency = multiprocessing,thread

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接