Pablo
Pablo

Reputation: 11021

How to set logging level in a unit test for Python

I am running a particular unit test in my library, and I would like to get more logging from it. I am running it in the following way:

python -m unittest my_module.my_submodule_test.MyTestClass.test_my_testcase

Because I'm doing this, the my_submodule_test.py file does not run the bottom part where I set the log level like so:

if __name__ == '__main__':
  logging.getLogger().setLevel(logging.DEBUG)
  unittest.main()

How can I programatically set the log level so that I can get more detailed logging from my test?

Also, I'd like to be able to set the logging via a command-line argument. Is there a way to do that?

Upvotes: 2

Views: 4478

Answers (1)

Pablo
Pablo

Reputation: 11021

One way in which this can be done is by doing it in the setUp code of your TestCase subclass. You would do the following:

class MyTestClass(unittest.TestCase):

  def setUp(self):
    logging.basicConfig(level=logging.DEBUG)
    logging.getLogger().setLevel(logging.DEBUG)

You can use either logging.basicConfig(level=logging.DEBUG), or logging.getLogger().setLevel(logging.DEBUG).

This should activate logging for your whole project (unless you are changing the level for loggers further down in the hierarchy that you care about).

I do not know of a way to do this from the command line, unfortunately.

Upvotes: 4

Related Questions