| 1 |
import itertools |
| 2 |
from collections.abc import Sequence |
| 3 |
from typing import Annotated |
| 4 |
from unittest.mock import Mock |
| 5 |
|
| 6 |
import pytest |
| 7 |
|
| 8 |
import cyclopts.group |
| 9 |
from cyclopts import App, ArgumentCollection, Group, Parameter, Token |
| 10 |
from cyclopts.exceptions import ValidationError |
| 11 |
from cyclopts.group import sort_groups |
| 12 |
|
| 13 |
|
| 14 |
def upper(type_, tokens: Sequence[Token]): |
| 15 |
return tokens[0].value.upper() |
| 16 |
|
| 17 |
|
| 18 |
def test_group_show_property(): |
| 19 |
assert Group().show is False |
| 20 |
assert Group("Foo").show is True |
| 21 |
assert Group("Foo", show=False).show is False |
| 22 |
|
| 23 |
|
| 24 |
def test_group_default_parameter_converter(app, assert_parse_args): |
| 25 |
food_group = Group("Food", default_parameter=Parameter(converter=upper)) |
| 26 |
|
| 27 |
@app.default |
| 28 |
def foo(ice_cream: Annotated[str, Parameter(group=food_group)]): |
| 29 |
pass |
| 30 |
|
| 31 |
assert_parse_args(foo, "chocolate", "CHOCOLATE") |
| 32 |
|
| 33 |
|
| 34 |
def test_command_validator(app, assert_parse_args): |
| 35 |
def bar_must_be_1(bar): |
| 36 |
if bar == 1: |
| 37 |
return |
| 38 |
raise ValueError |
| 39 |
|
| 40 |
@app.command(validator=bar_must_be_1) |
| 41 |
def foo(bar: int): |
| 42 |
pass |
| 43 |
|
| 44 |
assert_parse_args(foo, "foo 1", bar=1) |
| 45 |
|
| 46 |
with pytest.raises(ValidationError) as e: |
| 47 |
app("foo 2", exit_on_error=False) |
| 48 |
|
| 49 |
assert str(e.value) == 'Invalid values for command "foo".' |
| 50 |
|
| 51 |
|
| 52 |
def test_command_validator_with_message(app, assert_parse_args): |
| 53 |
def bar_must_be_1(bar): |
| 54 |
if bar == 1: |
| 55 |
return |
| 56 |
raise ValueError("The value 'bar' must be 1.") |
| 57 |
|
| 58 |
@app.command(validator=bar_must_be_1) |
| 59 |
def foo(bar: int): |
| 60 |
pass |
| 61 |
|
| 62 |
assert_parse_args(foo, "foo 1", bar=1) |
| 63 |
|
| 64 |
with pytest.raises(ValidationError) as e: |
| 65 |
app("foo 2", exit_on_error=False) |
| 66 |
|
| 67 |
assert str(e.value) == "Invalid values for command \"foo\". The value 'bar' must be 1." |
| 68 |
|
| 69 |
|
| 70 |
def test_group_command_default_parameter_resolution(app): |
| 71 |
app_validator = Mock() |
| 72 |
sub_app_validator = Mock() |
| 73 |
command_validator = Mock() |
| 74 |
command_group_validator = Mock() |
| 75 |
|
| 76 |
app.validator = app_validator |
| 77 |
app.command(bar := App("bar", validator=sub_app_validator)) |
| 78 |
|
| 79 |
@bar.command(validator=command_validator, group=Group("Test", validator=command_group_validator)) |
| 80 |
def cmd(foo=5): |
| 81 |
return 100 |
| 82 |
|
| 83 |
assert 100 == app("bar cmd") |
| 84 |
|
| 85 |
app_validator.assert_not_called() |
| 86 |
command_group_validator.assert_called_once() |
| 87 |
|
| 88 |
sub_app_validator.assert_not_called() |
| 89 |
command_validator.assert_called_once() |
| 90 |
|
| 91 |
|
| 92 |
def test_group_default_parameter_validator(app): |
| 93 |
validator = Mock() |
| 94 |
|
| 95 |
food_group = Group("Food", default_parameter=Parameter(validator=validator)) |
| 96 |
|
| 97 |
@app.default |
| 98 |
def foo(ice_cream: Annotated[str, Parameter(group=food_group)]): |
| 99 |
pass |
| 100 |
|
| 101 |
app.parse_args("chocolate") |
| 102 |
validator.assert_called_once() |
| 103 |
|
| 104 |
|
| 105 |
def test_group_validator(app): |
| 106 |
validator = Mock() |
| 107 |
|
| 108 |
group = Group("Spices", validator=validator) |
| 109 |
|
| 110 |
@app.default |
| 111 |
def foo( |
| 112 |
salt: Annotated[bool, Parameter("--rock-salt", group=group)] = False, |
| 113 |
pepper: Annotated[bool, Parameter("--peppercorn", group=group)] = False, |
| 114 |
ketchup: bool = False, |
| 115 |
): |
| 116 |
pass |
| 117 |
|
| 118 |
app.parse_args("--rock-salt --peppercorn --ketchup") |
| 119 |
|
| 120 |
validator.assert_called_once() |
| 121 |
provided_arguments = validator.call_args_list[0][0][0] |
| 122 |
assert len(provided_arguments) == 2 |
| 123 |
assert provided_arguments[0].name == "--rock-salt" |
| 124 |
assert provided_arguments[1].name == "--peppercorn" |
| 125 |
|
| 126 |
|
| 127 |
def test_group_sort_key_property(): |
| 128 |
assert Group().sort_key is None |
| 129 |
assert Group()._sort_key is cyclopts.group.UNSET |
| 130 |
|
| 131 |
g = Group(sort_key=1) |
| 132 |
assert g.sort_key == 1 |
| 133 |
|
| 134 |
|
| 135 |
def test_group_sort_key_generator(): |
| 136 |
"""Test that Group.sort_key accepts and processes generators.""" |
| 137 |
|
| 138 |
def sort_key_gen(): |
| 139 |
yield 5 |
| 140 |
|
| 141 |
|
| 142 |
g1 = Group("Test1", sort_key=sort_key_gen()) |
| 143 |
assert g1.sort_key == 5 |
| 144 |
|
| 145 |
|
| 146 |
g2 = Group("Test2", sort_key=(x for x in [10])) |
| 147 |
assert g2.sort_key == 10 |
| 148 |
|
| 149 |
|
| 150 |
g3 = Group.create_ordered("Test3", sort_key=(x * 2 for x in [7])) |
| 151 |
|
| 152 |
assert g3.sort_key[0] == 14 |
| 153 |
|
| 154 |
|
| 155 |
@pytest.fixture |
| 156 |
def mock_sort_key_counter(mocker): |
| 157 |
mock = mocker.patch("cyclopts.group._sort_key_counter") |
| 158 |
mock.__next__.side_effect = itertools.count() |
| 159 |
return mock |
| 160 |
|
| 161 |
|
| 162 |
def test_group_sorted_classmethod_basic(mock_sort_key_counter): |
| 163 |
g4 = Group("unsorted group") |
| 164 |
g1 = Group.create_ordered("foo") |
| 165 |
g2 = Group.create_ordered("bar") |
| 166 |
g3 = Group.create_ordered("baz", sort_key="non-int value") |
| 167 |
|
| 168 |
assert g1.sort_key == (cyclopts.group.UNSET, 0) |
| 169 |
assert g2.sort_key == (cyclopts.group.UNSET, 1) |
| 170 |
assert g3.sort_key == ("non-int value", 2) |
| 171 |
assert g4.sort_key is None |
| 172 |
|
| 173 |
res = sort_groups([g1, g2, g3, g4], ["a", "b", "c", "d"]) |
| 174 |
assert ([g3, g1, g2, g4], ["c", "a", "b", "d"]) == res |
| 175 |
|
| 176 |
|
| 177 |
def test_group_sorted_classmethod_tuple(mock_sort_key_counter): |
| 178 |
g1 = Group.create_ordered("foo1", sort_key=("tuple", 7)) |
| 179 |
g2 = Group.create_ordered("foo2", sort_key=lambda x: ("tuple", 5)) |
| 180 |
|
| 181 |
def f_tuple_str(x): |
| 182 |
return "tuple" |
| 183 |
|
| 184 |
g3 = Group.create_ordered("foo3", sort_key=(f_tuple_str, 3)) |
| 185 |
g4 = Group.create_ordered("foo4", sort_key=("tuple", 3)) |
| 186 |
|
| 187 |
res = sort_groups([g1, g2, g3, g4], ["a", "b", "c", "d"]) |
| 188 |
assert ([g3, g4, g2, g1], ["c", "d", "b", "a"]) == res |
| 189 |
|
| 190 |
|
| 191 |
def test_multiple_anonymous_groups(app, assert_parse_args): |
| 192 |
"""Test to ensure that multiple anonymous Groups do not get combined. |
| 193 |
|
| 194 |
https://github.com/BrianPugh/cyclopts/issues/479 |
| 195 |
""" |
| 196 |
|
| 197 |
def require_all_or_none(args: ArgumentCollection) -> None: |
| 198 |
got_args = args.filter_by(has_tokens=True) |
| 199 |
if len(got_args) == 0 or len(got_args) == len(args): |
| 200 |
return |
| 201 |
got_str = ", ".join(a.name for a in got_args) |
| 202 |
wanted_str = ", ".join(a.name for a in args) |
| 203 |
error_msg = f"Needs all of: {wanted_str}. Now only got: {got_str}." |
| 204 |
raise ValueError(error_msg) |
| 205 |
|
| 206 |
group1 = Group(validator=require_all_or_none) |
| 207 |
group2 = Group(validator=require_all_or_none) |
| 208 |
|
| 209 |
@app.default |
| 210 |
def default( |
| 211 |
*, |
| 212 |
foo: Annotated[str, Parameter(group=group1)] = "", |
| 213 |
bar: Annotated[str, Parameter(group=group1)] = "", |
| 214 |
fizz: Annotated[str, Parameter(group=group2)] = "", |
| 215 |
buzz: Annotated[str, Parameter(group=group2)] = "", |
| 216 |
): |
| 217 |
pass |
| 218 |
|
| 219 |
with pytest.raises(ValidationError): |
| 220 |
app("--foo foo", exit_on_error=False) |
| 221 |
|
| 222 |
with pytest.raises(ValidationError): |
| 223 |
app("--fizz fizz", exit_on_error=False) |
| 224 |
|
| 225 |
with pytest.raises(ValidationError): |
| 226 |
app("--foo foo --bar bar --fizz fizz", exit_on_error=False) |
| 227 |
|
| 228 |
assert_parse_args(default, "--foo foo --bar bar", foo="foo", bar="bar") |
| 229 |
assert_parse_args( |
| 230 |
default, |
| 231 |
"--foo foo --bar bar --fizz fizz --buzz buzz", |
| 232 |
foo="foo", |
| 233 |
bar="bar", |
| 234 |
fizz="fizz", |
| 235 |
buzz="buzz", |
| 236 |
) |
| 237 |
|
| 238 |
|
| 239 |
def test_nameless_group_parameters_in_help(app, console): |
| 240 |
"""Test that parameters assigned to nameless groups still appear in default Parameters group. |
| 241 |
|
| 242 |
When a parameter is assigned to a nameless Group (where group.show == False), |
| 243 |
it should still appear in the default "Parameters" group in the help output |
| 244 |
if it's not assigned to any named group. |
| 245 |
""" |
| 246 |
nameless_group = Group(validator=lambda args: None) |
| 247 |
|
| 248 |
@app.default |
| 249 |
def default( |
| 250 |
*, |
| 251 |
foo: Annotated[str, Parameter(group=nameless_group, help="Parameter in nameless group")] = "", |
| 252 |
bar: Annotated[str, Parameter(group=nameless_group, help="Another parameter in nameless group")] = "", |
| 253 |
baz: Annotated[str, Parameter(help="Parameter in default group")] = "", |
| 254 |
): |
| 255 |
"""Test function with parameters in nameless and default groups.""" |
| 256 |
pass |
| 257 |
|
| 258 |
|
| 259 |
with console.capture() as capture: |
| 260 |
app(["--help"], console=console) |
| 261 |
|
| 262 |
help_output = capture.get() |
| 263 |
|
| 264 |
|
| 265 |
|
| 266 |
assert "--foo" in help_output |
| 267 |
assert "--bar" in help_output |
| 268 |
assert "--baz" in help_output |
| 269 |
assert "Parameter in nameless group" in help_output |
| 270 |
assert "Another parameter in nameless group" in help_output |
| 271 |
assert "Parameter in default group" in help_output |
| 272 |
|
| 273 |
|
| 274 |
assert "Parameters" in help_output |
| 275 |
|
| 276 |
|
| 277 |
def test_nameless_group_validators_still_work(app, assert_parse_args): |
| 278 |
"""Test that validators in nameless groups still function correctly.""" |
| 279 |
|
| 280 |
def require_both(args: ArgumentCollection) -> None: |
| 281 |
got_args = args.filter_by(has_tokens=True) |
| 282 |
if len(got_args) == 1: |
| 283 |
raise ValueError("Must provide both foo and bar together") |
| 284 |
|
| 285 |
nameless_group = Group(validator=require_both) |
| 286 |
|
| 287 |
@app.default |
| 288 |
def default( |
| 289 |
*, |
| 290 |
foo: Annotated[str, Parameter(group=nameless_group)] = "", |
| 291 |
bar: Annotated[str, Parameter(group=nameless_group)] = "", |
| 292 |
baz: str = "", |
| 293 |
): |
| 294 |
pass |
| 295 |
|
| 296 |
|
| 297 |
assert_parse_args(default, "--foo hello --bar world", foo="hello", bar="world") |
| 298 |
|
| 299 |
|
| 300 |
assert_parse_args(default, "--baz test", baz="test") |
| 301 |
|
| 302 |
|
| 303 |
with pytest.raises(ValidationError): |
| 304 |
app("--foo hello", exit_on_error=False) |
| 305 |
|
| 306 |
|
| 307 |
def test_multiple_parameters_mixed_groups(app, console): |
| 308 |
"""Test that multiple parameters with different group configurations work correctly. |
| 309 |
|
| 310 |
This tests the edge case where resolved_groups accumulation could cause bugs. |
| 311 |
""" |
| 312 |
nameless_group1 = Group(validator=lambda args: None) |
| 313 |
nameless_group2 = Group(validator=lambda args: None) |
| 314 |
named_group = Group(name="Special Options", help="Special configuration options") |
| 315 |
|
| 316 |
@app.default |
| 317 |
def default( |
| 318 |
*, |
| 319 |
foo: Annotated[str, Parameter(group=nameless_group1, help="First nameless group param")] = "", |
| 320 |
bar: Annotated[str, Parameter(group=nameless_group2, help="Second nameless group param")] = "", |
| 321 |
special: Annotated[str, Parameter(group=named_group, help="Named group param")] = "", |
| 322 |
normal: Annotated[str, Parameter(help="Normal param without explicit group")] = "", |
| 323 |
): |
| 324 |
"""Test function with mixed group configurations.""" |
| 325 |
pass |
| 326 |
|
| 327 |
|
| 328 |
with console.capture() as capture: |
| 329 |
app(["--help"], console=console) |
| 330 |
|
| 331 |
help_output = capture.get() |
| 332 |
|
| 333 |
|
| 334 |
assert "--foo" in help_output |
| 335 |
assert "--bar" in help_output |
| 336 |
assert "--special" in help_output |
| 337 |
assert "--normal" in help_output |
| 338 |
|
| 339 |
|
| 340 |
assert "Parameters" in help_output |
| 341 |
assert "Special Options" in help_output |
| 342 |
|
| 343 |
|
| 344 |
assert "First nameless group param" in help_output |
| 345 |
assert "Second nameless group param" in help_output |
| 346 |
assert "Named group param" in help_output |
| 347 |
assert "Normal param without explicit group" in help_output |