Skip to content

Commit

Permalink
Test logger output after configuring logging
Browse files Browse the repository at this point in the history
#3
https://docs.pytest.org/en/latest/how-to/capture-stdout-stderr.html
https://docs.pytest.org/en/latest/how-to/logging.html

In addition to testing the methods that load the logging configuration,
it can also be useful to test that logger messages have the expected
format. This commit will add tests that output logger messages in
various formats and assert that each output matches the expected format.

As in the tests of the Gunicorn server output, these tests will use the
pytest `capfd` fixture. It is also possible to use the `caplog` fixture,
but I have not had as much success with it.
  • Loading branch information
br3ndonland committed Apr 18, 2021
1 parent 9a61fc2 commit 4da7f9f
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions tests/test_logging_conf.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import datetime
import os
from pathlib import Path

Expand Down Expand Up @@ -138,3 +139,44 @@ def test_configure_logging_tmp_module_no_dict(
logger.error.assert_called_once_with(
f"{logger_error_msg}: AttributeError {attribute_error_msg}."
)


class TestLoggingOutput:
"""Test logger output after configuring logging.
---
"""

def test_logging_output_default(self, capfd: pytest.CaptureFixture) -> None:
"""Test logger output with default format."""
logger = logging_conf.logging.getLogger()
logging_conf.configure_logging()
logger.info("Hello, World!")
captured = capfd.readouterr()
assert "INFO" in captured.out
assert "Hello, World!" in captured.out

@pytest.mark.parametrize(
"log_format,log_level_output", (("gunicorn", "[DEBUG]"), ("verbose", "DEBUG"))
)
def test_logging_output_custom_format(
self,
capfd: pytest.CaptureFixture,
log_format: str,
log_level_output: str,
logging_conf_tmp_file_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Test logger output with custom format."""
today = datetime.date.today()
logging_conf_file = f"{logging_conf_tmp_file_path}/tmp_log.py"
monkeypatch.setenv("LOG_FORMAT", "gunicorn")
monkeypatch.setenv("LOG_LEVEL", "debug")
logger = logging_conf.logging.getLogger()
logging_conf.configure_logging(logging_conf=logging_conf_file)
logger.debug("Hello, Customized World!")
captured = capfd.readouterr()
assert str(today) in captured.out
assert log_format not in captured.out
assert log_level_output in captured.out
assert f"Logging dict config loaded from {logging_conf_file}." in captured.out
assert "Hello, Customized World!" in captured.out

0 comments on commit 4da7f9f

Please sign in to comment.