Skip to content

Commit 461155b

Browse files
add util helper to pretty type errors
1 parent 4a57e99 commit 461155b

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

src/venvalid/utils_errors.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
def pretty_print_error(error: Exception) -> None:
2+
"""Pretty print errors using rich if available, else fallback to plain text"""
3+
try:
4+
from rich.console import Console
5+
6+
console = Console()
7+
console.print(f"[bold red]Error:[/bold red] {error}")
8+
except ImportError:
9+
print(f"Error: {error}")

tests/test_utils_errors.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import sys
2+
import types
3+
4+
import src.venvalid.utils_errors as utils_errors
5+
6+
7+
class DummyConsole:
8+
def __init__(self):
9+
self.last_message = None
10+
11+
def print(self, msg):
12+
self.last_message = msg
13+
14+
15+
def test_pretty_print_error_with_rich(monkeypatch):
16+
dummy_console = DummyConsole()
17+
18+
fake_rich_pkg = types.ModuleType("rich")
19+
fake_rich_pkg.__path__ = [] # mark as package
20+
21+
fake_console_mod = types.ModuleType("rich.console")
22+
setattr(fake_console_mod, "Console", lambda: dummy_console)
23+
24+
monkeypatch.setitem(sys.modules, "rich", fake_rich_pkg)
25+
monkeypatch.setitem(sys.modules, "rich.console", fake_console_mod)
26+
27+
utils_errors.pretty_print_error(ValueError("boom"))
28+
29+
assert dummy_console.last_message is not None
30+
assert "boom" in dummy_console.last_message
31+
32+
33+
def test_pretty_print_error_without_rich(monkeypatch, capsys):
34+
monkeypatch.delitem(sys.modules, "rich.console", raising=False)
35+
monkeypatch.delitem(sys.modules, "rich", raising=False)
36+
37+
utils_errors.pretty_print_error(ValueError("fail"))
38+
39+
out = capsys.readouterr().out
40+
assert "Error: fail" in out

0 commit comments

Comments
 (0)