File: test_logging.py

package info (click to toggle)
enrich 1.3.0-2.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 136 kB
  • sloc: python: 253; makefile: 4
file content (91 lines) | stat: -rw-r--r-- 2,571 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
"""Tests related to enriched RichHandler"""

from __future__ import annotations

import io
import logging
import re

import pytest
from enrich.console import Console
from enrich.logging import RichHandler


def strip_ansi_escape(text: str | bytes) -> str:
    """Remove all ANSI escapes from string or bytes.

    If bytes is passed instead of string, it will be converted to string
    using UTF-8.
    """
    if isinstance(text, bytes):
        text = text.decode("utf-8")

    return re.sub(r"\x1b[^m]*m", "", text)


@pytest.fixture(name="rich_logger")
def rich_logger_fixture() -> tuple[logging.Logger, RichHandler]:
    """Returns tuple with logger and handler to be tested."""
    rich_handler = RichHandler(
        console=Console(
            file=io.StringIO(),
            force_terminal=True,
            width=80,
            color_system="truecolor",
            soft_wrap=True,
        ),
        enable_link_path=False,
    )

    logging.basicConfig(
        level="NOTSET",
        format="%(message)s",
        datefmt="[DATE]",
        handlers=[rich_handler],
    )
    rich_log = logging.getLogger("rich")
    rich_log.addHandler(rich_handler)
    return (rich_log, rich_handler)


def test_logging(rich_logger: tuple[logging.Logger, RichHandler]) -> None:
    """Test that logger does not wrap."""
    (logger, rich_handler) = rich_logger

    text = 10 * "x"  # a long text that would likely wrap on a normal console
    logger.error("%s %s", text, 123)

    # verify that the long text was not wrapped
    output = strip_ansi_escape(rich_handler.console.file.getvalue())  # type: ignore
    assert text in output
    assert "ERROR" in output
    assert "\n" not in output[:-1]


if __name__ == "__main__":
    handler = RichHandler(
        console=Console(
            force_terminal=True,
            width=55510,  # this is expected to have no effect
            color_system="truecolor",
            soft_wrap=True,
        ),
        enable_link_path=False,
        show_time=True,
        show_level=True,
        show_path=True,
    )
    logging.basicConfig(
        level="NOTSET",
        format="%(message)s",
        # datefmt="[DATE]",
        handlers=[handler],
    )
    log = logging.getLogger("rich")
    # log.addHandler(handler)
    data = {"foo": "text", "bar": None, "number": 123}
    log.error("This was a long error")
    log.warning("This was warning %s apparently", 123)
    log.info("Having info is good")
    log.debug("Some kind of debug message %s", None)
    log.info("Does this dictionary %s render ok?", data)