From 5d425f2ded9d4063d1c3cfd2f11537a8460a9c03 Mon Sep 17 00:00:00 2001 From: Taka Date: Fri, 18 Mar 2022 19:26:11 +1100 Subject: [PATCH] Allow logging to a file during tests. --- conftest.py | 20 ++++++++++++++++++-- vasl_templates/webapp/tests/utils.py | 9 +++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/conftest.py b/conftest.py index ddde4b1..aaa0dea 100644 --- a/conftest.py +++ b/conftest.py @@ -100,7 +100,7 @@ def _make_webapp(): if webapp_url and not webapp_url.startswith( "http://" ): webapp_url = "http://" + webapp_url app.base_url = webapp_url if webapp_url else "http://localhost:{}".format( FLASK_WEBAPP_PORT ) - logging.disable( logging.CRITICAL ) + _disable_console_logging() # initialize # WTF?! https://github.com/pallets/flask/issues/824 @@ -191,7 +191,7 @@ def _make_webapp(): @pytest.fixture( scope="session" ) def test_client(): """Return a test client that can be used to connect to the webapp.""" - logging.disable( logging.CRITICAL ) + _disable_console_logging() return app.test_client() # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -232,3 +232,19 @@ def webdriver( request ): yield driver finally: driver.quit() + +# --------------------------------------------------------------------- + +def _disable_console_logging(): + """Disable Python logging to the console. + + We do this when running tests because: + (1) pytest's output is voluminous enough without including our stuff in there as well (and it tends to be + not that helpful, anyway) + (2) pytest captures all output and shows it when the test ends i.e. we don't get to see messages in real-time. + """ + for logger in utils.get_all_loggers(): + # NOTE: FileHandler derives from StreamHandler, and we want to keep those, so we can't use isinstance(). + handlers = [ h for h in logger.handlers if type( h ) is logging.StreamHandler ] #pylint: disable=unidiomatic-typecheck + for h in handlers: + logger.removeHandler( h ) diff --git a/vasl_templates/webapp/tests/utils.py b/vasl_templates/webapp/tests/utils.py index e4fb219..f504068 100644 --- a/vasl_templates/webapp/tests/utils.py +++ b/vasl_templates/webapp/tests/utils.py @@ -7,6 +7,7 @@ import time import re import typing import uuid +import logging from collections import defaultdict import lxml.html @@ -646,3 +647,11 @@ def get_css_classes( elem ): """Get the CSS classes for the specified element.""" classes = elem.get_attribute( "class" ) return classes.split() if classes else [] + +# --------------------------------------------------------------------- + +def get_all_loggers(): + """Return all Python loggers.""" + yield logging.getLogger() # nb: this is the root logger + for name in logging.root.manager.loggerDict: #pylint: disable=no-member + yield logging.getLogger( name )