Debian Codegraph @

tests/test_pt_utils.py

raw symbols SCIP
1 """Unit tests for cmd2/pt_utils.py"""
2
3 import io
4 import re
5 from typing import Any, cast
6 from unittest.mock import Mock
7
8 import pytest
9 from prompt_toolkit.document import Document
10 from prompt_toolkit.formatted_text import (
11 ANSI,
12 to_formatted_text,
13 )
14 from prompt_toolkit.output.color_depth import ColorDepth
15 from rich.table import Table
16
17 import cmd2
18 from cmd2 import (
19 Cmd2Style,
20 pt_utils,
21 stylize,
22 utils,
23 )
24 from cmd2 import rich_utils as ru
25 from cmd2 import string_utils as su
26 from cmd2.pt_utils import (
27 Cmd2Lexer,
28 pt_filter_style,
29 pt_resolve_color_depth,
30 )
31
32 from .conftest import with_ansi_style
33
34
35 # Mock for cmd2.Cmd
36 class MockCmd:
37 def __init__(self) -> None:
38 # Return empty completions by default
39 self.complete = Mock(return_value=cmd2.Completions())
40
41 self.stdout = io.StringIO()
42 self.statement_parser = Mock()
43 self.statement_parser.terminators = [";"]
44 self.statement_parser.shortcuts = []
45 self.statement_parser._command_pattern = re.compile(r"\A\s*(\S*?)(\s|\Z)")
46 self.aliases = {}
47 self.macros = {}
48 self.all_commands = []
49
50 def get_all_commands(self) -> list[str]:
51 return self.all_commands
52
53
54 @pytest.fixture
55 def mock_cmd_app() -> MockCmd:
56 return MockCmd()
57
58
59 @with_ansi_style(ru.AllowStyle.ALWAYS)
60 def test_pt_filter_style_always() -> None:
61 """This should preserve all styles and return ANSI."""
62 unstyled = "unstyled"
63 result = pt_filter_style(unstyled)
64 assert isinstance(result, ANSI)
65 assert result.value == unstyled
66
67 styled = stylize("styled", Cmd2Style.COMMAND_LINE)
68 result = pt_filter_style(styled)
69 assert isinstance(result, ANSI)
70 assert result.value == styled
71
72
73 @with_ansi_style(ru.AllowStyle.TERMINAL)
74 def test_pt_filter_style_terminal() -> None:
75 """This should preserve all styles and return ANSI."""
76 unstyled = "unstyled"
77 result = pt_filter_style(unstyled)
78 assert isinstance(result, ANSI)
79 assert result.value == unstyled
80
81 styled = stylize("styled", Cmd2Style.COMMAND_LINE)
82 result = pt_filter_style(styled)
83 assert isinstance(result, ANSI)
84 assert result.value == styled
85
86
87 @with_ansi_style(ru.AllowStyle.NEVER)
88 def test_pt_filter_style_never() -> None:
89 """This should strip all styles and return str."""
90 unstyled = "unstyled"
91 result = pt_filter_style(unstyled)
92 assert isinstance(result, str)
93 assert result == unstyled
94
95 styled = stylize("styled", Cmd2Style.COMMAND_LINE)
96 result = pt_filter_style(styled)
97 assert isinstance(result, str)
98 assert result == su.strip_style(styled)
99
100
101 @with_ansi_style(ru.AllowStyle.ALWAYS)
102 def test_pt_resolve_color_depth_always(monkeypatch) -> None:
103 # Clear NO_COLOR to ensure colors are not suppressed
104 monkeypatch.delenv("NO_COLOR", raising=False)
105 assert pt_resolve_color_depth() == ColorDepth.TRUE_COLOR
106
107
108 @with_ansi_style(ru.AllowStyle.TERMINAL)
109 def test_pt_resolve_color_depth_terminal(monkeypatch) -> None:
110 # Mock NO_COLOR to an empty string to ensure colors are not suppressed
111 monkeypatch.setenv("NO_COLOR", "")
112 assert pt_resolve_color_depth() == ColorDepth.TRUE_COLOR
113
114
115 @with_ansi_style(ru.AllowStyle.NEVER)
116 def test_pt_resolve_color_depth_never(monkeypatch) -> None:
117 # Under NEVER, colors are suppressed regardless of NO_COLOR
118 monkeypatch.delenv("NO_COLOR", raising=False)
119 assert pt_resolve_color_depth() == ColorDepth.MONOCHROME
120
121
122 @with_ansi_style(ru.AllowStyle.ALWAYS)
123 def test_pt_resolve_color_depth_no_color(monkeypatch) -> None:
124 # Mock NO_COLOR to ensure colors are suppressed
125 monkeypatch.setenv("NO_COLOR", "1")
126 assert pt_resolve_color_depth() == ColorDepth.MONOCHROME
127
128
129 class TestCmd2Lexer:
130 @with_ansi_style(ru.AllowStyle.NEVER)
131 def test_lex_document_no_style(self, mock_cmd_app):
132 """Test lexing when styles are disallowed."""
133 lexer = pt_utils.Cmd2Lexer(cast(Any, mock_cmd_app))
134
135 line = "help something"
136 document = Document(line)
137 get_line = lexer.lex_document(document)
138 tokens = get_line(0)
139
140 assert tokens == [("", line)]
141
142 def test_lex_document_command(self, mock_cmd_app):
143 """Test lexing a command name."""
144 mock_cmd_app.all_commands = ["help"]
145 lexer = pt_utils.Cmd2Lexer(cast(Any, mock_cmd_app))
146
147 line = "help something"
148 document = Document(line)
149 get_line = lexer.lex_document(document)
150 tokens = get_line(0)
151
152 assert tokens == [
153 (Cmd2Lexer.COMMAND_STYLE, "help"),
154 ("", " "),
155 (Cmd2Lexer.ARGUMENT_STYLE, "something"),
156 ]
157
158 def test_lex_document_alias(self, mock_cmd_app):
159 """Test lexing an alias."""
160 mock_cmd_app.aliases = {"ls": "dir"}
161 lexer = pt_utils.Cmd2Lexer(cast(Any, mock_cmd_app))
162
163 line = "ls -l"
164 document = Document(line)
165 get_line = lexer.lex_document(document)
166 tokens = get_line(0)
167
168 assert tokens == [
169 (Cmd2Lexer.ALIAS_STYLE, "ls"),
170 ("", " "),
171 (Cmd2Lexer.FLAG_STYLE, "-l"),
172 ]
173
174 def test_lex_document_macro(self, mock_cmd_app):
175 """Test lexing a macro."""
176 mock_cmd_app.macros = {"my_macro": "some value"}
177 lexer = pt_utils.Cmd2Lexer(cast(Any, mock_cmd_app))
178
179 line = "my_macro arg1"
180 document = Document(line)
181 get_line = lexer.lex_document(document)
182 tokens = get_line(0)
183
184 assert tokens == [
185 (Cmd2Lexer.MACRO_STYLE, "my_macro"),
186 ("", " "),
187 (Cmd2Lexer.ARGUMENT_STYLE, "arg1"),
188 ]
189
190 def test_lex_document_leading_whitespace(self, mock_cmd_app):
191 """Test lexing with leading whitespace."""
192 mock_cmd_app.all_commands = ["help"]
193 lexer = pt_utils.Cmd2Lexer(cast(Any, mock_cmd_app))
194
195 line = " help something"
196 document = Document(line)
197 get_line = lexer.lex_document(document)
198 tokens = get_line(0)
199
200 assert tokens == [
201 ("", " "),
202 (Cmd2Lexer.COMMAND_STYLE, "help"),
203 ("", " "),
204 (Cmd2Lexer.ARGUMENT_STYLE, "something"),
205 ]
206
207 def test_lex_document_unknown_command(self, mock_cmd_app):
208 """Test lexing an unknown command."""
209 lexer = pt_utils.Cmd2Lexer(cast(Any, mock_cmd_app))
210
211 line = "unknown command"
212 document = Document(line)
213 get_line = lexer.lex_document(document)
214 tokens = get_line(0)
215
216 assert tokens == [
217 ("", "unknown"),
218 ("", " "),
219 (Cmd2Lexer.ARGUMENT_STYLE, "command"),
220 ]
221
222 def test_lex_document_no_command(self, mock_cmd_app):
223 """Test lexing an empty line or line with only whitespace."""
224 lexer = pt_utils.Cmd2Lexer(cast(Any, mock_cmd_app))
225
226 line = " "
227 document = Document(line)
228 get_line = lexer.lex_document(document)
229 tokens = get_line(0)
230
231 assert tokens == [("", " ")]
232
233 def test_lex_document_no_match(self, mock_cmd_app):
234 """Test lexing when command pattern fails to match."""
235 # Force the pattern to not match anything
236 mock_cmd_app.statement_parser._command_pattern = re.compile(r"something_impossible")
237 lexer = pt_utils.Cmd2Lexer(cast(Any, mock_cmd_app))
238
239 line = "test command"
240 document = Document(line)
241 get_line = lexer.lex_document(document)
242 tokens = get_line(0)
243
244 assert tokens == [("", line)]
245
246 def test_lex_document_arguments(self, mock_cmd_app):
247 """Test lexing a command with flags and values."""
248 mock_cmd_app.all_commands = ["help"]
249 lexer = pt_utils.Cmd2Lexer(cast(Any, mock_cmd_app))
250
251 line = 'help -v --name "John Doe" > out.txt'
252 document = Document(line)
253 get_line = lexer.lex_document(document)
254 tokens = get_line(0)
255
256 assert tokens == [
257 (Cmd2Lexer.COMMAND_STYLE, "help"),
258 ("", " "),
259 (Cmd2Lexer.FLAG_STYLE, "-v"),
260 ("", " "),
261 (Cmd2Lexer.FLAG_STYLE, "--name"),
262 ("", " "),
263 (Cmd2Lexer.ARGUMENT_STYLE, '"John Doe"'),
264 ("", " "),
265 ("", ">"),
266 ("", " "),
267 (Cmd2Lexer.ARGUMENT_STYLE, "out.txt"),
268 ]
269
270 def test_lex_document_unclosed_quote(self, mock_cmd_app):
271 """Test lexing with an unclosed quote."""
272 mock_cmd_app.all_commands = ["echo"]
273 lexer = pt_utils.Cmd2Lexer(cast(Any, mock_cmd_app))
274
275 line = 'echo "hello'
276 document = Document(line)
277 get_line = lexer.lex_document(document)
278 tokens = get_line(0)
279
280 assert tokens == [
281 (Cmd2Lexer.COMMAND_STYLE, "echo"),
282 ("", " "),
283 (Cmd2Lexer.ARGUMENT_STYLE, '"hello'),
284 ]
285
286 def test_lex_document_shortcut(self, mock_cmd_app):
287 """Test lexing a shortcut."""
288 mock_cmd_app.statement_parser.shortcuts = [("!", "shell")]
289 lexer = pt_utils.Cmd2Lexer(cast(Any, mock_cmd_app))
290
291 # Case 1: Shortcut glued to argument
292 line = "!ls"
293 document = Document(line)
294 get_line = lexer.lex_document(document)
295 tokens = get_line(0)
296 assert tokens == [
297 (Cmd2Lexer.COMMAND_STYLE, "!"),
298 (Cmd2Lexer.ARGUMENT_STYLE, "ls"),
299 ]
300
301 line = "! ls"
302 document = Document(line)
303 get_line = lexer.lex_document(document)
304 tokens = get_line(0)
305 assert tokens == [
306 (Cmd2Lexer.COMMAND_STYLE, "!"),
307 ("", " "),
308 (Cmd2Lexer.ARGUMENT_STYLE, "ls"),
309 ]
310
311 def test_lex_document_multiline(self, mock_cmd_app):
312 """Test lexing a multiline command."""
313 mock_cmd_app.all_commands = ["orate"]
314 lexer = pt_utils.Cmd2Lexer(cast(Any, mock_cmd_app))
315
316 # Command on first line, argument on second line that looks like a command
317 line = "orate\nhelp"
318 document = Document(line)
319 get_line = lexer.lex_document(document)
320
321 # First line should have command
322 tokens0 = get_line(0)
323 assert tokens0 == [(Cmd2Lexer.COMMAND_STYLE, "orate")]
324
325 # Second line should have argument (not command)
326 tokens1 = get_line(1)
327 assert tokens1 == [(Cmd2Lexer.ARGUMENT_STYLE, "help")]
328
329
330 class TestCmd2Completer:
331 def test_get_completions(self, mock_cmd_app: MockCmd, monkeypatch) -> None:
332 """Test get_completions with matches."""
333 mock_print = Mock()
334 monkeypatch.setattr(pt_utils, "print_formatted_text", mock_print)
335
336 completer = pt_utils.Cmd2Completer(cast(Any, mock_cmd_app))
337
338 # Set up document
339 line = ""
340 document = Document(line, cursor_position=0)
341
342 # Test plain and styled values for display and display_meta
343 foo_text = "foo"
344 foo_display = "Foo Display"
345 foo_meta = "Foo Meta"
346
347 bar_text = "bar"
348 bar_display = stylize("Bar Display", Cmd2Style.SUCCESS)
349 bar_meta = stylize("Bar Meta", Cmd2Style.WARNING)
350
351 # Set up matches
352 completion_items = [
353 cmd2.CompletionItem(foo_text, display=foo_display, display_meta=foo_meta),
354 cmd2.CompletionItem(bar_text, display=bar_display, display_meta=bar_meta),
355 ]
356
357 table = Table("Table Header")
358 table.add_row("Table Data")
359 cmd2_completions = cmd2.Completions(completion_items, table=table)
360 mock_cmd_app.complete.return_value = cmd2_completions
361
362 # Call get_completions
363 completions = list(completer.get_completions(document, None))
364
365 assert len(completions) == len(cmd2_completions)
366
367 assert completions[0].text == bar_text
368 assert to_formatted_text(completions[0].display) == to_formatted_text(ANSI(bar_display))
369 assert to_formatted_text(completions[0].display_meta) == to_formatted_text(ANSI(bar_meta))
370
371 assert completions[1].text == foo_text
372 assert to_formatted_text(completions[1].display) == to_formatted_text(ANSI(foo_display))
373 assert to_formatted_text(completions[1].display_meta) == to_formatted_text(ANSI(foo_meta))
374
375 # Verify that only the completion table printed
376 assert mock_print.call_count == 1
377 args, _ = mock_print.call_args
378 assert "Table Header" in str(args[0])
379 assert "Table Data" in str(args[0])
380
381 def test_get_completions_no_matches(self, mock_cmd_app: MockCmd, monkeypatch) -> None:
382 """Test get_completions with no matches."""
383 mock_print = Mock()
384 monkeypatch.setattr(pt_utils, "print_formatted_text", mock_print)
385
386 completer = pt_utils.Cmd2Completer(cast(Any, mock_cmd_app))
387
388 document = Document("", cursor_position=0)
389
390 # Set up matches
391 cmd2_completions = cmd2.Completions(hint="Completion Hint")
392 mock_cmd_app.complete.return_value = cmd2_completions
393
394 completions = list(completer.get_completions(document, None))
395 assert not completions
396
397 # Verify that only the completion hint printed
398 assert mock_print.call_count == 1
399 args, _ = mock_print.call_args
400 assert cmd2_completions.hint in str(args[0])
401
402 def test_get_completions_with_error(self, mock_cmd_app: MockCmd, monkeypatch) -> None:
403 """Test get_completions with a completion error."""
404 mock_print = Mock()
405 monkeypatch.setattr(pt_utils, "print_formatted_text", mock_print)
406
407 completer = pt_utils.Cmd2Completer(cast(Any, mock_cmd_app))
408
409 document = Document("", cursor_position=0)
410
411 # Set up matches
412 cmd2_completions = cmd2.Completions(error="Completion Error")
413 mock_cmd_app.complete.return_value = cmd2_completions
414
415 completions = list(completer.get_completions(document, None))
416 assert not completions
417
418 # Verify that only the completion error printed
419 assert mock_print.call_count == 1
420 args, _ = mock_print.call_args
421 assert cmd2_completions.error in str(args[0])
422
423 @pytest.mark.parametrize(
424 # search_text_offset is the starting index of the user-provided search text within a full match.
425 # This accounts for leading shortcuts (e.g., in '@has', the offset is 1).
426 ("line", "match", "search_text_offset"),
427 [
428 ("has", "has space", 0),
429 ("@has", "@has space", 1),
430 ],
431 )
432 def test_get_completions_add_opening_quote_and_abort(self, line, match, search_text_offset, mock_cmd_app) -> None:
433 """Test case where adding an opening quote changes text before cursor.
434
435 This applies when there is search text.
436 """
437 completer = pt_utils.Cmd2Completer(cast(Any, mock_cmd_app))
438
439 # Set up document
440 document = Document(line, cursor_position=len(line))
441
442 # Set up matches
443 completion_items = [cmd2.CompletionItem(match)]
444 cmd2_completions = cmd2.Completions(
445 completion_items,
446 _add_opening_quote=True,
447 _search_text_offset=search_text_offset,
448 _quote_char='"',
449 )
450 mock_cmd_app.complete.return_value = cmd2_completions
451
452 # Call get_completions
453 completions = list(completer.get_completions(document, None))
454
455 # get_completions inserted an opening quote in the buffer and then aborted before returning completions
456 assert not completions
457
458 @pytest.mark.parametrize(
459 # search_text_offset is the starting index of the user-provided search text within a full match.
460 # This accounts for leading shortcuts (e.g., in '@has', the offset is 1).
461 ("line", "matches", "search_text_offset", "quote_char", "expected"),
462 [
463 # Single matches need opening quote, closing quote, and trailing space
464 ("", ["has space"], 0, '"', ['"has space" ']),
465 ("@", ["@has space"], 1, "'", ["@'has space' "]),
466 # Multiple matches only need opening quote
467 ("", ["has space", "more space"], 0, '"', ['"has space', '"more space']),
468 ("@", ["@has space", "@more space"], 1, "'", ["@'has space", "@'more space"]),
469 ],
470 )
471 def test_get_completions_add_opening_quote_and_return_results(
472 self, line, matches, search_text_offset, quote_char, expected, mock_cmd_app
473 ) -> None:
474 """Test case where adding an opening quote does not change text before cursor.
475
476 This applies when search text is empty.
477 """
478 completer = pt_utils.Cmd2Completer(cast(Any, mock_cmd_app))
479
480 # Set up document
481 document = Document(line, cursor_position=len(line))
482
483 # Set up matches
484 completion_items = [cmd2.CompletionItem(match) for match in matches]
485
486 cmd2_completions = cmd2.Completions(
487 completion_items,
488 _add_opening_quote=True,
489 _search_text_offset=search_text_offset,
490 _quote_char=quote_char,
491 )
492 mock_cmd_app.complete.return_value = cmd2_completions
493
494 # Call get_completions
495 completions = list(completer.get_completions(document, None))
496
497 # Compare results
498 completion_texts = [c.text for c in completions]
499 assert completion_texts == expected
500
501 @pytest.mark.parametrize(
502 ("line", "match", "quote_char", "end_of_line", "expected"),
503 [
504 # --- Unquoted search text ---
505 # Append a trailing space when end_of_line is True
506 ("ma", "match", "", True, "match "),
507 ("ma", "match", "", False, "match"),
508 # --- Quoted search text ---
509 # Ensure closing quotes are added
510 # Append a trailing space when end_of_line is True
511 ('"ma', '"match', '"', True, '"match" '),
512 ("'ma", "'match", "'", False, "'match'"),
513 ],
514 )
515 def test_get_completions_allow_finalization(
516 self, line, match, quote_char, end_of_line, expected, mock_cmd_app: MockCmd
517 ) -> None:
518 """Test that get_completions correctly handles finalizing single matches."""
519 completer = pt_utils.Cmd2Completer(cast(Any, mock_cmd_app))
520
521 # Set up document
522 cursor_position = len(line) if end_of_line else len(line) - 1
523 document = Document(line, cursor_position=cursor_position)
524
525 # Set up matches
526 completion_items = [cmd2.CompletionItem(match)]
527 cmd2_completions = cmd2.Completions(completion_items, _quote_char=quote_char)
528 mock_cmd_app.complete.return_value = cmd2_completions
529
530 # Call get_completions and compare results
531 completions = list(completer.get_completions(document, None))
532 assert completions[0].text == expected
533
534 @pytest.mark.parametrize(
535 ("line", "match", "quote_char", "end_of_line", "expected"),
536 [
537 # Do not add a trailing space or closing quote to any of the matches
538 ("ma", "match", "", True, "match"),
539 ("ma", "match", "", False, "match"),
540 ('"ma', '"match', '"', True, '"match'),
541 ("'ma", "'match", "'", False, "'match"),
542 ],
543 )
544 def test_get_completions_do_not_allow_finalization(
545 self, line, match, quote_char, end_of_line, expected, mock_cmd_app: MockCmd
546 ) -> None:
547 """Test that get_completions does not finalize single matches when allow_finalization if False."""
548 completer = pt_utils.Cmd2Completer(cast(Any, mock_cmd_app))
549
550 # Set up document
551 cursor_position = len(line) if end_of_line else len(line) - 1
552 document = Document(line, cursor_position=cursor_position)
553
554 # Set up matches
555 completion_items = [cmd2.CompletionItem(match)]
556 cmd2_completions = cmd2.Completions(
557 completion_items,
558 allow_finalization=False,
559 _quote_char=quote_char,
560 )
561 mock_cmd_app.complete.return_value = cmd2_completions
562
563 # Call get_completions and compare results
564 completions = list(completer.get_completions(document, None))
565 assert completions[0].text == expected
566
567 def test_init_with_custom_settings(self, mock_cmd_app: MockCmd) -> None:
568 """Test initializing with custom settings."""
569 mock_parser = Mock()
570 custom_settings = utils.CustomCompletionSettings(parser=mock_parser)
571 completer = pt_utils.Cmd2Completer(cast(Any, mock_cmd_app), custom_settings=custom_settings)
572
573 document = Document("", cursor_position=0)
574
575 mock_cmd_app.complete.return_value = cmd2.Completions()
576
577 list(completer.get_completions(document, None))
578
579 mock_cmd_app.complete.assert_called_once()
580 assert mock_cmd_app.complete.call_args[1]["custom_settings"] == custom_settings
581
582 def test_get_completions_custom_delimiters(self, mock_cmd_app: MockCmd) -> None:
583 """Test that custom delimiters (terminators) are respected."""
584 mock_cmd_app.statement_parser.terminators = ["#"]
585 completer = pt_utils.Cmd2Completer(cast(Any, mock_cmd_app))
586
587 # '#' should act as a word boundary
588 document = Document("cmd#arg", cursor_position=7)
589 list(completer.get_completions(document, None))
590
591 # text should be "arg", begidx=4, endidx=7
592 mock_cmd_app.complete.assert_called_with("arg", line="cmd#arg", begidx=4, endidx=7, custom_settings=None)
593
594
595 class TestCmd2History:
596 def test_load_history_strings(self):
597 """Test loading history strings yields all items newest to oldest."""
598
599 history_strings = ["cmd1", "cmd2", "cmd2", "cmd3", "cmd2"]
600 history = pt_utils.Cmd2History(history_strings)
601 assert history._loaded
602
603 # Consecutive duplicates are removed
604 expected = ["cmd2", "cmd3", "cmd2", "cmd1"]
605 assert list(history.load_history_strings()) == expected
606
607 def test_load_history_strings_empty(self):
608 """Test loading history strings with empty history."""
609 history = pt_utils.Cmd2History()
610 assert history._loaded
611 assert list(history.load_history_strings()) == []
612
613 history = pt_utils.Cmd2History([])
614 assert history._loaded
615 assert list(history.load_history_strings()) == []
616
617 history = pt_utils.Cmd2History(None)
618 assert history._loaded
619 assert list(history.load_history_strings()) == []
620
621 def test_get_strings(self):
622 history_strings = ["cmd1", "cmd2", "cmd2", "cmd3", "cmd2"]
623 history = pt_utils.Cmd2History(history_strings)
624 assert history._loaded
625
626 # Consecutive duplicates are removed
627 expected = ["cmd1", "cmd2", "cmd3", "cmd2"]
628 assert history.get_strings() == expected
629
630 def test_append_string(self):
631 """Test that append_string() adds data."""
632 history = pt_utils.Cmd2History()
633 assert history._loaded
634 assert not history._loaded_strings
635
636 history.append_string("new command")
637 assert len(history._loaded_strings) == 1
638 assert history._loaded_strings[0] == "new command"
639
640 # Show that consecutive duplicates are filtered
641 history.append_string("new command")
642 assert len(history._loaded_strings) == 1
643 assert history._loaded_strings[0] == "new command"
644
645 # Show that new items are placed at the front
646 history.append_string("even newer command")
647 assert len(history._loaded_strings) == 2
648 assert history._loaded_strings[0] == "even newer command"
649 assert history._loaded_strings[1] == "new command"
650
651 def test_store_string(self):
652 """Test that store_string() does nothing."""
653 history = pt_utils.Cmd2History()
654 assert history._loaded
655 assert not history._loaded_strings
656
657 history.store_string("new command")
658 assert not history._loaded_strings
659
660 def test_clear(self):
661 history_strings = ["cmd1", "cmd2"]
662 history = pt_utils.Cmd2History(history_strings)
663 assert history._loaded
664 assert history.get_strings() == history_strings
665
666 history.clear()
667 assert not history.get_strings()
668
669
670 class TestRichToPtColor:
671 def test_rich_to_pt_color_none(self):
672 assert pt_utils.rich_to_pt_color(None) == "default"
673
674 def test_rich_to_pt_color_default(self):
675 from rich.color import Color
676
677 c = Color.parse("default")
678 assert pt_utils.rich_to_pt_color(c) == "default"
679
680 def test_rich_to_pt_color_standard(self):
681 from rich.color import Color
682
683 c = Color.parse("red")
684 assert pt_utils.rich_to_pt_color(c) == "ansired"
685 c = Color.parse("bright_red")
686 assert pt_utils.rich_to_pt_color(c) == "ansibrightred"
687 # Test a standard color initialized by number
688 c = Color.from_ansi(2)
689 assert pt_utils.rich_to_pt_color(c) == "ansigreen"
690
691 def test_rich_to_pt_color_eight_bit(self):
692 from rich.color import Color
693
694 # 155 is an 8-bit color
695 c = Color.from_ansi(155)
696 # Should convert to truecolor hex equivalent #afff5f
697 assert pt_utils.rich_to_pt_color(c) == "#afff5f"
698
699 def test_rich_to_pt_color_truecolor(self):
700 from rich.color import Color
701
702 c = Color.parse("#123456")
703 assert pt_utils.rich_to_pt_color(c) == "#123456"
704
705
706 class TestRichToPtStyle:
707 def test_rich_to_pt_style_none(self):
708 assert pt_utils.rich_to_pt_style(None) == ""
709
710 def test_rich_to_pt_style_string(self):
711 pt_style = pt_utils.rich_to_pt_style("bold red on blue")
712 assert "fg:ansired" in pt_style
713 assert "bg:ansiblue" in pt_style
714 assert "bold" in pt_style
715 assert "nobold" not in pt_style
716
717 def test_rich_to_pt_style_color(self):
718 from rich.style import Style
719
720 style = Style(color="#123456")
721 pt_style = pt_utils.rich_to_pt_style(style)
722 assert "fg:#123456" in pt_style
723 assert "bg:default" in pt_style
724
725 def test_rich_to_pt_style_bgcolor(self):
726 from rich.style import Style
727
728 style = Style(bgcolor="#654321")
729 pt_style = pt_utils.rich_to_pt_style(style)
730 assert "fg:default" in pt_style
731 assert "bg:#654321" in pt_style
732
733 def test_rich_to_pt_style_default_color(self):
734 from rich.style import Style
735
736 style = Style(color="default", bgcolor="default")
737 pt_style = pt_utils.rich_to_pt_style(style)
738 assert "fg:default" in pt_style
739 assert "bg:default" in pt_style
740
741 def test_rich_to_pt_style_bold(self):
742 from rich.style import Style
743
744 style = Style(bold=True)
745 pt_style = pt_utils.rich_to_pt_style(style)
746 assert "bold" in pt_style
747 assert "nobold" not in pt_style
748
749 def test_rich_to_pt_style_nobold(self):
750 from rich.style import Style
751
752 style = Style(bold=False)
753 pt_style = pt_utils.rich_to_pt_style(style)
754 assert "nobold" in pt_style
755
756 def test_rich_to_pt_style_underline(self):
757 from rich.style import Style
758
759 style = Style(underline=True)
760 pt_style = pt_utils.rich_to_pt_style(style)
761 assert "underline" in pt_style
762
763 def test_rich_to_pt_style_nounderline(self):
764 from rich.style import Style
765
766 style = Style(underline=False)
767 pt_style = pt_utils.rich_to_pt_style(style)
768 assert "nounderline" in pt_style
769
770 def test_rich_to_pt_style_strike(self):
771 from rich.style import Style
772
773 style = Style(strike=True)
774 pt_style = pt_utils.rich_to_pt_style(style)
775 assert "strike" in pt_style
776
777 def test_rich_to_pt_style_nostrike(self):
778 from rich.style import Style
779
780 style = Style(strike=False)
781 pt_style = pt_utils.rich_to_pt_style(style)
782 assert "nostrike" in pt_style
783
784 def test_rich_to_pt_style_italic(self):
785 from rich.style import Style
786
787 style = Style(italic=True)
788 pt_style = pt_utils.rich_to_pt_style(style)
789 assert "italic" in pt_style
790
791 def test_rich_to_pt_style_noitalic(self):
792 from rich.style import Style
793
794 style = Style(italic=False)
795 pt_style = pt_utils.rich_to_pt_style(style)
796 assert "noitalic" in pt_style
797
798 def test_rich_to_pt_style_blink(self):
799 from rich.style import Style
800
801 style = Style(blink=True)
802 pt_style = pt_utils.rich_to_pt_style(style)
803 assert "blink" in pt_style
804
805 def test_rich_to_pt_style_noblink(self):
806 from rich.style import Style
807
808 style = Style(blink=False)
809 pt_style = pt_utils.rich_to_pt_style(style)
810 assert "noblink" in pt_style
811
812 def test_rich_to_pt_style_reverse(self):
813 from rich.style import Style
814
815 style = Style(reverse=True)
816 pt_style = pt_utils.rich_to_pt_style(style)
817 assert "reverse" in pt_style
818
819 def test_rich_to_pt_style_noreverse(self):
820 from rich.style import Style
821
822 style = Style(reverse=False)
823 pt_style = pt_utils.rich_to_pt_style(style)
824 assert "noreverse" in pt_style
825
826 def test_rich_to_pt_style_hidden_conceal(self):
827 from rich.style import Style
828
829 style = Style(conceal=True)
830 pt_style = pt_utils.rich_to_pt_style(style)
831 assert "hidden" in pt_style
832
833 def test_rich_to_pt_style_nohidden_conceal(self):
834 from rich.style import Style
835
836 style = Style(conceal=False)
837 pt_style = pt_utils.rich_to_pt_style(style)
838 assert "nohidden" in pt_style
839
840 def test_rich_to_pt_style_dim(self):
841 from rich.style import Style
842
843 style = Style(dim=True)
844 pt_style = pt_utils.rich_to_pt_style(style)
845 assert "dim" in pt_style
846
847 def test_rich_to_pt_style_nodim(self):
848 from rich.style import Style
849
850 style = Style(dim=False)
851 pt_style = pt_utils.rich_to_pt_style(style)
852 assert "nodim" in pt_style