Source

unittest2-cov / unittest2_cov.py

Full commit
"""Coverage plugin for unittest2."""

import cov_core
import unittest2
import StringIO
import sys

class CovPlugin(unittest2.events.Plugin):

    def __init__(self):
        """Get our config, add our options and attach to hooks."""

        self.ourOptions = unittest2.events.getConfig('cov')
        self.covSource = self.ourOptions.as_list('cov', default=[])
        self.covReport = self.ourOptions.as_list('cov-report', default=[])
        self.covConfig = self.ourOptions.get('cov-config', '.coverage').strip()

        unittest2.events.addOption(self.covSource, None, 'cov', 'Measure coverage for selected dirs')
        unittest2.events.addOption(self.covReport, None, 'cov-report', 'Generate selected reports, available types: term, term-missing, annotate, html, xml')
        unittest2.events.addOption(self.covConfig, None, 'cov-config', 'Config file for coverage, default: .coveragerc')

        unittest2.events.hooks.startTestRun += self.start
        unittest2.events.hooks.stopTestRun += self.stop

    def start(self, event):
        """If we are enabled then start coverage."""

        if self.covSource:
            self.covReport = self.covReport or ['term']
            self.covController = cov_core.Central(self.covSource, self.covReport, self.covConfig)
            self.covController.start()

    def stop(self, event):
        """If we are enabled then produce coverage reports."""

        if self.covSource:
            stream = StringIO.StringIO()
            self.covController.finish()
            self.covController.summary(stream)
            sys.stdout.write(stream.getvalue())