A unittest green bar for the console

One thing the unittest module is missing for me is a green bar of success (or a red bar of fail), so here’s one I cooked up to scratch my itch (windows only at the mo’, sorry):

import sys
import ctypes
import unittest

class GreenBarRunner(unittest.TextTestRunner):
    FOREGROUND_GREEN= 0x0A
    FOREGROUND_RED  = 0x0C
    FOREGROUND_WHITE= 0x0F
    FOREGROUND_YELLOW=0x0E

    def __init__(self, verbosity=2):
        unittest.TextTestRunner.__init__(self, verbosity=verbosity)
        STD_OUTPUT_HANDLE = -11
        self.std_out_handle = ctypes.windll.kernel32.GetStdHandle(
            STD_OUTPUT_HANDLE)

    def set_color(self, color):
        bool = ctypes.windll.kernel32.SetConsoleTextAttribute(
            self.std_out_handle, color)
        return bool

    def run(self, test):
        r = unittest.TextTestRunner.run(self, test)

        failed_count = len(r.failures)
        errored_count = len(r.errors)
        total = r.testsRun
        ok_count = total - (failed_count + errored_count)

        sys.stdout.write('\n[')
        self.set_color(self.FOREGROUND_RED)
        sys.stdout.write('#' * errored_count)
        self.set_color(self.FOREGROUND_YELLOW)
        sys.stdout.write('#' * failed_count)
        self.set_color(self.FOREGROUND_GREEN)
        sys.stdout.write('#' * ok_count)
        self.set_color(self.FOREGROUND_WHITE)
        sys.stdout.write(']\n')

Usage:

suite = unittest.TestLoader().loadTestsFromModule(example_module)
GreenBarRunner(verbosity=2).run(suite)

It’ll execute the TextTestRunner so you won’t lose the test names and stack traces and afterwards display a red/yellow/green bar:

GreenBarTestRunner

Ta-da.

 

2 thoughts on “A unittest green bar for the console

  1. Hey Dale,
    I like this a lot, thanks!

    There really should be a simple way to do colored console things like this in a cross-platform manner. I wonder what would need to happen to make it happen?

Leave a Reply

Your email address will not be published. Required fields are marked *