Redirecting unittest output to a Text widget

Peter Otten __peter__ at web.de
Wed May 10 10:02:23 CEST 2006


MrBlueSky wrote:

> Morning!  I'm writing my first Python program, so please have patience!
> 
> I'd like to redirect the output from my application's unit tests
> ("import unittest") to a Tkinter Text object.  I found the magic to
> redirect stdout and stderr:
>     sys.stdout = myTextWindow
>     sys.stderr = myTextWindow
> where myTextWindow inherits from Text and implements write() and
> writelines().
> 
> But the output from my UT still appears in the command window, not the
> Text box.  My own "print" statements *do* appear in the Text box.
> 
> Can anyone suggest a way forward here?

Provide your file-like object to an explicitly instantiated TextTestRunner:

tr = unittest.TextTestRunner(stream=myTextWindow, verbosity=2)
unittest.main(testRunner=tr)

If you want to accept a verbosity option from the commandline you have to
subclass unittest.TestProgram and override its runTests() method,
unfortunately.

Peter



More information about the Python-list mailing list