Search code examples
pythonunit-testing

How to run initialization code before tests when using Python's unittest module as a testrunner?


How can a user of a library run his own initialization code (setting debug levels of loggers for example) before running tests supplied with the library? Python's unittest module is used as a testrunner.


Solution

  • You can try using pytest to run the unittests. If that works (many unittest based test suites work), then you can create a little module, for example "mymod.py", defining a pytest configuration hook:

    # content of mymod.py
    def pytest_configure():
        import logging
        logging.getLogger().setLevel(logging.WARN)
    

    If you now execute py.test like this:

    $ py.test -p mymmod --pyargs mylib
    

    Then the "mylib" package will be searched for tests and ahead of running them the logging level is modified. The "-p" option specifies a plugin to load and the "--pyargs" tells pytest to try importing the arguments first, instead of treating them as directory or file names (the default).

    For more info: http://pytest.org and http://pytest.org/latest/unittest.html

    HTH, holger