From 90e5767567ae1ad46ae28a80353fab49a65a4de0 Mon Sep 17 00:00:00 2001 From: Paolo Quadri Date: Wed, 27 Mar 2024 10:30:26 +0100 Subject: [PATCH] feat: test non json logger --- remote_log_formatter/__init__.py | 6 ++--- tests/test_formatter.py | 43 +++++++++++++++++++++++++++++--- 2 files changed, 42 insertions(+), 7 deletions(-) diff --git a/remote_log_formatter/__init__.py b/remote_log_formatter/__init__.py index 52460dc..189efd3 100644 --- a/remote_log_formatter/__init__.py +++ b/remote_log_formatter/__init__.py @@ -88,7 +88,7 @@ def setup_logging(json: bool = True) -> None: formatters={ "generic": {"class": "remote_log_formatter.JSONFormatter"}, "simple": { - "format": "%(asctime)s |%(levelname)s | %(name)s | %(message)s", + "format": "%(asctime)s | %(levelname)s | %(message)s | %(pathname)s:%(lineno)s ", }, }, ) @@ -96,5 +96,5 @@ def setup_logging(json: bool = True) -> None: logging.config.dictConfig(LOG_CONFIG) -def get_logger() -> logging.Logger: - return logging.getLogger("remote") +def get_logger(name="remote") -> logging.Logger: + return logging.getLogger(name) diff --git a/tests/test_formatter.py b/tests/test_formatter.py index 1e42fc1..a6657e0 100644 --- a/tests/test_formatter.py +++ b/tests/test_formatter.py @@ -13,11 +13,18 @@ @lru_cache() @pytest.fixture() -def logger_json(setup_logging: None) -> None: +def logger_json() -> None: _setup() return _logger() +@lru_cache() +@pytest.fixture() +def logger_plain() -> None: + _setup(json=False) + return _logger() + + @dataclass(frozen=True) class Foo: bar: str @@ -34,7 +41,7 @@ class Foo: pytest.param(Foo(bar=42), "Foo(bar=42)", id="dataclass"), ], ) -def test_logger( +def test_json_logger( logger_json: logging.Logger, caplog: pytest.LogCaptureFixture, message: Any, @@ -55,8 +62,36 @@ def test_logger( "processname": "MainProcess", "pathname": data["context"]["pathname"], "module": "test_formatter", - "function": "test_logger", - "lineno": 48, + "function": "test_json_logger", + "lineno": data["context"]["lineno"], }, "extra": {"type": "log"}, } + + +@lru_cache() +@pytest.mark.parametrize( + "message,expected", + [ + pytest.param("foo", "foo", id="str"), + pytest.param(42, "42", id="integer"), + pytest.param(Decimal(42), "42", id="decimal"), + pytest.param(42.0, "42.0", id="float"), + pytest.param(Foo(bar=42), "Foo(bar=42)", id="dataclass"), + ], +) +def test_plain_logger( + logger_plain: logging.Logger, + caplog: pytest.LogCaptureFixture, + message: Any, + expected: str, +) -> None: + logger_plain.info(message) + assert caplog.records + r = caplog.records[0] + + data = logger_plain.handlers[0].format(r) + + _ts, level, message, path = data.split("|") + assert message.strip() == expected + assert level.strip() == "INFO"