rich/tests/test_logging.py

96 lines
2.1 KiB
Python
Raw Permalink Normal View History

2020-04-26 11:38:38 +00:00
import io
2020-09-22 23:22:27 +00:00
import os
2020-04-26 11:38:38 +00:00
import logging
import pytest
2020-04-26 11:38:38 +00:00
from rich.console import Console
from rich.logging import RichHandler
handler = RichHandler(
2020-06-14 14:23:43 +00:00
console=Console(
2021-03-01 19:42:00 +00:00
file=io.StringIO(),
force_terminal=True,
width=80,
color_system="truecolor",
_environ={},
2020-06-14 14:38:45 +00:00
),
enable_link_path=False,
2020-04-26 11:38:38 +00:00
)
2021-03-01 19:42:00 +00:00
2020-04-26 11:38:38 +00:00
logging.basicConfig(
level="NOTSET", format="%(message)s", datefmt="[DATE]", handlers=[handler]
2020-04-26 11:38:38 +00:00
)
log = logging.getLogger("rich")
2020-09-22 23:22:27 +00:00
skip_win = pytest.mark.skipif(
os.name == "nt",
reason="rendered differently on windows",
)
2020-09-22 23:22:27 +00:00
@skip_win
def test_exception():
console = Console(
2021-03-01 19:42:00 +00:00
file=io.StringIO(),
force_terminal=True,
width=140,
color_system=None,
_environ={},
)
handler_with_tracebacks = RichHandler(
2020-09-26 14:56:27 +00:00
console=console, enable_link_path=False, rich_tracebacks=True
)
2021-03-01 19:42:00 +00:00
formatter = logging.Formatter("FORMATTER %(message)s %(asctime)s")
handler_with_tracebacks.setFormatter(formatter)
log.addHandler(handler_with_tracebacks)
2021-03-01 19:42:00 +00:00
log.error("foo")
try:
1 / 0
except ZeroDivisionError:
log.exception("message")
render = handler_with_tracebacks.console.file.getvalue()
print(render)
2021-03-01 19:42:00 +00:00
assert "FORMATTER foo" in render
2020-09-24 19:05:42 +00:00
assert "ZeroDivisionError" in render
assert "message" in render
assert "division by zero" in render
def test_exception_with_extra_lines():
console = Console(
2021-03-01 19:42:00 +00:00
file=io.StringIO(),
force_terminal=True,
width=140,
color_system=None,
_environ={},
)
handler_extra_lines = RichHandler(
console=console,
enable_link_path=False,
markup=True,
2020-09-26 14:56:27 +00:00
rich_tracebacks=True,
tracebacks_extra_lines=5,
)
log.addHandler(handler_extra_lines)
try:
1 / 0
except ZeroDivisionError:
log.exception("message")
render = handler_extra_lines.console.file.getvalue()
print(render)
2020-09-24 19:05:42 +00:00
assert "ZeroDivisionError" in render
assert "message" in render
assert "division by zero" in render
2020-04-26 11:38:38 +00:00
if __name__ == "__main__":
render = make_log()
print(render)
print(repr(render))