我正试图用一个使用pythonthreading
模块创建的线程的代码来衡量代码覆盖率。我使用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__.:
我非常感谢你的建议!!
您需要指定"线程";作为并发设置的一部分:
concurrency = multiprocessing,thread
我不确定你是否需要多重处理。您的示例程序没有使用它,也许您的真实程序也没有。