Skip to content

Commit

Permalink
feat: Add unittest and mock test for logger module
Browse files Browse the repository at this point in the history
  • Loading branch information
MissterHao committed Feb 10, 2023
1 parent 85e160c commit 47bde4b
Show file tree
Hide file tree
Showing 5 changed files with 117 additions and 12 deletions.
2 changes: 2 additions & 0 deletions .coveragerc
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
omit =
tests/*.py
runtests.py
dysession/logger/handler/colorful_console.py

[report]
# Regexes for lines to exclude from consideration
exclude_lines =
Expand Down
34 changes: 24 additions & 10 deletions dysession/logger/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
import sys
from enum import Enum, auto
from functools import lru_cache
from typing import Optional
from typing import Literal

from handler.colorful_console import ColorfulConsoleLoggerHandler
from .handler.colorful_console import ColorfulConsoleLoggerHandler


class LoggingType(Enum):
Expand All @@ -23,9 +23,22 @@ def is_tty() -> bool:

def get_logger(
logger_name: str = "dysession",
logger_type: LoggingType = LoggingType.CONSOLE,
logger_type: Literal[LoggingType.CONSOLE, LoggingType.FILE] = LoggingType.CONSOLE,
level: int = logging.DEBUG,
) -> logging.Logger:
"""
This function return a logging.Logger with handlers.
Handlers could be `ColorfulConsoleLoggerHandler`, `StreamHandler`, `FileHandler`.
```
logger = get_logger()
logger.debug("This is a DEBUG log.")
logger.info("This is a INFO log.")
logger.warning("This is a WARNING log.")
logger.critical("This is a CRITICAL log.")
logger.fatal("This is a FATAL log.")
```
"""

logger = logging.getLogger(logger_name)
format = logging.Formatter(
Expand All @@ -44,14 +57,15 @@ def get_logger(

handler.setFormatter(format)
logger.addHandler(handler)
else:
logger.warning(
f"Dysession logger had already initialized with logger({logger.handlers})"
)

return logger


if __name__ == "__main__":
logger = get_logger()
logger.debug("This is a DEBUG log.")
logger.info("This is a INFO log.")
logger.warning("This is a WARNING log.")
logger.critical("This is a CRITICAL log.")
logger.fatal("This is a FATAL log.")
__all__ = (
LoggingType,
get_logger,
)
2 changes: 0 additions & 2 deletions dysession/logger/handler/colorful_console.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ class ColorfulConsoleLoggerHandler(logging.StreamHandler):

def emit(self, record):
try:
# record.msg = "QQQQQQQQQQQQQQ"
# record.levelname = "\033[91m" + record.levelname + "\033[0m"
record.levelname = (
LOGLEVEL_TRANSFORM[record.levelno]
+ f"{record.levelname:>8}"
Expand Down
61 changes: 61 additions & 0 deletions tests/test_logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import logging
import sys
from unittest import mock

from django.test import TestCase
from parameterized import parameterized

from dysession.logger import LoggingType, get_logger, is_tty
from dysession.logger.handler.colorful_console import ColorfulConsoleLoggerHandler


class LoggerTestCase(TestCase):
def test_get_logger_with_second_logger_type_passed_in(self):

with self.assertLogs("dysession") as cm:
logger = get_logger()
logger.info("This is a test content")
self.assertIn("This is a test content", "\n".join(cm.output))

with self.assertLogs("dysession") as cm:
logger = get_logger(logger_type=LoggingType.FILE)
logger.info("This is a test content")
self.assertIn("WARNING", "\n".join(cm.output))

@mock.patch("sys.stdout.isatty")
def test_logger_is_tty_handlers(self, mock_is_tty):
is_tty.cache_clear()
mock_is_tty.return_value = True

logger = get_logger()
self.assertEqual(len(logger.handlers), 1)
self.assertEqual(logger.name, "dysession")
self.assertIs(type(logger.handlers[0]), ColorfulConsoleLoggerHandler)

logger.handlers = []

@mock.patch("sys.stdout.isatty")
def test_logger_is_not_tty_handlers(self, mock_is_tty):
is_tty.cache_clear()
mock_is_tty.return_value = False

logger = get_logger()
self.assertEqual(len(logger.handlers), 1)
self.assertEqual(logger.name, "dysession")
self.assertIs(type(logger.handlers[0]), logging.StreamHandler)

logger.handlers = []

def test_logger_file_handler(self):

logger = get_logger(logger_type=LoggingType.FILE)

self.assertEqual(len(logger.handlers), 1)
self.assertEqual(logger.name, "dysession")
self.assertIsInstance(logger.handlers[0], logging.FileHandler)

with self.assertLogs("dysession") as cm:
logger.info("This is a test content")
self.assertIn("This is a test content", "\n".join(cm.output))

logger.handlers = []
30 changes: 30 additions & 0 deletions tests/test_logger_handler_ansi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from typing import Any

from django.test import TestCase
from parameterized import parameterized

from dysession.logger import get_logger
from dysession.logger.handler.ansi import ANSIColor, colorful_it


class ANSITestCase(TestCase):
@parameterized.expand(
[
[ANSIColor.HEADER],
[ANSIColor.OKBLUE],
[ANSIColor.OKCYAN],
[ANSIColor.OKGREEN],
[ANSIColor.SUCCESSFUL],
[ANSIColor.WARNING],
[ANSIColor.FAIL],
[ANSIColor.DEBUG],
[ANSIColor.BOLD],
[ANSIColor.UNDERLINE],
]
)
def test_ansi_colorful_it_func(self, ansi_color: ANSIColor):

self.assertEqual(
colorful_it(ansi_color, "Content"),
f"{ansi_color.value}Content{ANSIColor.ENDC.value}",
)

0 comments on commit 47bde4b

Please sign in to comment.