|
1 | 1 | """Unit/functional testing for argparse customizations in cmd2""" |
2 | 2 |
|
3 | 3 | import argparse |
| 4 | +import sys |
4 | 5 |
|
5 | 6 | import pytest |
6 | 7 |
|
|
12 | 13 | ) |
13 | 14 | from cmd2.argparse_custom import ( |
14 | 15 | ChoicesCallable, |
| 16 | + Cmd2HelpFormatter, |
| 17 | + Cmd2RichArgparseConsole, |
15 | 18 | generate_range_error, |
16 | 19 | ) |
17 | 20 |
|
@@ -353,3 +356,47 @@ def test_completion_items_as_choices(capsys) -> None: |
353 | 356 | # Confirm error text contains correct value type of int |
354 | 357 | _out, err = capsys.readouterr() |
355 | 358 | assert 'invalid choice: 3 (choose from 1, 2)' in err |
| 359 | + |
| 360 | + |
| 361 | +def test_formatter_console() -> None: |
| 362 | + # self._console = console (inside console.setter) |
| 363 | + formatter = Cmd2HelpFormatter(prog='test') |
| 364 | + new_console = Cmd2RichArgparseConsole() |
| 365 | + formatter.console = new_console |
| 366 | + assert formatter._console is new_console |
| 367 | + |
| 368 | + |
| 369 | +@pytest.mark.skipif( |
| 370 | + sys.version_info < (3, 14), |
| 371 | + reason="Argparse didn't support color until Python 3.14", |
| 372 | +) |
| 373 | +def test_formatter_set_color(mocker) -> None: |
| 374 | + formatter = Cmd2HelpFormatter(prog='test') |
| 375 | + |
| 376 | + # return (inside _set_color if sys.version_info < (3, 14)) |
| 377 | + mocker.patch('cmd2.argparse_custom.sys.version_info', (3, 13, 0)) |
| 378 | + # This should return early without calling super()._set_color |
| 379 | + mock_set_color = mocker.patch('rich_argparse.RichHelpFormatter._set_color') |
| 380 | + formatter._set_color(True) |
| 381 | + mock_set_color.assert_not_called() |
| 382 | + |
| 383 | + # except TypeError and super()._set_color(color) |
| 384 | + mocker.patch('cmd2.argparse_custom.sys.version_info', (3, 15, 0)) |
| 385 | + |
| 386 | + # Reset mock and make it raise TypeError when called with kwargs |
| 387 | + mock_set_color.reset_mock() |
| 388 | + |
| 389 | + def side_effect(color, **kwargs): |
| 390 | + if kwargs: |
| 391 | + raise TypeError("unexpected keyword argument 'file'") |
| 392 | + return |
| 393 | + |
| 394 | + mock_set_color.side_effect = side_effect |
| 395 | + |
| 396 | + # This call should trigger the TypeError and then the fallback call |
| 397 | + formatter._set_color(True, file=sys.stdout) |
| 398 | + |
| 399 | + # It should have been called twice: once with kwargs (failed) and once without (fallback) |
| 400 | + assert mock_set_color.call_count == 2 |
| 401 | + mock_set_color.assert_any_call(True, file=sys.stdout) |
| 402 | + mock_set_color.assert_any_call(True) |
0 commit comments