89 lines
2.7 KiB
Python
89 lines
2.7 KiB
Python
import logging
|
|
import pytest
|
|
import pytest
|
|
import sys
|
|
import os
|
|
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
|
from slic.utils.logign import *
|
|
from slic.utils.logcfg import add_log_Level, logcfg
|
|
|
|
import logzero
|
|
from logzero import logger as log, LogFormatter
|
|
|
|
# Configure logging for pytest capture
|
|
@pytest.fixture(scope="function", autouse=True)
|
|
def setup_logging():
|
|
|
|
# Clear existing handlers
|
|
for handler in log.handlers[:]:
|
|
log.removeHandler(handler)
|
|
|
|
# Add new handler to stderr (will be captured by pytest)
|
|
handler = logging.StreamHandler(sys.stderr)
|
|
handler.setFormatter(LogFormatter())
|
|
log.addHandler(handler)
|
|
|
|
# Setup custom log levels
|
|
add_log_Level(log, "ENLARGE", logging.INFO + 5, func_name="enlarge")
|
|
log.setLevel(logging.DEBUG) # Capture all levels
|
|
|
|
# Test cases for log message filtering
|
|
@pytest.mark.parametrize("level,msg,should_appear", [
|
|
("WARNING", "warn to ignore", False),
|
|
("WARNING", "warn to keep", True),
|
|
("INFO", "info message", True),
|
|
("ENLARGE", "enlarge to ignore", False),
|
|
("ENLARGE", "other enlarge", True),
|
|
])
|
|
def test_ignore_log_msg_filter(capfd, level, msg, should_appear):
|
|
# Clear previous captures
|
|
capfd.readouterr()
|
|
|
|
# Test the filter
|
|
with ignore_log_msg(log, lvl=level, msg=msg):
|
|
log.warning("warn to ignore")
|
|
log.warning("warn to keep")
|
|
log.info("info message")
|
|
log.enlarge("enlarge to ignore")
|
|
log.enlarge("other enlarge")
|
|
|
|
# Verify results
|
|
captured = capfd.readouterr().err
|
|
if should_appear:
|
|
assert msg in captured, f"Message '{msg}' should appear in logs"
|
|
else:
|
|
assert msg not in captured, f"Message '{msg}' should be filtered"
|
|
|
|
def test_ignore_only_by_level(capfd):
|
|
capfd.readouterr()
|
|
|
|
with ignore_log_msg(log, lvl="WARNING", msg=None):
|
|
log.warning("should be ignored")
|
|
log.info("should appear")
|
|
|
|
captured = capfd.readouterr().err
|
|
assert "should be ignored" not in captured
|
|
assert "should appear" in captured
|
|
|
|
def test_ignore_only_by_msg(capfd):
|
|
capfd.readouterr()
|
|
|
|
with ignore_log_msg(log, lvl=None, msg="skip this"):
|
|
log.warning("skip this")
|
|
log.warning("keep this")
|
|
|
|
captured = capfd.readouterr().err
|
|
assert "skip this" not in captured
|
|
assert "keep this" in captured
|
|
|
|
def test_filter_removed_after_context(capfd):
|
|
capfd.readouterr()
|
|
|
|
# Filter during context
|
|
with ignore_log_msg(log, lvl="WARNING", msg="temp msg"):
|
|
log.warning("temp msg")
|
|
|
|
# Should log after context
|
|
log.warning("temp msg")
|
|
captured = capfd.readouterr().err
|
|
assert "temp msg" in captured |