1

My unittest module breaks when testing my main file because my main file references a logger that was not initialized.

We have the following simple example.

logger_main.py:

import logging

def some_func():
    logger.info(__name__ + " started ")
    # Do something
    logger.info(__name__ + " finished ")
    return 1

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)
    some_func()

logger_main_tests.py:

import unittest
import logging
from logger_main import some_func

class Test(unittest.TestCase):
    def setUp(self):
        logging.basicConfig(level=logging.DEBUG)
        logger = logging.getLogger(__name__)

    def testName(self):
        self.assertEqual(some_func(), 1)

if __name__ == "__main__":
    unittest.main()

logger_main.py runs as expected, however, logger_main_tests.py gives the following error.

Finding files... done.
Importing test modules ... done.

======================================================================
ERROR: testName (logger_main_tests.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\workspaces\PythonPlayground\DataStoreHierarchy\logger_main_tests.py", line 11, in testName
    self.assertEqual(some_func(), 1)
  File "C:\workspaces\PythonPlayground\DataStoreHierarchy\logger_main.py", line 4, in some_func
    logger.info(__name__ + " started ")
NameError: name 'logger' is not defined

----------------------------------------------------------------------
Ran 1 test in 0.003s

FAILED (errors=1)        

The error makes sense since some_func() is trying to use logger that doesn't exists in its scope and I would like to figure out how to set up my unittests with a logger (set at the DEBUG level) so that any logger.info or logger.debug statement inside of my functions (such as some_func()) in logger_main.py would be printed out at the appropriate level.

2 Answers 2

5

Move this line outside of your main declaration.

logger = logging.getLogger(__name__)

The main will defined where the logs goes, but should not be used to defined the logger. Your module should declare the logger in its global context.

You can (and should) defined as many loggers as you need, it is common to have one per file or class and declaring it after you imports so it is available anywhere in the code that follow.

import logging

logger = logging.getLogger(__name__)

def some_func():
    .....
Sign up to request clarification or add additional context in comments.

3 Comments

Would you provide exactly how my logger_main_tests.py should look like for this to work? I tried moving that line around without success.
Oh, you meant to move that line in the logger_main.py file. Thanks this makes sense now!
@bourbaki4481472 for logger_main_tests.py, simply remove logger = logging.getLogger(__name__) as you never use the logger in this file.
1

This is because the logger is only being defined when __name__ == "__main__".

Generally you'll define one logger per file, something like:

logger = logging.getLogger(__name__)

At the top of the file, after the imports.

Also, notice that the logger defined in Test.setUp is local to the function, so it won't do anything.

1 Comment

Would you provide exactly how my logger_main_tests.py should look like for this to work? I tried moving that line around without success.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.