Debian Codegraph @

tests/test_result_action.py

raw symbols SCIP
1 """Tests for App result_action parameter with explicit naming."""
2
3 from contextlib import redirect_stdout
4 from io import StringIO
5 from typing import Annotated
6
7 import pytest
8
9 from cyclopts import App, Parameter
10
11 # ==============================================================================
12 # return_value tests
13 # ==============================================================================
14
15
16 def test_result_action_return_value_with_string():
17 """return_value: returns string unchanged."""
18 app = App(result_action="return_value")
19
20 @app.command
21 def greet(name: str) -> str:
22 return f"Hello {name}!"
23
24 result = app(["greet", "Alice"])
25 assert result == "Hello Alice!"
26
27
28 def test_result_action_return_value_with_int():
29 """return_value: returns int unchanged."""
30 app = App(result_action="return_value")
31
32 @app.command
33 def double(number: int) -> int:
34 return number * 2
35
36 result = app(["double", "5"])
37 assert result == 10
38
39
40 def test_result_action_return_value_with_none():
41 """return_value: returns None unchanged."""
42 app = App(result_action="return_value")
43
44 @app.command
45 def do_nothing() -> None:
46 pass
47
48 result = app(["do-nothing"])
49 assert result is None
50
51
52 # ==============================================================================
53 # print_non_int_return_int_as_exit_code tests
54 # ==============================================================================
55
56
57 def test_result_action_print_non_int_return_int_as_exit_code_with_string():
58 """print_non_int_return_int_as_exit_code: prints string and returns 0."""
59 app = App(result_action="print_non_int_return_int_as_exit_code")
60
61 @app.command
62 def greet(name: str) -> str:
63 return f"Hello {name}!"
64
65 buf = StringIO()
66 with redirect_stdout(buf):
67 result = app(["greet", "Bob"])
68
69 assert result == 0
70 assert buf.getvalue() == "Hello Bob!\n"
71
72
73 def test_result_action_print_non_int_return_int_as_exit_code_with_int():
74 """print_non_int_return_int_as_exit_code: returns int as exit code, no print."""
75 app = App(result_action="print_non_int_return_int_as_exit_code")
76
77 @app.command
78 def get_exit_code(code: int) -> int:
79 return code
80
81 buf = StringIO()
82 with redirect_stdout(buf):
83 result = app(["get-exit-code", "5"])
84
85 assert result == 5
86 assert buf.getvalue() == ""
87
88
89 def test_result_action_print_non_int_return_int_as_exit_code_with_none():
90 """print_non_int_return_int_as_exit_code: returns 0 for None without printing."""
91 app = App(result_action="print_non_int_return_int_as_exit_code")
92
93 @app.command
94 def do_nothing() -> None:
95 pass
96
97 buf = StringIO()
98 with redirect_stdout(buf):
99 result = app(["do-nothing"])
100
101 assert result == 0
102 assert buf.getvalue() == ""
103
104
105 def test_result_action_print_non_int_return_int_as_exit_code_with_list():
106 """print_non_int_return_int_as_exit_code: prints list and returns 0."""
107 app = App(result_action="print_non_int_return_int_as_exit_code")
108
109 @app.command
110 def get_list() -> list:
111 return [1, 2, 3]
112
113 buf = StringIO()
114 with redirect_stdout(buf):
115 result = app(["get-list"])
116
117 assert result == 0
118 assert buf.getvalue() == "[1, 2, 3]\n"
119
120
121 def test_result_action_print_non_int_return_int_as_exit_code_with_true():
122 """print_non_int_return_int_as_exit_code: True returns 0."""
123 app = App(result_action="print_non_int_return_int_as_exit_code")
124
125 @app.command
126 def check() -> bool:
127 return True
128
129 buf = StringIO()
130 with redirect_stdout(buf):
131 result = app(["check"])
132
133 assert result == 0
134 assert buf.getvalue() == ""
135
136
137 def test_result_action_print_non_int_return_int_as_exit_code_with_false():
138 """print_non_int_return_int_as_exit_code: False returns 1."""
139 app = App(result_action="print_non_int_return_int_as_exit_code")
140
141 @app.command
142 def check() -> bool:
143 return False
144
145 buf = StringIO()
146 with redirect_stdout(buf):
147 result = app(["check"])
148
149 assert result == 1
150 assert buf.getvalue() == ""
151
152
153 # ==============================================================================
154 # print_str_return_int_as_exit_code tests
155 # ==============================================================================
156
157
158 def test_result_action_print_str_return_int_as_exit_code_with_string():
159 """print_str_return_int_as_exit_code: prints string and returns 0."""
160 app = App(result_action="print_str_return_int_as_exit_code")
161
162 @app.command
163 def greet(name: str) -> str:
164 return f"Hello {name}!"
165
166 buf = StringIO()
167 with redirect_stdout(buf):
168 result = app(["greet", "Alice"])
169
170 assert result == 0
171 assert buf.getvalue() == "Hello Alice!\n"
172
173
174 def test_result_action_print_str_return_int_as_exit_code_with_int():
175 """print_str_return_int_as_exit_code: returns int as exit code, no print."""
176 app = App(result_action="print_str_return_int_as_exit_code")
177
178 @app.command
179 def get_exit_code(code: int) -> int:
180 return code
181
182 buf = StringIO()
183 with redirect_stdout(buf):
184 result = app(["get-exit-code", "5"])
185
186 assert result == 5
187 assert buf.getvalue() == ""
188
189
190 def test_result_action_print_str_return_int_as_exit_code_with_list():
191 """print_str_return_int_as_exit_code: doesn't print non-string objects, returns 0."""
192 app = App(result_action="print_str_return_int_as_exit_code")
193
194 @app.command
195 def get_list() -> list:
196 return [1, 2, 3]
197
198 buf = StringIO()
199 with redirect_stdout(buf):
200 result = app(["get-list"])
201
202 assert result == 0
203 assert buf.getvalue() == ""
204
205
206 def test_result_action_print_str_return_int_as_exit_code_with_true():
207 """print_str_return_int_as_exit_code: True returns 0."""
208 app = App(result_action="print_str_return_int_as_exit_code")
209
210 @app.command
211 def check() -> bool:
212 return True
213
214 buf = StringIO()
215 with redirect_stdout(buf):
216 result = app(["check"])
217
218 assert result == 0
219 assert buf.getvalue() == ""
220
221
222 def test_result_action_print_str_return_int_as_exit_code_with_false():
223 """print_str_return_int_as_exit_code: False returns 1."""
224 app = App(result_action="print_str_return_int_as_exit_code")
225
226 @app.command
227 def check() -> bool:
228 return False
229
230 buf = StringIO()
231 with redirect_stdout(buf):
232 result = app(["check"])
233
234 assert result == 1
235 assert buf.getvalue() == ""
236
237
238 # ==============================================================================
239 # print_str_return_zero tests
240 # ==============================================================================
241
242
243 def test_result_action_print_str_return_zero_with_string():
244 """print_str_return_zero: prints string and returns 0."""
245 app = App(result_action="print_str_return_zero")
246
247 @app.command
248 def greet(name: str) -> str:
249 return f"Hello {name}!"
250
251 buf = StringIO()
252 with redirect_stdout(buf):
253 result = app(["greet", "Alice"])
254
255 assert result == 0
256 assert buf.getvalue() == "Hello Alice!\n"
257
258
259 def test_result_action_print_str_return_zero_with_int():
260 """print_str_return_zero: doesn't print int, returns 0."""
261 app = App(result_action="print_str_return_zero")
262
263 @app.command
264 def get_number() -> int:
265 return 42
266
267 buf = StringIO()
268 with redirect_stdout(buf):
269 result = app(["get-number"])
270
271 assert result == 0
272 assert buf.getvalue() == ""
273
274
275 # ==============================================================================
276 # print_non_none_return_int_as_exit_code tests
277 # ==============================================================================
278
279
280 def test_result_action_print_non_none_return_int_as_exit_code_with_string():
281 """print_non_none_return_int_as_exit_code: prints string and returns 0."""
282 app = App(result_action="print_non_none_return_int_as_exit_code")
283
284 @app.command
285 def greet(name: str) -> str:
286 return f"Hello {name}!"
287
288 buf = StringIO()
289 with redirect_stdout(buf):
290 result = app(["greet", "Alice"])
291
292 assert result == 0
293 assert buf.getvalue() == "Hello Alice!\n"
294
295
296 def test_result_action_print_non_none_return_int_as_exit_code_with_int():
297 """print_non_none_return_int_as_exit_code: prints int but returns it as exit code."""
298 app = App(result_action="print_non_none_return_int_as_exit_code")
299
300 @app.command
301 def get_number() -> int:
302 return 42
303
304 buf = StringIO()
305 with redirect_stdout(buf):
306 result = app(["get-number"])
307
308 assert result == 42
309 assert buf.getvalue() == "42\n"
310
311
312 def test_result_action_print_non_none_return_int_as_exit_code_with_true():
313 """print_non_none_return_int_as_exit_code: prints True and returns 0."""
314 app = App(result_action="print_non_none_return_int_as_exit_code")
315
316 @app.command
317 def check() -> bool:
318 return True
319
320 buf = StringIO()
321 with redirect_stdout(buf):
322 result = app(["check"])
323
324 assert result == 0
325 assert buf.getvalue() == "True\n"
326
327
328 def test_result_action_print_non_none_return_int_as_exit_code_with_false():
329 """print_non_none_return_int_as_exit_code: prints False and returns 1."""
330 app = App(result_action="print_non_none_return_int_as_exit_code")
331
332 @app.command
333 def check() -> bool:
334 return False
335
336 buf = StringIO()
337 with redirect_stdout(buf):
338 result = app(["check"])
339
340 assert result == 1
341 assert buf.getvalue() == "False\n"
342
343
344 # ==============================================================================
345 # print_non_none_return_zero tests
346 # ==============================================================================
347
348
349 def test_result_action_print_non_none_return_zero_with_string():
350 """print_non_none_return_zero: prints string and returns 0."""
351 app = App(result_action="print_non_none_return_zero")
352
353 @app.command
354 def greet(name: str) -> str:
355 return f"Hello {name}!"
356
357 buf = StringIO()
358 with redirect_stdout(buf):
359 result = app(["greet", "Alice"])
360
361 assert result == 0
362 assert buf.getvalue() == "Hello Alice!\n"
363
364
365 def test_result_action_print_non_none_return_zero_with_int():
366 """print_non_none_return_zero: prints int but returns 0."""
367 app = App(result_action="print_non_none_return_zero")
368
369 @app.command
370 def get_number() -> int:
371 return 42
372
373 buf = StringIO()
374 with redirect_stdout(buf):
375 result = app(["get-number"])
376
377 assert result == 0
378 assert buf.getvalue() == "42\n"
379
380
381 # ==============================================================================
382 # return_int_as_exit_code_else_zero tests
383 # ==============================================================================
384
385
386 def test_result_action_return_int_as_exit_code_else_zero_with_string():
387 """return_int_as_exit_code_else_zero: doesn't print string, returns 0."""
388 app = App(result_action="return_int_as_exit_code_else_zero")
389
390 @app.command
391 def greet(name: str) -> str:
392 return f"Hello {name}!"
393
394 buf = StringIO()
395 with redirect_stdout(buf):
396 result = app(["greet", "Bob"])
397
398 assert result == 0
399 assert buf.getvalue() == ""
400
401
402 def test_result_action_return_int_as_exit_code_else_zero_with_int():
403 """return_int_as_exit_code_else_zero: returns int as exit code, no print."""
404 app = App(result_action="return_int_as_exit_code_else_zero")
405
406 @app.command
407 def get_exit_code(code: int) -> int:
408 return code
409
410 buf = StringIO()
411 with redirect_stdout(buf):
412 result = app(["get-exit-code", "3"])
413
414 assert result == 3
415 assert buf.getvalue() == ""
416
417
418 def test_result_action_return_int_as_exit_code_else_zero_with_true():
419 """return_int_as_exit_code_else_zero: True returns 0."""
420 app = App(result_action="return_int_as_exit_code_else_zero")
421
422 @app.command
423 def check() -> bool:
424 return True
425
426 buf = StringIO()
427 with redirect_stdout(buf):
428 result = app(["check"])
429
430 assert result == 0
431 assert buf.getvalue() == ""
432
433
434 def test_result_action_return_int_as_exit_code_else_zero_with_false():
435 """return_int_as_exit_code_else_zero: False returns 1."""
436 app = App(result_action="return_int_as_exit_code_else_zero")
437
438 @app.command
439 def check() -> bool:
440 return False
441
442 buf = StringIO()
443 with redirect_stdout(buf):
444 result = app(["check"])
445
446 assert result == 1
447 assert buf.getvalue() == ""
448
449
450 # ==============================================================================
451 # print_non_int_sys_exit tests
452 # ==============================================================================
453
454
455 def test_result_action_print_non_int_sys_exit_with_string(monkeypatch):
456 """print_non_int_sys_exit: prints and calls sys.exit(0)."""
457 app = App(result_action="print_non_int_sys_exit")
458
459 @app.command
460 def greet(name: str) -> str:
461 return f"Hello {name}!"
462
463 exit_code = None
464
465 def mock_exit(code):
466 nonlocal exit_code
467 exit_code = code
468
469 monkeypatch.setattr("sys.exit", mock_exit)
470
471 buf = StringIO()
472 with redirect_stdout(buf):
473 app(["greet", "Alice"])
474
475 assert exit_code == 0
476 assert buf.getvalue() == "Hello Alice!\n"
477
478
479 def test_result_action_print_non_int_sys_exit_with_int(monkeypatch):
480 """print_non_int_sys_exit: calls sys.exit with int value."""
481 app = App(result_action="print_non_int_sys_exit")
482
483 @app.command
484 def get_exit_code(code: int) -> int:
485 return code
486
487 exit_code = None
488
489 def mock_exit(code):
490 nonlocal exit_code
491 exit_code = code
492
493 monkeypatch.setattr("sys.exit", mock_exit)
494
495 buf = StringIO()
496 with redirect_stdout(buf):
497 app(["get-exit-code", "5"])
498
499 assert exit_code == 5
500 assert buf.getvalue() == ""
501
502
503 def test_result_action_print_non_int_sys_exit_with_true(monkeypatch):
504 """print_non_int_sys_exit: True calls sys.exit(0)."""
505 app = App(result_action="print_non_int_sys_exit")
506
507 @app.command
508 def check() -> bool:
509 return True
510
511 exit_code = None
512
513 def mock_exit(code):
514 nonlocal exit_code
515 exit_code = code
516
517 monkeypatch.setattr("sys.exit", mock_exit)
518
519 buf = StringIO()
520 with redirect_stdout(buf):
521 app(["check"])
522
523 assert exit_code == 0
524 assert buf.getvalue() == ""
525
526
527 def test_result_action_print_non_int_sys_exit_with_false(monkeypatch):
528 """print_non_int_sys_exit: False calls sys.exit(1)."""
529 app = App(result_action="print_non_int_sys_exit")
530
531 @app.command
532 def check() -> bool:
533 return False
534
535 exit_code = None
536
537 def mock_exit(code):
538 nonlocal exit_code
539 exit_code = code
540
541 monkeypatch.setattr("sys.exit", mock_exit)
542
543 buf = StringIO()
544 with redirect_stdout(buf):
545 app(["check"])
546
547 assert exit_code == 1
548 assert buf.getvalue() == ""
549
550
551 # ==============================================================================
552 # sys_exit tests
553 # ==============================================================================
554
555
556 def test_result_action_sys_exit_with_string(monkeypatch):
557 """sys_exit: string returns sys.exit(0) without printing."""
558 app = App(result_action="sys_exit")
559
560 @app.command
561 def greet(name: str) -> str:
562 return f"Hello {name}!"
563
564 exit_code = None
565
566 def mock_exit(code):
567 nonlocal exit_code
568 exit_code = code
569
570 monkeypatch.setattr("sys.exit", mock_exit)
571
572 buf = StringIO()
573 with redirect_stdout(buf):
574 app(["greet", "Alice"])
575
576 assert exit_code == 0
577 assert buf.getvalue() == "" # Should NOT print
578
579
580 def test_result_action_sys_exit_with_int(monkeypatch):
581 """sys_exit: calls sys.exit with int value."""
582 app = App(result_action="sys_exit")
583
584 @app.command
585 def get_exit_code(code: int) -> int:
586 return code
587
588 exit_code = None
589
590 def mock_exit(code):
591 nonlocal exit_code
592 exit_code = code
593
594 monkeypatch.setattr("sys.exit", mock_exit)
595
596 buf = StringIO()
597 with redirect_stdout(buf):
598 app(["get-exit-code", "5"])
599
600 assert exit_code == 5
601 assert buf.getvalue() == ""
602
603
604 def test_result_action_sys_exit_with_true(monkeypatch):
605 """sys_exit: True calls sys.exit(0)."""
606 app = App(result_action="sys_exit")
607
608 @app.command
609 def check() -> bool:
610 return True
611
612 exit_code = None
613
614 def mock_exit(code):
615 nonlocal exit_code
616 exit_code = code
617
618 monkeypatch.setattr("sys.exit", mock_exit)
619
620 buf = StringIO()
621 with redirect_stdout(buf):
622 app(["check"])
623
624 assert exit_code == 0
625 assert buf.getvalue() == ""
626
627
628 def test_result_action_sys_exit_with_false(monkeypatch):
629 """sys_exit: False calls sys.exit(1)."""
630 app = App(result_action="sys_exit")
631
632 @app.command
633 def check() -> bool:
634 return False
635
636 exit_code = None
637
638 def mock_exit(code):
639 nonlocal exit_code
640 exit_code = code
641
642 monkeypatch.setattr("sys.exit", mock_exit)
643
644 buf = StringIO()
645 with redirect_stdout(buf):
646 app(["check"])
647
648 assert exit_code == 1
649 assert buf.getvalue() == ""
650
651
652 def test_result_action_sys_exit_with_none(monkeypatch):
653 """sys_exit: None calls sys.exit(0)."""
654 app = App(result_action="sys_exit")
655
656 @app.command
657 def do_nothing() -> None:
658 pass
659
660 exit_code = None
661
662 def mock_exit(code):
663 nonlocal exit_code
664 exit_code = code
665
666 monkeypatch.setattr("sys.exit", mock_exit)
667
668 buf = StringIO()
669 with redirect_stdout(buf):
670 app(["do-nothing"])
671
672 assert exit_code == 0
673 assert buf.getvalue() == ""
674
675
676 # ==============================================================================
677 # Default and inheritance tests
678 # ==============================================================================
679
680
681 def test_result_action_default_is_print_non_int_sys_exit():
682 """Default result_action should be 'print_non_int_sys_exit'."""
683 app = App()
684
685 @app.command
686 def greet(name: str) -> str:
687 return f"Hello {name}!"
688
689 # Default mode should print strings and call sys.exit(0)
690 buf = StringIO()
691 with redirect_stdout(buf):
692 with pytest.raises(SystemExit) as exc_info:
693 app(["greet", "Charlie"])
694 assert exc_info.value.code == 0
695 assert buf.getvalue() == "Hello Charlie!\n"
696
697
698 def test_result_action_override_in_call():
699 """result_action can be overridden in __call__."""
700 app = App(result_action="return_value")
701
702 @app.command
703 def greet(name: str) -> str:
704 return f"Hello {name}!"
705
706 # Default behavior from App
707 result = app(["greet", "Alice"])
708 assert result == "Hello Alice!"
709
710 # Override to print_non_int_return_int_as_exit_code
711 buf = StringIO()
712 with redirect_stdout(buf):
713 result = app(["greet", "Bob"], result_action="print_non_int_return_int_as_exit_code")
714 assert result == 0
715 assert buf.getvalue() == "Hello Bob!\n"
716
717 # Override to return_int_as_exit_code_else_zero
718 buf = StringIO()
719 with redirect_stdout(buf):
720 result = app(["greet", "Charlie"], result_action="return_int_as_exit_code_else_zero")
721 assert result == 0
722 assert buf.getvalue() == ""
723
724
725 def test_result_action_inheritance():
726 """result_action inherits from parent app when None and called through parent."""
727 parent_app = App(result_action="return_value")
728
729 child_app = App(name="child") # result_action=None, should inherit
730 parent_app.command(child_app)
731
732 @child_app.default
733 def greet(name: str) -> str:
734 return f"Hello {name}!"
735
736 # Child should inherit parent's return_value mode when called through parent
737 result = parent_app(["child", "Alice"])
738 assert result == "Hello Alice!"
739
740 # Test with different parent mode
741 parent_app2 = App(result_action="return_int_as_exit_code_else_zero")
742 child_app2 = App(name="child2") # result_action=None
743 parent_app2.command(child_app2)
744
745 @child_app2.default
746 def greet2(name: str) -> str:
747 return f"Hello {name}!"
748
749 # Child should inherit parent's silent mode when called through parent
750 buf = StringIO()
751 with redirect_stdout(buf):
752 result = parent_app2(["child2", "Bob"])
753 assert result == 0
754 assert buf.getvalue() == ""
755
756
757 def test_result_action_none_defaults_to_print_non_int_sys_exit():
758 """result_action=None defaults to print_non_int_sys_exit when called standalone."""
759 app = App() # result_action=None
760
761 @app.default
762 def greet(name: str) -> str:
763 return f"Hello {name}!"
764
765 # Should use default fallback: print_non_int_sys_exit
766 buf = StringIO()
767 with redirect_stdout(buf):
768 with pytest.raises(SystemExit) as exc_info:
769 app(["Alice"])
770 assert exc_info.value.code == 0
771 assert buf.getvalue() == "Hello Alice!\n"
772
773
774 # ==============================================================================
775 # Meta app tests
776 # ==============================================================================
777
778
779 def test_result_action_with_meta_app_exit_mode(monkeypatch):
780 """result_action with meta app: exit modes should apply at meta level, not inner level."""
781 app = App(result_action="print_non_int_sys_exit")
782
783 @app.meta.default
784 def meta(*tokens: Annotated[str, Parameter(allow_leading_hyphen=True)]):
785 # Inner call should return value, not exit
786 result = app(tokens)
787 # This should execute (meta function should complete)
788 return f"Meta wrapper: {result}"
789
790 @app.default
791 def command() -> str:
792 return "Hello from command"
793
794 exit_code = None
795
796 def mock_exit(code):
797 nonlocal exit_code
798 exit_code = code
799
800 monkeypatch.setattr("sys.exit", mock_exit)
801
802 buf = StringIO()
803 with redirect_stdout(buf):
804 app.meta([])
805
806 # Should print "Meta wrapper: Hello from command"
807 assert buf.getvalue() == "Meta wrapper: Hello from command\n"
808 # Should call sys.exit at meta level
809 assert exit_code == 0
810
811
812 def test_result_action_with_meta_app_return_mode():
813 """result_action with meta app: non-exit modes should work correctly."""
814 app = App(result_action="print_non_int_return_int_as_exit_code")
815
816 @app.meta.default
817 def meta(*tokens: Annotated[str, Parameter(allow_leading_hyphen=True)]):
818 # Inner call should return value
819 result = app(tokens)
820 # This should execute (meta function should complete)
821 return f"Meta: {result}"
822
823 @app.default
824 def command() -> str:
825 return "Hello"
826
827 buf = StringIO()
828 with redirect_stdout(buf):
829 result = app.meta([])
830
831 # Inner command returns "Hello", meta wraps it as "Meta: Hello"
832 assert result == 0
833 assert buf.getvalue() == "Meta: Hello\n"
834
835
836 # ==============================================================================
837 # Callable result_action tests
838 # ==============================================================================
839
840
841 def test_result_action_callable_basic():
842 """Callable result_action: can use custom function."""
843
844 def custom_handler(result):
845 return f"CUSTOM: {result}"
846
847 app = App(result_action=custom_handler)
848
849 @app.command
850 def greet(name: str) -> str:
851 return f"Hello {name}!"
852
853 result = app(["greet", "Alice"])
854 assert result == "CUSTOM: Hello Alice!"
855
856
857 def test_result_action_callable_with_print():
858 """Callable result_action: can print and return exit code."""
859
860 def custom_handler(result):
861 if result:
862 print(f"SUCCESS: {result}")
863 return 0
864 else:
865 print("FAILED")
866 return 1
867
868 app = App(result_action=custom_handler)
869
870 @app.command
871 def process() -> str:
872 return "Done"
873
874 buf = StringIO()
875 with redirect_stdout(buf):
876 exit_code = app(["process"])
877
878 assert exit_code == 0
879 assert buf.getvalue() == "SUCCESS: Done\n"
880
881
882 def test_result_action_callable_transforms_result():
883 """Callable result_action: can transform result before returning."""
884
885 def uppercase_handler(result):
886 if isinstance(result, str):
887 return result.upper()
888 return result
889
890 app = App(result_action=uppercase_handler)
891
892 @app.command
893 def greet() -> str:
894 return "hello world"
895
896 result = app(["greet"])
897 assert result == "HELLO WORLD"
898
899
900 def test_result_action_callable_handles_none():
901 """Callable result_action: handles None results."""
902
903 def none_handler(result):
904 return result if result is not None else "DEFAULT"
905
906 app = App(result_action=none_handler)
907
908 @app.command
909 def no_return() -> None:
910 pass
911
912 result = app(["no-return"])
913 assert result == "DEFAULT"
914
915
916 def test_result_action_callable_override_in_call():
917 """Callable result_action: can be overridden in __call__."""
918
919 def handler1(result):
920 return f"HANDLER1: {result}"
921
922 def handler2(result):
923 return f"HANDLER2: {result}"
924
925 app = App(result_action=handler1)
926
927 @app.command
928 def cmd() -> str:
929 return "test"
930
931 result1 = app(["cmd"])
932 assert result1 == "HANDLER1: test"
933
934 result2 = app(["cmd"], result_action=handler2)
935 assert result2 == "HANDLER2: test"
936
937
938 def test_result_action_callable_with_lambda():
939 """Callable result_action: works with lambda functions."""
940 app = App(result_action=lambda x: x * 2 if isinstance(x, int) else x)
941
942 @app.command
943 def double(n: int) -> int:
944 return n
945
946 result = app(["double", "5"])
947 assert result == 10
948
949
950 # ==============================================================================
951 # return_none tests
952 # ==============================================================================
953
954
955 def test_result_action_return_none_with_string():
956 """return_none: returns None regardless of result."""
957 app = App(result_action="return_none")
958
959 @app.command
960 def greet(name: str) -> str:
961 return f"Hello {name}!"
962
963 buf = StringIO()
964 with redirect_stdout(buf):
965 result = app(["greet", "Alice"])
966
967 assert result is None
968 assert buf.getvalue() == ""
969
970
971 def test_result_action_return_none_with_int():
972 """return_none: returns None regardless of result."""
973 app = App(result_action="return_none")
974
975 @app.command
976 def get_number() -> int:
977 return 42
978
979 buf = StringIO()
980 with redirect_stdout(buf):
981 result = app(["get-number"])
982
983 assert result is None
984 assert buf.getvalue() == ""
985
986
987 # ==============================================================================
988 # return_zero tests
989 # ==============================================================================
990
991
992 def test_result_action_return_zero_with_string():
993 """return_zero: returns 0 regardless of result."""
994 app = App(result_action="return_zero")
995
996 @app.command
997 def greet(name: str) -> str:
998 return f"Hello {name}!"
999
1000 buf = StringIO()
1001 with redirect_stdout(buf):
1002 result = app(["greet", "Alice"])
1003
1004 assert result == 0
1005 assert buf.getvalue() == ""
1006
1007
1008 def test_result_action_return_zero_with_int():
1009 """return_zero: returns 0 regardless of result."""
1010 app = App(result_action="return_zero")
1011
1012 @app.command
1013 def get_number() -> int:
1014 return 42
1015
1016 buf = StringIO()
1017 with redirect_stdout(buf):
1018 result = app(["get-number"])
1019
1020 assert result == 0
1021 assert buf.getvalue() == ""
1022
1023
1024 # ==============================================================================
1025 # print_return_zero tests
1026 # ==============================================================================
1027
1028
1029 def test_result_action_print_return_zero_with_string():
1030 """print_return_zero: prints result and returns 0."""
1031 app = App(result_action="print_return_zero")
1032
1033 @app.command
1034 def greet(name: str) -> str:
1035 return f"Hello {name}!"
1036
1037 buf = StringIO()
1038 with redirect_stdout(buf):
1039 result = app(["greet", "Alice"])
1040
1041 assert result == 0
1042 assert buf.getvalue() == "Hello Alice!\n"
1043
1044
1045 def test_result_action_print_return_zero_with_int():
1046 """print_return_zero: prints result and returns 0."""
1047 app = App(result_action="print_return_zero")
1048
1049 @app.command
1050 def get_number() -> int:
1051 return 42
1052
1053 buf = StringIO()
1054 with redirect_stdout(buf):
1055 result = app(["get-number"])
1056
1057 assert result == 0
1058 assert buf.getvalue() == "42\n"
1059
1060
1061 def test_result_action_print_return_zero_with_none():
1062 """print_return_zero: prints None and returns 0."""
1063 app = App(result_action="print_return_zero")
1064
1065 @app.command
1066 def do_nothing() -> None:
1067 pass
1068
1069 buf = StringIO()
1070 with redirect_stdout(buf):
1071 result = app(["do-nothing"])
1072
1073 assert result == 0
1074 assert buf.getvalue() == "None\n"
1075
1076
1077 # ==============================================================================
1078 # sys_exit_zero tests
1079 # ==============================================================================
1080
1081
1082 def test_result_action_sys_exit_zero_with_string(monkeypatch):
1083 """sys_exit_zero: calls sys.exit(0) regardless of result."""
1084 app = App(result_action="sys_exit_zero")
1085
1086 @app.command
1087 def greet(name: str) -> str:
1088 return f"Hello {name}!"
1089
1090 exit_code = None
1091
1092 def mock_exit(code):
1093 nonlocal exit_code
1094 exit_code = code
1095
1096 monkeypatch.setattr("sys.exit", mock_exit)
1097
1098 buf = StringIO()
1099 with redirect_stdout(buf):
1100 app(["greet", "Alice"])
1101
1102 assert exit_code == 0
1103 assert buf.getvalue() == ""
1104
1105
1106 def test_result_action_sys_exit_zero_with_int(monkeypatch):
1107 """sys_exit_zero: calls sys.exit(0) even with int result."""
1108 app = App(result_action="sys_exit_zero")
1109
1110 @app.command
1111 def get_number() -> int:
1112 return 42
1113
1114 exit_code = None
1115
1116 def mock_exit(code):
1117 nonlocal exit_code
1118 exit_code = code
1119
1120 monkeypatch.setattr("sys.exit", mock_exit)
1121
1122 buf = StringIO()
1123 with redirect_stdout(buf):
1124 app(["get-number"])
1125
1126 assert exit_code == 0
1127 assert buf.getvalue() == ""
1128
1129
1130 # ==============================================================================
1131 # print_sys_exit_zero tests
1132 # ==============================================================================
1133
1134
1135 def test_result_action_print_sys_exit_zero_with_string(monkeypatch):
1136 """print_sys_exit_zero: prints result and calls sys.exit(0)."""
1137 app = App(result_action="print_sys_exit_zero")
1138
1139 @app.command
1140 def greet(name: str) -> str:
1141 return f"Hello {name}!"
1142
1143 exit_code = None
1144
1145 def mock_exit(code):
1146 nonlocal exit_code
1147 exit_code = code
1148
1149 monkeypatch.setattr("sys.exit", mock_exit)
1150
1151 buf = StringIO()
1152 with redirect_stdout(buf):
1153 app(["greet", "Alice"])
1154
1155 assert exit_code == 0
1156 assert buf.getvalue() == "Hello Alice!\n"
1157
1158
1159 def test_result_action_print_sys_exit_zero_with_int(monkeypatch):
1160 """print_sys_exit_zero: prints result and calls sys.exit(0)."""
1161 app = App(result_action="print_sys_exit_zero")
1162
1163 @app.command
1164 def get_number() -> int:
1165 return 42
1166
1167 exit_code = None
1168
1169 def mock_exit(code):
1170 nonlocal exit_code
1171 exit_code = code
1172
1173 monkeypatch.setattr("sys.exit", mock_exit)
1174
1175 buf = StringIO()
1176 with redirect_stdout(buf):
1177 app(["get-number"])
1178
1179 assert exit_code == 0
1180 assert buf.getvalue() == "42\n"
1181
1182
1183 # ==============================================================================
1184 # call_if_callable tests
1185 # ==============================================================================
1186
1187
1188 def test_result_action_call_if_callable_with_callable():
1189 """call_if_callable: calls the result if it's callable."""
1190 app = App(result_action="call_if_callable")
1191
1192 @app.command
1193 def get_greeter(name: str):
1194 def greeter():
1195 return f"Hello {name}!"
1196
1197 return greeter
1198
1199 result = app(["get-greeter", "Alice"])
1200 assert result == "Hello Alice!"
1201
1202
1203 def test_result_action_call_if_callable_with_non_callable():
1204 """call_if_callable: returns non-callable result as-is."""
1205 app = App(result_action="call_if_callable")
1206
1207 @app.command
1208 def greet(name: str) -> str:
1209 return f"Hello {name}!"
1210
1211 result = app(["greet", "Bob"])
1212 assert result == "Hello Bob!"
1213
1214
1215 def test_result_action_call_if_callable_with_none():
1216 """call_if_callable: returns None as-is."""
1217 app = App(result_action="call_if_callable")
1218
1219 @app.command
1220 def do_nothing() -> None:
1221 pass
1222
1223 result = app(["do-nothing"])
1224 assert result is None
1225
1226
1227 def test_result_action_call_if_callable_with_dataclass():
1228 """call_if_callable: works with dataclass __call__ pattern."""
1229 import dataclasses as dc
1230
1231 app = App(result_action="call_if_callable")
1232
1233 @app.command
1234 @dc.dataclass
1235 class Hello:
1236 """Say hello."""
1237
1238 name: str = "World"
1239 _: dc.KW_ONLY
1240 formal: bool = False
1241
1242 def __call__(self):
1243 return f"{'Hello' if self.formal else 'Hey'} {self.name}."
1244
1245 result = app(["hello", "Jude"])
1246 assert result == "Hey Jude."
1247
1248 result = app(["hello", "Sir", "--formal"])
1249 assert result == "Hello Sir."
1250
1251
1252 # ==============================================================================
1253 # Sequence result_action tests
1254 # ==============================================================================
1255
1256
1257 def test_result_action_sequence_single_element():
1258 """Sequence with single element should work like single value."""
1259 app = App(result_action=["return_value"])
1260
1261 @app.command
1262 def greet(name: str) -> str:
1263 return f"Hello {name}!"
1264
1265 result = app(["greet", "Alice"])
1266 assert result == "Hello Alice!"
1267
1268
1269 def test_result_action_sequence_multiple_callables():
1270 """Sequence with multiple callables should chain results."""
1271 call_order = []
1272
1273 def handler1(result):
1274 call_order.append("handler1")
1275 return f"[1:{result}]"
1276
1277 def handler2(result):
1278 call_order.append("handler2")
1279 return f"[2:{result}]"
1280
1281 app = App(result_action=[handler1, handler2])
1282
1283 @app.command
1284 def cmd() -> str:
1285 return "test"
1286
1287 result = app(["cmd"])
1288 assert result == "[2:[1:test]]"
1289 assert call_order == ["handler1", "handler2"]
1290
1291
1292 def test_result_action_empty_sequence_raises_error():
1293 """Empty sequence should raise ValueError."""
1294 with pytest.raises(ValueError, match="result_action cannot be an empty sequence"):
1295 App(result_action=[])
1296
1297
1298 def test_result_action_call_if_callable_composition(monkeypatch):
1299 """Composition: call_if_callable with print_non_int_sys_exit for dataclass pattern."""
1300 import dataclasses as dc
1301
1302 app = App(result_action=["call_if_callable", "print_non_int_sys_exit"])
1303
1304 @app.command
1305 @dc.dataclass
1306 class Hello:
1307 """Say hello."""
1308
1309 name: str = "World"
1310 _: dc.KW_ONLY
1311 formal: bool = False
1312
1313 def __call__(self):
1314 return f"{'Hello' if self.formal else 'Hey'} {self.name}."
1315
1316 exit_code = None
1317
1318 def mock_exit(code):
1319 nonlocal exit_code
1320 exit_code = code
1321
1322 monkeypatch.setattr("sys.exit", mock_exit)
1323
1324 buf = StringIO()
1325 with redirect_stdout(buf):
1326 app(["hello", "Jude"])
1327
1328 assert buf.getvalue() == "Hey Jude.\n"
1329 assert exit_code == 0
1330
1331
1332 # ==============================================================================
1333 # __cyclopts_returncode__ tests
1334 # ==============================================================================
1335
1336
1337 class _CustomResult:
1338 """Result object that advertises a custom return code via __cyclopts_returncode__."""
1339
1340 def __init__(self, message: str = "custom", returncode: int = 7):
1341 self.message = message
1342 self._returncode = returncode
1343
1344 def __cyclopts_returncode__(self) -> int:
1345 return self._returncode
1346
1347 def __str__(self) -> str:
1348 return self.message
1349
1350
1351 def test_cyclopts_returncode_print_non_int_sys_exit(monkeypatch):
1352 """print_non_int_sys_exit honors __cyclopts_returncode__ for non-int results."""
1353 app = App(result_action="print_non_int_sys_exit")
1354
1355 @app.command
1356 def run() -> _CustomResult:
1357 return _CustomResult("hi", returncode=7)
1358
1359 exit_code = None
1360
1361 def mock_exit(code):
1362 nonlocal exit_code
1363 exit_code = code
1364
1365 monkeypatch.setattr("sys.exit", mock_exit)
1366
1367 buf = StringIO()
1368 with redirect_stdout(buf):
1369 app(["run"])
1370
1371 assert exit_code == 7
1372 assert buf.getvalue() == "hi\n"
1373
1374
1375 def test_cyclopts_returncode_sys_exit(monkeypatch):
1376 """sys_exit honors __cyclopts_returncode__ for non-int results."""
1377 app = App(result_action="sys_exit")
1378
1379 @app.command
1380 def run() -> _CustomResult:
1381 return _CustomResult(returncode=3)
1382
1383 exit_code = None
1384
1385 def mock_exit(code):
1386 nonlocal exit_code
1387 exit_code = code
1388
1389 monkeypatch.setattr("sys.exit", mock_exit)
1390
1391 buf = StringIO()
1392 with redirect_stdout(buf):
1393 app(["run"])
1394
1395 assert exit_code == 3
1396 assert buf.getvalue() == ""
1397
1398
1399 def test_cyclopts_returncode_print_non_int_return_int_as_exit_code():
1400 """print_non_int_return_int_as_exit_code honors __cyclopts_returncode__."""
1401 app = App(result_action="print_non_int_return_int_as_exit_code")
1402
1403 @app.command
1404 def run() -> _CustomResult:
1405 return _CustomResult("hello", returncode=4)
1406
1407 buf = StringIO()
1408 with redirect_stdout(buf):
1409 result = app(["run"])
1410
1411 assert result == 4
1412 assert buf.getvalue() == "hello\n"
1413
1414
1415 def test_cyclopts_returncode_print_str_return_int_as_exit_code_for_str_subclass():
1416 """print_str_return_int_as_exit_code honors __cyclopts_returncode__ on str subclasses."""
1417
1418 class CustomStr(str):
1419 def __cyclopts_returncode__(self) -> int:
1420 return 9
1421
1422 app = App(result_action="print_str_return_int_as_exit_code")
1423
1424 @app.command
1425 def run() -> CustomStr:
1426 return CustomStr("hello")
1427
1428 buf = StringIO()
1429 with redirect_stdout(buf):
1430 result = app(["run"])
1431
1432 assert result == 9
1433 assert buf.getvalue() == "hello\n"
1434
1435
1436 def test_cyclopts_returncode_print_str_return_int_as_exit_code_for_other():
1437 """print_str_return_int_as_exit_code honors __cyclopts_returncode__ for non-str/int results."""
1438 app = App(result_action="print_str_return_int_as_exit_code")
1439
1440 @app.command
1441 def run() -> _CustomResult:
1442 return _CustomResult(returncode=5)
1443
1444 buf = StringIO()
1445 with redirect_stdout(buf):
1446 result = app(["run"])
1447
1448 assert result == 5
1449 assert buf.getvalue() == "" # non-str silently ignored for printing
1450
1451
1452 def test_cyclopts_returncode_print_str_return_zero():
1453 """print_str_return_zero honors __cyclopts_returncode__."""
1454 app = App(result_action="print_str_return_zero")
1455
1456 @app.command
1457 def run() -> _CustomResult:
1458 return _CustomResult(returncode=6)
1459
1460 buf = StringIO()
1461 with redirect_stdout(buf):
1462 result = app(["run"])
1463
1464 assert result == 6
1465
1466
1467 def test_cyclopts_returncode_print_non_none_return_int_as_exit_code():
1468 """print_non_none_return_int_as_exit_code honors __cyclopts_returncode__."""
1469 app = App(result_action="print_non_none_return_int_as_exit_code")
1470
1471 @app.command
1472 def run() -> _CustomResult:
1473 return _CustomResult("hi", returncode=8)
1474
1475 buf = StringIO()
1476 with redirect_stdout(buf):
1477 result = app(["run"])
1478
1479 assert result == 8
1480 assert buf.getvalue() == "hi\n"
1481
1482
1483 def test_cyclopts_returncode_print_non_none_return_zero():
1484 """print_non_none_return_zero honors __cyclopts_returncode__."""
1485 app = App(result_action="print_non_none_return_zero")
1486
1487 @app.command
1488 def run() -> _CustomResult:
1489 return _CustomResult("hi", returncode=2)
1490
1491 buf = StringIO()
1492 with redirect_stdout(buf):
1493 result = app(["run"])
1494
1495 assert result == 2
1496 assert buf.getvalue() == "hi\n"
1497
1498
1499 def test_cyclopts_returncode_return_int_as_exit_code_else_zero():
1500 """return_int_as_exit_code_else_zero honors __cyclopts_returncode__."""
1501 app = App(result_action="return_int_as_exit_code_else_zero")
1502
1503 @app.command
1504 def run() -> _CustomResult:
1505 return _CustomResult(returncode=11)
1506
1507 result = app(["run"])
1508 assert result == 11
1509
1510
1511 def test_cyclopts_returncode_return_zero():
1512 """return_zero honors __cyclopts_returncode__."""
1513 app = App(result_action="return_zero")
1514
1515 @app.command
1516 def run() -> _CustomResult:
1517 return _CustomResult(returncode=12)
1518
1519 result = app(["run"])
1520 assert result == 12
1521
1522
1523 def test_cyclopts_returncode_print_return_zero():
1524 """print_return_zero honors __cyclopts_returncode__."""
1525 app = App(result_action="print_return_zero")
1526
1527 @app.command
1528 def run() -> _CustomResult:
1529 return _CustomResult("hello", returncode=13)
1530
1531 buf = StringIO()
1532 with redirect_stdout(buf):
1533 result = app(["run"])
1534
1535 assert result == 13
1536 assert buf.getvalue() == "hello\n"
1537
1538
1539 def test_cyclopts_returncode_sys_exit_zero(monkeypatch):
1540 """sys_exit_zero honors __cyclopts_returncode__."""
1541 app = App(result_action="sys_exit_zero")
1542
1543 @app.command
1544 def run() -> _CustomResult:
1545 return _CustomResult(returncode=14)
1546
1547 exit_code = None
1548
1549 def mock_exit(code):
1550 nonlocal exit_code
1551 exit_code = code
1552
1553 monkeypatch.setattr("sys.exit", mock_exit)
1554
1555 app(["run"])
1556
1557 assert exit_code == 14
1558
1559
1560 def test_cyclopts_returncode_print_sys_exit_zero(monkeypatch):
1561 """print_sys_exit_zero honors __cyclopts_returncode__."""
1562 app = App(result_action="print_sys_exit_zero")
1563
1564 @app.command
1565 def run() -> _CustomResult:
1566 return _CustomResult("hi", returncode=15)
1567
1568 exit_code = None
1569
1570 def mock_exit(code):
1571 nonlocal exit_code
1572 exit_code = code
1573
1574 monkeypatch.setattr("sys.exit", mock_exit)
1575
1576 buf = StringIO()
1577 with redirect_stdout(buf):
1578 app(["run"])
1579
1580 assert exit_code == 15
1581 assert buf.getvalue() == "hi\n"
1582
1583
1584 def test_cyclopts_returncode_falls_back_to_zero_when_not_callable():
1585 """__cyclopts_returncode__ is ignored when not callable (fall back to 0)."""
1586
1587 class BadResult:
1588 __cyclopts_returncode__ = 42 # not callable
1589
1590 def __str__(self) -> str:
1591 return "bad"
1592
1593 app = App(result_action="print_non_int_return_int_as_exit_code")
1594
1595 @app.command
1596 def run() -> BadResult:
1597 return BadResult()
1598
1599 buf = StringIO()
1600 with redirect_stdout(buf):
1601 result = app(["run"])
1602
1603 assert result == 0
1604 assert buf.getvalue() == "bad\n"
1605
1606
1607 def test_cyclopts_returncode_default_zero_when_not_defined():
1608 """Results without __cyclopts_returncode__ continue to use 0 as default."""
1609 app = App(result_action="print_non_int_return_int_as_exit_code")
1610
1611 @app.command
1612 def greet(name: str) -> str:
1613 return f"Hello {name}!"
1614
1615 buf = StringIO()
1616 with redirect_stdout(buf):
1617 result = app(["greet", "Alice"])
1618
1619 assert result == 0
1620 assert buf.getvalue() == "Hello Alice!\n"