Mayil-SB-Internal-Prod / loguru-II

MIT License
0 stars 0 forks source link

How to test loguru logger with unittest? (hashtag616) #80

Open vikramsubramanian opened 5 months ago

vikramsubramanian commented 5 months ago

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:

hashtag test_loguru.py

import contextlib
import io
from unittest import TestCase

from loguru import logger

class LoggerTest(TestCase):
    def test_logger_stderr(self):
        f = io.StringIO()
        with contextlib.redirect_stderr(f):
            logger.info("loguru log right here")

        self.assertEqual("loguru log right here\n", f.getvalue())

Running the test reveals I'm unsuccessful in capturing the loguru output:

$ python -m unittest test_loguru.py
2022-03-14 15:01:40.597 | INFO     | test_loguru:test_logger_stderr:12 - loguru log right here
F
======================================================================
FAIL: test_logger_stderr (test_loguru.LoggerTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/fredrik/code/repos/logger/test_loguru.py", line 14, in test_logger_stderr
    self.assertEqual("loguru log right here\n", f.getvalue())
AssertionError: 'loguru log right here\n' != ''
- loguru log right here

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)

)

mayil-ai[bot] commented 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: