Debian Codegraph @

tests/test_rich_utils.py

raw symbols SCIP
1 """Unit testing for cmd2/rich_utils.py module"""
2
3 import sys
4 from typing import Any
5 from unittest import mock
6
7 import pytest
8 import rich.box
9 from pytest_mock import MockerFixture
10 from rich.console import Console
11 from rich.table import Table
12 from rich.text import Text
13
14 from cmd2 import (
15 Cmd2ArgumentParser,
16 Color,
17 )
18 from cmd2 import rich_utils as ru
19
20 from .conftest import with_ansi_style
21
22
23 def test_cmd2_base_console() -> None:
24 # Test the keyword arguments which are not allowed.
25 with pytest.raises(TypeError) as excinfo:
26 ru.Cmd2BaseConsole(color_system="auto")
27 assert "color_system" in str(excinfo.value)
28
29 with pytest.raises(TypeError) as excinfo:
30 ru.Cmd2BaseConsole(force_terminal=True)
31 assert "force_terminal" in str(excinfo.value)
32
33 with pytest.raises(TypeError) as excinfo:
34 ru.Cmd2BaseConsole(force_interactive=True)
35 assert "force_interactive" in str(excinfo.value)
36
37 with pytest.raises(TypeError) as excinfo:
38 ru.Cmd2BaseConsole(theme=None)
39 assert "theme" in str(excinfo.value)
40
41
42 def test_indented_text() -> None:
43 console = Console(width=20)
44
45 # With an indention of 10, text will be evenly split across two lines.
46 text = "A" * 20
47 level = 10
48 indented_text = ru.indent(text, level)
49
50 with console.capture() as capture:
51 console.print(indented_text)
52 result = capture.get().splitlines()
53
54 padding = " " * level
55 expected_line = padding + ("A" * 10)
56 assert result[0] == expected_line
57 assert result[1] == expected_line
58
59
60 def test_indented_table() -> None:
61 console = Console()
62
63 level = 2
64 table = Table("Column", box=rich.box.ASCII)
65 table.add_row("Some Data")
66 indented_table = ru.indent(table, level)
67
68 with console.capture() as capture:
69 console.print(indented_table)
70 result = capture.get().splitlines()
71
72 padding = " " * level
73 assert result[0].startswith(padding + "+-----------+")
74 assert result[1].startswith(padding + "| Column |")
75 assert result[2].startswith(padding + "|-----------|")
76 assert result[3].startswith(padding + "| Some Data |")
77 assert result[4].startswith(padding + "+-----------+")
78
79
80 @pytest.mark.parametrize(
81 ("rich_text", "string"),
82 [
83 (Text("Hello"), "Hello"),
84 (Text("Hello\n"), "Hello\n"),
85 # Test standard color support
86 (Text("Standard", style="blue"), "\x1b[34mStandard\x1b[0m"),
87 # Test 256-color support
88 (Text("256-color", style=Color.NAVY_BLUE), "\x1b[38;5;17m256-color\x1b[0m"),
89 # Test 24-bit color (TrueColor) support
90 (Text("TrueColor", style="#123456"), "\x1b[38;2;18;52;86mTrueColor\x1b[0m"),
91 ],
92 )
93 def test_rich_text_to_string(rich_text: Text, string: str) -> None:
94 assert ru.rich_text_to_string(rich_text) == string
95
96
97 def test_rich_text_to_string_type_error() -> None:
98 with pytest.raises(TypeError) as excinfo:
99 ru.rich_text_to_string("not a Text object") # type: ignore[arg-type]
100 assert "rich_text_to_string() expected a rich.text.Text object, but got str" in str(excinfo.value)
101
102
103 def test_cmd2_base_console_print(mocker: MockerFixture) -> None:
104 """Test that Cmd2BaseConsole.print() calls prepare_objects_for_rendering()."""
105 # Mock prepare_objects_for_rendering to return a specific value
106 prepared_val = ("prepared",)
107 mock_prepare = mocker.patch("cmd2.rich_utils.prepare_objects_for_rendering", return_value=prepared_val)
108
109 # Mock the superclass print() method
110 mock_super_print = mocker.patch("rich.console.Console.print")
111
112 console = ru.Cmd2BaseConsole()
113 console.print("hello")
114
115 # Verify that prepare_objects_for_rendering() was called with the input objects
116 mock_prepare.assert_called_once_with("hello")
117
118 # Verify that the superclass print() method was called with the prepared objects
119 args, _ = mock_super_print.call_args
120 assert args == prepared_val
121
122
123 def test_cmd2_base_console_log(mocker: MockerFixture) -> None:
124 """Test that Cmd2BaseConsole.log() calls prepare_objects_for_rendering() and increments _stack_offset."""
125 # Mock prepare_objects_for_rendering to return a specific value
126 prepared_val = ("prepared",)
127 mock_prepare = mocker.patch("cmd2.rich_utils.prepare_objects_for_rendering", return_value=prepared_val)
128
129 # Mock the superclass log() method
130 mock_super_log = mocker.patch("rich.console.Console.log")
131
132 console = ru.Cmd2BaseConsole()
133 console.log("test", _stack_offset=2)
134
135 # Verify that prepare_objects_for_rendering() was called with the input objects
136 mock_prepare.assert_called_once_with("test")
137
138 # Verify that the superclass log() method was called with the prepared objects
139 # and that the stack offset was correctly incremented.
140 args, kwargs = mock_super_log.call_args
141 assert args == prepared_val
142 assert kwargs["_stack_offset"] == 3
143
144
145 @with_ansi_style(ru.AllowStyle.ALWAYS)
146 def test_cmd2_base_console_init_always_interactive_true() -> None:
147 """Test Cmd2BaseConsole initialization when ALLOW_STYLE is ALWAYS and is_interactive is True."""
148 with (
149 mock.patch("rich.console.Console.__init__", return_value=None) as mock_base_init,
150 mock.patch("cmd2.rich_utils.Console", autospec=True) as mock_detect_console_class,
151 ):
152 mock_detect_console = mock_detect_console_class.return_value
153 mock_detect_console.is_interactive = True
154
155 ru.Cmd2BaseConsole()
156
157 # Verify arguments passed to super().__init__
158 _, kwargs = mock_base_init.call_args
159 assert kwargs["color_system"] == "truecolor"
160 assert kwargs["force_terminal"] is True
161 assert kwargs["force_interactive"] is True
162
163
164 @with_ansi_style(ru.AllowStyle.ALWAYS)
165 def test_cmd2_base_console_init_always_interactive_false() -> None:
166 """Test Cmd2BaseConsole initialization when ALLOW_STYLE is ALWAYS and is_interactive is False."""
167 with (
168 mock.patch("rich.console.Console.__init__", return_value=None) as mock_base_init,
169 mock.patch("cmd2.rich_utils.Console", autospec=True) as mock_detect_console_class,
170 ):
171 mock_detect_console = mock_detect_console_class.return_value
172 mock_detect_console.is_interactive = False
173
174 ru.Cmd2BaseConsole()
175
176 _, kwargs = mock_base_init.call_args
177 assert kwargs["color_system"] == "truecolor"
178 assert kwargs["force_terminal"] is True
179 assert kwargs["force_interactive"] is False
180
181
182 @with_ansi_style(ru.AllowStyle.TERMINAL)
183 def test_cmd2_base_console_init_terminal_true() -> None:
184 """Test Cmd2BaseConsole initialization when ALLOW_STYLE is TERMINAL and it is a terminal."""
185 with (
186 mock.patch("rich.console.Console.__init__", return_value=None) as mock_base_init,
187 mock.patch("cmd2.rich_utils.Console", autospec=True) as mock_detect_console_class,
188 ):
189 mock_detect_console = mock_detect_console_class.return_value
190 mock_detect_console.is_terminal = True
191
192 ru.Cmd2BaseConsole()
193
194 _, kwargs = mock_base_init.call_args
195 assert kwargs["color_system"] == "truecolor"
196 assert kwargs["force_terminal"] is None
197 assert kwargs["force_interactive"] is None
198
199
200 @with_ansi_style(ru.AllowStyle.TERMINAL)
201 def test_cmd2_base_console_init_terminal_false() -> None:
202 """Test Cmd2BaseConsole initialization when ALLOW_STYLE is TERMINAL and it is not a terminal."""
203 with (
204 mock.patch("rich.console.Console.__init__", return_value=None) as mock_base_init,
205 mock.patch("cmd2.rich_utils.Console", autospec=True) as mock_detect_console_class,
206 ):
207 mock_detect_console = mock_detect_console_class.return_value
208 mock_detect_console.is_terminal = False
209
210 ru.Cmd2BaseConsole()
211
212 _, kwargs = mock_base_init.call_args
213 assert kwargs["color_system"] is None
214 assert kwargs["force_terminal"] is None
215 assert kwargs["force_interactive"] is None
216
217
218 @with_ansi_style(ru.AllowStyle.NEVER)
219 def test_cmd2_base_console_init_never() -> None:
220 """Test Cmd2BaseConsole initialization when ALLOW_STYLE is NEVER."""
221 with mock.patch("rich.console.Console.__init__", return_value=None) as mock_base_init:
222 ru.Cmd2BaseConsole()
223
224 _, kwargs = mock_base_init.call_args
225 assert kwargs["color_system"] is None
226 assert kwargs["force_terminal"] is False
227 assert kwargs["force_interactive"] is None
228
229
230 def test_text_group_in_parser(capsys: pytest.CaptureFixture[str]) -> None:
231 """Print a TextGroup with argparse."""
232 parser = Cmd2ArgumentParser(prog="test")
233 parser.epilog = ru.TextGroup("Notes", "Some text")
234
235 # Render help
236 parser.print_help()
237 out, _ = capsys.readouterr()
238
239 assert "Notes:" in out
240 assert " Some text" in out
241
242
243 def test_formatter_init_mutually_exclusive() -> None:
244 """Test that providing both file and console to Cmd2HelpFormatter raises TypeError."""
245 with pytest.raises(TypeError, match="cannot provide both 'file' and 'console' arguments"):
246 ru.Cmd2HelpFormatter(prog="test", file=sys.stdout, console=ru.Cmd2RichArgparseConsole())
247
248
249 def test_formatter_lazy_console_with_file() -> None:
250 """Test that Cmd2HelpFormatter lazily creates a console bound to the provided file."""
251 import io
252
253 buf = io.StringIO()
254 formatter = ru.Cmd2HelpFormatter(prog="test", file=buf)
255
256 # Console should not be created yet
257 assert formatter._console is None
258
259 # Accessing console should create it bound to buf
260 console = formatter.console
261 assert isinstance(console, ru.Cmd2RichArgparseConsole)
262 assert console.file is buf
263
264
265 def test_formatter_console_setter() -> None:
266 formatter = ru.Cmd2HelpFormatter(prog="test")
267 new_console = ru.Cmd2RichArgparseConsole()
268 formatter.console = new_console
269 assert formatter._console is new_console
270
271
272 def test_formatter_console_setter_clears_file() -> None:
273 """Test that setting console explicitly clears the internal file stream."""
274 import io
275
276 buf = io.StringIO()
277 formatter = ru.Cmd2HelpFormatter(prog="test", file=buf)
278
279 new_console = ru.Cmd2RichArgparseConsole()
280 formatter.console = new_console
281
282 assert formatter._console is new_console
283 assert formatter._file is None
284
285
286 @pytest.mark.skipif(
287 sys.version_info < (3, 14),
288 reason="Argparse didn't support color until Python 3.14",
289 )
290 def test_formatter_set_color(mocker: MockerFixture) -> None:
291 formatter = ru.Cmd2HelpFormatter(prog="test")
292
293 # return (inside _set_color if sys.version_info < (3, 14))
294 mocker.patch("cmd2.argparse_utils.sys.version_info", (3, 13, 0))
295 # This should return early without calling super()._set_color
296 mock_set_color = mocker.patch("rich_argparse.RichHelpFormatter._set_color")
297 formatter._set_color(True)
298 mock_set_color.assert_not_called()
299
300 # except TypeError and super()._set_color(color)
301 mocker.patch("cmd2.argparse_utils.sys.version_info", (3, 15, 0))
302
303 # Reset mock and make it raise TypeError when called with kwargs
304 mock_set_color.reset_mock()
305
306 def side_effect(color: bool, **kwargs: Any) -> None:
307 if kwargs:
308 raise TypeError("unexpected keyword argument 'file'")
309 return
310
311 mock_set_color.side_effect = side_effect
312
313 # This call should trigger the TypeError and then the fallback call
314 formatter._set_color(True, file=sys.stdout)
315
316 # It should have been called twice: once with kwargs (failed) and once without (fallback)
317 assert mock_set_color.call_count == 2
318 mock_set_color.assert_any_call(True, file=sys.stdout)
319 mock_set_color.assert_any_call(True)
320
321
322 @pytest.mark.parametrize("line_break", ["\n", "\r\n"])
323 def test_ansi_decoder_patch(line_break: str) -> None:
324 # Check if we are still patching AnsiDecoder.decode(). If this check fails, then Rich
325 # has fixed the bug. Therefore, we can remove this test function and ru._AnsiDecoder_decode.
326 from rich.ansi import AnsiDecoder
327
328 assert AnsiDecoder.decode is ru._AnsiDecoder_decode
329
330 assert Text.from_ansi("").plain == ""
331 assert Text.from_ansi(f"{line_break}").plain == "\n"
332 assert Text.from_ansi(f"{line_break}{line_break}").plain == "\n\n"
333 assert Text.from_ansi("Hello").plain == "Hello"
334 assert Text.from_ansi(f"{line_break}Hello").plain == "\nHello"
335 assert Text.from_ansi(f"Hello{line_break}").plain == "Hello\n"
336 assert Text.from_ansi(f"Hello{line_break}{line_break}").plain == "Hello\n\n"
337 assert Text.from_ansi(f"Hello{line_break}World").plain == "Hello\nWorld"
338 assert Text.from_ansi(f"Hello{line_break}{line_break}World").plain == "Hello\n\nWorld"
339 assert Text.from_ansi(f"Hello{line_break}World{line_break}").plain == "Hello\nWorld\n"
340 assert Text.from_ansi(f"Hello{line_break}World{line_break}{line_break}").plain == "Hello\nWorld\n\n"
341 assert Text.from_ansi(f"{line_break}Hello{line_break}World{line_break}{line_break}").plain == "\nHello\nWorld\n\n"
342
343 # Include a mixture of line break types
344 assert Text.from_ansi(f"Hello{line_break}\n\r\nWorld").plain == "Hello\n\n\nWorld"