| 1 |
from dataclasses import dataclass |
| 2 |
from textwrap import dedent |
| 3 |
from typing import Annotated |
| 4 |
|
| 5 |
import pytest |
| 6 |
|
| 7 |
from cyclopts import ( |
| 8 |
App, |
| 9 |
Argument, |
| 10 |
ArgumentOrderError, |
| 11 |
CoercionError, |
| 12 |
MissingArgumentError, |
| 13 |
MixedArgumentError, |
| 14 |
Parameter, |
| 15 |
Token, |
| 16 |
UnknownCommandError, |
| 17 |
ValidationError, |
| 18 |
) |
| 19 |
|
| 20 |
|
| 21 |
def positive_validator(type_, value): |
| 22 |
if value <= 0: |
| 23 |
|
| 24 |
raise ValueError("Value must be positive.") |
| 25 |
|
| 26 |
|
| 27 |
def multi_positive_validator(type_, values): |
| 28 |
for value in values: |
| 29 |
if value <= 0: |
| 30 |
raise ValueError("Value must be positive.") |
| 31 |
|
| 32 |
|
| 33 |
def test_exceptions_missing_argument_single(app, console): |
| 34 |
@app.command |
| 35 |
def foo(bar: int): |
| 36 |
pass |
| 37 |
|
| 38 |
with console.capture() as capture, pytest.raises(MissingArgumentError): |
| 39 |
app("foo", error_console=console, exit_on_error=False) |
| 40 |
|
| 41 |
actual = capture.get() |
| 42 |
|
| 43 |
expected = dedent( |
| 44 |
"""\ |
| 45 |
╭─ Error ────────────────────────────────────────────────────────────╮ |
| 46 |
│ Command "foo" parameter --bar requires an argument. │ |
| 47 |
╰────────────────────────────────────────────────────────────────────╯ |
| 48 |
""" |
| 49 |
) |
| 50 |
|
| 51 |
assert actual == expected |
| 52 |
|
| 53 |
|
| 54 |
def test_exceptions_missing_argument_flag(app, console): |
| 55 |
@app.command |
| 56 |
def foo(bar: bool): |
| 57 |
pass |
| 58 |
|
| 59 |
with console.capture() as capture, pytest.raises(MissingArgumentError): |
| 60 |
app("foo", error_console=console, exit_on_error=False) |
| 61 |
|
| 62 |
actual = capture.get() |
| 63 |
|
| 64 |
expected = dedent( |
| 65 |
"""\ |
| 66 |
╭─ Error ────────────────────────────────────────────────────────────╮ |
| 67 |
│ Command "foo" parameter --bar flag required. │ |
| 68 |
╰────────────────────────────────────────────────────────────────────╯ |
| 69 |
""" |
| 70 |
) |
| 71 |
|
| 72 |
assert actual == expected |
| 73 |
|
| 74 |
|
| 75 |
def test_exceptions_missing_argument_with_short_flag(app, console): |
| 76 |
"""Error message should reference the flag actually used, not the canonical name.""" |
| 77 |
|
| 78 |
@app.command |
| 79 |
def foo(option: Annotated[int, Parameter(alias="-o")]): |
| 80 |
pass |
| 81 |
|
| 82 |
with console.capture() as capture, pytest.raises(MissingArgumentError): |
| 83 |
|
| 84 |
app("foo -o", error_console=console, exit_on_error=False) |
| 85 |
|
| 86 |
actual = capture.get() |
| 87 |
|
| 88 |
expected = dedent( |
| 89 |
"""\ |
| 90 |
╭─ Error ────────────────────────────────────────────────────────────╮ |
| 91 |
│ Command "foo" parameter -o requires an argument. │ |
| 92 |
╰────────────────────────────────────────────────────────────────────╯ |
| 93 |
""" |
| 94 |
) |
| 95 |
|
| 96 |
assert actual == expected |
| 97 |
|
| 98 |
|
| 99 |
def test_exceptions_validation_error_cli_single_positional(app, console): |
| 100 |
argument = Argument( |
| 101 |
hint=int, |
| 102 |
parameter=Parameter(name=("--bar",), validator=positive_validator), |
| 103 |
tokens=[ |
| 104 |
Token(keyword=None, value="-2", source="cli"), |
| 105 |
], |
| 106 |
) |
| 107 |
with pytest.raises(ValidationError) as e: |
| 108 |
argument.convert_and_validate() |
| 109 |
|
| 110 |
expected = dedent( |
| 111 |
""" |
| 112 |
ValidationError |
| 113 |
Invalid value "-2" for BAR. Value must be positive. |
| 114 |
""" |
| 115 |
).strip() |
| 116 |
assert str(e.value) == expected |
| 117 |
|
| 118 |
|
| 119 |
def test_exceptions_validation_error_cli_single_keyword(app, console): |
| 120 |
argument = Argument( |
| 121 |
hint=int, |
| 122 |
parameter=Parameter(name=("--bar",), validator=positive_validator), |
| 123 |
tokens=[ |
| 124 |
Token(keyword="--bar", value="-2", source="cli"), |
| 125 |
], |
| 126 |
) |
| 127 |
with pytest.raises(ValidationError) as e: |
| 128 |
argument.convert_and_validate() |
| 129 |
|
| 130 |
expected = dedent( |
| 131 |
""" |
| 132 |
ValidationError |
| 133 |
Invalid value "-2" for --bar. Value must be positive. |
| 134 |
""" |
| 135 |
).strip() |
| 136 |
assert str(e.value) == expected |
| 137 |
|
| 138 |
|
| 139 |
def test_exceptions_validation_error_class(app, console): |
| 140 |
"""Double checks that error message is appropriately handled for class validators. |
| 141 |
|
| 142 |
https://github.com/BrianPugh/cyclopts/issues/432 |
| 143 |
""" |
| 144 |
|
| 145 |
def v(type_, value): |
| 146 |
raise ValueError("My custom message.") |
| 147 |
|
| 148 |
@Parameter(validator=v) |
| 149 |
@dataclass |
| 150 |
class Movie: |
| 151 |
title: str |
| 152 |
year: int |
| 153 |
|
| 154 |
@app.command |
| 155 |
def add(movie: Movie): |
| 156 |
pass |
| 157 |
|
| 158 |
with pytest.raises(ValidationError) as e: |
| 159 |
app("add foo 2020", exit_on_error=False) |
| 160 |
|
| 161 |
expected = """My custom message.""" |
| 162 |
assert str(e.value) == expected |
| 163 |
|
| 164 |
|
| 165 |
def test_exceptions_validation_error_non_cli_single_keyword(app, console): |
| 166 |
argument = Argument( |
| 167 |
hint=int, |
| 168 |
parameter=Parameter(name=("--bar",), validator=positive_validator), |
| 169 |
tokens=[ |
| 170 |
Token(value="-2", source="test"), |
| 171 |
], |
| 172 |
) |
| 173 |
with pytest.raises(ValidationError) as e: |
| 174 |
argument.convert_and_validate() |
| 175 |
|
| 176 |
expected = dedent( |
| 177 |
""" |
| 178 |
ValidationError |
| 179 |
Invalid value "-2" for BAR provided by test. Value must be positive. |
| 180 |
""" |
| 181 |
).strip() |
| 182 |
assert str(e.value) == expected |
| 183 |
|
| 184 |
|
| 185 |
def test_exceptions_validation_error_cli_multi_positional(app, console): |
| 186 |
argument = Argument( |
| 187 |
hint=tuple[int, int], |
| 188 |
parameter=Parameter(name=("--bar",), validator=multi_positive_validator), |
| 189 |
tokens=[ |
| 190 |
Token(keyword=None, value="100", source="cli"), |
| 191 |
Token(keyword=None, value="-2", source="cli"), |
| 192 |
], |
| 193 |
) |
| 194 |
with pytest.raises(ValidationError) as e: |
| 195 |
argument.convert_and_validate() |
| 196 |
|
| 197 |
expected = dedent( |
| 198 |
""" |
| 199 |
ValidationError |
| 200 |
Invalid value "(100, -2)" for BAR. Value must be positive. |
| 201 |
""" |
| 202 |
).strip() |
| 203 |
assert str(e.value) == expected |
| 204 |
|
| 205 |
|
| 206 |
def test_exceptions_validation_error_cli_multi_keyword(app, console): |
| 207 |
argument = Argument( |
| 208 |
hint=tuple[int, int], |
| 209 |
parameter=Parameter(name=("--bar",), validator=multi_positive_validator), |
| 210 |
tokens=[ |
| 211 |
Token(keyword="--bar", value="100", source="cli"), |
| 212 |
Token(keyword="--bar", value="-2", source="cli"), |
| 213 |
], |
| 214 |
) |
| 215 |
with pytest.raises(ValidationError) as e: |
| 216 |
argument.convert_and_validate() |
| 217 |
|
| 218 |
expected = dedent( |
| 219 |
""" |
| 220 |
ValidationError |
| 221 |
Invalid value "(100, -2)" for --bar. Value must be positive. |
| 222 |
""" |
| 223 |
).strip() |
| 224 |
assert str(e.value) == expected |
| 225 |
|
| 226 |
|
| 227 |
def test_exceptions_coercion_error_from_positional_cli(app, console): |
| 228 |
@app.command |
| 229 |
def foo(bar: int): |
| 230 |
pass |
| 231 |
|
| 232 |
with console.capture() as capture, pytest.raises(CoercionError): |
| 233 |
app("foo fizz", error_console=console, exit_on_error=False) |
| 234 |
|
| 235 |
actual = capture.get() |
| 236 |
|
| 237 |
expected = dedent( |
| 238 |
"""\ |
| 239 |
╭─ Error ────────────────────────────────────────────────────────────╮ |
| 240 |
│ Invalid value for BAR: unable to convert "fizz" into int. │ |
| 241 |
╰────────────────────────────────────────────────────────────────────╯ |
| 242 |
""" |
| 243 |
) |
| 244 |
|
| 245 |
assert actual == expected |
| 246 |
|
| 247 |
|
| 248 |
def test_exceptions_coercion_error_from_keyword_cli(app, console): |
| 249 |
@app.command |
| 250 |
def foo(bar: Annotated[int, Parameter(name=("--bar", "-b"))]): |
| 251 |
pass |
| 252 |
|
| 253 |
with console.capture() as capture, pytest.raises(CoercionError): |
| 254 |
app("foo -b fizz", error_console=console, exit_on_error=False) |
| 255 |
|
| 256 |
actual = capture.get() |
| 257 |
|
| 258 |
expected = dedent( |
| 259 |
"""\ |
| 260 |
╭─ Error ────────────────────────────────────────────────────────────╮ |
| 261 |
│ Invalid value for -b: unable to convert "fizz" into int. │ |
| 262 |
╰────────────────────────────────────────────────────────────────────╯ |
| 263 |
""" |
| 264 |
) |
| 265 |
|
| 266 |
assert actual == expected |
| 267 |
|
| 268 |
|
| 269 |
def test_exceptions_coercion_error_verbose(app, console): |
| 270 |
@app.command |
| 271 |
def foo(bar: int): |
| 272 |
pass |
| 273 |
|
| 274 |
with console.capture() as capture, pytest.raises(CoercionError): |
| 275 |
app("foo fizz", error_console=console, exit_on_error=False, verbose=True) |
| 276 |
|
| 277 |
actual = capture.get() |
| 278 |
|
| 279 |
expected = dedent( |
| 280 |
"""\ |
| 281 |
╭─ Error ────────────────────────────────────────────────────────────╮ |
| 282 |
│ CoercionError │ |
| 283 |
""" |
| 284 |
) |
| 285 |
assert actual.startswith(expected) |
| 286 |
|
| 287 |
expected = dedent( |
| 288 |
"""\ |
| 289 |
│ foo(bar: int) │ |
| 290 |
│ Root Input Tokens: ['foo', 'fizz'] │ |
| 291 |
│ Invalid value for BAR: unable to convert "fizz" into int. │ |
| 292 |
╰────────────────────────────────────────────────────────────────────╯ |
| 293 |
""" |
| 294 |
) |
| 295 |
assert actual.endswith(expected) |
| 296 |
|
| 297 |
|
| 298 |
def test_exceptions_mixed_argument_error(app, console): |
| 299 |
@app.default |
| 300 |
def foo(bar: int | dict): |
| 301 |
pass |
| 302 |
|
| 303 |
with console.capture() as capture, pytest.raises(MixedArgumentError): |
| 304 |
app("--bar 5 --bar.baz fizz", error_console=console, exit_on_error=False) |
| 305 |
|
| 306 |
actual = capture.get() |
| 307 |
|
| 308 |
expected = dedent( |
| 309 |
"""\ |
| 310 |
╭─ Error ────────────────────────────────────────────────────────────╮ |
| 311 |
│ Cannot supply keyword & non-keyword arguments to --bar. │ |
| 312 |
╰────────────────────────────────────────────────────────────────────╯ |
| 313 |
""" |
| 314 |
) |
| 315 |
assert actual == expected |
| 316 |
|
| 317 |
|
| 318 |
def test_exceptions_unknown_command(app, console): |
| 319 |
@app.command |
| 320 |
def foo(bar: int): |
| 321 |
pass |
| 322 |
|
| 323 |
with console.capture() as capture, pytest.raises(UnknownCommandError): |
| 324 |
app("bar fizz", error_console=console, exit_on_error=False) |
| 325 |
|
| 326 |
actual = capture.get() |
| 327 |
|
| 328 |
expected = dedent( |
| 329 |
"""\ |
| 330 |
╭─ Error ────────────────────────────────────────────────────────────╮ |
| 331 |
│ Unknown command "bar". Available commands: foo. │ |
| 332 |
╰────────────────────────────────────────────────────────────────────╯ |
| 333 |
""" |
| 334 |
) |
| 335 |
|
| 336 |
assert actual == expected |
| 337 |
|
| 338 |
|
| 339 |
def test_exceptions_argument_order_error_singular(app, console): |
| 340 |
@app.command |
| 341 |
def foo(a, b, c): |
| 342 |
pass |
| 343 |
|
| 344 |
with console.capture() as capture, pytest.raises(ArgumentOrderError): |
| 345 |
app("foo --b=5 1 2", error_console=console, exit_on_error=False) |
| 346 |
|
| 347 |
actual = capture.get() |
| 348 |
|
| 349 |
expected = dedent( |
| 350 |
"""\ |
| 351 |
╭─ Error ────────────────────────────────────────────────────────────╮ |
| 352 |
│ Cannot specify token "2" positionally for parameter c due to │ |
| 353 |
│ previously specified keyword --b. --b must either be passed │ |
| 354 |
│ positionally, or "2" must be passed as a keyword to --c. │ |
| 355 |
╰────────────────────────────────────────────────────────────────────╯ |
| 356 |
""" |
| 357 |
) |
| 358 |
|
| 359 |
assert actual == expected |
| 360 |
|
| 361 |
|
| 362 |
def test_exceptions_argument_order_error_plural(app, console): |
| 363 |
@app.command |
| 364 |
def foo(a, b, c): |
| 365 |
pass |
| 366 |
|
| 367 |
with console.capture() as capture, pytest.raises(ArgumentOrderError): |
| 368 |
app("foo --a=1 --b=5 3", error_console=console, exit_on_error=False) |
| 369 |
|
| 370 |
actual = capture.get() |
| 371 |
|
| 372 |
expected = dedent( |
| 373 |
"""\ |
| 374 |
╭─ Error ────────────────────────────────────────────────────────────╮ |
| 375 |
│ Cannot specify token "3" positionally for parameter c due to │ |
| 376 |
│ previously specified keywords ['--a', '--b']. ['--a', '--b'] must │ |
| 377 |
│ either be passed positionally, or "3" must be passed as a keyword │ |
| 378 |
│ to --c. │ |
| 379 |
╰────────────────────────────────────────────────────────────────────╯ |
| 380 |
""" |
| 381 |
) |
| 382 |
|
| 383 |
assert actual == expected |
| 384 |
|
| 385 |
|
| 386 |
def test_exceptions_combined_short_option_error(app, console): |
| 387 |
"""With GNU-style support, -bo is now valid: -b with value 'o'. |
| 388 |
|
| 389 |
The CombinedShortOptionError for mixing value-taking options is no longer possible |
| 390 |
because the first value-taking option consumes the rest of the string as its value. |
| 391 |
This test now verifies that GNU-style combinations work correctly. |
| 392 |
""" |
| 393 |
|
| 394 |
@app.command |
| 395 |
def foo( |
| 396 |
*, |
| 397 |
bar: Annotated[str, Parameter(name=("--bar", "-b"))], |
| 398 |
): |
| 399 |
pass |
| 400 |
|
| 401 |
|
| 402 |
_, bound, _ = app.parse_args("foo -bo", exit_on_error=False) |
| 403 |
assert bound.arguments["bar"] == "o" |
| 404 |
|
| 405 |
|
| 406 |
def test_unknown_option_starting_with_h(): |
| 407 |
"""Test that --h (not --help) is treated as an unknown option, not a NameError. |
| 408 |
|
| 409 |
Previously, passing --h would trigger a NameError about Console not being defined, |
| 410 |
because it would try to inspect the help_print method's signature which had a |
| 411 |
forward reference to Console that wasn't available at runtime. |
| 412 |
|
| 413 |
From issue #697. |
| 414 |
""" |
| 415 |
app = App(exit_on_error=False) |
| 416 |
|
| 417 |
@app.default |
| 418 |
def foo(loops: int): |
| 419 |
for i in range(loops): |
| 420 |
print(f"Looping! {i}") |
| 421 |
|
| 422 |
|
| 423 |
with pytest.raises(Exception) as exc_info: |
| 424 |
app.parse_args(["--h"]) |
| 425 |
|
| 426 |
|
| 427 |
assert not (isinstance(exc_info.value, NameError) and "Console" in str(exc_info.value)) |
| 428 |
|
| 429 |
|
| 430 |
assert "Unknown option" in str(exc_info.value) or "unknown" in str(exc_info.value).lower() |