diff --git a/tests/conftest.py b/tests/conftest.py index 77643c22e..6b11ffb82 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,3 +1,4 @@ +import logging import sys import threading from functools import partial @@ -81,7 +82,16 @@ def create_dummy_scan_spec(x_steps, y_steps, z_steps): return [spec.consume().midpoints for spec in specs] -def _destroy_loggers(loggers): +def _reset_loggers(loggers): + """Clear all handlers and tear down the logging hierarchy, leave logger references intact.""" + clear_log_handlers(loggers) + for logger in loggers: + if logger.name != "Hyperion": + # Hyperion parent is configured on module import, do not remove + logger.parent = logging.getLogger() + + +def clear_log_handlers(loggers): for logger in loggers: for handler in logger.handlers: handler.close() @@ -115,12 +125,15 @@ def pytest_runtest_setup(item): ) else: print("Skipping log setup for log test - deleting existing handlers") - _destroy_loggers([*ALL_LOGGERS, dodal_logger]) + _reset_loggers([*ALL_LOGGERS, dodal_logger]) -def pytest_runtest_teardown(): +def pytest_runtest_teardown(item): if "dodal.beamlines.beamline_utils" in sys.modules: sys.modules["dodal.beamlines.beamline_utils"].clear_devices() + markers = [m.name for m in item.own_markers] + if "skip_log_setup" in markers: + _reset_loggers([*ALL_LOGGERS, dodal_logger]) @pytest.fixture diff --git a/tests/unit_tests/hyperion/test_log/conftest.py b/tests/unit_tests/hyperion/test_log/conftest.py index f18915797..14024856d 100644 --- a/tests/unit_tests/hyperion/test_log/conftest.py +++ b/tests/unit_tests/hyperion/test_log/conftest.py @@ -2,12 +2,12 @@ from hyperion.log import ALL_LOGGERS -from ....conftest import _destroy_loggers +from ....conftest import _reset_loggers def pytest_runtest_setup(): - _destroy_loggers([*ALL_LOGGERS, LOGGER]) + _reset_loggers([*ALL_LOGGERS, LOGGER]) def pytest_runtest_teardown(): - _destroy_loggers([*ALL_LOGGERS, LOGGER]) + _reset_loggers([*ALL_LOGGERS, LOGGER]) diff --git a/tests/unit_tests/hyperion/test_log/test_log.py b/tests/unit_tests/hyperion/test_log/test_log.py index 5fa1255f5..e50cc7042 100644 --- a/tests/unit_tests/hyperion/test_log/test_log.py +++ b/tests/unit_tests/hyperion/test_log/test_log.py @@ -14,12 +14,12 @@ LogUidTaggingCallback, ) -from .conftest import _destroy_loggers +from ....conftest import clear_log_handlers @pytest.fixture(scope="function") def clear_and_mock_loggers(): - _destroy_loggers([*log.ALL_LOGGERS, dodal_logger]) + clear_log_handlers([*log.ALL_LOGGERS, dodal_logger]) mock_open_with_tell = MagicMock() mock_open_with_tell.tell.return_value = 0 with ( @@ -30,7 +30,7 @@ def clear_and_mock_loggers(): graylog_emit.reset_mock() filehandler_emit.reset_mock() yield filehandler_emit, graylog_emit - _destroy_loggers([*log.ALL_LOGGERS, dodal_logger]) + clear_log_handlers([*log.ALL_LOGGERS, dodal_logger]) @pytest.mark.skip_log_setup