-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathtest_defopt.py
1613 lines (1364 loc) · 56.1 KB
/
test_defopt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import builtins
import contextlib
import inspect
import multiprocessing as mp
import re
import runpy
import subprocess
import sys
import tokenize
import types
import typing
import unittest
from concurrent.futures import ProcessPoolExecutor
from contextlib import ExitStack
from enum import Enum
from io import StringIO
from pathlib import Path
from docutils.utils import SystemMessage
import defopt
from defopt import __version__, _options
from examples import (
annotations, booleans, choices, exceptions, lists, parsers, short,
starargs, styles)
Choice = Enum('Choice', [('one', 1), ('two', 2), ('%', 0.01)])
Pair = typing.NamedTuple('Pair', [('first', int), ('second', str)])
def _parse_none(i):
if i.lower() == ':none:':
return None
else:
raise ValueError(f'{i} is not a valid None string')
# Also check that the Attributes section doesn't trip docutils.
class ConstructibleFromStr:
"""
Attributes
----------
s : str
The s.
"""
def __init__(self, s):
""":type s: str"""
self.s = s
class NotConstructibleFromStr:
def __init__(self, s):
pass
class TestDefopt(unittest.TestCase):
def test_main(self):
def main(foo):
""":type foo: str"""
return foo
self.assertEqual(defopt.run(main, argv=['foo']), 'foo')
def test_subcommands(self):
def sub(*bar):
""":type bar: float"""
return bar
def sub_with_dash(*, baz=None):
""":type baz: int"""
return baz
self.assertEqual(
defopt.run([sub, sub_with_dash], argv=['sub', '1.1']), (1.1,))
self.assertEqual(
defopt.run([sub, sub_with_dash],
argv=['sub-with-dash', '--baz', '1']), 1)
self.assertEqual(
defopt.run({"sub1": sub, "sub_2": sub_with_dash},
argv=['sub1', '1.2']), (1.2,))
self.assertEqual(
defopt.run({"sub1": sub, "sub_2": sub_with_dash},
argv=['sub_2', '--baz', '1']), 1)
def test_nested_lists_invalid(self):
def sub1(*bar):
""":type bar: float"""
def subsub1(*, baz=None):
""":type baz: int"""
def subsub2(*foo):
""":type foo: float"""
with self.assertRaises(ValueError):
defopt.run([sub1, [subsub1, subsub2]], argv=['sub1', '1.2'])
def test_nested_subcommands1(self):
def sub1(*bar):
""":type bar: float"""
return bar
def subsub1(*, baz=None):
""":type baz: int"""
return baz
def subsub2(*foo):
""":type foo: float"""
return foo
self.assertEqual(
defopt.run({"sub-1": [sub1], "sub-2": [subsub1, subsub2]},
argv=['sub-1', 'sub1', '1.2']), (1.2,))
self.assertEqual(
defopt.run({"sub-1": [sub1], "sub-2": [subsub1, subsub2]},
argv=['sub-2', 'subsub1', '--baz', '1']), 1)
self.assertEqual(
defopt.run({"sub-1": [sub1], "sub-2": [subsub1, subsub2]},
argv=['sub-2', 'subsub2', '1.5']), (1.5,))
def test_nested_subcommands2(self):
def sub1(*bar):
""":type bar: float"""
return bar
def subsub1(*, baz=None):
""":type baz: int"""
return baz
def subsub2(*foo):
""":type foo: float"""
return foo
self.assertEqual(
defopt.run({"sub-1": sub1, "sub-2": [subsub1, subsub2]},
argv=['sub-1', '1.2']), (1.2,))
self.assertEqual(
defopt.run({"sub1": sub1, "sub-2": [subsub1, subsub2]},
argv=['sub-2', 'subsub1', '--baz', '1']), 1)
self.assertEqual(
defopt.run({"sub1": sub1, "sub-2": [subsub1, subsub2]},
argv=['sub-2', 'subsub2', '1.5']), (1.5,))
def test_nested_subcommands3(self):
def sub1(*bar):
""":type bar: float"""
return bar
def subsub1(*, baz=None):
""":type baz: int"""
return baz
def subsub2(*foo):
""":type foo: float"""
return foo
self.assertEqual(
defopt.run({"sub-1": sub1,
"sub-2": {'subsub1': subsub1, 'subsub2': subsub2}},
argv=['sub-1', '1.2']), (1.2,))
self.assertEqual(
defopt.run({"sub-1": sub1,
"sub-2": {'subsub1': subsub1, 'subsub2': subsub2}},
argv=['sub-2', 'subsub1', '--baz', '1']), 1)
self.assertEqual(
defopt.run({"sub-1": sub1,
"sub-2": {'subsub1': subsub1, 'subsub2': subsub2}},
argv=['sub-2', 'subsub2', '1.5']), (1.5,))
def test_nested_subcommands_deep(self):
def sub(*bar):
""":type bar: float"""
return bar
self.assertEqual(
defopt.run({'a': {'b': {'c': {'d': {'e': sub}}}}},
argv=['a', 'b', 'c', 'd', 'e', '1.2']), (1.2,))
self.assertEqual(
defopt.run({'a': {'b': {'c': {'d': {'e': [sub]}}}}},
argv=['a', 'b', 'c', 'd', 'e', 'sub', '1.2']), (1.2,))
def test_nested_subcommands_mixed_invalid1(self):
def sub1(*bar):
""":type bar: float"""
def subsub1(*, baz=None):
""":type baz: int"""
def subsub2(*foo):
""":type foo: float"""
with self.assertRaises(ValueError):
defopt.run([sub1, {'sub2': [subsub1, subsub2]}],
argv=['sub1', '1.2'])
with self.assertRaises(ValueError):
defopt.run([sub1, {'sub2': [subsub1, subsub2]}],
argv=['sub2', 'subsub1', '--baz', '1'])
with self.assertRaises(ValueError):
defopt.run([sub1, {'sub2': [subsub1, subsub2]}],
argv=['sub2', 'subsub2', '1.1'])
def test_nested_subcommands_mixed_invalid2(self):
def sub(*bar):
""":type bar: float"""
def subsub_with_dash(*, baz=None):
""":type baz: int"""
def subsub(*foo):
""":type foo: float"""
with self.assertRaises(ValueError):
defopt.run([sub, {'subsub1': subsub_with_dash, 'subsub2': subsub}],
argv=['sub', '1.2'])
with self.assertRaises(ValueError):
defopt.run([sub, {'subsub1': subsub_with_dash, 'subsub2': subsub}],
argv=['subsub1', '--baz', '1'])
with self.assertRaises(ValueError):
defopt.run([sub, {'subsub1': subsub_with_dash, 'subsub2': subsub}],
argv=['subsub2', '1.5'])
def test_var_positional(self):
for doc in [
":type foo: int", r":type \*foo: int", ":param int foo: doc"]:
def main(*foo): return foo
main.__doc__ = doc
self.assertEqual(defopt.run(main, argv=['1', '2']), (1, 2))
self.assertEqual(defopt.run(main, argv=[]), ())
def test_no_default(self):
def main(a):
""":type a: str"""
with self.assertRaises(SystemExit):
defopt.run(main, argv=[])
def test_keyword_only(self):
def main(foo='bar', *, baz='quux'):
"""
:type foo: str
:type baz: str
"""
return foo, baz
self.assertEqual(defopt.run(main, argv=['FOO', '--baz', 'BAZ']),
('FOO', 'BAZ'))
self.assertEqual(defopt.run(main, argv=[]), ('bar', 'quux'))
def test_keyword_only_no_default(self):
def main(*, foo):
""":type foo: str"""
return foo
self.assertEqual(defopt.run(main, argv=['--foo', 'baz']), 'baz')
with self.assertRaises(SystemExit):
defopt.run(main, argv=[])
def test_var_keywords(self):
def bad(**kwargs):
""":type kwargs: str"""
with self.assertRaises(ValueError):
defopt.run(bad)
def test_bad_arg(self):
with self.assertRaises(TypeError):
defopt.run(foo=None)
def test_no_subparser_specified(self):
def sub1(): assert False
def sub2(): assert False
with self.assertRaises(SystemExit):
defopt.run([sub1, sub2], argv=[])
def test_no_param_doc(self):
def bad(foo):
"""Test function"""
with self.assertRaisesRegex(ValueError, 'type.*foo'):
defopt.run(bad, argv=['foo'])
def test_no_type_doc(self):
def bad(foo):
""":param foo: no type info"""
with self.assertRaisesRegex(ValueError, 'type.*foo'):
defopt.run(bad, argv=['foo'])
def test_return(self):
def one(): return 1
def none(): pass
self.assertEqual(defopt.run([one, none], argv=['one']), 1)
self.assertEqual(defopt.run([one, none], argv=['none']), None)
def test_underscores(self):
def main(a_b_c, *, d_e_f=None):
"""Test function
:type a_b_c: int
:type d_e_f: int
"""
return a_b_c, d_e_f
self.assertEqual(defopt.run(main, argv=['1', '--d-e-f', '2']), (1, 2))
def test_private_with_default(self):
def main(_a=None): pass
defopt.run(main, argv=[])
def test_private_without_default(self):
def main(_a: int): assert False
with self.assertRaisesRegex(ValueError,
# Older Pythons have no space post-colon.
r'parameter _a of main\(_a: ?int\) is '
r'private but has no default'):
defopt.run(main, argv=[])
def test_argparse_kwargs(self):
def main(*, a=None):
""":type a: str"""
return a
self.assertEqual(
defopt.run(main, argparse_kwargs={'prefix_chars': '+'},
argv=['+a', 'foo']),
'foo')
def test_intermixed(self):
def main(*args: int, key: str): return args, key
with self.assertRaises(SystemExit):
defopt.run(main, argv=['1', '-kk', '2'])
if sys.version_info >= (3, 7):
self.assertEqual(
defopt.run(main, argv=['1', '-kk', '2'], intermixed=True),
((1, 2), 'k'))
else:
with self.assertRaises(RuntimeError):
defopt.run(main, argv=['1', '-kk', '2'], intermixed=True)
class TestBindKnown(unittest.TestCase):
def test_bind_known(self):
def main(*args: int, key: str): return args, key
call, rest = defopt.bind_known(
main, argv=['1', '2', '-kk', '-qq'])
self.assertEqual((call(), rest), (((1, 2), 'k'), ['-qq']))
call, rest = defopt.bind_known(
main, argv=['1', '-kk', '2', '-qq'])
self.assertEqual((call(), rest), (((1,), 'k'), ['2', '-qq']))
if sys.version_info >= (3, 7):
call, rest = defopt.bind_known(
main, argv=['1', '-kk', '2', '-qq'], intermixed=True)
self.assertEqual((call(), rest), (((1, 2), 'k'), ['-qq']))
class TestParsers(unittest.TestCase):
def test_parser(self):
def main(value):
""":type value: int"""
return value
self.assertEqual(defopt.run(main, argv=['1']), 1)
def test_overridden_parser(self):
def parser(string):
return int(string) * 2
def main(value):
""":type value: int"""
return value
self.assertEqual(
defopt.run(main, parsers={int: parser}, argv=['1']), 2)
def test_overridden_none_parser(self):
def parser(string):
if string == 'nil':
return None
else:
raise ValueError("Not nil")
def main(ints, strs):
"""
:type ints: typing.List[typing.Optional[int]]
:type strs: typing.List[typing.Optional[str]]
"""
return ints, strs
self.assertEqual(
defopt.run(main, parsers={type(None): parser},
argv=['-i', 'nil', '0', '-s', 'nil', 's']),
([None, 0], [None, 's']))
def test_parse_bool(self):
parser = defopt._get_parser(bool, {})
self.assertEqual(parser('t'), True)
self.assertEqual(parser('FALSE'), False)
self.assertEqual(parser('1'), True)
with self.assertRaises(ValueError):
parser('foo')
def test_parse_path(self):
def main(value):
""":type value: Path"""
return value
self.assertEqual(defopt.run(main, argv=['foo']), Path('foo'))
def test_parse_slice(self):
parser = defopt._get_parser(slice, {})
self.assertEqual(parser(':'), slice(None))
self.assertEqual(parser(':1'), slice(None, 1))
self.assertEqual(parser('"a":"b":"c"'), slice("a", "b", "c"))
with self.assertRaises(ValueError):
parser('1')
def test_no_parser(self):
with self.assertRaisesRegex(Exception, 'no parser'):
defopt._get_parser(object, parsers={type: type})
def test_containers(self):
def main(foo, bar):
"""
:type foo: tuple[float]
:type bar: list[float]
"""
return foo, bar
self.assertEqual(defopt.run(main, argv=['1.1', '--bar', '2.2', '3.3']),
((1.1,), [2.2, 3.3]))
def test_list_kwarg(self):
def main(foo=None):
""":type foo: list[float]"""
return foo
self.assertEqual(
defopt.run(main, argv=['--foo', '1.1', '2.2']), [1.1, 2.2])
def test_list_bare(self):
with self.assertRaises(ValueError):
defopt._get_parser(list, {})
def test_list_keyword_only(self):
def main(*, foo):
""":type foo: list[int]"""
return foo
self.assertEqual(defopt.run(main, argv=['--foo', '1', '2']), [1, 2])
with self.assertRaises(SystemExit):
defopt.run(main, argv=[])
def test_list_var_positional(self):
def modern(*foo):
""":type foo: typing.Iterable[int]"""
return foo
def legacy(*foo):
""":type foo: list[int]"""
return foo
for func in modern, legacy:
out = defopt.run(func, argv=['--foo', '1', '--foo', '2', '3'])
self.assertEqual(out, ([1], [2, 3]))
self.assertEqual(defopt.run(func, argv=[]), ())
def test_bool(self):
def main(foo):
""":type foo: bool"""
return foo
self.assertIs(defopt.run(main, argv=['1']), True)
self.assertIs(defopt.run(main, argv=['0']), False)
with self.assertRaises(SystemExit):
defopt.run(main, argv=[])
def test_bool_optional(self):
def main(foo=None):
""":type foo: typing.Optional[bool]"""
return foo
self.assertIs(defopt.run(main, argv=['1'],
parsers={type(None): _parse_none}), True)
self.assertIs(defopt.run(main, argv=['0'],
parsers={type(None): _parse_none}), False)
with self.assertRaises(SystemExit):
defopt.run(main, argv=[':none:'])
self.assertIs(defopt.run(main, argv=[':none:'],
parsers={type(None): _parse_none}), None)
self.assertIs(defopt.run(main, argv=[],
parsers={type(None): _parse_none}), None)
def test_bool_optional_keyword_none(self):
def main(*, foo=None):
""":type foo: typing.Optional[bool]"""
return foo
self.assertIs(defopt.run(main, argv=['--foo']), True)
self.assertIs(defopt.run(main, argv=['--no-foo']), False)
self.assertIs(defopt.run(main, argv=[]), None)
def test_bool_optional_keyword_true(self):
def main(*, foo=True):
""":type foo: typing.Optional[bool]"""
return foo
# cannot get a None value in this case from the CLI
self.assertIs(defopt.run(main, argv=['--foo']), True)
self.assertIs(defopt.run(main, argv=['--no-foo']), False)
self.assertIs(defopt.run(main, argv=[]), True)
def test_bool_optional_keyword_false(self):
def main(*, foo=False):
""":type foo: typing.Optional[bool]"""
return foo
self.assertIs(defopt.run(main, argv=['--foo']), True)
self.assertIs(defopt.run(main, argv=['--no-foo']), False)
self.assertIs(defopt.run(main, argv=[]), False)
def test_bool_optional_keyword_none_no_negated_flags(self):
def main(*, foo=None):
""":type foo: typing.Optional[bool]"""
return foo
self.assertIs(defopt.run(main, argv=['--foo'], no_negated_flags=True),
True)
with self.assertRaises(SystemExit):
self.assertIs(defopt.run(main, argv=['--no-foo'],
no_negated_flags=True), False)
self.assertIs(defopt.run(main, argv=[], no_negated_flags=True), None)
def test_bool_optional_keyword_true_no_negated_flags(self):
def main(*, foo=True):
""":type foo: typing.Optional[bool]"""
return foo
self.assertIs(defopt.run(main, argv=['--foo'], no_negated_flags=True),
True)
# negated flag is still added, else foo could only be True
self.assertIs(defopt.run(main, argv=['--no-foo'],
no_negated_flags=True), False)
self.assertIs(defopt.run(main, argv=[], no_negated_flags=True), True)
def test_bool_optional_keyword_false_no_negated_flags(self):
def main(*, foo=False):
""":type foo: typing.Optional[bool]"""
return foo
self.assertIs(defopt.run(main, argv=['--foo'], no_negated_flags=True),
True)
with self.assertRaises(SystemExit):
self.assertIs(defopt.run(main, argv=['--no-foo'],
no_negated_flags=True), False)
self.assertIs(defopt.run(main, argv=[], no_negated_flags=True), False)
def test_bool_list(self):
def main(foo):
""":type foo: list[bool]"""
return foo
self.assertEqual(
defopt.run(main, argv=['--foo', '1', '0']), [True, False])
def test_bool_var_positional(self):
def main(*foo):
""":type foo: bool"""
return foo
self.assertEqual(
defopt.run(main, argv=['1', '1', '0']), (True, True, False))
self.assertEqual(
defopt.run(main, argv=[]), ())
def test_bool_list_var_positional(self):
def main(*foo):
""":type foo: list[bool]"""
return foo
argv = ['--foo', '1', '--foo', '0', '0']
self.assertEqual(
defopt.run(main, argv=argv), ([True], [False, False]))
self.assertEqual(
defopt.run(main, argv=[]), ())
def test_bool_kwarg(self):
def main(foo='default'):
""":type foo: bool"""
return foo
self.assertIs(defopt.run(main, cli_options='has_default',
argv=[]), 'default')
self.assertIs(defopt.run(main, cli_options='has_default',
argv=['--foo']), True)
self.assertIs(defopt.run(main, cli_options='has_default',
argv=['--no-foo']), False)
self.assertIs(defopt.run(main, cli_options='has_default',
argv=['--foo', '--no-foo']), False)
def test_bool_keyword_only(self):
def main(*, foo):
""":type foo: bool"""
return foo
self.assertIs(defopt.run(main, argv=['--foo']), True)
self.assertIs(defopt.run(main, argv=['--no-foo']), False)
with self.assertRaises(SystemExit):
defopt.run(main, argv=[])
def test_cli_options(self):
def main(foo):
""":type foo: bool"""
return foo
self.assertIs(
defopt.run(main, cli_options='all', argv=['--foo']), True)
self.assertIs(
defopt.run(main, cli_options='all', argv=['--no-foo']), False)
with self.assertRaises(SystemExit):
defopt.run(main, cli_options='all', argv=['1'])
with self.assertRaises(SystemExit):
defopt.run(main, argv=['--foo'])
with self.assertRaises(SystemExit):
defopt.run(main, argv=['--no-foo'])
with self.assertRaises(SystemExit):
defopt.run(main, argv=[])
def test_implicit_parser(self):
def ok(foo):
""":type foo: ConstructibleFromStr"""
return foo
self.assertEqual(defopt.run(ok, argv=["foo"]).s, "foo")
def test_implicit_noparser(self):
def notok(foo):
""":type foo: NotConstructibleFromStr"""
with self.assertRaisesRegex(Exception, 'no parser.*NotConstructible'):
defopt.run(notok, argv=["foo"])
class TestFlags(unittest.TestCase):
def test_short_flags(self):
def func(foo=1):
""":type foo: int"""
return foo
self.assertEqual(
defopt.run(func, short={'foo': 'f'}, cli_options='has_default',
argv=['-f', '2']),
2)
def test_short_negation(self):
def func(*, foo=False):
""":type foo: bool"""
return foo
self.assertIs(
defopt.run(func, short={'foo': 'f', 'no-foo': 'F'}, argv=['-f']),
True)
self.assertIs(
defopt.run(func, short={'foo': 'f', 'no-foo': 'F'}, argv=['-F']),
False)
def test_auto_short(self):
def func(*, foo=1, bar=2, baz=3):
"""
:type foo: int
:type bar: int
:type baz: int
"""
return foo
self.assertEqual(defopt.run(func, argv=['-f', '2']), 2)
with self.assertRaises(SystemExit):
defopt.run(func, argv=['-b', '2'])
def test_auto_short_help(self):
def func(*, hello="world"):
""":type hello: str"""
defopt.run(func, argv=[])
with self.assertRaises(SystemExit):
defopt.run(func, argv=["-h", ""])
self.assertEqual(
defopt.run(
func, argparse_kwargs={"add_help": False}, argv=["-h", ""]),
None)
class TestEnums(unittest.TestCase):
def test_enum(self):
def main(foo):
""":type foo: Choice"""
return foo
self.assertEqual(defopt.run(main, argv=['one']), Choice.one)
self.assertEqual(defopt.run(main, argv=['two']), Choice.two)
with self.assertRaises(SystemExit):
defopt.run(main, argv=['three'])
def test_optional(self):
def main(*, foo=None):
""":type foo: Choice"""
return foo
self.assertEqual(defopt.run(main, argv=['--foo', 'one']), Choice.one)
self.assertIs(defopt.run(main, argv=[]), None)
def test_subcommand(self):
def sub1(foo):
""":type foo: Choice"""
return foo
def sub2(bar):
""":type bar: Choice"""
return bar
self.assertEqual(
defopt.run([sub1, sub2], argv=['sub1', 'one']), Choice.one)
self.assertEqual(
defopt.run([sub1, sub2], argv=['sub2', 'two']), Choice.two)
class TestTuple(unittest.TestCase):
def test_tuple(self):
def main(foo):
""":param typing.Tuple[int,str] foo: foo"""
return foo
self.assertEqual(defopt.run(main, argv=['1', '2']), (1, '2'))
def test_tuple_variable_length(self):
def main(foo):
""":param typing.Tuple[int,...] foo: foo"""
return foo
self.assertEqual(defopt.run(main, argv=['1', '2', '3']), (1, 2, 3))
def test_tupleenum(self):
def main(foo: typing.Tuple[Choice] = None):
return foo
self.assertEqual(defopt.run(main, argv=['one']), (Choice.one,))
def test_namedtuple(self):
# Add a second argument after the tuple to ensure that the converter
# closes over the correct type.
def main(foo, bar):
"""
:param Pair foo: foo
:param int bar: bar
"""
return foo
# Instances of the Pair class compare equal to tuples, so we compare
# their __str__ instead to make sure that the type is correct too.
self.assertEqual(str(defopt.run(main, argv=['1', '2', '3'])),
str(Pair(1, '2')))
def test_enumnamedtuple(self):
class EnumPair(Pair, Enum):
a = Pair('A', 1)
b = Pair('B', 2)
def main(foo: EnumPair): return foo
self.assertEqual(defopt.run(main, argv=['a']), EnumPair.a)
def test_tuple_fails_early(self):
def main(foo):
""":param typing.Tuple[int,NotConstructibleFromStr] foo: foo"""
with self.assertRaisesRegex(Exception, 'no parser'):
defopt.run(main, argv=['-h'])
class TestUnion(unittest.TestCase):
def test_union(self):
def main(foo, bar=None):
"""
:param typing.Union[int,str] foo: foo
:param bar: bar
:type bar: float or str
"""
return type(foo), type(bar)
self.assertEqual(defopt.run(main, argv=['1', '2']), (int, float))
self.assertEqual(defopt.run(main, argv=['1', 'b']), (int, str))
self.assertEqual(defopt.run(main, argv=['a', '2']), (str, float))
def test_or_union(self):
if not hasattr(types, "UnionType"):
raise unittest.SkipTest("A|B-style unions not supported")
def main(foo):
""":param int|str foo: foo"""
return type(foo)
self.assertEqual(defopt.run(main, argv=['1']), int)
self.assertEqual(defopt.run(main, argv=['x']), str)
def test_bad_parse(self):
def main(foo):
""":param typing.Union[int,float] foo: foo"""
with self.assertRaises(SystemExit):
defopt.run(main, argv=['bar'])
def test_bad_union(self):
def main(foo):
""":param typing.Union[int,typing.List[str]] foo: foo"""
with self.assertRaises(ValueError):
defopt.run(main, argv=['1'])
def main(foo):
"""
:param foo: foo
:type foo: int or list[str]
"""
with self.assertRaises(ValueError):
defopt.run(main, argv=['1'])
def test_not_bad_union(self):
# get_type_hints reports a type of Union[List[int], NoneType] so check
# that this doesn't get reported as "unsupported union including
# container type".
def main(foo: typing.List[int] = None): return foo
self.assertEqual(defopt.run(main, argv=['--foo', '1']), [1])
def test_union_infaillible_and_unparseable(self):
def main(foo: typing.Union[str, NotConstructibleFromStr],
bar: typing.Union[Path, NotConstructibleFromStr]):
return foo, bar
self.assertEqual(defopt.run(main, argv=['a', 'b']), ('a', Path('b')))
def test_union_unparseable_and_infaillible(self):
def main(foo: typing.Union[NotConstructibleFromStr, str]): return foo
with self.assertRaises(Exception):
defopt.run(main, argv=['foo'])
def main(foo: typing.Union[NotConstructibleFromStr, Path]): return foo
with self.assertRaises(Exception):
defopt.run(main, argv=['foo'])
class TestOptional(unittest.TestCase):
def test_optional_hint_list(self):
def main(op: typing.Optional[typing.List[str]]): return op
self.assertEqual(defopt.run(main, argv=['--op', '1', '2']), ['1', '2'])
def test_optional_hint_tuple(self):
def main(op: typing.Optional[typing.Tuple[int]]): return op
self.assertEqual(defopt.run(main, argv=['1']), (1,))
def test_optional_doc_list(self):
def main(op):
""":param typing.Optional[typing.List[int]] op: op"""
return op
self.assertEqual(defopt.run(main, argv=['--op', '1', '2']), [1, 2])
def test_optional_doc_tuple(self):
def main(op):
""":param typing.Optional[typing.Tuple[str]] op: op"""
return op
self.assertEqual(defopt.run(main, argv=['1']), ('1',))
def test_union_operator_hint_list(self):
if not hasattr(types, "UnionType"):
raise unittest.SkipTest("A|B-style unions not supported")
def main(op: typing.List[str] | None): return op
self.assertEqual(defopt.run(main, argv=['--op', '1', '2']), ['1', '2'])
def test_union_operator_hint_tuple(self):
if not hasattr(types, "UnionType"):
raise unittest.SkipTest("A|B-style unions not supported")
def main(op: typing.Tuple[int] | None): return op
self.assertEqual(defopt.run(main, argv=['1']), (1,))
def test_union_operator_doc_list(self):
if not hasattr(types, "UnionType"):
raise unittest.SkipTest("A|B-style unions not supported")
def main(op):
""":param list[int]|None op: op"""
return op
self.assertEqual(defopt.run(main, argv=['--op', '1', '2']), [1, 2])
def test_union_operator_doc_one_item_tuple(self):
if not hasattr(types, "UnionType"):
raise unittest.SkipTest("A|B-style unions not supported")
def main(op):
""":param tuple[int]|None op: op"""
return op
self.assertEqual(defopt.run(main, argv=['1']), (1,))
def test_union_operator_doc_multiple_item_tuple(self):
if not hasattr(types, "UnionType"):
raise unittest.SkipTest("A|B-style unions not supported")
def main(op):
""":param tuple[str,str]|None op: op"""
return op
self.assertEqual(defopt.run(main, argv=['a', 'b']), ('a', 'b'))
def test_multiple_item_optional_tuple_none_parser(self):
def main(op):
""":param typing.Optional[typing.Tuple[int, int]] op: op"""
with self.assertRaises(ValueError):
defopt.run(main, argv=['1', '2'],
parsers={type(None): _parse_none})
def test_one_item_optional_tuple_none_parser(self):
def main(op):
""":param typing.Optional[typing.Tuple[int]] op: op"""
return op
self.assertEqual(defopt.run(main, argv=['1'],
parsers={type(None): _parse_none}),
(1,))
self.assertEqual(defopt.run(main, argv=[':none:'],
parsers={type(None): _parse_none}),
None)
with self.assertRaises(SystemExit):
defopt.run(main, argv=['foo'],
parsers={type(None): _parse_none})
class TestLiteral(unittest.TestCase):
def test_literal(self):
def main(foo):
""":param defopt.Literal[Choice.one,"bar","baz"] foo: foo"""
return foo
self.assertEqual(defopt.run(main, argv=['bar']), 'bar')
self.assertEqual(defopt.run(main, argv=['one']), Choice.one)
with self.assertRaises(SystemExit):
defopt.run(main, argv=['quux'])
class TestExceptions(unittest.TestCase):
def test_exceptions(self):
def main(name):
"""
:param str name: name
:raises RuntimeError:
"""
raise getattr(builtins, name)('oops')
with self.assertRaises(SystemExit):
defopt.run(main, argv=['RuntimeError'])
with self.assertRaises(ValueError):
defopt.run(main, argv=['ValueError'])
class TestDoc(unittest.TestCase):
def test_parse_docstring(self):
doc = """
Test function
:param one: first param
:type one: int
:param float two: second param
:returns: str
:junk one two: nothing
"""
doc_sig = defopt._parse_docstring(inspect.cleandoc(doc))
self.assertEqual(doc_sig.doc, 'Test function\n\n')
one = doc_sig.parameters['one']
self.assertEqual(one.doc, 'first param')
self.assertEqual(one.annotation, 'int')
two = doc_sig.parameters['two']
self.assertEqual(two.doc, 'second param')
self.assertEqual(two.annotation, 'float')
def test_parse_params(self):
doc = """
Test function
:param first: first param
:parameter int second: second param
:arg third: third param
:argument float fourth: fourth param
:key fifth: fifth param
:keyword str sixth: sixth param
"""
doc_sig = defopt._parse_docstring(inspect.cleandoc(doc))
self.assertEqual(doc_sig.parameters['first'].doc, 'first param')
self.assertEqual(doc_sig.parameters['second'].doc, 'second param')
self.assertEqual(doc_sig.parameters['third'].doc, 'third param')
self.assertEqual(doc_sig.parameters['fourth'].doc, 'fourth param')
self.assertEqual(doc_sig.parameters['fifth'].doc, 'fifth param')
self.assertEqual(doc_sig.parameters['sixth'].doc, 'sixth param')
def test_parse_doubles(self):
doc = """
Test function
:param int param: the parameter
:type param: int
"""
with self.assertRaises(ValueError):
defopt._parse_docstring(inspect.cleandoc(doc))
doc = """Test function
:type param: int
:param int param: the parameter
"""
with self.assertRaises(ValueError):
defopt._parse_docstring(inspect.cleandoc(doc))
def test_no_doc(self):
doc_sig = defopt._parse_docstring(None)
self.assertEqual(doc_sig.doc, '')
self.assertEqual(doc_sig.parameters, {})
def test_param_only(self):
doc_sig = defopt._parse_docstring(""":param int param: test""")
self.assertEqual(doc_sig.doc, '')
param = doc_sig.parameters['param']
self.assertEqual(param.doc, 'test')
self.assertEqual(param.annotation, 'int')
def test_implicit_role(self):
doc_sig = defopt._parse_docstring("""start `int` end""")
self.assertEqual(doc_sig.doc, 'start \033[4mint\033[0m end\n\n')
def test_explicit_role(self):
doc_sig = defopt._parse_docstring(
"""start :py:class:`int` :kbd:`ctrl` end""")
self.assertEqual(doc_sig.doc, 'start int ctrl end\n\n')
def test_sphinx(self):
doc = """
One line summary.
Extended description.
:param int arg1: Description of arg1
:param str arg2: Description of arg2
And more about arg2
:keyword float arg3: Description of arg3
:returns: Description of return value.
:rtype: str
.. rubric:: examples
>>> print("hello, world")
"""
doc_sig = defopt._parse_docstring(inspect.cleandoc(doc))
self._check_doc(doc_sig)
def test_google(self):
# Docstring modified from Napoleon's example.
doc = """
One line summary.
Extended description.
Args:
arg1(int): Description of arg1
arg2(str): Description of arg2
And more about arg2
Keyword Arguments:
arg3(float): Description of arg3
Returns:
str: Description of return value.
Examples:
>>> print("hello, world")