-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
#8711: Handle disabled logging in 'caplog.set_level' and 'caplog.at_level' #8758
Merged
nicoddemus
merged 4 commits into
pytest-dev:main
from
alexlambson:issue-8711-handle-disabled-logging
May 18, 2023
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
e480dfe
Handle disabled logging in 'caplog.set_level' and 'caplog.at_level' #…
bc5a27f
caplog un-disable logging, feedback per review #8711
alexlambson 150914d
caplog un-disable logging, add missing test coverage
alexlambson 7f89996
caplog un-disable logging, add missing test coverage
alexlambson File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
:func:`_pytest.logging.LogCaptureFixture.set_level` and :func:`_pytest.logging.LogCaptureFixture.at_level` | ||
will temporarily enable the requested ``level`` if ``level`` was disabled globally via | ||
``logging.disable(LEVEL)``. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -376,18 +376,23 @@ def __init__(self, item: nodes.Node, *, _ispytest: bool = False) -> None: | |
self._initial_handler_level: Optional[int] = None | ||
# Dict of log name -> log level. | ||
self._initial_logger_levels: Dict[Optional[str], int] = {} | ||
self._initial_disabled_logging_level: Optional[int] = None | ||
|
||
def _finalize(self) -> None: | ||
"""Finalize the fixture. | ||
|
||
This restores the log levels changed by :meth:`set_level`. | ||
This restores the log levels and the disabled logging levels changed by :meth:`set_level`. | ||
""" | ||
# Restore log levels. | ||
if self._initial_handler_level is not None: | ||
self.handler.setLevel(self._initial_handler_level) | ||
for logger_name, level in self._initial_logger_levels.items(): | ||
logger = logging.getLogger(logger_name) | ||
logger.setLevel(level) | ||
# Disable logging at the original disabled logging level. | ||
if self._initial_disabled_logging_level is not None: | ||
logging.disable(self._initial_disabled_logging_level) | ||
self._initial_disabled_logging_level = None | ||
|
||
@property | ||
def handler(self) -> LogCaptureHandler: | ||
|
@@ -453,13 +458,49 @@ def clear(self) -> None: | |
"""Reset the list of log records and the captured log text.""" | ||
self.handler.clear() | ||
|
||
def _force_enable_logging( | ||
self, level: Union[int, str], logger_obj: logging.Logger | ||
) -> int: | ||
"""Enable the desired logging level if the global level was disabled via ``logging.disabled``. | ||
|
||
Only enables logging levels greater than or equal to the requested ``level``. | ||
|
||
Does nothing if the desired ``level`` wasn't disabled. | ||
|
||
:param level: | ||
The logger level caplog should capture. | ||
All logging is enabled if a non-standard logging level string is supplied. | ||
Valid level strings are in :data:`logging._nameToLevel`. | ||
:param logger_obj: The logger object to check. | ||
|
||
:return: The original disabled logging level. | ||
""" | ||
original_disable_level: int = logger_obj.manager.disable # type: ignore[attr-defined] | ||
|
||
if isinstance(level, str): | ||
# Try to translate the level string to an int for `logging.disable()` | ||
level = logging.getLevelName(level) | ||
|
||
if not isinstance(level, int): | ||
# The level provided was not valid, so just un-disable all logging. | ||
logging.disable(logging.NOTSET) | ||
elif not logger_obj.isEnabledFor(level): | ||
# Each level is `10` away from other levels. | ||
# https://docs.python.org/3/library/logging.html#logging-levels | ||
disable_level = max(level - 10, logging.NOTSET) | ||
logging.disable(disable_level) | ||
|
||
return original_disable_level | ||
|
||
def set_level(self, level: Union[int, str], logger: Optional[str] = None) -> None: | ||
"""Set the level of a logger for the duration of a test. | ||
|
||
.. versionchanged:: 3.4 | ||
The levels of the loggers changed by this function will be | ||
restored to their initial values at the end of the test. | ||
|
||
Will enable the requested logging level if it was disabled via :meth:`logging.disable`. | ||
|
||
:param level: The level. | ||
:param logger: The logger to update. If not given, the root logger. | ||
""" | ||
|
@@ -470,6 +511,9 @@ def set_level(self, level: Union[int, str], logger: Optional[str] = None) -> Non | |
if self._initial_handler_level is None: | ||
self._initial_handler_level = self.handler.level | ||
self.handler.setLevel(level) | ||
initial_disabled_logging_level = self._force_enable_logging(level, logger_obj) | ||
if self._initial_disabled_logging_level is None: | ||
self._initial_disabled_logging_level = initial_disabled_logging_level | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We could remove this magic for a parameter if magic is frowned upon. |
||
|
||
@contextmanager | ||
def at_level( | ||
|
@@ -479,6 +523,8 @@ def at_level( | |
the end of the 'with' statement the level is restored to its original | ||
value. | ||
|
||
Will enable the requested logging level if it was disabled via :meth:`logging.disable`. | ||
|
||
:param level: The level. | ||
:param logger: The logger to update. If not given, the root logger. | ||
""" | ||
|
@@ -487,11 +533,13 @@ def at_level( | |
logger_obj.setLevel(level) | ||
handler_orig_level = self.handler.level | ||
self.handler.setLevel(level) | ||
original_disable_level = self._force_enable_logging(level, logger_obj) | ||
try: | ||
yield | ||
finally: | ||
logger_obj.setLevel(orig_level) | ||
self.handler.setLevel(handler_orig_level) | ||
logging.disable(original_disable_level) | ||
|
||
|
||
@fixture | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Linter doesn't like runtime attributes, so the ignore is needed to the best of my knowledge.