Add tests/test_utils_logcfg.py
Run CI Tests / test (push) Successful in 26s

This commit is contained in:
2025-07-28 14:01:23 +02:00
parent af49f6320a
commit f0636ddcd4
+76
View File
@@ -0,0 +1,76 @@
import logging
import logzero
from logzero import logger as log
import pytest
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from slic.utils.logcfg import *
# Test : add_log_Level()
# Fixture: Register custom log levels once for the module
@pytest.fixture(scope="module", autouse=True)
def setup_custom_levels():
# Add custom log levels with names, numeric values, functions, and colors
add_log_Level(log, "LONG", logging.INFO + 5, func_name="long", color="cyan")
add_log_Level(log, "ENLARGE", logging.INFO + 6, func_name="enlarge", color="green")
# Set default log level (will display LONG, ENLARGE and higher)
logcfg("LONG")
# ANSI escape codes to verify colors
ANSI_CYAN = "\x1b[36m"
ANSI_GREEN = "\x1b[32m"
ANSI_RESET = "\x1b[0m"
# Parametrized test: custom log levels
@pytest.mark.parametrize("levelname, logfunc, message, ansi_color", [
("LONG", lambda msg: log.long(msg), "This is a LONG message", ANSI_CYAN),
("ENLARGE", lambda msg: log.enlarge(msg), "Please ENLARGE this!", ANSI_GREEN),
])
def test_custom_levels_are_logged(levelname, logfunc, message, ansi_color, capsys):
# Call the custom log function
logfunc(message)
# Capture stderr where logzero outputs messages
captured = capsys.readouterr().err
assert ansi_color in captured, f"Expected color code {ansi_color} not found in log output"
assert message in captured, "Expected log message not found in output"
assert captured.strip().endswith(ANSI_RESET), "Missing ANSI reset code at end of log line"
# Test : setup_import_logging()
def test_import_logging_multiple_modules(capfd):
# Setup custom TRACE log level with color
add_log_Level(log, "TRACE", logging.DEBUG - 1, color="magenta")
# Initialize both logzero and logging configurations to use TRACE level
logcfg("TRACE")
# Fuction to test
setup_import_logging()
# Perform various imports
import json
import math
import io
import json # Duplicate
import math # Duplicate
import random
import random # Duplicate
# Capture the printed output
out, err = capfd.readouterr()
# Check that each unique module import appears once in the logs
expected_imports = {"json", "math", "io", "random"}
for mod in expected_imports:
assert f"importing: {mod}" in out
# Ensure duplicates are only logged once
assert out.count("importing: json") == 1
assert out.count("importing: math") == 1
assert out.count("importing: random") == 1
# Verify that our custom log level is actually used
assert "TRACE" in out.upper()