user3475234
user3475234

Reputation: 1573

filter out exception messages from unittest output

Is it possible to scrap all the exception text that comes as output from using unittest?

I.e., if I have a bunch of tests, and some of them throw exceptions, the unittest module takes it upon itself to print in red (in IDLE at least) all the exceptions. Is there a way to just not print the exceptions (but leave in any text I print using the print keyword?

For example, I have text to print in a tearDownClass() function, and while I'd like that to print, it'd be nice if it wasn't followed by 30 lines of red exception text. Is this possible?

Upvotes: 2

Views: 1101

Answers (2)

ivan_pozdeev
ivan_pozdeev

Reputation: 36008

So, according to comment-41597224, you want to deliberately wipe useful output because you feel it's not your problem.

In that case, replace/make relevant changes to Lib\unittest\result.py:_exc_info_to_string or a method that uses it that applies to your specific case (probably, addError or addFailure).

Alternatively, you can pipe the output to an independent script/command that would postprocess it with regexes.

  • If results happen to be written to stdout while exceptions to stderr, it's as simple as 2>nul at the command line.

But, I still advise against this. You do care what exceptions you get, because:

  • they might turn out to be a result of YOUR mistake as well as student's
  • you could reply with the verbatim output rather than just "pass/fail" that is both less work for you and gives the loser a better hint to fix it

You can get the best of both worlds if you make it so that you get BOTH the (filtered) summary and the opportunity to see the full output if you suspect something is not right.

Upvotes: 0

Stephen Lin
Stephen Lin

Reputation: 4912

If I understand you right, you just want a self-defined logger, right?

Put all the unit tests in a bit try-except block and catch all the exceptions. Then print it out as you like.

...
try:
    def test1(unit.tests):
        pass
    def test2(unit.tests):
        pass
except Exception, e:
    print 'here is the exception message', repr(e)
    # Use your own function to deal with print function or whatever you want here

...

Upvotes: 1

Related Questions