5

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!!

1

1 Answer 1

6

You need to specify "thread" as part of your concurrency setting:

concurrency = multiprocessing,thread

I'm not sure you need multiprocessing. Your sample program doesn't use it, maybe your real program doesn't either.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.