I am trying to measure code coverage with a code that uses threads created by the python threading
module.
I am using coverage
to measure coverage.
However I can not get the code that is run within a thread to get measured. I tried following the suggestion on the coverage docs to measure coverage in subprocesses but no luck.
Here is a minimal example file 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%
>
As you can see the lines 6-8 (the thread()
function) is executed but not measured.
For context I am running on a linux machine, Python 3.9.0, coverage
6.2. The directory contains this .coveragerc
file:
# .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__.:
I am very thankful for any suggestion!!