Skip to content

Commit

Permalink
Add console tests with snapshots (#194)
Browse files Browse the repository at this point in the history
  • Loading branch information
pederhan authored Aug 29, 2024
1 parent e1286df commit da1dc10
Show file tree
Hide file tree
Showing 3 changed files with 156 additions and 6 deletions.
9 changes: 7 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ zabbix-cli-init = "zabbix_cli.scripts.init:main"
zabbix-cli-bulk-execution = "zabbix_cli.scripts.bulk_execution:main"

[project.optional-dependencies]
test = ["pytest", "pytest-cov", "freezegun"]
test = ["pytest", "pytest-cov", "freezegun", "inline-snapshot"]

[tool.hatch.version]
path = "zabbix_cli/__about__.py"
Expand Down Expand Up @@ -118,7 +118,12 @@ exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"]
[tool.ruff]
src = ["zabbix_cli"]
extend-exclude = ["zabbix_cli/__init__.py"]
include = ["pyproject.toml", "zabbix_cli/**/*.py", "scripts/**/*.py"]
include = [
"pyproject.toml",
"zabbix_cli/**/*.py",
"scripts/**/*.py",
"tests/**/*.py",
]

[tool.pyright]
pythonVersion = "3.8"
Expand Down
144 changes: 144 additions & 0 deletions tests/test_console.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
from __future__ import annotations

import logging
from typing import Any
from typing import Dict

import pytest
from inline_snapshot import snapshot
from zabbix_cli.output.console import RESERVED_EXTRA_KEYS
from zabbix_cli.output.console import debug
from zabbix_cli.output.console import debug_kv
from zabbix_cli.output.console import error
from zabbix_cli.output.console import get_extra_dict
from zabbix_cli.output.console import info
from zabbix_cli.output.console import success
from zabbix_cli.output.console import warning


@pytest.mark.parametrize(
"inp,expect",
[
# No extras
({}, {}),
# 1 extra
({"name": "foo"}, {"name_": "foo"}),
# 2 extras
({"name": "foo", "level": "DEBUG"}, {"name_": "foo", "level_": "DEBUG"}),
# 3 extras (2 reserved)
(
{"name": "foo", "level": "DEBUG", "key": "value"},
{"name_": "foo", "level_": "DEBUG", "key": "value"},
),
],
)
def test_get_extra_dict(inp: Dict[str, Any], expect: Dict[str, Any]) -> None:
extra = get_extra_dict(**inp)
assert extra == expect


def test_get_extra_dict_reserved_keys() -> None:
"""Test that all reserved keys are renamed."""
d: Dict[str, Any] = {}
for key in RESERVED_EXTRA_KEYS:
d[key] = key
extra = get_extra_dict(**d)
assert extra == snapshot(
{
"name_": "name",
"level_": "level",
"pathname_": "pathname",
"lineno_": "lineno",
"msg_": "msg",
"args_": "args",
"exc_info_": "exc_info",
"func_": "func",
"sinfo_": "sinfo",
}
)


def test_debug_kv(
capsys: pytest.CaptureFixture[str], caplog: pytest.LogCaptureFixture
) -> None:
caplog.set_level(logging.DEBUG)
debug_kv("hello", "world")
captured = capsys.readouterr()
assert captured.err == snapshot(
"""\
hello : world
"""
)
assert caplog.record_tuples == snapshot(
[("zabbix_cli", 10, "hello : world")]
)


def test_debug(
capsys: pytest.CaptureFixture[str], caplog: pytest.LogCaptureFixture
) -> None:
caplog.set_level(logging.DEBUG)
debug("Hello, world!")
captured = capsys.readouterr()
assert captured.err == snapshot(
"""\
Hello, world!
"""
)
assert caplog.record_tuples == snapshot([("zabbix_cli", 10, "Hello, world!")])


def test_info(
capsys: pytest.CaptureFixture[str], caplog: pytest.LogCaptureFixture
) -> None:
caplog.set_level(logging.INFO)
info("Hello, world!")
captured = capsys.readouterr()
assert captured.err == snapshot(
"""\
! Hello, world!
"""
)
assert caplog.record_tuples == snapshot([("zabbix_cli", 20, "Hello, world!")])


def test_success(
capsys: pytest.CaptureFixture[str], caplog: pytest.LogCaptureFixture
) -> None:
caplog.set_level(logging.INFO)
success("Hello, world!")
captured = capsys.readouterr()
assert captured.err == snapshot(
"""\
✓ Hello, world!
"""
)
assert caplog.record_tuples == snapshot([("zabbix_cli", 20, "Hello, world!")])


def test_warning(
capsys: pytest.CaptureFixture[str], caplog: pytest.LogCaptureFixture
) -> None:
caplog.set_level(logging.INFO)
warning("Hello, world!")
captured = capsys.readouterr()
assert captured.err == snapshot(
"""\
⚠ Hello, world!
"""
)
assert caplog.record_tuples == snapshot([("zabbix_cli", 30, "Hello, world!")])


def test_error(
capsys: pytest.CaptureFixture[str], caplog: pytest.LogCaptureFixture
) -> None:
caplog.set_level(logging.INFO)
error("Hello, world!")
captured = capsys.readouterr()
assert captured.err == snapshot(
"""\
✗ ERROR: Hello, world!
"""
)
assert caplog.record_tuples == snapshot([("zabbix_cli", 40, "Hello, world!")])
9 changes: 5 additions & 4 deletions zabbix_cli/output/console.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,17 +52,18 @@ def get_extra_dict(**kwargs: Any) -> Dict[str, Any]:
See: https://docs.python.org/3.11/library/logging.html#logging.LogRecord
"""
for k, v in list(kwargs.items()): # must be list to change while iterating
for k in list(kwargs): # iterate over copy while mutating
if k in RESERVED_EXTRA_KEYS:
kwargs[f"{k}_"] = v # add trailing underscore to avoid collision
del kwargs[k]
kwargs[f"{k}_"] = kwargs.pop(k)
return kwargs


def debug_kv(key: str, value: Any) -> None:
"""Print and log a key value pair."""
msg = f"[bold]{key:<20}:[/bold] {value}"
logger.debug(msg, extra=get_extra_dict(key=key, value=value))
from rich.markup import render

logger.debug(render(msg).plain, extra=get_extra_dict(key=key, value=value))
err_console.print(msg)


Expand Down

0 comments on commit da1dc10

Please sign in to comment.