11# In conftest.py or test_logging_utils.py
2+ import contextlib
23import logging
34from collections .abc import Iterator
45from contextlib import contextmanager
5- from unittest .mock import patch
66
77import pytest
8+ from pytest_mock import MockerFixture
89from servicelib .logging_utils import setup_async_loggers_lifespan
910
1011
1112@pytest .fixture (autouse = True )
12- def preserve_caplog_for_async_logging (request ):
13- """Automatically preserve caplog handlers when both caplog and async logging are used."""
14- # Check if this test uses caplog fixture
15- if "caplog" not in request .fixturenames :
16- yield # No caplog, no patching needed
17- return
18-
13+ def preserve_caplog_for_async_logging (
14+ request : pytest .FixtureRequest , mocker : MockerFixture
15+ ) -> None :
1916 # Patch setup_async_loggers_lifespan to preserve caplog handlers
2017 original_setup = setup_async_loggers_lifespan
2118
@@ -34,16 +31,12 @@ def patched_setup_async_loggers_lifespan(**kwargs) -> Iterator[None]:
3431 root_logger .addHandler (handler )
3532 yield
3633
37- with patch (
34+ methods_to_patch = [
3835 "servicelib.logging_utils.setup_async_loggers_lifespan" ,
39- patched_setup_async_loggers_lifespan ,
40- ):
41- try :
42- with patch (
43- "tests.test_logging_utils.setup_async_loggers_lifespan" ,
44- patched_setup_async_loggers_lifespan ,
45- ):
46- yield
47- except ModuleNotFoundError :
48- # NOTE: this is for tests running in service library
49- yield
36+ "servicelib.fastapi.logging_lifespan.setup_async_loggers_lifespan" ,
37+ "tests.test_logging_utils.setup_async_loggers_lifespan" ,
38+ ]
39+ for method in methods_to_patch :
40+ with contextlib .suppress (AttributeError , ModuleNotFoundError ):
41+ # Patch the method to use our patched version
42+ mocker .patch (method , patched_setup_async_loggers_lifespan )
0 commit comments