Created
February 26, 2020 20:07
-
-
Save jtprince/f3a9a0fcd81af49d94d4d54394d033e9 to your computer and use it in GitHub Desktop.
quietcaplog is a pytest fixture like caplog but which quiets output to any StreamHandler handlers on the root logger
This file contains hidden or 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
@pytest.fixture | |
def quietcaplog(caplog): | |
""" Capture logging while suppressing output to stderr and stdout. | |
quietcaplog IS a caplog fixture (so anything you can do with the caplog | |
fixture you can do with it). BUT it also removes any StreamHandler | |
loggers from the root logger before the test and replaces them on the root | |
logger after the test is over. That means your tests are quiet, but you | |
can also inspect the log messages being produced if needed. | |
See caplog: | |
https://docs.pytest.org/en/latest/logging.html#caplog-fixture | |
Example: | |
# quietcaplog is a caplog object | |
def test_this(self, quietcaplog): | |
... | |
# see what was captured as log output: | |
print(quietcaplog.record_tuples) | |
""" | |
root_logger = logging.getLogger() | |
before_handlers = root_logger.handlers | |
no_stream_handlers = [ | |
handler for handler in root_logger.handlers if not isinstance(handler, logging.StreamHandler) | |
] | |
root_logger.handlers = no_stream_handlers | |
yield caplog | |
root_logger.handlers = before_handlers |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment