Debian Codegraph @

tests/test_parameter_n_tokens.py

raw symbols SCIP
1 """Tests for Parameter.n_tokens feature (issue #646)."""
2
3 from typing import Annotated
4
5 import pytest
6
7 from cyclopts import Parameter
8 from cyclopts.exceptions import MissingArgumentError
9
10
11 def test_n_tokens_basic_custom_converter(app, assert_parse_args):
12 """Test n_tokens=1 with custom converter that loads a complex type from a single token."""
13
14 class ComplexType:
15 """A type that normally requires multiple tokens but can be loaded from a file."""
16
17 def __init__(self, name: str, value: int):
18 self.name = name
19 self.value = value
20
21 def __eq__(self, other):
22 return self.name == other.name and self.value == other.value
23
24 def load_from_id(type_, tokens):
25 """Custom converter that loads ComplexType from a single ID token."""
26 id_value = tokens[0].value
27 # Simulate loading from database/file based on ID
28 return ComplexType(name=f"loaded_{id_value}", value=int(id_value) * 100)
29
30 @app.default
31 def foo(obj: Annotated[ComplexType, Parameter(n_tokens=1, converter=load_from_id, accepts_keys=False)]):
32 pass
33
34 assert_parse_args(foo, "5", obj=ComplexType(name="loaded_5", value=500))
35
36
37 def test_n_tokens_two_tokens(app, assert_parse_args):
38 """Test n_tokens=2 with custom converter."""
39
40 def combine_tokens(type_, tokens):
41 """Custom converter that combines two tokens."""
42 return f"{tokens[0].value}:{tokens[1].value}"
43
44 @app.default
45 def foo(*, value: Annotated[str, Parameter(n_tokens=2, converter=combine_tokens)]):
46 pass
47
48 assert_parse_args(foo, "--value hello world", value="hello:world")
49
50
51 def test_n_tokens_consume_all(app, assert_parse_args):
52 """Test n_tokens=-1 to consume all remaining tokens."""
53
54 def join_all(type_, tokens):
55 """Custom converter that joins all tokens."""
56 return " ".join(t.value for t in tokens)
57
58 @app.default
59 def foo(*, msg: Annotated[str, Parameter(n_tokens=-1, consume_multiple=True, converter=join_all)]):
60 pass
61
62 assert_parse_args(foo, "--msg hello world from cyclopts", msg="hello world from cyclopts")
63
64
65 def test_n_tokens_var_positional(app, assert_parse_args):
66 """Test n_tokens with *args to verify per-element behavior."""
67
68 def pair_converter(type_, tokens):
69 """Convert two tokens into a tuple."""
70 return (tokens[0].value, int(tokens[1].value))
71
72 @app.default
73 def foo(*pairs: Annotated[tuple[str, int], Parameter(n_tokens=2, converter=pair_converter)]):
74 pass
75
76 assert_parse_args(foo, "alice 10 bob 20 charlie 30", ("alice", 10), ("bob", 20), ("charlie", 30))
77
78
79 def test_n_tokens_without_converter(app, assert_parse_args):
80 """Test n_tokens works without custom converter (though, a bit non-sensical)."""
81
82 @app.default
83 def foo(*, values: Annotated[tuple[int, int], Parameter(n_tokens=2)]):
84 pass
85
86 assert_parse_args(foo, "--values 10 20", values=(10, 20))
87
88
89 def test_n_tokens_error_message(app):
90 """Test that error messages reflect custom n_tokens."""
91
92 def failing_converter(type_, tokens):
93 """Converter that expects 2 tokens."""
94 return int(tokens[0].value) + int(tokens[1].value)
95
96 @app.default
97 def foo(*, value: Annotated[int, Parameter(n_tokens=2, converter=failing_converter)]):
98 return value
99
100 # Provide only 1 token when 2 are expected
101 with pytest.raises(MissingArgumentError) as exc_info:
102 app("--value 10", exit_on_error=False)
103
104 # The error should mention that 2 tokens are required
105 assert "2" in str(exc_info.value)
106
107
108 def test_n_tokens_accepts_keys_false(app, assert_parse_args):
109 """Test n_tokens with accepts_keys=False."""
110
111 class Config:
112 """A config type that would normally have sub-keys."""
113
114 def __init__(self, host: str, port: int):
115 self.host = host
116 self.port = port
117
118 def __eq__(self, other):
119 return self.host == other.host and self.port == other.port
120
121 def load_config(type_, tokens):
122 """Load config from a file path."""
123 # Simulate loading from a file
124 filepath = tokens[0].value
125 if filepath == "prod.conf":
126 return Config("prod.example.com", 443)
127 else:
128 return Config("dev.example.com", 8080)
129
130 @app.default
131 def foo(*, config: Annotated[Config, Parameter(n_tokens=1, converter=load_config, accepts_keys=False)]):
132 pass
133
134 assert_parse_args(foo, "--config prod.conf", config=Config("prod.example.com", 443))
135
136
137 def test_n_tokens_with_iterable_type(app, assert_parse_args):
138 """Test n_tokens with list type to override default consume-all behavior."""
139
140 def limited_list_converter(type_, tokens):
141 """Convert exactly 3 tokens into a list."""
142 return [int(t.value) for t in tokens]
143
144 @app.default
145 def foo(*, values: Annotated[list[int], Parameter(n_tokens=3, converter=limited_list_converter)]):
146 pass
147
148 assert_parse_args(foo, "--values 10 20 30", values=[10, 20, 30])
149
150
151 def test_n_tokens_positional_arg(app, assert_parse_args):
152 """Test n_tokens with positional arguments."""
153
154 def pair_converter(type_, tokens):
155 """Convert two tokens into a string."""
156 return f"{tokens[0].value}-{tokens[1].value}"
157
158 @app.default
159 def foo(pair: Annotated[str, Parameter(n_tokens=2, converter=pair_converter)]):
160 pass
161
162 assert_parse_args(foo, "hello world", pair="hello-world")
163
164
165 def test_n_tokens_kwargs(app, assert_parse_args):
166 """Test n_tokens with **kwargs - each value should consume n_tokens."""
167
168 def pair_converter(type_, tokens):
169 """Combine two tokens with a dash."""
170 return f"{tokens[0].value}-{tokens[1].value}"
171
172 @app.default
173 def foo(**kwargs: Annotated[str, Parameter(n_tokens=2, converter=pair_converter)]):
174 pass
175
176 assert_parse_args(foo, "--key1 a b --key2 c d", key1="a-b", key2="c-d")
177
178
179 def test_n_tokens_dict_type(app, assert_parse_args):
180 """Test n_tokens with dict type - each value should consume n_tokens."""
181
182 def dict_converter(type_, tokens):
183 """Convert dict where each value is 2 tokens combined."""
184 result = {}
185 for key, token_list in tokens.items():
186 # Each value should have 2 tokens
187 result[key] = f"{token_list[0].value}:{token_list[1].value}"
188 return result
189
190 @app.default
191 def foo(*, config: Annotated[dict[str, str], Parameter(n_tokens=2, converter=dict_converter)]):
192 pass
193
194 assert_parse_args(
195 foo,
196 "--config.host localhost 8080 --config.db postgres 5432",
197 config={"host": "localhost:8080", "db": "postgres:5432"},
198 )
199
200
201 def test_n_tokens_tuple_element_without_converter(app, assert_parse_args):
202 """Test n_tokens on tuple elements without custom converter.
203
204 Note: n_tokens works for token counting, but the tuple gets a list of values
205 instead of a combined string since there's no custom converter at the element level.
206 """
207
208 @app.default
209 def foo(
210 data: tuple[
211 Annotated[list[str], Parameter(n_tokens=2)], # Will be list of 2 strings
212 int,
213 ],
214 ):
215 pass
216
217 assert_parse_args(foo, "a b 10", data=(["a", "b"], 10))
218
219
220 def test_n_tokens_list_consume_all(app, assert_parse_args):
221 """Test that n_tokens with list correctly maintains consume_all behavior.
222
223 When n_tokens is used with a list, the converter receives ALL tokens and must
224 handle the grouping itself. The n_tokens value affects how many tokens are consumed
225 from the CLI, maintaining consume_all behavior for iterables.
226 """
227
228 def list_converter(type_, tokens):
229 """Group tokens into pairs and combine them."""
230 from cyclopts.utils import grouper
231
232 pairs = grouper(tokens, 2)
233 return [f"{a.value}-{b.value}" for a, b in pairs]
234
235 @app.default
236 def foo(*, items: Annotated[list[str], Parameter(n_tokens=2, converter=list_converter, consume_multiple=True)]):
237 pass
238
239 assert_parse_args(foo, "--items a b c d e f", items=["a-b", "c-d", "e-f"])
240
241
242 def test_n_tokens_decorated_converter(app, assert_parse_args):
243 """Test that converter functions decorated with @Parameter(n_tokens=...) use that value."""
244
245 class ComplexType:
246 """A type that normally requires multiple tokens but can be loaded from a single token."""
247
248 def __init__(self, name: str, value: int):
249 self.name = name
250 self.value = value
251
252 def __eq__(self, other):
253 return self.name == other.name and self.value == other.value
254
255 @Parameter(n_tokens=1, accepts_keys=False)
256 def load_from_id(type_, tokens):
257 """Custom converter decorated with n_tokens=1."""
258 id_value = tokens[0].value
259 return ComplexType(name=f"loaded_{id_value}", value=int(id_value) * 100)
260
261 @app.default
262 def foo(obj: Annotated[ComplexType, Parameter(converter=load_from_id)]):
263 pass
264
265 assert_parse_args(foo, "5", obj=ComplexType(name="loaded_5", value=500))
266
267
268 def test_n_tokens_decorated_converter_with_option(app, assert_parse_args):
269 """Test decorated converter with keyword option."""
270
271 @Parameter(n_tokens=2)
272 def combine_two(type_, tokens):
273 """Converter that combines two tokens."""
274 return f"{tokens[0].value}+{tokens[1].value}"
275
276 @app.default
277 def foo(*, value: Annotated[str, Parameter(converter=combine_two)]):
278 pass
279
280 assert_parse_args(foo, "--value hello world", value="hello+world")
281
282
283 def test_n_tokens_signature_overrides_decorated_converter(app, assert_parse_args):
284 """Test that n_tokens in signature annotation takes priority over decorated converter."""
285
286 @Parameter(n_tokens=2)
287 def combine_two(type_, tokens):
288 """Converter decorated with n_tokens=2."""
289 return f"{tokens[0].value}+{tokens[1].value}"
290
291 @Parameter(n_tokens=3)
292 def combine_three(type_, tokens):
293 """Converter decorated with n_tokens=3, but signature will override."""
294 # Even though decorated with n_tokens=3, signature says n_tokens=2
295 return f"{tokens[0].value}+{tokens[1].value}"
296
297 @app.default
298 def foo(
299 *,
300 # Signature explicitly sets n_tokens=2, which should override the decorator's n_tokens=3
301 value: Annotated[str, Parameter(n_tokens=2, converter=combine_three)],
302 ):
303 pass
304
305 # Should consume 2 tokens (from signature), not 3 (from decorator)
306 assert_parse_args(foo, "--value hello world", value="hello+world")
307
308
309 def test_n_tokens_decorated_converter_var_positional(app, assert_parse_args):
310 """Test decorated converter with *args."""
311
312 @Parameter(n_tokens=2)
313 def pair_converter(type_, tokens):
314 """Convert two tokens into a tuple."""
315 return (tokens[0].value, int(tokens[1].value))
316
317 @app.default
318 def foo(*pairs: Annotated[tuple[str, int], Parameter(converter=pair_converter)]):
319 pass
320
321 assert_parse_args(foo, "alice 10 bob 20", ("alice", 10), ("bob", 20))
322
323
324 def test_n_tokens_decorated_converter_kwargs(app, assert_parse_args):
325 """Test decorated converter with **kwargs."""
326
327 @Parameter(n_tokens=2)
328 def pair_converter(type_, tokens):
329 """Combine two tokens with a colon."""
330 return f"{tokens[0].value}:{tokens[1].value}"
331
332 @app.default
333 def foo(**config: Annotated[str, Parameter(converter=pair_converter)]):
334 pass
335
336 assert_parse_args(foo, "--host localhost 8080 --db postgres 5432", host="localhost:8080", db="postgres:5432")
337
338
339 def test_accepts_keys_signature_overrides_decorated_converter(app):
340 """Test that accepts_keys in signature takes priority over decorated converter.
341
342 When signature sets accepts_keys=True, it should override the converter's accepts_keys=False
343 and allow the argument collection to be built with sub-keys.
344 """
345
346 class Config:
347 def __init__(self, host: str = "localhost", port: int = 8080):
348 self.host = host
349 self.port = port
350
351 @Parameter(accepts_keys=False, n_tokens=1)
352 def load_from_file(type_, tokens):
353 """Converter that loads from a file (decorated with accepts_keys=False)."""
354 # Simulate loading from file based on tokens[0].value
355 return Config("file.example.com", 443)
356
357 @app.default
358 def foo(
359 *,
360 # Signature explicitly sets accepts_keys=True to allow sub-keys
361 # This should override the converter's accepts_keys=False
362 config: Annotated[Config, Parameter(converter=load_from_file, accepts_keys=True)],
363 ):
364 pass
365
366 # With accepts_keys=True in signature, sub-keys like --config.host should be recognized
367 # (even though converter says accepts_keys=False)
368 # This verifies that the signature setting takes priority
369 argument_collection = app.assemble_argument_collection()
370
371 # Should have child arguments for host and port since accepts_keys=True
372 config_arg = argument_collection[0]
373 assert config_arg.name == "--config"
374 assert len(list(config_arg.children)) > 0 # Should have children
375
376
377 def test_n_tokens_class_decorated_with_converter(app, assert_parse_args):
378 """Test that a class decorated with @Parameter(converter=...) inherits the converter's n_tokens.
379
380 When a class is decorated with @Parameter(converter=load_from_id), and the converter itself
381 is decorated with @Parameter(n_tokens=1, accepts_keys=False), the class should automatically
382 use those settings without needing an Annotated wrapper in the function signature.
383 """
384
385 @Parameter(n_tokens=1, accepts_keys=False)
386 def load_from_id(type_, tokens):
387 """Custom converter decorated with n_tokens=1."""
388 id_value = tokens[0].value
389 # Simulate loading from database/file based on ID
390 return type_(name=f"loaded_{id_value}", value=int(id_value) * 100)
391
392 @Parameter(converter=load_from_id)
393 class ComplexType:
394 """A type with a converter attached via class decorator."""
395
396 def __init__(self, name: str, value: int):
397 self.name = name
398 self.value = value
399
400 def __eq__(self, other):
401 return self.name == other.name and self.value == other.value
402
403 @app.default
404 def foo(obj: ComplexType):
405 pass
406
407 # The converter's n_tokens=1 should be inherited from the class decoration
408 assert_parse_args(foo, "5", obj=ComplexType(name="loaded_5", value=500))
409
410
411 def test_classmethod_converter_string_reference(app, assert_parse_args):
412 """Test that string references to classmethods work as converters."""
413
414 @Parameter(converter="from_id", n_tokens=1, accepts_keys=False)
415 class Config:
416 def __init__(self, host: str, port: int):
417 self.host = host
418 self.port = port
419
420 @classmethod
421 def from_id(cls, tokens):
422 config_id = tokens[0].value
423 return cls(host=f"server-{config_id}.example.com", port=443)
424
425 def __eq__(self, other):
426 return self.host == other.host and self.port == other.port
427
428 @app.default
429 def foo(config: Config):
430 pass
431
432 assert_parse_args(foo, "prod", config=Config(host="server-prod.example.com", port=443))
433
434
435 def test_classmethod_converter_direct_reference(app, assert_parse_args):
436 """Test that direct classmethod references work as converters."""
437
438 class Config:
439 def __init__(self, host: str, port: int):
440 self.host = host
441 self.port = port
442
443 @classmethod
444 def from_id(cls, tokens):
445 config_id = tokens[0].value
446 return cls(host=f"server-{config_id}.example.com", port=443)
447
448 def __eq__(self, other):
449 return self.host == other.host and self.port == other.port
450
451 @app.default
452 def foo(config: Annotated[Config, Parameter(converter=Config.from_id, n_tokens=1, accepts_keys=False)]):
453 pass
454
455 assert_parse_args(foo, "prod", config=Config(host="server-prod.example.com", port=443))
456
457
458 def test_classmethod_converter_with_parameter_decoration(app, assert_parse_args):
459 """Test that @Parameter on classmethods (above @classmethod) works correctly."""
460
461 class Config:
462 def __init__(self, host: str, port: int):
463 self.host = host
464 self.port = port
465
466 @Parameter(n_tokens=1, accepts_keys=False)
467 @classmethod
468 def from_id(cls, tokens):
469 config_id = tokens[0].value
470 return cls(host=f"server-{config_id}.example.com", port=443)
471
472 def __eq__(self, other):
473 return self.host == other.host and self.port == other.port
474
475 @app.default
476 def foo(config: Annotated[Config, Parameter(converter=Config.from_id)]):
477 pass
478
479 # n_tokens=1 should be inherited from the classmethod's @Parameter decoration
480 assert_parse_args(foo, "prod", config=Config(host="server-prod.example.com", port=443))
481
482
483 def test_classmethod_string_reference_with_n_tokens(app, assert_parse_args):
484 """Test string reference with explicit n_tokens on class decoration."""
485
486 @Parameter(converter="from_id", n_tokens=1, accepts_keys=False)
487 class Config:
488 def __init__(self, host: str, port: int):
489 self.host = host
490 self.port = port
491
492 @classmethod
493 def from_id(cls, tokens):
494 config_id = tokens[0].value
495 return cls(host=f"server-{config_id}.example.com", port=443)
496
497 def __eq__(self, other):
498 return self.host == other.host and self.port == other.port
499
500 @app.default
501 def foo(config: Config):
502 pass
503
504 assert_parse_args(foo, "prod", config=Config(host="server-prod.example.com", port=443))
505
506
507 def test_classmethod_inherits_parameter_from_method(app, assert_parse_args):
508 """Test that class decoration with classmethod inherits @Parameter from the method."""
509
510 @Parameter(converter="from_id")
511 class Config:
512 def __init__(self, host: str, port: int):
513 self.host = host
514 self.port = port
515
516 @Parameter(n_tokens=1, accepts_keys=False)
517 @classmethod
518 def from_id(cls, tokens):
519 config_id = tokens[0].value
520 return cls(host=f"server-{config_id}.example.com", port=443)
521
522 def __eq__(self, other):
523 return self.host == other.host and self.port == other.port
524
525 @app.default
526 def foo(config: Config):
527 pass
528
529 # n_tokens=1 should be inherited from the classmethod's decoration
530 assert_parse_args(foo, "prod", config=Config(host="server-prod.example.com", port=443))
531
532
533 def test_staticmethod_converter(app, assert_parse_args):
534 """Test that staticmethods can be used as converters."""
535
536 class Processor:
537 @staticmethod
538 def parse(type_, tokens):
539 value = int(tokens[0].value)
540 return type_(value * 2)
541
542 @app.default
543 def foo(value: Annotated[int, Parameter(converter=Processor.parse)]):
544 pass
545
546 assert_parse_args(foo, "5", value=10)