4

I have the following structure in a project:

app/
    __init__.py
    main.py
    tests/
        __init__.py
        test_a.py
        test_b.py

I would like to initialize logging for tests under the tests package. I placed the initialization code in app/tests/__init__.py under the assumption that it is run before any test is run, however I've discovered this is not the case.

How can I make this initialization code run in the following scenarios?

  • When running python test_a.py from the command prompt
  • When running test_a.py as a unit-test under eclipse\aptana\pycharm
  • When running the entire test suite under eclipse\aptana\pycharm
Jonathan Livni
  • 101,334
  • 104
  • 266
  • 359
  • If I'm going about this the wrong way, please let me know. e.g. if I could simply have a `setup_logging.py` and import it at the start of each test. I simply wanted to minimize boiler plate code... – Jonathan Livni Jun 12 '12 at 10:23
  • If you run `test_a.py` directly it is not considered as part of the package, just as a regular file. So, `__init__.py` has nothing to do here. Just commenting, I don't know the solution to your problem though... – jadkik94 Jun 12 '12 at 10:32

1 Answers1

0

You can use logger config files for normal run and tests, which is the most secure way to have different configurations.

The 'workaround' way is to re-create loggers. You've probably just added new loggers in __init__.py? Once configured, logging keeps it config and only allows extending. However you can try re-creating the whole logger, as described here: Python logging before you run logging.basicConfig? e.g.:

root = logging.getLogger()
if root.handlers:
    for handler in root.handlers:
        root.removeHandler(handler)
# now create your test config
logging.basicConfig(format='%(asctime)s %(message)s',level=logging.DEBUG)

Add this code to your test.py file, or add it into __init__.py but you might probably need:

from tests import *

to make it execute in the tests.

Community
  • 1
  • 1
Tisho
  • 8,320
  • 6
  • 44
  • 52