Open vikramsubramanian opened 5 months ago
To test log statements made by loguru using unittest, you can use the logger.add()
method to add a sink that writes to a StringIO
object. This allows you to capture the log output and assert its contents in your test. Here's how you can modify your test to capture loguru 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())
# Add more tests as needed
setUp
to add a StringIO
sink before each test.tearDown
to remove the sink after each test to prevent side effects.self.log_sink.getvalue()
to get the captured log output for assertions.self.log_sink.seek(0)
before reading from StringIO
to ensure you're reading from the beginning of the stream.
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:
)