argentpepper
argentpepper

Reputation: 4432

setuptools command for coverage.py

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

Upvotes: 2

Views: 1351

Answers (2)

Senthil Kumaran
Senthil Kumaran

Reputation: 56841

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.

Upvotes: 2

argentpepper
argentpepper

Reputation: 4432

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.

Upvotes: 0

Related Questions