I am writing functional tests for my Python application. I use Python standard logging package in the code I am testing. In my Unit Tests I have mocked the logging package but for the functional tests I would like to test 2 things:
I am able to capture logs and check that the messages are correct. Here is the code I am using:
with assertLogs('', level='INFO') as captured_logs:
do_something()
assertEqual(captured_logs.records[0].msg, "expected message")
This works fine but I am only testing my point 1, logs are produced and the messages are as expected.
My question is how can I test that those logs are actually being sent to stdout and not to a file or stderr, etc.?
Edit:
An example of the code to test could be
import logging
def do_something():
logging.warning("expected message")
The result from testing that code will be that the test passes because the message logged is the expected one. But it will pass no matter if the log goes to a file, or to sys.stdout
or sys.stderr
... My question would be what do I need to add to the test code to make sure the test only passes when the log message goes to stdout
Thanks!!
You check the handlers of the root logger to verify that StreamHandler
(which is the handler that logs on the console) is its only logger.
For example:
from logging import getLogger, StreamHandler
root_logger = getLogger('')
assert len(root_logger.handlers) == 1
assert isinstance(root_logger.handlers[0], StreamHandler)