4

It seems that the unittest module has been changed a lot in Python 2.7

I have a test case:

class DemoTest(unittest.TestCase):
  def test_foo(self):
      """Test foo"""
      pass

The console output is:

Test foo ... ok

After upgrading to Python 2.7, the console output is now:

test_foo (testcase.demotest.DemoTest)

Test foo ... ok

The first line of description is useless. I want to hide it, but do not know how to.

stanleyxu2005
  • 8,081
  • 14
  • 59
  • 94

1 Answers1

5

Given that you've taken the trouble to write docstrings for your test, the extra output looks a bit redundant. Below is one way it could be suppressed; you'd need to add this to the top of your test file:

from unittest.runner import TextTestResult
TextTestResult.getDescription = lambda _, test: test.shortDescription()
samplebias
  • 37,113
  • 6
  • 107
  • 103
  • 1
    I love the smell me monkey patching in the morning. – David Heffernan Mar 11 '11 at 20:16
  • Hehe, I agree, and I wish there was a less hacky way to do this in 2.7. I tried a few other things, but this ended up being the shortest path to producing the desired output. – samplebias Mar 11 '11 at 21:52
  • Wheh I try this on python 2.7 I get "TypeError: expected a character buffer object" It can be fixed just casting to string: `TextTestResult.getDescription = lambda _, test: str(test.shortDescription())` – Euribates Sep 16 '11 at 12:47
  • Thanks! Without this adjustment, you'll get the exception above instead of any error in your test or code. – ckhan Mar 27 '13 at 19:36
  • Can I store the value of description in a variable? How? And Is it possible to suppress second line Test foo ... as well? – owgitt Jan 02 '17 at 06:49
  • Yes. I could store it like this: x= self.shortDescription() – owgitt Jan 02 '17 at 07:13