Open vikramsubramanian opened 5 months ago
To test log statements made by loguru using unittest, you can add a sink to the logger that writes to a StringIO object, and then assert the contents of that StringIO object. Here's how you can modify your test to capture the log output:
from loguru import logger
from unittest import TestCase
import io
class LoggerTest(TestCase):
def setUp(self):
self.log_sink = io.StringIO()
logger.add(self.log_sink, format="{message}")
def tearDown(self):
logger.remove(self.log_sink)
def test_logger_info(self):
logger.info("loguru log right here")
self.log_sink.seek(0) # Move to the beginning of StringIO to read its content
self.assertEqual("loguru log right here\n", self.log_sink.getvalue())
def test_logger_error(self):
logger.error("an error occurred")
self.log_sink.seek(0)
self.assertEqual("an error occurred\n", self.log_sink.getvalue())
In this example:
setUp
method is used to add a sink to the logger before each test.tearDown
method is used to remove the sink after each test to prevent side effects.self.log_sink.seek(0)
is used to move the cursor to the beginning of the StringIO object before reading its content.self.log_sink.getvalue()
is used to get the content of the StringIO object for assertion.
I've got a project which is not using pytest. How can I successfully assert log statements made by loguru using unittests?
For example, I've got:
Running the test reveals I'm unsuccessful in capturing the loguru output:
)