6

I have a module mymodule that I test with unittest. The module logs to stdout diagnostics messages when is in verbose mode (e.g. mymodule.set_verbose(True)) and remains silent otherwise. I would like that when I import the module in the main program it is in the silent mode and when the unittest runs, it is verbose.

I tried to hack it in the unittest main loop, but it doesn't work

if __name__ == "__main__":
  mymodule.set_verbose( True )
  unittest.main() 
# apparently, modules are loaded on each test separately

How to increase verbosity in python unittest? was not helpful.

Community
  • 1
  • 1
Jakub M.
  • 32,471
  • 48
  • 110
  • 179
  • related: [How to run initialization code before tests when using Python's unittest module as a testrunner?](http://stackoverflow.com/q/8607767/95735) – Piotr Dobrogost Oct 23 '12 at 19:12

3 Answers3

12
if __name__ == '__main__':
    unittest.main(verbosity=2)

see: https://docs.python.org/2/library/unittest.html

Robert
  • 31,925
  • 8
  • 35
  • 33
6

Alternatively you could directly use unittest.TextTestRunner to run your tests. This allows to set the verbosity level:

suite = unittest.TestLoader().loadTestsFromTestCase(TestCaseClass)
unittest.TextTestRunner(verbosity=2).run(suite)

This will run all your tests from within TestCaseClass.

Piotr Dobrogost
  • 41,292
  • 40
  • 236
  • 366
user_noname_00
  • 269
  • 3
  • 8
  • Verbosity passed to `TextTestRunner` partain to test runner itself and has nothing to do with `set_verbose()` function defined in the module being tested. – Piotr Dobrogost Oct 23 '12 at 20:54
3

You can call set_verbose from the setUp method of the unittest.

GilZ
  • 6,418
  • 5
  • 30
  • 40
  • Of course, so simple. Thanks. By the way can I make setUp on the higher level, so I don't need to run it in every test Class? I could make it by inheriting TestCase..., but maybe there is some default unittest-ish way – Jakub M. Oct 23 '12 at 15:52
  • @JakubM. There is and it's called `setUpModule()` - see [this](http://stackoverflow.com/a/12904030/95735) answer. – Piotr Dobrogost Oct 23 '12 at 19:10
  • @PiotrDobrogost: dzięki, apparently it's worth reading docpages from time to time – Jakub M. Oct 23 '12 at 20:40