2

What is the best way to create a command for setuptools which generates a code coverage report using coverage.py?

2 Answers 2

2

What you are looking for is Extending Distutils capabilities through extensions and it is covered in the docs that I have linked. The basic idea is to give the command and the entr5y point for execution and the entry point should follow some of setuptools Component based terminology. I think, you are luck here, because someone has already tried successfully ( Adding Test Code Coverage Analysis to a Python Project's setup Command ) integrating it for his project and you should be able to adopt it for your purposes.

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

Comments

0

Here is one simple solution which uses subprocess calls to the coverage executable. I assume you have a Python package called mycoolpackage which contains the code for which you want to measure test coverage, and you have a mytests package which exposes a suite function which returns the test suite.

First, create a run-tests.py file:

import os.path, sys
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))

import unittest
from mytests import suite

unittest.main(defaultTest='suite')    

then in setup.py create the following command and add it to the cmdclass argument of the setup() function.

class run_coverage(Command):
    description = "Generate a test coverage report."
    user_options = []    
    def initialize_options(self): pass
    def finalize_options(self): pass 
    def run(self):
        import subprocess
        subprocess.call(['coverage', 'run', '--source=mycoolpackage', 'run-tests.py'])
        subprocess.call(['coverage', 'html'])

Note that coverage.py does have an API which would allow you to accomplish this without using a subprocess call.

1 Comment

Adding a coverage command would really only be useful if you use the internal testrunner of setuptools. With this you can just as well just run the coverage command.

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.