FlowFX

Disable Django/Python logging with pytest fixture

Yesterday, I added Sentry error tracking to my Django app, and configured it to register every log entry with level INFO and above. Now, everytime I ran my test suite, there were events logged with Sentry that I didn’t really care about. Naturally, I wanted to disable the default logging behavior for tests.

StackOverflow, naturally, provides part of the answer:

logging.disable(logging.CRITICAL)

will disable all logging calls with levels less severe than or equal to CRITICAL.

(http://stackoverflow.com/a/5255760)

But how to run this on every test? Pytest to the rescue! I use an autouse fixture:

  • if an autouse fixture is defined in a conftest.py file then all tests in all test modules below its directory will invoke the fixture.

And this is what I put into my conftest.py files:

@pytest.fixture(autouse=True)
def disable_logging():
    """Disable logging in all tests."""
    logging.disable(logging.INFO)

That’s it. Love it!

Categories: #Tech Tags: #Python #Django #Logging #Pytest #Fixture