| 1 |
"""Unit/functional testing for argparse customizations in cmd2""" |
| 2 |
|
| 3 |
import argparse |
| 4 |
import sys |
| 5 |
|
| 6 |
import pytest |
| 7 |
from pytest_mock import MockerFixture |
| 8 |
|
| 9 |
import cmd2 |
| 10 |
from cmd2 import ( |
| 11 |
Choices, |
| 12 |
Cmd2ArgumentParser, |
| 13 |
SubcommandRecord, |
| 14 |
argparse_utils, |
| 15 |
constants, |
| 16 |
) |
| 17 |
from cmd2 import rich_utils as ru |
| 18 |
from cmd2 import string_utils as su |
| 19 |
from cmd2.argparse_utils import ( |
| 20 |
build_range_error, |
| 21 |
register_argparse_argument_parameter, |
| 22 |
) |
| 23 |
|
| 24 |
from .conftest import ( |
| 25 |
run_cmd, |
| 26 |
with_ansi_style, |
| 27 |
) |
| 28 |
|
| 29 |
|
| 30 |
class ApCustomTestApp(cmd2.Cmd): |
| 31 |
"""Test app for cmd2's argparse customization""" |
| 32 |
|
| 33 |
def __init__(self, *args, **kwargs) -> None: |
| 34 |
super().__init__(*args, **kwargs) |
| 35 |
|
| 36 |
range_parser = Cmd2ArgumentParser() |
| 37 |
range_parser.add_argument("--arg0", nargs=1) |
| 38 |
range_parser.add_argument("--arg1", nargs=2) |
| 39 |
range_parser.add_argument("--arg2", nargs=(3,)) |
| 40 |
range_parser.add_argument("--arg3", nargs=(2, 3)) |
| 41 |
|
| 42 |
@cmd2.with_argparser(range_parser) |
| 43 |
def do_range(self, _) -> None: |
| 44 |
pass |
| 45 |
|
| 46 |
|
| 47 |
@pytest.fixture |
| 48 |
def cust_app(): |
| 49 |
return ApCustomTestApp() |
| 50 |
|
| 51 |
|
| 52 |
def fake_func() -> None: |
| 53 |
pass |
| 54 |
|
| 55 |
|
| 56 |
@pytest.mark.parametrize( |
| 57 |
("kwargs", "is_valid"), |
| 58 |
[ |
| 59 |
({"choices_provider": fake_func}, True), |
| 60 |
({"completer": fake_func}, True), |
| 61 |
({"choices_provider": fake_func, "completer": fake_func}, False), |
| 62 |
], |
| 63 |
) |
| 64 |
def test_apcustom_completion_callable_count(kwargs, is_valid) -> None: |
| 65 |
parser = Cmd2ArgumentParser() |
| 66 |
if is_valid: |
| 67 |
parser.add_argument("name", **kwargs) |
| 68 |
else: |
| 69 |
expected_err = "Only one of the following parameters" |
| 70 |
with pytest.raises(ValueError, match=expected_err): |
| 71 |
parser.add_argument("name", **kwargs) |
| 72 |
|
| 73 |
|
| 74 |
@pytest.mark.parametrize("kwargs", [({"choices_provider": fake_func}), ({"completer": fake_func})]) |
| 75 |
def test_apcustom_no_completion_callable_alongside_choices(kwargs) -> None: |
| 76 |
parser = Cmd2ArgumentParser() |
| 77 |
|
| 78 |
expected_err = "None of the following parameters can be used alongside a choices parameter" |
| 79 |
with pytest.raises(ValueError, match=expected_err): |
| 80 |
parser.add_argument("name", choices=["my", "choices", "list"], **kwargs) |
| 81 |
|
| 82 |
|
| 83 |
@pytest.mark.parametrize("kwargs", [({"choices_provider": fake_func}), ({"completer": fake_func})]) |
| 84 |
def test_apcustom_no_completion_callable_when_nargs_is_0(kwargs) -> None: |
| 85 |
parser = Cmd2ArgumentParser() |
| 86 |
|
| 87 |
expected_err = "None of the following parameters can be used on an action that takes no arguments" |
| 88 |
with pytest.raises(ValueError, match=expected_err): |
| 89 |
parser.add_argument("--name", action="store_true", **kwargs) |
| 90 |
|
| 91 |
|
| 92 |
def test_apcustom_usage() -> None: |
| 93 |
usage = "A custom usage statement" |
| 94 |
parser = Cmd2ArgumentParser(usage=usage) |
| 95 |
assert usage in parser.format_help() |
| 96 |
|
| 97 |
|
| 98 |
def test_apcustom_nargs_help_format(cust_app) -> None: |
| 99 |
out, _err = run_cmd(cust_app, "help range") |
| 100 |
assert "Usage: range [-h] [--arg0 ARG0] [--arg1 ARG1{2}] [--arg2 ARG2{3+}]" in out[0] |
| 101 |
assert " [--arg3 ARG3{2..3}]" in out[1] |
| 102 |
|
| 103 |
|
| 104 |
def test_apcustom_nargs_range_validation(cust_app) -> None: |
| 105 |
|
| 106 |
_out, err = run_cmd(cust_app, "range --arg2 one two") |
| 107 |
assert "Error: argument --arg2: expected at least 3 arguments" in err[2] |
| 108 |
|
| 109 |
_out, err = run_cmd(cust_app, "range --arg2 one two three") |
| 110 |
assert not err |
| 111 |
|
| 112 |
_out, err = run_cmd(cust_app, "range --arg2 one two three four") |
| 113 |
assert not err |
| 114 |
|
| 115 |
|
| 116 |
_out, err = run_cmd(cust_app, "range --arg3 one") |
| 117 |
assert "Error: argument --arg3: expected 2 to 3 arguments" in err[2] |
| 118 |
|
| 119 |
_out, err = run_cmd(cust_app, "range --arg3 one two") |
| 120 |
assert not err |
| 121 |
|
| 122 |
_out, err = run_cmd(cust_app, "range --arg2 one two three") |
| 123 |
assert not err |
| 124 |
|
| 125 |
|
| 126 |
@pytest.mark.parametrize( |
| 127 |
("nargs", "expected_parts"), |
| 128 |
[ |
| 129 |
|
| 130 |
( |
| 131 |
2, |
| 132 |
[("arg", True), ("{2}", False)], |
| 133 |
), |
| 134 |
|
| 135 |
( |
| 136 |
(2,), |
| 137 |
[("arg", True), ("{2+}", False)], |
| 138 |
), |
| 139 |
|
| 140 |
( |
| 141 |
(0, 5), |
| 142 |
[("arg", True), ("{0..5}", False)], |
| 143 |
), |
| 144 |
], |
| 145 |
) |
| 146 |
def test_rich_metavar_parts( |
| 147 |
nargs: int | tuple[int, int | float], |
| 148 |
expected_parts: list[tuple[str, bool]], |
| 149 |
) -> None: |
| 150 |
""" |
| 151 |
Test cmd2's override of _rich_metavar_parts which handles custom nargs formats. |
| 152 |
|
| 153 |
:param nargs: the arguments nargs value |
| 154 |
:param expected_parts: list to compare to _rich_metavar_parts's return value |
| 155 |
|
| 156 |
Each element in this list is a 2-item tuple. |
| 157 |
item 1: one part of the argument string outputted by _format_args |
| 158 |
item 2: boolean stating whether rich-argparse should color this part |
| 159 |
""" |
| 160 |
parser = Cmd2ArgumentParser() |
| 161 |
help_formatter = parser._get_formatter() |
| 162 |
|
| 163 |
action = parser.add_argument("arg", nargs=nargs) |
| 164 |
default_metavar = help_formatter._get_default_metavar_for_positional(action) |
| 165 |
|
| 166 |
parts = help_formatter._rich_metavar_parts(action, default_metavar) |
| 167 |
assert list(parts) == expected_parts |
| 168 |
|
| 169 |
|
| 170 |
@pytest.mark.parametrize( |
| 171 |
"nargs_tuple", |
| 172 |
[ |
| 173 |
(), |
| 174 |
("f", 5), |
| 175 |
(5, "f"), |
| 176 |
(1, 2, 3), |
| 177 |
], |
| 178 |
) |
| 179 |
def test_apcustom_narg_invalid_tuples(nargs_tuple) -> None: |
| 180 |
parser = Cmd2ArgumentParser() |
| 181 |
expected_err = "Ranged values for nargs must be a tuple of 1 or 2 integers" |
| 182 |
with pytest.raises(ValueError, match=expected_err): |
| 183 |
parser.add_argument("invalid_tuple", nargs=nargs_tuple) |
| 184 |
|
| 185 |
|
| 186 |
def test_apcustom_narg_tuple_order() -> None: |
| 187 |
parser = Cmd2ArgumentParser() |
| 188 |
expected_err = "Invalid nargs range. The first value must be less than the second" |
| 189 |
with pytest.raises(ValueError, match=expected_err): |
| 190 |
parser.add_argument("invalid_tuple", nargs=(2, 1)) |
| 191 |
|
| 192 |
|
| 193 |
def test_apcustom_narg_tuple_negative() -> None: |
| 194 |
parser = Cmd2ArgumentParser() |
| 195 |
expected_err = "Negative numbers are invalid for nargs range" |
| 196 |
with pytest.raises(ValueError, match=expected_err): |
| 197 |
parser.add_argument("invalid_tuple", nargs=(-1, 1)) |
| 198 |
|
| 199 |
|
| 200 |
def test_apcustom_narg_tuple_zero_base() -> None: |
| 201 |
parser = Cmd2ArgumentParser() |
| 202 |
arg = parser.add_argument("arg", nargs=(0,)) |
| 203 |
assert arg.nargs == argparse.ZERO_OR_MORE |
| 204 |
assert arg.get_nargs_range() is None |
| 205 |
assert "[arg ...]" in parser.format_help() |
| 206 |
|
| 207 |
parser = Cmd2ArgumentParser() |
| 208 |
arg = parser.add_argument("arg", nargs=(0, 1)) |
| 209 |
assert arg.nargs == argparse.OPTIONAL |
| 210 |
assert arg.get_nargs_range() is None |
| 211 |
assert "[arg]" in parser.format_help() |
| 212 |
|
| 213 |
parser = Cmd2ArgumentParser() |
| 214 |
arg = parser.add_argument("arg", nargs=(0, 3)) |
| 215 |
assert arg.nargs == argparse.ZERO_OR_MORE |
| 216 |
assert arg.get_nargs_range() == (0, 3) |
| 217 |
assert "arg{0..3}" in parser.format_help() |
| 218 |
|
| 219 |
|
| 220 |
def test_apcustom_narg_tuple_one_base() -> None: |
| 221 |
parser = Cmd2ArgumentParser() |
| 222 |
arg = parser.add_argument("arg", nargs=(1,)) |
| 223 |
assert arg.nargs == argparse.ONE_OR_MORE |
| 224 |
assert arg.get_nargs_range() is None |
| 225 |
assert "arg [arg ...]" in parser.format_help() |
| 226 |
|
| 227 |
parser = Cmd2ArgumentParser() |
| 228 |
arg = parser.add_argument("arg", nargs=(1, 5)) |
| 229 |
assert arg.nargs == argparse.ONE_OR_MORE |
| 230 |
assert arg.get_nargs_range() == (1, 5) |
| 231 |
assert "arg{1..5}" in parser.format_help() |
| 232 |
|
| 233 |
|
| 234 |
def test_apcustom_narg_tuple_other_ranges() -> None: |
| 235 |
|
| 236 |
parser = Cmd2ArgumentParser() |
| 237 |
arg = parser.add_argument("arg", nargs=(2,)) |
| 238 |
assert arg.nargs == argparse.ONE_OR_MORE |
| 239 |
assert arg.get_nargs_range() == (2, constants.INFINITY) |
| 240 |
|
| 241 |
|
| 242 |
parser = Cmd2ArgumentParser() |
| 243 |
arg = parser.add_argument("arg", nargs=(2, 5)) |
| 244 |
assert arg.nargs == argparse.ONE_OR_MORE |
| 245 |
assert arg.get_nargs_range() == (2, 5) |
| 246 |
|
| 247 |
|
| 248 |
def test_apcustom_print_message(capsys) -> None: |
| 249 |
test_message = "The test message" |
| 250 |
|
| 251 |
|
| 252 |
parser = Cmd2ArgumentParser() |
| 253 |
parser._print_message(test_message, file=sys.stdout) |
| 254 |
out, err = capsys.readouterr() |
| 255 |
assert test_message in out |
| 256 |
|
| 257 |
|
| 258 |
parser = Cmd2ArgumentParser() |
| 259 |
parser._print_message(test_message) |
| 260 |
out, err = capsys.readouterr() |
| 261 |
assert test_message in err |
| 262 |
|
| 263 |
|
| 264 |
def test_build_range_error() -> None: |
| 265 |
|
| 266 |
err_msg = build_range_error(1, constants.INFINITY) |
| 267 |
assert err_msg == "expected at least 1 argument" |
| 268 |
|
| 269 |
err_msg = build_range_error(2, constants.INFINITY) |
| 270 |
assert err_msg == "expected at least 2 arguments" |
| 271 |
|
| 272 |
|
| 273 |
err_msg = build_range_error(1, 1) |
| 274 |
assert err_msg == "expected 1 argument" |
| 275 |
|
| 276 |
err_msg = build_range_error(2, 2) |
| 277 |
assert err_msg == "expected 2 arguments" |
| 278 |
|
| 279 |
|
| 280 |
err_msg = build_range_error(0, 1) |
| 281 |
assert err_msg == "expected 0 to 1 argument" |
| 282 |
|
| 283 |
err_msg = build_range_error(0, 2) |
| 284 |
assert err_msg == "expected 0 to 2 arguments" |
| 285 |
|
| 286 |
|
| 287 |
def test_apcustom_metavar_tuple() -> None: |
| 288 |
|
| 289 |
parser = Cmd2ArgumentParser() |
| 290 |
parser.add_argument("--aflag", nargs=2, metavar=("foo", "bar"), help="This is a test") |
| 291 |
assert "[--aflag foo bar]" in parser.format_help() |
| 292 |
|
| 293 |
|
| 294 |
def test_register_argparse_argument_parameter() -> None: |
| 295 |
|
| 296 |
param_name = "test_unique_param" |
| 297 |
register_argparse_argument_parameter(param_name) |
| 298 |
|
| 299 |
assert param_name in argparse_utils._CUSTOM_ACTION_ATTRIBS |
| 300 |
assert hasattr(argparse.Action, f"get_{param_name}") |
| 301 |
assert hasattr(argparse.Action, f"set_{param_name}") |
| 302 |
|
| 303 |
|
| 304 |
expected_err = "already registered" |
| 305 |
with pytest.raises(KeyError, match=expected_err): |
| 306 |
register_argparse_argument_parameter(param_name) |
| 307 |
|
| 308 |
|
| 309 |
expected_err = "must be a valid Python identifier" |
| 310 |
with pytest.raises(ValueError, match=expected_err): |
| 311 |
register_argparse_argument_parameter("invalid name") |
| 312 |
|
| 313 |
|
| 314 |
expected_err = "conflicts with an existing attribute on argparse.Action" |
| 315 |
with pytest.raises(KeyError, match=expected_err): |
| 316 |
register_argparse_argument_parameter("format_usage") |
| 317 |
|
| 318 |
|
| 319 |
try: |
| 320 |
argparse.Action.get_colliding_param = lambda self: None |
| 321 |
expected_err = "Accessor methods for 'colliding_param' already exist on argparse.Action" |
| 322 |
with pytest.raises(KeyError, match=expected_err): |
| 323 |
register_argparse_argument_parameter("colliding_param") |
| 324 |
finally: |
| 325 |
del argparse.Action.get_colliding_param |
| 326 |
|
| 327 |
|
| 328 |
try: |
| 329 |
attr_name = constants.cmd2_private_attr_name("internal_collision") |
| 330 |
setattr(argparse.Action, attr_name, None) |
| 331 |
expected_err = f"The internal attribute '{attr_name}' already exists on argparse.Action" |
| 332 |
with pytest.raises(KeyError, match=expected_err): |
| 333 |
register_argparse_argument_parameter("internal_collision") |
| 334 |
finally: |
| 335 |
delattr(argparse.Action, attr_name) |
| 336 |
|
| 337 |
|
| 338 |
def test_subcommand_attachment() -> None: |
| 339 |
"""Test Cmd2ArgumentParser convenience methods for attaching and detaching subcommands.""" |
| 340 |
|
| 341 |
|
| 342 |
|
| 343 |
|
| 344 |
root_parser = Cmd2ArgumentParser(prog="root", description="root command") |
| 345 |
root_subparsers = root_parser.add_subparsers() |
| 346 |
|
| 347 |
child_parser = Cmd2ArgumentParser(prog="child", description="child command") |
| 348 |
child_subparsers = child_parser.add_subparsers() |
| 349 |
|
| 350 |
grandchild_parser = Cmd2ArgumentParser(prog="grandchild", description="grandchild command") |
| 351 |
|
| 352 |
|
| 353 |
|
| 354 |
|
| 355 |
|
| 356 |
|
| 357 |
child_record = SubcommandRecord( |
| 358 |
name="child", |
| 359 |
command="root", |
| 360 |
parser=child_parser, |
| 361 |
help="a child command", |
| 362 |
aliases=("child_alias",), |
| 363 |
) |
| 364 |
root_parser.attach_subcommand(child_record) |
| 365 |
|
| 366 |
|
| 367 |
grandchild_record = SubcommandRecord( |
| 368 |
name="grandchild", |
| 369 |
command="root", |
| 370 |
parser=grandchild_parser, |
| 371 |
help="a grandchild command", |
| 372 |
) |
| 373 |
root_parser.attach_subcommand(grandchild_record, subcommand_path=["child"]) |
| 374 |
|
| 375 |
|
| 376 |
|
| 377 |
|
| 378 |
|
| 379 |
assert root_parser.find_parser(["child", "grandchild"]) is grandchild_parser |
| 380 |
assert root_parser.find_parser(["child"]) is child_parser |
| 381 |
assert root_parser.find_parser([]) is root_parser |
| 382 |
|
| 383 |
|
| 384 |
|
| 385 |
|
| 386 |
|
| 387 |
|
| 388 |
assert root_subparsers._name_parser_map["child"] is child_parser |
| 389 |
assert root_subparsers._name_parser_map["child_alias"] is child_parser |
| 390 |
|
| 391 |
|
| 392 |
assert child_subparsers._name_parser_map["grandchild"] is grandchild_parser |
| 393 |
|
| 394 |
|
| 395 |
assert any(action.dest == "child" for action in root_subparsers._choices_actions) |
| 396 |
assert any(action.dest == "grandchild" for action in child_subparsers._choices_actions) |
| 397 |
|
| 398 |
|
| 399 |
|
| 400 |
|
| 401 |
|
| 402 |
|
| 403 |
detached_grandchild_info = root_parser.detach_subcommand(["child"], "grandchild") |
| 404 |
assert detached_grandchild_info.parser is grandchild_parser |
| 405 |
assert detached_grandchild_info.name == "grandchild" |
| 406 |
assert "grandchild" not in child_subparsers._name_parser_map |
| 407 |
assert not any(action.dest == "grandchild" for action in child_subparsers._choices_actions) |
| 408 |
|
| 409 |
|
| 410 |
detached_child_info = root_parser.detach_subcommand([], "child") |
| 411 |
assert detached_child_info.parser is child_parser |
| 412 |
assert detached_child_info.name == "child" |
| 413 |
assert "child" not in root_subparsers._name_parser_map |
| 414 |
assert "child_alias" not in root_subparsers._name_parser_map |
| 415 |
assert not any(action.dest == "child" for action in root_subparsers._choices_actions) |
| 416 |
|
| 417 |
|
| 418 |
def test_detach_subcommand_by_alias() -> None: |
| 419 |
"""Test detaching a subcommand using one of its alias names.""" |
| 420 |
root_parser = Cmd2ArgumentParser(prog="root") |
| 421 |
root_subparsers = root_parser.add_subparsers() |
| 422 |
|
| 423 |
child_parser = Cmd2ArgumentParser(prog="child") |
| 424 |
child_record = SubcommandRecord( |
| 425 |
name="child", |
| 426 |
command="root", |
| 427 |
parser=child_parser, |
| 428 |
help="a child command", |
| 429 |
aliases=("alias1", "alias2"), |
| 430 |
) |
| 431 |
root_parser.attach_subcommand(child_record) |
| 432 |
|
| 433 |
|
| 434 |
assert root_subparsers._name_parser_map["child"] is child_parser |
| 435 |
assert root_subparsers._name_parser_map["alias1"] is child_parser |
| 436 |
assert root_subparsers._name_parser_map["alias2"] is child_parser |
| 437 |
|
| 438 |
|
| 439 |
assert any(action.dest == "child" for action in root_subparsers._choices_actions) |
| 440 |
|
| 441 |
|
| 442 |
detached_info = root_parser.detach_subcommand([], "alias1") |
| 443 |
assert detached_info.parser is child_parser |
| 444 |
assert detached_info.name == "child" |
| 445 |
|
| 446 |
|
| 447 |
assert "child" not in root_subparsers._name_parser_map |
| 448 |
assert "alias1" not in root_subparsers._name_parser_map |
| 449 |
assert "alias2" not in root_subparsers._name_parser_map |
| 450 |
|
| 451 |
|
| 452 |
assert not any(action.dest == "child" for action in root_subparsers._choices_actions) |
| 453 |
|
| 454 |
|
| 455 |
def test_subcommand_attachment_errors() -> None: |
| 456 |
root_parser = Cmd2ArgumentParser(prog="root", description="root command") |
| 457 |
child_parser = Cmd2ArgumentParser(prog="child", description="child command") |
| 458 |
child_record = SubcommandRecord(name="child", command="root", parser=child_parser) |
| 459 |
|
| 460 |
|
| 461 |
with pytest.raises(ValueError, match="Command 'root' does not support subcommands"): |
| 462 |
root_parser.attach_subcommand(child_record) |
| 463 |
with pytest.raises(ValueError, match="Command 'root' does not support subcommands"): |
| 464 |
root_parser.detach_subcommand([], "child") |
| 465 |
|
| 466 |
|
| 467 |
root_parser.add_subparsers() |
| 468 |
|
| 469 |
|
| 470 |
with pytest.raises(ValueError, match="Subcommand 'nonexistent' does not exist for 'root'"): |
| 471 |
root_parser.attach_subcommand(child_record, subcommand_path=["nonexistent"]) |
| 472 |
with pytest.raises(ValueError, match="Subcommand 'nonexistent' does not exist for 'root'"): |
| 473 |
root_parser.detach_subcommand(["nonexistent"], "child") |
| 474 |
|
| 475 |
|
| 476 |
with pytest.raises(ValueError, match="Subcommand 'fake' does not exist for 'root'"): |
| 477 |
root_parser.detach_subcommand([], "fake") |
| 478 |
|
| 479 |
|
| 480 |
ap_parser = argparse.ArgumentParser(prog="non-cmd2-parser") |
| 481 |
ap_record = SubcommandRecord(name="sub", command="root", parser=ap_parser) |
| 482 |
with pytest.raises(TypeError, match=r"must be an instance of 'Cmd2ArgumentParser'"): |
| 483 |
root_parser.attach_subcommand(ap_record) |
| 484 |
|
| 485 |
|
| 486 |
sub_parser = Cmd2ArgumentParser(prog="sub") |
| 487 |
sub_record = SubcommandRecord(name="sub", command="root", parser=sub_parser) |
| 488 |
root_parser.attach_subcommand(sub_record) |
| 489 |
with pytest.raises(ValueError, match="Subcommand 'sub' already exists for 'root'"): |
| 490 |
root_parser.attach_subcommand(sub_record) |
| 491 |
|
| 492 |
|
| 493 |
def test_subcommand_attachment_parser_class_override() -> None: |
| 494 |
class MyParser(Cmd2ArgumentParser): |
| 495 |
pass |
| 496 |
|
| 497 |
class MySubParser(MyParser): |
| 498 |
pass |
| 499 |
|
| 500 |
root_parser = Cmd2ArgumentParser(prog="root") |
| 501 |
|
| 502 |
|
| 503 |
root_parser.add_subparsers(parser_class=MyParser) |
| 504 |
|
| 505 |
|
| 506 |
my_parser = MyParser(prog="sub") |
| 507 |
my_record = SubcommandRecord(name="sub", command="root", parser=my_parser) |
| 508 |
root_parser.attach_subcommand(my_record) |
| 509 |
|
| 510 |
|
| 511 |
my_sub_parser = MySubParser(prog="sub2") |
| 512 |
my_sub_record = SubcommandRecord(name="sub2", command="root", parser=my_sub_parser) |
| 513 |
root_parser.attach_subcommand(my_sub_record) |
| 514 |
|
| 515 |
|
| 516 |
standard_parser = Cmd2ArgumentParser(prog="standard") |
| 517 |
standard_record = SubcommandRecord(name="fail", command="root", parser=standard_parser) |
| 518 |
with pytest.raises(TypeError, match=r"must be an instance of 'MyParser'"): |
| 519 |
root_parser.attach_subcommand(standard_record) |
| 520 |
|
| 521 |
|
| 522 |
def test_completion_items_as_choices(capsys) -> None: |
| 523 |
"""Test cmd2's patch to Argparse._check_value() which supports CompletionItems as choices. |
| 524 |
Choices are compared to CompletionItems.orig_value instead of the CompletionItem instance. |
| 525 |
""" |
| 526 |
|
| 527 |
|
| 528 |
|
| 529 |
|
| 530 |
choices = Choices.from_values(["1", "2"]) |
| 531 |
parser = Cmd2ArgumentParser() |
| 532 |
parser.add_argument("choices_arg", type=str, choices=choices) |
| 533 |
|
| 534 |
|
| 535 |
args = parser.parse_args(["1"]) |
| 536 |
assert args.choices_arg == "1" |
| 537 |
|
| 538 |
args = parser.parse_args(["2"]) |
| 539 |
assert args.choices_arg == "2" |
| 540 |
|
| 541 |
|
| 542 |
with pytest.raises(SystemExit): |
| 543 |
args = parser.parse_args(["3"]) |
| 544 |
|
| 545 |
|
| 546 |
_out, err = capsys.readouterr() |
| 547 |
assert "invalid choice: '3' (choose from '1', '2')" in err |
| 548 |
|
| 549 |
|
| 550 |
|
| 551 |
|
| 552 |
choices = Choices.from_values([1, 2]) |
| 553 |
parser = Cmd2ArgumentParser() |
| 554 |
parser.add_argument("choices_arg", type=int, choices=choices) |
| 555 |
|
| 556 |
|
| 557 |
args = parser.parse_args(["1"]) |
| 558 |
assert args.choices_arg == 1 |
| 559 |
|
| 560 |
args = parser.parse_args(["2"]) |
| 561 |
assert args.choices_arg == 2 |
| 562 |
|
| 563 |
|
| 564 |
with pytest.raises(SystemExit): |
| 565 |
args = parser.parse_args(["3"]) |
| 566 |
|
| 567 |
|
| 568 |
_out, err = capsys.readouterr() |
| 569 |
assert "invalid choice: 3 (choose from 1, 2)" in err |
| 570 |
|
| 571 |
|
| 572 |
def test_update_prog() -> None: |
| 573 |
"""Test Cmd2ArgumentParser.update_prog() across various scenarios.""" |
| 574 |
|
| 575 |
|
| 576 |
old_app = "old_app" |
| 577 |
root = Cmd2ArgumentParser(prog=old_app) |
| 578 |
|
| 579 |
|
| 580 |
root.add_argument("pos1") |
| 581 |
|
| 582 |
|
| 583 |
group = root.add_mutually_exclusive_group(required=True) |
| 584 |
group.add_argument("posA", nargs="?") |
| 585 |
group.add_argument("posB", nargs="?") |
| 586 |
|
| 587 |
|
| 588 |
root_subparsers = root.add_subparsers(dest="cmd") |
| 589 |
|
| 590 |
|
| 591 |
sub1 = root_subparsers.add_parser("sub1", aliases=["s1", "alias1"], help="help for sub1") |
| 592 |
|
| 593 |
|
| 594 |
sub2 = root_subparsers.add_parser("sub2") |
| 595 |
|
| 596 |
|
| 597 |
sub2.add_argument("inner_pos") |
| 598 |
sub2_subparsers = sub2.add_subparsers(dest="sub2_cmd") |
| 599 |
leaf = sub2_subparsers.add_parser("leaf", help="leaf help") |
| 600 |
|
| 601 |
|
| 602 |
orig_root_prog = root.prog |
| 603 |
orig_sub1_prog = sub1.prog |
| 604 |
orig_sub2_prog = sub2.prog |
| 605 |
orig_leaf_prog = leaf.prog |
| 606 |
|
| 607 |
|
| 608 |
new_app = "new_app" |
| 609 |
root.update_prog(new_app) |
| 610 |
|
| 611 |
|
| 612 |
assert root.prog.startswith(new_app) |
| 613 |
assert root.prog == orig_root_prog.replace(old_app, new_app, 1) |
| 614 |
|
| 615 |
assert sub1.prog.startswith(new_app) |
| 616 |
assert sub1.prog == orig_sub1_prog.replace(old_app, new_app, 1) |
| 617 |
|
| 618 |
assert sub2.prog.startswith(new_app) |
| 619 |
assert sub2.prog == orig_sub2_prog.replace(old_app, new_app, 1) |
| 620 |
|
| 621 |
assert leaf.prog.startswith(new_app) |
| 622 |
assert leaf.prog == orig_leaf_prog.replace(old_app, new_app, 1) |
| 623 |
|
| 624 |
|
| 625 |
sub3 = root_subparsers.add_parser("sub3") |
| 626 |
assert sub3.prog.startswith(new_app) |
| 627 |
assert sub3.prog == root_subparsers._prog_prefix + " sub3" |
| 628 |
|
| 629 |
|
| 630 |
for action in root._actions: |
| 631 |
if isinstance(action, argparse._SubParsersAction): |
| 632 |
assert action.choices["s1"].prog == sub1.prog |
| 633 |
assert action.choices["alias1"].prog == sub1.prog |
| 634 |
|
| 635 |
|
| 636 |
def test_parser_output_to_context_manager() -> None: |
| 637 |
"""Test that output_to() correctly shadows and restores current_output_file.""" |
| 638 |
import io |
| 639 |
|
| 640 |
parser = Cmd2ArgumentParser() |
| 641 |
buf1 = io.StringIO() |
| 642 |
buf2 = io.StringIO() |
| 643 |
|
| 644 |
assert parser._thread_locals.current_output_file is None |
| 645 |
|
| 646 |
with parser.output_to(buf1): |
| 647 |
assert parser._thread_locals.current_output_file is buf1 |
| 648 |
with parser.output_to(buf2): |
| 649 |
assert parser._thread_locals.current_output_file is buf2 |
| 650 |
assert parser._thread_locals.current_output_file is buf1 |
| 651 |
|
| 652 |
assert parser._thread_locals.current_output_file is None |
| 653 |
|
| 654 |
|
| 655 |
def test_parser_print_help_output_to(mocker: MockerFixture) -> None: |
| 656 |
"""Test that print_help(file=my_file) correctly sets the context for the formatter.""" |
| 657 |
import io |
| 658 |
|
| 659 |
parser = Cmd2ArgumentParser(prog="test") |
| 660 |
buf = io.StringIO() |
| 661 |
|
| 662 |
|
| 663 |
|
| 664 |
|
| 665 |
mock_formatter_class = mocker.patch("cmd2.argparse_utils.Cmd2HelpFormatter", autospec=True) |
| 666 |
parser.formatter_class = mock_formatter_class |
| 667 |
|
| 668 |
|
| 669 |
|
| 670 |
mock_formatter_class.return_value.format_help.return_value = "Help Text" |
| 671 |
|
| 672 |
parser.print_help(buf) |
| 673 |
|
| 674 |
|
| 675 |
mock_formatter_class.assert_called_with(prog="test", file=buf) |
| 676 |
|
| 677 |
|
| 678 |
def test_parser_error_output_to(mocker: MockerFixture) -> None: |
| 679 |
"""Test that error() shadows to sys.stderr and uses it for styling.""" |
| 680 |
from cmd2 import rich_utils |
| 681 |
|
| 682 |
parser = Cmd2ArgumentParser(prog="test") |
| 683 |
|
| 684 |
|
| 685 |
mocker.patch.object(parser, "exit") |
| 686 |
|
| 687 |
|
| 688 |
mocker.patch.object(parser, "print_usage") |
| 689 |
|
| 690 |
|
| 691 |
mock_formatter = mocker.Mock(spec=rich_utils.Cmd2HelpFormatter) |
| 692 |
mock_console = mocker.MagicMock(spec=rich_utils.Cmd2RichArgparseConsole) |
| 693 |
mock_formatter.console = mock_console |
| 694 |
|
| 695 |
mocker.patch.object(parser, "_get_formatter", return_value=mock_formatter) |
| 696 |
|
| 697 |
|
| 698 |
mock_capture = mocker.MagicMock() |
| 699 |
mock_console.capture.return_value.__enter__.return_value = mock_capture |
| 700 |
mock_capture.get.return_value = "Styled Error" |
| 701 |
|
| 702 |
parser.error("some message") |
| 703 |
|
| 704 |
|
| 705 |
|
| 706 |
parser.print_usage.assert_called_once_with(sys.stderr) |
| 707 |
|
| 708 |
|
| 709 |
mock_console.print.assert_called_once() |
| 710 |
args, kwargs = mock_console.print.call_args |
| 711 |
assert "Error: some message" in args[0] |
| 712 |
assert kwargs["style"] == argparse_utils.Cmd2Style.ERROR |
| 713 |
|
| 714 |
|
| 715 |
def test_parser_implicit_output_to(mocker: MockerFixture) -> None: |
| 716 |
"""Test that print_help() and print_usage() use thread-local context when no file is provided.""" |
| 717 |
import io |
| 718 |
|
| 719 |
parser = Cmd2ArgumentParser(prog="test") |
| 720 |
buf = io.StringIO() |
| 721 |
|
| 722 |
mock_formatter_class = mocker.patch("cmd2.argparse_utils.Cmd2HelpFormatter", autospec=True) |
| 723 |
parser.formatter_class = mock_formatter_class |
| 724 |
mock_formatter_class.return_value.format_help.return_value = "Help/Usage Text" |
| 725 |
|
| 726 |
|
| 727 |
with parser.output_to(buf): |
| 728 |
|
| 729 |
parser.print_help() |
| 730 |
|
| 731 |
mock_formatter_class.assert_called_with(prog="test", file=buf) |
| 732 |
|
| 733 |
mock_formatter_class.reset_mock() |
| 734 |
|
| 735 |
|
| 736 |
parser.print_usage() |
| 737 |
|
| 738 |
mock_formatter_class.assert_called_with(prog="test", file=buf) |
| 739 |
|
| 740 |
|
| 741 |
@with_ansi_style(ru.AllowStyle.NEVER) |
| 742 |
def test_argparse_output_capture(base_app: cmd2.Cmd) -> None: |
| 743 |
"""Test that both help code paths capture the same output.""" |
| 744 |
|
| 745 |
|
| 746 |
unstyled_help_out, help_err = run_cmd(base_app, "help alias") |
| 747 |
unstyled_flag_out, flag_err = run_cmd(base_app, "alias -h") |
| 748 |
assert unstyled_help_out == unstyled_flag_out |
| 749 |
assert not help_err |
| 750 |
assert not flag_err |
| 751 |
|
| 752 |
|
| 753 |
ru.ALLOW_STYLE = ru.AllowStyle.ALWAYS |
| 754 |
|
| 755 |
styled_help_out, help_err = run_cmd(base_app, "help alias") |
| 756 |
styled_flag_out, flag_err = run_cmd(base_app, "alias -h") |
| 757 |
assert styled_help_out == styled_flag_out |
| 758 |
assert not help_err |
| 759 |
assert not flag_err |
| 760 |
|
| 761 |
|
| 762 |
assert styled_help_out != unstyled_help_out |
| 763 |
assert su.strip_style("\n".join(styled_help_out)) == "\n".join(unstyled_help_out) |
| 764 |
|
| 765 |
|
| 766 |
def test_detach_all_subcommands() -> None: |
| 767 |
root_parser = Cmd2ArgumentParser(prog="root") |
| 768 |
root_parser.add_subparsers() |
| 769 |
|
| 770 |
child1 = Cmd2ArgumentParser(prog="child1") |
| 771 |
child2 = Cmd2ArgumentParser(prog="child2") |
| 772 |
|
| 773 |
child1_record = SubcommandRecord( |
| 774 |
name="child1", |
| 775 |
command="root", |
| 776 |
parser=child1, |
| 777 |
help="help1", |
| 778 |
aliases=("alias1",), |
| 779 |
) |
| 780 |
child2_record = SubcommandRecord( |
| 781 |
name="child2", |
| 782 |
command="root", |
| 783 |
parser=child2, |
| 784 |
help="help2", |
| 785 |
) |
| 786 |
|
| 787 |
root_parser.attach_subcommand(child1_record) |
| 788 |
root_parser.attach_subcommand(child2_record) |
| 789 |
|
| 790 |
removed = root_parser.detach_all_subcommands([]) |
| 791 |
assert len(removed) == 2 |
| 792 |
|
| 793 |
|
| 794 |
removed.sort(key=lambda x: x.name) |
| 795 |
|
| 796 |
assert removed[0].name == "child1" |
| 797 |
assert removed[0].parser is child1 |
| 798 |
assert removed[0].help == "help1" |
| 799 |
assert removed[0].aliases == ("alias1",) |
| 800 |
|
| 801 |
assert removed[1].name == "child2" |
| 802 |
assert removed[1].parser is child2 |
| 803 |
assert removed[1].help == "help2" |
| 804 |
assert removed[1].aliases == () |
| 805 |
|
| 806 |
|
| 807 |
subparsers_action = root_parser.get_subparsers_action() |
| 808 |
assert not subparsers_action._name_parser_map |
| 809 |
assert not subparsers_action._choices_actions |
| 810 |
|
| 811 |
|
| 812 |
def test_subcommand_move() -> None: |
| 813 |
root = Cmd2ArgumentParser(prog="root") |
| 814 |
root.add_subparsers() |
| 815 |
|
| 816 |
other = Cmd2ArgumentParser(prog="other") |
| 817 |
other.add_subparsers() |
| 818 |
|
| 819 |
child = Cmd2ArgumentParser(prog="child") |
| 820 |
child_record = SubcommandRecord(name="child", command="root", parser=child) |
| 821 |
|
| 822 |
|
| 823 |
root.attach_subcommand(child_record) |
| 824 |
assert child_record.command == "root" |
| 825 |
|
| 826 |
|
| 827 |
detached_info = root.detach_subcommand([], "child") |
| 828 |
assert detached_info.command == "root" |
| 829 |
|
| 830 |
|
| 831 |
other.attach_subcommand(detached_info) |
| 832 |
assert detached_info.command == "other" |
| 833 |
assert child.prog == "other child" |
| 834 |
|
| 835 |
|
| 836 |
@pytest.mark.skipif( |
| 837 |
sys.version_info < (3, 13), |
| 838 |
reason="deprecated subcommands require Python 3.13+", |
| 839 |
) |
| 840 |
def test_deprecated_subcommand() -> None: |
| 841 |
root = Cmd2ArgumentParser(prog="root") |
| 842 |
root.add_subparsers() |
| 843 |
|
| 844 |
child = Cmd2ArgumentParser(prog="child") |
| 845 |
child_record = SubcommandRecord( |
| 846 |
name="old", |
| 847 |
command="root", |
| 848 |
parser=child, |
| 849 |
deprecated=True, |
| 850 |
aliases=("old_alias",), |
| 851 |
) |
| 852 |
|
| 853 |
root.attach_subcommand(child_record) |
| 854 |
|
| 855 |
subparsers_action = root.get_subparsers_action() |
| 856 |
assert "old" in subparsers_action._deprecated |
| 857 |
assert "old_alias" in subparsers_action._deprecated |
| 858 |
|
| 859 |
|
| 860 |
detached_info = root.detach_subcommand([], "old") |
| 861 |
assert detached_info.deprecated is True |
| 862 |
|
| 863 |
|
| 864 |
assert "old" not in subparsers_action._deprecated |
| 865 |
assert "old_alias" not in subparsers_action._deprecated |
| 866 |
|
| 867 |
|
| 868 |
def test_set_default_argument_parser() -> None: |
| 869 |
"""Test altering the app-wide default Cmd2ArgumentParser class""" |
| 870 |
|
| 871 |
class CustomParser(Cmd2ArgumentParser): |
| 872 |
pass |
| 873 |
|
| 874 |
try: |
| 875 |
|
| 876 |
assert argparse_utils.DEFAULT_ARGUMENT_PARSER is Cmd2ArgumentParser |
| 877 |
|
| 878 |
default_app = cmd2.Cmd() |
| 879 |
default_alias_parser = default_app.command_parsers.get(default_app.do_alias) |
| 880 |
assert type(default_alias_parser) is Cmd2ArgumentParser |
| 881 |
|
| 882 |
|
| 883 |
argparse_utils.set_default_argument_parser(CustomParser) |
| 884 |
assert argparse_utils.DEFAULT_ARGUMENT_PARSER is CustomParser |
| 885 |
|
| 886 |
custom_app = cmd2.Cmd() |
| 887 |
custom_alias_parser = custom_app.command_parsers.get(custom_app.do_alias) |
| 888 |
assert type(custom_alias_parser) is CustomParser |
| 889 |
|
| 890 |
finally: |
| 891 |
|
| 892 |
argparse_utils.set_default_argument_parser(Cmd2ArgumentParser) |