249 lines
10 KiB
Python
249 lines
10 KiB
Python
"""Tests for the shared logging configuration (SPEC 7.17)."""
|
|
|
|
import logging
|
|
import re
|
|
|
|
import pytest
|
|
|
|
from fiona.logging_config import (
|
|
TOOL_LOGGER_NAMES,
|
|
load_log_level,
|
|
load_settings,
|
|
setup_logging,
|
|
)
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def clean_log_env(monkeypatch):
|
|
"""Keep LOG_LEVEL and tool logger levels isolated between tests."""
|
|
monkeypatch.delenv("LOG_LEVEL", raising=False)
|
|
levels = {name: logging.getLogger(name).level for name in TOOL_LOGGER_NAMES}
|
|
root_handlers = list(logging.getLogger().handlers)
|
|
yield
|
|
for name, level in levels.items():
|
|
logging.getLogger(name).setLevel(level)
|
|
for handler in list(logging.getLogger().handlers):
|
|
if handler not in root_handlers:
|
|
logging.getLogger().removeHandler(handler)
|
|
if isinstance(handler, logging.FileHandler):
|
|
handler.close()
|
|
|
|
|
|
class TestLoadLogLevel:
|
|
"""Tests for log level resolution precedence."""
|
|
|
|
def test_settings_value_used(self):
|
|
"""Should read fiona.log_level from the settings dict."""
|
|
assert load_log_level({"fiona": {"log_level": "INFO"}}) == "INFO"
|
|
|
|
def test_settings_value_normalized(self):
|
|
"""Should normalize the settings value to upper case."""
|
|
assert load_log_level({"fiona": {"log_level": "debug"}}) == "DEBUG"
|
|
|
|
def test_env_var_wins_over_settings(self, monkeypatch):
|
|
"""Should let LOG_LEVEL override the settings value."""
|
|
monkeypatch.setenv("LOG_LEVEL", "ERROR")
|
|
assert load_log_level({"fiona": {"log_level": "INFO"}}) == "ERROR"
|
|
|
|
def test_missing_fiona_section_defaults_to_warning(self):
|
|
"""Should fall back to WARNING without a fiona section."""
|
|
assert load_log_level({}) == "WARNING"
|
|
|
|
def test_invalid_level_name_defaults_to_warning(self, caplog):
|
|
"""Should warn and fall back to WARNING on an unknown level name."""
|
|
with caplog.at_level(logging.WARNING):
|
|
assert load_log_level({"fiona": {"log_level": "VERBOSE"}}) == "WARNING"
|
|
assert "VERBOSE" in caplog.text
|
|
|
|
def test_non_string_level_defaults_to_warning(self):
|
|
"""Should fall back to WARNING on a non-string value."""
|
|
assert load_log_level({"fiona": {"log_level": 10}}) == "WARNING"
|
|
|
|
def test_none_settings_defaults_to_warning(self):
|
|
"""Should fall back to WARNING without settings."""
|
|
assert load_log_level(None) == "WARNING"
|
|
|
|
|
|
class TestLoadSettings:
|
|
"""Tests for loading the full settings file."""
|
|
|
|
def test_load_settings_reads_file(self, tmp_path):
|
|
"""Should return the full settings mapping."""
|
|
settings_file = tmp_path / "fiona-settings.json"
|
|
settings_file.write_text('{"fiona": {"log_level": "DEBUG"}}', encoding="utf-8")
|
|
assert load_settings(settings_file) == {"fiona": {"log_level": "DEBUG"}}
|
|
|
|
def test_load_settings_missing_file_returns_empty(self, tmp_path):
|
|
"""Should return an empty dict for a missing settings file."""
|
|
assert load_settings(tmp_path / "missing.json") == {}
|
|
|
|
def test_load_settings_invalid_json_returns_empty(self, tmp_path):
|
|
"""Should return an empty dict for an unparseable settings file."""
|
|
settings_file = tmp_path / "fiona-settings.json"
|
|
settings_file.write_text("{not json", encoding="utf-8")
|
|
assert load_settings(settings_file) == {}
|
|
|
|
def test_load_settings_defaults_to_packaged_file(self):
|
|
"""Should load the packaged template settings by default."""
|
|
settings = load_settings()
|
|
assert settings.get("fiona", {}).get("log_level") == "INFO"
|
|
|
|
|
|
class TestSetupLogging:
|
|
"""Tests for the project-wide logging setup."""
|
|
|
|
def test_returns_effective_level(self):
|
|
"""Should return the resolved level name."""
|
|
assert setup_logging({"fiona": {"log_level": "INFO"}}) == "INFO"
|
|
|
|
def test_sets_tool_logger_levels(self):
|
|
"""Should set the level explicitly on every tool logger."""
|
|
setup_logging({"fiona": {"log_level": "INFO"}})
|
|
for name in TOOL_LOGGER_NAMES:
|
|
assert logging.getLogger(name).level == logging.INFO
|
|
|
|
def test_env_var_overrides_settings(self, monkeypatch):
|
|
"""Should honor LOG_LEVEL over the settings value."""
|
|
monkeypatch.setenv("LOG_LEVEL", "ERROR")
|
|
assert setup_logging({"fiona": {"log_level": "INFO"}}) == "ERROR"
|
|
|
|
def test_repeated_calls_do_not_duplicate_handlers(self):
|
|
"""Should not add a second root handler on repeated calls."""
|
|
setup_logging({"fiona": {"log_level": "INFO"}})
|
|
count = len(logging.getLogger().handlers)
|
|
setup_logging({"fiona": {"log_level": "INFO"}})
|
|
assert len(logging.getLogger().handlers) == count
|
|
|
|
def test_missing_settings_file_uses_warning(self, tmp_path):
|
|
"""Should configure WARNING when the settings file is missing."""
|
|
assert setup_logging(settings_file=tmp_path / "missing.json") == "WARNING"
|
|
|
|
def test_settings_file_argument_used(self, tmp_path):
|
|
"""Should read the level from the given settings file."""
|
|
settings_file = tmp_path / "fiona-settings.json"
|
|
settings_file.write_text('{"fiona": {"log_level": "DEBUG"}}', encoding="utf-8")
|
|
assert setup_logging(settings_file=settings_file) == "DEBUG"
|
|
|
|
|
|
class TestFileLogging:
|
|
"""Tests for physical-file logging (fiona.file_log_* settings)."""
|
|
|
|
def _tagged_handlers(self):
|
|
return [
|
|
handler
|
|
for handler in logging.getLogger().handlers
|
|
if getattr(handler, "fiona_file_log", False)
|
|
]
|
|
|
|
def test_file_handler_writes_records(self, tmp_path):
|
|
"""Should write log records to the configured file."""
|
|
location = tmp_path / "fiona.log"
|
|
setup_logging({
|
|
"fiona": {
|
|
"log_level": "INFO",
|
|
"file_log_level": "INFO",
|
|
"file_log_location": str(location),
|
|
}
|
|
})
|
|
logging.getLogger("fiona.librarian").info("hello file")
|
|
content = location.read_text(encoding="utf-8")
|
|
assert "hello file" in content
|
|
assert "INFO" in content
|
|
|
|
def test_file_log_line_has_timestamp(self, tmp_path):
|
|
"""Should prefix file lines with an asctime stamp."""
|
|
location = tmp_path / "fiona.log"
|
|
setup_logging({
|
|
"fiona": {
|
|
"log_level": "INFO",
|
|
"file_log_location": str(location),
|
|
}
|
|
})
|
|
logging.getLogger("fiona.librarian").info("stamped")
|
|
line = location.read_text(encoding="utf-8").strip()
|
|
assert re.match(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}", line)
|
|
|
|
def test_file_log_level_filters_records(self, tmp_path):
|
|
"""Should apply file_log_level independently of log_level."""
|
|
location = tmp_path / "fiona.log"
|
|
setup_logging({
|
|
"fiona": {
|
|
"log_level": "DEBUG",
|
|
"file_log_level": "ERROR",
|
|
"file_log_location": str(location),
|
|
}
|
|
})
|
|
logging.getLogger("fiona.librarian").info("info record")
|
|
logging.getLogger("fiona.librarian").error("error record")
|
|
content = location.read_text(encoding="utf-8")
|
|
assert "error record" in content
|
|
assert "info record" not in content
|
|
|
|
def test_file_log_level_defaults_to_console_level(self, tmp_path):
|
|
"""Should fall back to log_level without file_log_level."""
|
|
location = tmp_path / "fiona.log"
|
|
setup_logging({
|
|
"fiona": {
|
|
"log_level": "DEBUG",
|
|
"file_log_location": str(location),
|
|
}
|
|
})
|
|
logging.getLogger("fiona.librarian").debug("debug record")
|
|
assert "debug record" in location.read_text(encoding="utf-8")
|
|
|
|
def test_no_location_adds_no_file_handler(self):
|
|
"""Should not add a file handler without file_log_location."""
|
|
setup_logging({"fiona": {"log_level": "INFO"}})
|
|
assert self._tagged_handlers() == []
|
|
|
|
def test_repeated_setup_does_not_duplicate_handlers(self, tmp_path):
|
|
"""Should keep a single file handler across repeated setups."""
|
|
settings = {"fiona": {"log_level": "INFO", "file_log_location": str(tmp_path / "a.log")}}
|
|
setup_logging(settings)
|
|
setup_logging(settings)
|
|
assert len(self._tagged_handlers()) == 1
|
|
|
|
def test_changed_location_moves_handler(self, tmp_path):
|
|
"""Should write only to the newest location after a change."""
|
|
first = tmp_path / "first.log"
|
|
second = tmp_path / "second.log"
|
|
setup_logging({"fiona": {"log_level": "INFO", "file_log_location": str(first)}})
|
|
setup_logging({"fiona": {"log_level": "INFO", "file_log_location": str(second)}})
|
|
logging.getLogger("fiona.librarian").info("moved record")
|
|
assert "moved record" in second.read_text(encoding="utf-8")
|
|
assert not first.exists() or "moved record" not in first.read_text(encoding="utf-8")
|
|
|
|
def test_disabling_location_removes_handler(self, tmp_path):
|
|
"""Should remove the file handler when the location is dropped."""
|
|
location = tmp_path / "fiona.log"
|
|
setup_logging({"fiona": {"log_level": "INFO", "file_log_location": str(location)}})
|
|
setup_logging({"fiona": {"log_level": "INFO"}})
|
|
assert self._tagged_handlers() == []
|
|
|
|
def test_invalid_file_log_level_warns_and_uses_console_level(self, tmp_path, caplog):
|
|
"""Should warn and use log_level for an unknown file_log_level."""
|
|
location = tmp_path / "fiona.log"
|
|
with caplog.at_level(logging.WARNING):
|
|
setup_logging({
|
|
"fiona": {
|
|
"log_level": "INFO",
|
|
"file_log_level": "VERBOSE",
|
|
"file_log_location": str(location),
|
|
}
|
|
})
|
|
assert "VERBOSE" in caplog.text
|
|
logging.getLogger("fiona.librarian").info("fallback record")
|
|
assert "fallback record" in location.read_text(encoding="utf-8")
|
|
|
|
def test_unwritable_location_warns_and_continues(self, tmp_path, caplog):
|
|
"""Should warn and keep console logging when the file cannot open."""
|
|
with caplog.at_level(logging.WARNING):
|
|
level = setup_logging({
|
|
"fiona": {
|
|
"log_level": "INFO",
|
|
"file_log_location": str(tmp_path / "missing_dir" / "fiona.log"),
|
|
}
|
|
})
|
|
assert level == "INFO"
|
|
assert self._tagged_handlers() == []
|