Files
slic/tests/test_utils_logign.py
T
tligui_y ddceb3f607
Run CI Tests / test (push) Successful in 31s
Update tests/test_utils_logign.py
2025-07-28 16:27:23 +02:00

80 lines
2.4 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
@pytest.fixture(autouse=True)
def setup_logging():
# Clear existing handlers for pytest capture
for handler in log.handlers[:]:
log.removeHandler(handler)
handler = logging.StreamHandler()
log.addHandler(handler)
log.setLevel(logging.DEBUG)
# Parametrized test for various log levels and messages
@pytest.mark.parametrize("level,msg,should_appear", [
("WARNING", "warn to ignore", False),
("WARNING", "warn to keep", True),
("INFO", "info message", True),
("WARNING", "another warning", True),
])
def test_ignore_log_msg_exact_match(capsys, level, msg, should_appear):
capsys.readouterr() # Clear previous capture
with ignore_log_msg(log, lvl=level, msg=msg):
log.warning("warn to ignore")
log.warning("warn to keep")
log.info("info message")
log.warning("another warning")
captured = capsys.readouterr().err
if should_appear:
assert msg in captured, f"'{msg}' should appear in logs"
else:
assert msg not in captured, f"'{msg}' should be filtered out"
# Test filtering only by log level
def test_ignore_only_by_level(capsys):
capsys.readouterr()
with ignore_log_msg(log, lvl="WARNING", msg=None):
log.warning("should be ignored")
log.info("should appear")
captured = capsys.readouterr().err
assert "should be ignored" not in captured
assert "should appear" in captured
# Test filtering only by message content
def test_ignore_only_by_msg(capsys):
capsys.readouterr()
with ignore_log_msg(log, lvl=None, msg="skip this"):
log.warning("skip this")
log.warning("keep this")
captured = capsys.readouterr().err
assert "skip this" not in captured
assert "keep this" in captured
# Test that filter is removed after exiting the context manager
def test_filter_removed_after_context(capsys):
capsys.readouterr()
with ignore_log_msg(log, lvl="WARNING", msg="temp msg"):
log.warning("temp msg")
# Outside the context: the message should now be logged
log.warning("temp msg")
captured = capsys.readouterr().err
assert "temp msg" in captured