| 1 |
from dataclasses import dataclass |
| 2 |
from typing import Annotated |
| 3 |
from unittest.mock import Mock |
| 4 |
|
| 5 |
import pytest |
| 6 |
|
| 7 |
from cyclopts import Parameter, ValidationError |
| 8 |
from cyclopts.exceptions import CoercionError |
| 9 |
from cyclopts.token import Token |
| 10 |
|
| 11 |
|
| 12 |
@pytest.fixture |
| 13 |
def validator(): |
| 14 |
return Mock() |
| 15 |
|
| 16 |
|
| 17 |
def test_custom_converter(app, assert_parse_args): |
| 18 |
def custom_converter(type_, tokens): |
| 19 |
return 2 * int(tokens[0].value) |
| 20 |
|
| 21 |
@app.default |
| 22 |
def foo(age: Annotated[int, Parameter(converter=custom_converter)]): |
| 23 |
pass |
| 24 |
|
| 25 |
assert_parse_args(foo, "5", age=10) |
| 26 |
|
| 27 |
|
| 28 |
def test_custom_converter_dict(app, assert_parse_args): |
| 29 |
def custom_converter(type_, tokens): |
| 30 |
return {k: 2 * int(v[0].value) for k, v in tokens.items()} |
| 31 |
|
| 32 |
@app.default |
| 33 |
def foo(*, color: Annotated[dict[str, int], Parameter(converter=custom_converter)]): |
| 34 |
pass |
| 35 |
|
| 36 |
assert_parse_args(foo, "--color.red 5 --color.green 10", color={"red": 10, "green": 20}) |
| 37 |
|
| 38 |
|
| 39 |
def test_custom_converter_user_value_error_single_token(app): |
| 40 |
def custom_converter(type_, tokens): |
| 41 |
raise ValueError |
| 42 |
|
| 43 |
@app.default |
| 44 |
def foo(age: Annotated[int, Parameter(converter=custom_converter)]): |
| 45 |
pass |
| 46 |
|
| 47 |
with pytest.raises(CoercionError) as e: |
| 48 |
app("5", exit_on_error=False) |
| 49 |
assert str(e.value) == 'Invalid value for AGE: unable to convert "5" into int.' |
| 50 |
|
| 51 |
|
| 52 |
def test_custom_converter_user_value_error_multi_token(app): |
| 53 |
def custom_converter(type_, tokens): |
| 54 |
raise ValueError |
| 55 |
|
| 56 |
@app.default |
| 57 |
def foo(age: Annotated[tuple[int, int], Parameter(converter=custom_converter)]): |
| 58 |
pass |
| 59 |
|
| 60 |
with pytest.raises(CoercionError) as e: |
| 61 |
app("5 6", exit_on_error=False) |
| 62 |
assert str(e.value) == "Invalid value for --age: unable to convert value to tuple[int, int]." |
| 63 |
|
| 64 |
|
| 65 |
def test_custom_converter_user_value_error_with_message(app): |
| 66 |
def custom_converter(type_, tokens): |
| 67 |
raise ValueError("Some user-provided message.") |
| 68 |
|
| 69 |
@app.default |
| 70 |
def foo(age: Annotated[int, Parameter(converter=custom_converter)]): |
| 71 |
pass |
| 72 |
|
| 73 |
with pytest.raises(CoercionError) as e: |
| 74 |
app("5", exit_on_error=False) |
| 75 |
assert str(e.value) == "Some user-provided message." |
| 76 |
|
| 77 |
|
| 78 |
def test_custom_converter_user_kwargs_error(app): |
| 79 |
def custom_converter(type_, tokens): |
| 80 |
raise ValueError |
| 81 |
|
| 82 |
@app.default |
| 83 |
def foo(**kwargs: Annotated[int, Parameter(converter=custom_converter)]): |
| 84 |
pass |
| 85 |
|
| 86 |
with pytest.raises(CoercionError) as e: |
| 87 |
app("--foo 5", exit_on_error=False) |
| 88 |
assert str(e.value) == 'Invalid value for --foo: unable to convert "5" into int.' |
| 89 |
|
| 90 |
|
| 91 |
def test_custom_converter_user_kwargs_error_with_message(app): |
| 92 |
def custom_converter(type_, tokens): |
| 93 |
raise ValueError("Some user-provided message.") |
| 94 |
|
| 95 |
@app.default |
| 96 |
def foo(**kwargs: Annotated[int, Parameter(converter=custom_converter)]): |
| 97 |
pass |
| 98 |
|
| 99 |
with pytest.raises(CoercionError) as e: |
| 100 |
app("--foo 5", exit_on_error=False) |
| 101 |
assert str(e.value) == "Invalid value for --foo: Some user-provided message." |
| 102 |
|
| 103 |
|
| 104 |
def test_custom_validator_positional_or_keyword(app, assert_parse_args, validator): |
| 105 |
@app.default |
| 106 |
def foo(age: Annotated[int, Parameter(validator=validator)]): |
| 107 |
pass |
| 108 |
|
| 109 |
assert_parse_args(foo, "10", age=10) |
| 110 |
validator.assert_called_once_with(int, 10) |
| 111 |
|
| 112 |
|
| 113 |
def test_custom_validator_var_keyword(app, assert_parse_args, validator): |
| 114 |
@app.default |
| 115 |
def foo(**age: Annotated[int, Parameter(validator=validator)]): |
| 116 |
pass |
| 117 |
|
| 118 |
assert_parse_args(foo, "--age=10", age=10) |
| 119 |
validator.assert_called_once_with(int, 10) |
| 120 |
|
| 121 |
|
| 122 |
def test_custom_validator_var_positional(app, assert_parse_args, validator): |
| 123 |
@app.default |
| 124 |
def foo(*age: Annotated[int, Parameter(validator=validator)]): |
| 125 |
pass |
| 126 |
|
| 127 |
assert_parse_args(foo, "10", 10) |
| 128 |
validator.assert_called_once_with(int, 10) |
| 129 |
|
| 130 |
|
| 131 |
def test_custom_validators(app, assert_parse_args): |
| 132 |
def lower_bound(type_, value): |
| 133 |
if value <= 0: |
| 134 |
raise ValueError("An unreasonable age was entered.") |
| 135 |
|
| 136 |
def upper_bound(type_, value): |
| 137 |
if value > 150: |
| 138 |
raise ValueError("An unreasonable age was entered.") |
| 139 |
|
| 140 |
@app.default |
| 141 |
def foo(age: Annotated[int, Parameter(validator=[lower_bound, upper_bound])]): |
| 142 |
pass |
| 143 |
|
| 144 |
assert_parse_args(foo, "10", 10) |
| 145 |
|
| 146 |
with pytest.raises(ValidationError): |
| 147 |
app.parse_args("0", print_error=False, exit_on_error=False) |
| 148 |
|
| 149 |
with pytest.raises(ValidationError): |
| 150 |
app.parse_args("200", print_error=False, exit_on_error=False) |
| 151 |
|
| 152 |
|
| 153 |
def test_custom_converter_and_validator(app, assert_parse_args, validator): |
| 154 |
def custom_validator(type_, value): |
| 155 |
if not (0 < value < 150): |
| 156 |
raise ValueError("An unreasonable age was entered.") |
| 157 |
|
| 158 |
def custom_converter(type_, tokens): |
| 159 |
return 2 * int(tokens[0].value) |
| 160 |
|
| 161 |
@app.default |
| 162 |
def foo(age: Annotated[int, Parameter(converter=custom_converter, validator=validator)]): |
| 163 |
pass |
| 164 |
|
| 165 |
assert_parse_args(foo, "5", 10) |
| 166 |
|
| 167 |
validator.assert_called_once_with(int, 10) |
| 168 |
|
| 169 |
|
| 170 |
def test_custom_validator_on_default_signature_value(app, validator): |
| 171 |
@app.default |
| 172 |
def foo(age: Annotated[int, Parameter(validator=validator)] = -1): |
| 173 |
pass |
| 174 |
|
| 175 |
app.parse_args("", print_error=False, exit_on_error=False) |
| 176 |
validator.assert_called_once_with(int, -1) |
| 177 |
|
| 178 |
|
| 179 |
def test_custom_command_validator(app, assert_parse_args): |
| 180 |
validator = Mock() |
| 181 |
|
| 182 |
@app.default(validator=validator) |
| 183 |
def foo(a: int, b: int, c: int): |
| 184 |
pass |
| 185 |
|
| 186 |
assert_parse_args(foo, "1 2 3", 1, 2, 3) |
| 187 |
validator.assert_called_once_with(a=1, b=2, c=3) |
| 188 |
|
| 189 |
|
| 190 |
def test_custom_converter_inside_class(app, mocker): |
| 191 |
converter = mocker.Mock(return_value=5) |
| 192 |
|
| 193 |
@Parameter(name="*") |
| 194 |
@dataclass |
| 195 |
class Config: |
| 196 |
foo: Annotated[int, Parameter(converter=converter)] |
| 197 |
|
| 198 |
@app.default |
| 199 |
def default(config: Config): |
| 200 |
pass |
| 201 |
|
| 202 |
app("bar") |
| 203 |
|
| 204 |
converter.assert_called_once_with(int, (Token(value="bar", source="cli"),)) |
| 205 |
|
| 206 |
|
| 207 |
def test_classmethod_validator_string_reference(app, assert_parse_args): |
| 208 |
"""String reference to a classmethod validator on a Parameter-decorated class.""" |
| 209 |
|
| 210 |
@Parameter(name="*", validator="validate") |
| 211 |
@dataclass |
| 212 |
class TextStyle: |
| 213 |
color: str |
| 214 |
bold: bool = False |
| 215 |
italic: bool = False |
| 216 |
|
| 217 |
@classmethod |
| 218 |
def validate(cls, value): |
| 219 |
if value.bold and value.italic: |
| 220 |
raise ValueError("Cannot use both --bold and --italic together.") |
| 221 |
|
| 222 |
@app.default |
| 223 |
def main(style: TextStyle): |
| 224 |
pass |
| 225 |
|
| 226 |
assert_parse_args(main, "--color red --bold", style=TextStyle(color="red", bold=True)) |
| 227 |
|
| 228 |
with pytest.raises(ValidationError): |
| 229 |
app.parse_args("--color red --bold --italic", print_error=False, exit_on_error=False) |
| 230 |
|
| 231 |
|
| 232 |
def test_classmethod_validator_direct_reference(app, assert_parse_args): |
| 233 |
"""Direct classmethod reference exercises the inspect.ismethod branch.""" |
| 234 |
|
| 235 |
@dataclass |
| 236 |
class TextStyle: |
| 237 |
color: str |
| 238 |
bold: bool = False |
| 239 |
italic: bool = False |
| 240 |
|
| 241 |
@classmethod |
| 242 |
def validate(cls, value): |
| 243 |
if value.bold and value.italic: |
| 244 |
raise ValueError("Cannot use both --bold and --italic together.") |
| 245 |
|
| 246 |
@app.default |
| 247 |
def main(style: Annotated[TextStyle, Parameter(name="*", validator=TextStyle.validate)]): |
| 248 |
pass |
| 249 |
|
| 250 |
assert_parse_args(main, "--color red --bold", style=TextStyle(color="red", bold=True)) |
| 251 |
|
| 252 |
with pytest.raises(ValidationError): |
| 253 |
app.parse_args("--color red --bold --italic", print_error=False, exit_on_error=False) |
| 254 |
|
| 255 |
|
| 256 |
def test_staticmethod_validator_string_reference(app, assert_parse_args): |
| 257 |
"""Staticmethods follow the (type_, value) calling convention.""" |
| 258 |
seen = {} |
| 259 |
|
| 260 |
@Parameter(name="*", validator="validate") |
| 261 |
@dataclass |
| 262 |
class TextStyle: |
| 263 |
color: str |
| 264 |
bold: bool = False |
| 265 |
|
| 266 |
@staticmethod |
| 267 |
def validate(type_, value): |
| 268 |
seen["type_"] = type_ |
| 269 |
seen["value"] = value |
| 270 |
if value.color == "invalid": |
| 271 |
raise ValueError("bad color") |
| 272 |
|
| 273 |
@app.default |
| 274 |
def main(style: TextStyle): |
| 275 |
pass |
| 276 |
|
| 277 |
assert_parse_args(main, "--color red --bold", style=TextStyle(color="red", bold=True)) |
| 278 |
assert seen["type_"] is TextStyle |
| 279 |
assert seen["value"] == TextStyle(color="red", bold=True) |
| 280 |
|
| 281 |
|
| 282 |
def test_staticmethod_validator_direct_reference(app, assert_parse_args): |
| 283 |
"""Direct staticmethod reference.""" |
| 284 |
|
| 285 |
@dataclass |
| 286 |
class TextStyle: |
| 287 |
color: str |
| 288 |
|
| 289 |
@staticmethod |
| 290 |
def validate(type_, value): |
| 291 |
if value.color == "invalid": |
| 292 |
raise ValueError("bad color") |
| 293 |
|
| 294 |
@app.default |
| 295 |
def main(style: Annotated[TextStyle, Parameter(name="*", validator=TextStyle.validate)]): |
| 296 |
pass |
| 297 |
|
| 298 |
assert_parse_args(main, "--color red", style=TextStyle(color="red")) |
| 299 |
|
| 300 |
with pytest.raises(ValidationError): |
| 301 |
app.parse_args("--color invalid", print_error=False, exit_on_error=False) |
| 302 |
|
| 303 |
|
| 304 |
def test_validator_string_reference_in_list(app, assert_parse_args): |
| 305 |
"""Strings can be intermixed with callables in a validator list.""" |
| 306 |
external_calls = [] |
| 307 |
|
| 308 |
def external(type_, value): |
| 309 |
external_calls.append(value) |
| 310 |
|
| 311 |
@Parameter(name="*", validator=["validate_a", external, "validate_b"]) |
| 312 |
@dataclass |
| 313 |
class Config: |
| 314 |
n: int |
| 315 |
|
| 316 |
@classmethod |
| 317 |
def validate_a(cls, value): |
| 318 |
if value.n < 0: |
| 319 |
raise ValueError("n must be >= 0") |
| 320 |
|
| 321 |
@classmethod |
| 322 |
def validate_b(cls, value): |
| 323 |
if value.n > 100: |
| 324 |
raise ValueError("n must be <= 100") |
| 325 |
|
| 326 |
@app.default |
| 327 |
def main(config: Config): |
| 328 |
pass |
| 329 |
|
| 330 |
assert_parse_args(main, "--n 5", config=Config(n=5)) |
| 331 |
assert external_calls == [Config(n=5)] |
| 332 |
|
| 333 |
with pytest.raises(ValidationError): |
| 334 |
app.parse_args("--n -1", print_error=False, exit_on_error=False) |
| 335 |
|
| 336 |
with pytest.raises(ValidationError): |
| 337 |
app.parse_args("--n 200", print_error=False, exit_on_error=False) |
| 338 |
|
| 339 |
|
| 340 |
def test_classmethod_validator_string_reference_nested_annotated(app, assert_parse_args): |
| 341 |
"""String validator on a nested Annotated type triggers the ``_convert`` validator path.""" |
| 342 |
seen = [] |
| 343 |
|
| 344 |
class Score(int): |
| 345 |
@classmethod |
| 346 |
def validate(cls, value): |
| 347 |
seen.append(value) |
| 348 |
if value > 100: |
| 349 |
raise ValueError("score too high") |
| 350 |
|
| 351 |
Validated = Annotated[Score, Parameter(validator="validate")] |
| 352 |
|
| 353 |
@app.default |
| 354 |
def main(scores: tuple[Validated, Validated]): |
| 355 |
pass |
| 356 |
|
| 357 |
assert_parse_args(main, "10 20", scores=(Score(10), Score(20))) |
| 358 |
assert seen == [10, 20] |
| 359 |
|
| 360 |
with pytest.raises(ValidationError): |
| 361 |
app.parse_args("10 200", print_error=False, exit_on_error=False) |
| 362 |
|
| 363 |
|
| 364 |
def test_staticmethod_validator_string_reference_nested_annotated(app, assert_parse_args): |
| 365 |
"""Staticmethod string validator on a nested Annotated follows the ``(type_, value)`` calling convention in ``_convert``.""" |
| 366 |
seen = [] |
| 367 |
|
| 368 |
class Score(int): |
| 369 |
@staticmethod |
| 370 |
def validate(type_, value): |
| 371 |
seen.append((type_, value)) |
| 372 |
if value > 100: |
| 373 |
raise ValueError("score too high") |
| 374 |
|
| 375 |
Validated = Annotated[Score, Parameter(validator="validate")] |
| 376 |
|
| 377 |
@app.default |
| 378 |
def main(scores: tuple[Validated, Validated]): |
| 379 |
pass |
| 380 |
|
| 381 |
assert_parse_args(main, "10 20", scores=(Score(10), Score(20))) |
| 382 |
assert seen == [(Score, 10), (Score, 20)] |
| 383 |
|
| 384 |
|
| 385 |
def test_classmethod_validator_string_reference_var_keyword(app, assert_parse_args): |
| 386 |
"""String validator with ``**kwargs`` exercises the ``VAR_KEYWORD`` branch in ``Argument.validate``.""" |
| 387 |
seen = [] |
| 388 |
|
| 389 |
class Bounded(int): |
| 390 |
@classmethod |
| 391 |
def validate(cls, value): |
| 392 |
seen.append(value) |
| 393 |
if value < 0: |
| 394 |
raise ValueError("must be non-negative") |
| 395 |
|
| 396 |
@app.default |
| 397 |
def main(**vals: Annotated[Bounded, Parameter(validator="validate")]): |
| 398 |
pass |
| 399 |
|
| 400 |
assert_parse_args(main, "--a=1 --b=2", a=Bounded(1), b=Bounded(2)) |
| 401 |
assert sorted(seen) == [1, 2] |
| 402 |
|
| 403 |
with pytest.raises(ValidationError): |
| 404 |
app.parse_args("--a=-1", print_error=False, exit_on_error=False) |
| 405 |
|
| 406 |
|
| 407 |
def test_staticmethod_validator_string_reference_var_keyword(app, assert_parse_args): |
| 408 |
"""Staticmethod string validator with ``**kwargs`` uses ``(type_, value)`` calling convention.""" |
| 409 |
seen = [] |
| 410 |
|
| 411 |
class Bounded(int): |
| 412 |
@staticmethod |
| 413 |
def validate(type_, value): |
| 414 |
seen.append((type_, value)) |
| 415 |
|
| 416 |
@app.default |
| 417 |
def main(**vals: Annotated[Bounded, Parameter(validator="validate")]): |
| 418 |
pass |
| 419 |
|
| 420 |
assert_parse_args(main, "--a=1 --b=2", a=Bounded(1), b=Bounded(2)) |
| 421 |
assert sorted(seen) == [(Bounded, 1), (Bounded, 2)] |
| 422 |
|
| 423 |
|
| 424 |
def test_classmethod_validator_string_reference_var_positional(app, assert_parse_args): |
| 425 |
"""String validator with ``*args`` exercises the ``VAR_POSITIONAL`` branch in ``Argument.validate``.""" |
| 426 |
seen = [] |
| 427 |
|
| 428 |
class Bounded(int): |
| 429 |
@classmethod |
| 430 |
def validate(cls, value): |
| 431 |
seen.append(value) |
| 432 |
if value < 0: |
| 433 |
raise ValueError("must be non-negative") |
| 434 |
|
| 435 |
@app.default |
| 436 |
def main(*vals: Annotated[Bounded, Parameter(validator="validate")]): |
| 437 |
pass |
| 438 |
|
| 439 |
assert_parse_args(main, "1 2 3", Bounded(1), Bounded(2), Bounded(3)) |
| 440 |
assert seen == [1, 2, 3] |
| 441 |
|
| 442 |
with pytest.raises(ValidationError): |
| 443 |
app.parse_args("1 -1", print_error=False, exit_on_error=False) |
| 444 |
|
| 445 |
|
| 446 |
def test_staticmethod_validator_string_reference_var_positional(app, assert_parse_args): |
| 447 |
"""Staticmethod string validator with ``*args`` uses ``(type_, value)`` calling convention.""" |
| 448 |
seen = [] |
| 449 |
|
| 450 |
class Bounded(int): |
| 451 |
@staticmethod |
| 452 |
def validate(type_, value): |
| 453 |
seen.append((type_, value)) |
| 454 |
|
| 455 |
@app.default |
| 456 |
def main(*vals: Annotated[Bounded, Parameter(validator="validate")]): |
| 457 |
pass |
| 458 |
|
| 459 |
assert_parse_args(main, "1 2", Bounded(1), Bounded(2)) |
| 460 |
assert seen == [(Bounded, 1), (Bounded, 2)] |