-
-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathtest.py
executable file
·1463 lines (1190 loc) · 58.6 KB
/
test.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
#!/usr/bin/env python
import argparse
import contextlib
import os
import os.path
import re
import shutil
import subprocess
import sys
import unittest
import unittest.util
from io import StringIO
from tempfile import NamedTemporaryFile, TemporaryFile, mkdtemp
import pexpect
from pexpect.replwrap import PEXPECT_CONTINUATION_PROMPT, PEXPECT_PROMPT, REPLWrapper
TEST_DIR = os.path.abspath(os.path.dirname(__file__))
BASE_DIR = os.path.dirname(TEST_DIR)
sys.path.insert(0, BASE_DIR)
from argparse import SUPPRESS, ArgumentParser # noqa: E402
import argcomplete # noqa: E402
import argcomplete.io # noqa: E402
from argcomplete import ( # noqa: E402
CompletionFinder,
ExclusiveCompletionFinder,
_check_module,
autocomplete,
shellcode,
warn,
)
from argcomplete.completers import DirectoriesCompleter, FilesCompleter, SuppressCompleter # noqa: E402
from argcomplete.lexers import split_line # noqa: E402
# Default max length is insufficient for troubleshooting.
unittest.util._MAX_LENGTH = 1000
IFS = "\013"
COMP_WORDBREAKS = " \t\n\"'><=;|&(:"
BASH_VERSION = subprocess.check_output(["bash", "-c", "echo $BASH_VERSION"]).decode()
BASH_MAJOR_VERSION = int(BASH_VERSION.split(".")[0])
class ArgcompleteREPLWrapper(REPLWrapper):
def run_command(self, command, **kwargs):
if "\n" in command:
raise Exception("newlines not supported in REPL input")
res = super().run_command(command, **kwargs)
if self.child.command.split("/")[-1] == "zsh":
if "\n" not in res:
raise Exception("Expected to see a newline in command response")
echo_cmd, actual_res = res.split("\n", 1)
res_without_ansi_seqs = re.sub(r"\x1b\[0m.+\x1b\[J", "", actual_res)
# Unsure why some environments produce trailing null characters,
# but they break tests and trimming them seems to be harmless.
# https://github.com/kislyuk/argcomplete/issues/447
res_without_null_chars = res_without_ansi_seqs.rstrip("\x00")
return res_without_null_chars
else:
return res
def _repl_sh(command, args, non_printable_insert):
os.environ["PS1"] = "$"
os.environ["TERM"] = ""
child = pexpect.spawn(command, args, echo=False, encoding="utf-8")
ps1 = PEXPECT_PROMPT[:5] + non_printable_insert + PEXPECT_PROMPT[5:]
ps2 = PEXPECT_CONTINUATION_PROMPT[:5] + non_printable_insert + PEXPECT_CONTINUATION_PROMPT[5:]
prompt_change = f"PS1='{ps1}' PS2='{ps2}' PROMPT_COMMAND=''"
return ArgcompleteREPLWrapper(child, "\\$", prompt_change, extra_init_cmd="export PAGER=cat")
def bash_repl(command="bash"):
bashrc = os.path.join(os.path.dirname(pexpect.__file__), "bashrc.sh")
sh = _repl_sh(command, ["--rcfile", bashrc], non_printable_insert="\\[\\]")
return sh
def zsh_repl(command="zsh"):
sh = _repl_sh(command, ["--no-rcs", "--no-globalrcs", "-V"], non_printable_insert="%(!..)")
# Require two tabs to print all options (some tests rely on this).
sh.run_command("setopt BASH_AUTO_LIST")
return sh
def setUpModule():
os.environ["INPUTRC"] = os.path.join(os.path.dirname(__file__), "inputrc")
class TempDir:
"""
Temporary directory for testing FilesCompletion
Usage:
with TempDir(prefix="temp_fc") as t:
print("tempdir", t)
# you are not chdir-ed to the temporary directory
# everything created here will be deleted
"""
def __init__(self, suffix="", prefix="tmpdir", dir=None):
self.tmp_dir = mkdtemp(suffix=suffix, prefix=prefix, dir=dir)
self.old_dir = os.getcwd()
def __enter__(self):
os.chdir(self.tmp_dir)
return self.tmp_dir
def __exit__(self, *err):
os.chdir(self.old_dir)
shutil.rmtree(self.tmp_dir)
class TestArgcomplete(unittest.TestCase):
def setUp(self):
self._os_environ = os.environ
os.environ = os.environ.copy()
os.environ["_ARGCOMPLETE"] = "1"
os.environ["_ARC_DEBUG"] = "yes"
os.environ["IFS"] = IFS
os.environ["_ARGCOMPLETE_COMP_WORDBREAKS"] = COMP_WORDBREAKS
os.environ["_ARGCOMPLETE_SHELL"] = "bash"
def tearDown(self):
os.environ = self._os_environ
def run_completer(self, parser, command, point=None, completer=autocomplete, shell="bash", **kwargs):
if point is None:
point = str(len(command))
with TemporaryFile(mode="w+") as t:
os.environ["COMP_LINE"] = command
os.environ["COMP_POINT"] = point
os.environ["_ARGCOMPLETE_SHELL"] = shell
with self.assertRaises(SystemExit) as cm:
completer(parser, output_stream=t, exit_method=sys.exit, **kwargs)
if cm.exception.code != 0:
raise Exception("Unexpected exit code %d" % cm.exception.code)
t.seek(0)
return t.read().split(IFS)
def test_basic_completion(self):
p = ArgumentParser()
p.add_argument("--foo")
p.add_argument("--bar")
completions = self.run_completer(p, "prog ")
self.assertEqual(set(completions), set(["-h", "--help", "--foo", "--bar"]))
completions = self.run_completer(p, "prog -")
self.assertEqual(set(completions), set(["-h", "--help", "--foo", "--bar"]))
completions = self.run_completer(p, "prog ", always_complete_options=False)
self.assertEqual(set(completions), set([""]))
completions = self.run_completer(p, "prog -", always_complete_options=False)
self.assertEqual(set(completions), set(["-h", "--help", "--foo", "--bar"]))
def test_choices(self):
def make_parser():
parser = ArgumentParser()
parser.add_argument("--ship", choices=["submarine", "speedboat"])
return parser
expected_outputs = (
("prog ", ["--ship", "-h", "--help"]),
("prog --shi", ["--ship "]),
("prog --ship ", ["submarine", "speedboat"]),
("prog --ship s", ["submarine", "speedboat"]),
("prog --ship su", ["submarine "]),
("prog --ship=", ["submarine", "speedboat"]),
("prog --ship=s", ["submarine", "speedboat"]),
("prog --ship=su", ["submarine "]),
)
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd)), set(output))
def test_non_str_choices(self):
def make_parser():
parser = ArgumentParser()
parser.add_argument("x", type=int, choices=[4, 8, 15, 16, 23, 42])
return parser
expected_outputs = (
("prog ", ["4", "8", "15", "16", "23", "42", "-h", "--help"]),
("prog 1", ["15", "16"]),
("prog 2", ["23 "]),
("prog 4", ["4", "42"]),
("prog 4 ", ["-h", "--help"]),
)
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd)), set(output))
def test_suppress_args(self):
def make_parser():
parser = ArgumentParser()
parser.add_argument("--foo")
parser.add_argument("--bar", help=SUPPRESS)
return parser
expected_outputs = (("prog ", ["--foo", "-h", "--help"]), ("prog --b", [""]))
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd)), set(output))
expected_outputs = (("prog ", ["--foo", "--bar", "-h", "--help"]), ("prog --b", ["--bar "]))
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd, print_suppressed=True)), set(output))
def test_suppress_completer(self):
def make_parser():
parser = ArgumentParser()
parser.add_argument("--foo")
arg = parser.add_argument("--bar")
arg.completer = SuppressCompleter()
return parser
expected_outputs = (("prog ", ["--foo", "-h", "--help"]), ("prog --b", [""]))
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd)), set(output))
expected_outputs = (("prog ", ["--foo", "--bar", "-h", "--help"]), ("prog --b", ["--bar "]))
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd, print_suppressed=True)), set(output))
def test_action_activation(self):
def make_parser():
parser = ArgumentParser()
parser.add_argument("var", choices=["bus", "car"])
parser.add_argument("value", choices=["orange", "apple"])
return parser
expected_outputs = (
("prog ", ["bus", "car", "-h", "--help"]),
("prog bu", ["bus "]),
("prog bus ", ["apple", "orange", "-h", "--help"]),
("prog bus appl", ["apple "]),
("prog bus apple ", ["-h", "--help"]),
)
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd)), set(output))
def test_action_activation_with_subparser(self):
def make_parser():
parser = ArgumentParser()
parser.add_argument("name", nargs=2, choices=["a", "b", "c"])
subparsers = parser.add_subparsers(title="subcommands", metavar="subcommand")
subparser_build = subparsers.add_parser("build")
subparser_build.add_argument("var", choices=["bus", "car"])
subparser_build.add_argument("--profile", nargs=1)
return parser
expected_outputs = (
("prog ", ["a", "b", "c", "-h", "--help"]),
("prog b", ["b "]),
("prog b ", ["a", "b", "c", "-h", "--help"]),
("prog c b ", ["build", "-h", "--help"]),
("prog c b bu", ["build "]),
("prog c b build ", ["bus", "car", "--profile", "-h", "--help"]),
("prog c b build ca", ["car "]),
("prog c b build car ", ["--profile", "-h", "--help"]),
("prog build car ", ["-h", "--help"]),
("prog a build car ", ["-h", "--help"]),
)
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd)), set(output))
def test_completers(self):
self.completions = ["http://url1", "http://url2"]
def c_url(prefix, parsed_args, **kwargs):
return self.completions
def make_parser():
parser = ArgumentParser()
parser.add_argument("--url").completer = c_url
parser.add_argument("--email", nargs=3, choices=["a@b.c", "a@b.d", "ab@c.d", "bcd@e.f", "bce@f.g"])
return parser
expected_outputs = (
("prog --url ", ["http://url1", "http://url2"]),
('prog --url "', ["http://url1", "http://url2"]),
('prog --url "http://url1" --email ', ["a@b.c", "a@b.d", "ab@c.d", "bcd@e.f", "bce@f.g"]),
('prog --url "http://url1" --email a', ["a@b.c", "a@b.d", "ab@c.d"]),
('prog --url "http://url1" --email "a@', ["a@b.c", "a@b.d"]),
('prog --url "http://url1" --email "a@b.c" "a@b.d" "a@', ["a@b.c", "a@b.d"]),
('prog --url "http://url1" --email "a@b.c" "a@b.d" "ab@c.d" ', ["--url", "--email", "-h", "--help"]),
)
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd)), set(output))
self.completions = {"http://url1": "foo", "http://url2": "bar"}
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd)), set(output))
zsh_expected_outputs = (
("prog --url ", ["http\\://url1:foo", "http\\://url2:bar"]),
('prog --url "', ["http\\://url1:foo", "http\\://url2:bar"]),
('prog --url "http://url1" --email ', ["a@b.c:", "a@b.d:", "ab@c.d:", "bcd@e.f:", "bce@f.g:"]),
('prog --url "http://url1" --email a', ["a@b.c:", "a@b.d:", "ab@c.d:"]),
('prog --url "http://url1" --email "a@', ["a@b.c:", "a@b.d:"]),
('prog --url "http://url1" --email "a@b.c" "a@b.d" "a@', ["a@b.c:", "a@b.d:"]),
(
'prog --url "http://url1" --email "a@b.c" "a@b.d" "ab@c.d" ',
["--url:", "--email:", "-h:show this help message and exit", "--help:show this help message and exit"],
),
)
for cmd, output in zsh_expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd, shell="zsh")), set(output))
def test_subparser_completers(self):
def c_depends_on_positional_arg1(prefix, parsed_args, **kwargs):
return [parsed_args.arg1]
def c_depends_on_optional_arg5(prefix, parsed_args, **kwargs):
return [parsed_args.arg5]
def make_parser():
parser = ArgumentParser()
subparsers = parser.add_subparsers()
subparser = subparsers.add_parser("subcommand")
subparser.add_argument("arg1")
subparser.add_argument("arg2").completer = c_depends_on_positional_arg1
subparser.add_argument("arg3").completer = c_depends_on_optional_arg5
subparser.add_argument("--arg4").completer = c_depends_on_optional_arg5
subparser.add_argument("--arg5")
return parser
expected_outputs = (
("prog subcommand val1 ", ["val1", "--arg4", "--arg5", "-h", "--help"]),
("prog subcommand val1 val2 --arg5 val5 ", ["val5", "--arg4", "--arg5", "-h", "--help"]),
("prog subcommand val1 val2 --arg5 val6 --arg4 v", ["val6 "]),
)
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd)), set(output))
def test_file_completion(self):
# setup and teardown should probably be in class
with TempDir(prefix="test_dir_fc", dir="."):
fc = FilesCompleter()
os.makedirs(os.path.join("abcdefж", "klm"))
self.assertEqual(fc("a"), ["abcdefж/"])
os.makedirs(os.path.join("abcaha", "klm"))
with open("abcxyz", "w") as fp:
fp.write("test")
self.assertEqual(set(fc("a")), set(["abcdefж/", "abcaha/", "abcxyz"]))
def test_filescompleter_filetype_integration(self):
def make_parser():
parser = ArgumentParser()
parser.add_argument("--r", type=argparse.FileType("r"))
parser.add_argument("--w", type=argparse.FileType("w"))
return parser
with TempDir(prefix="test_dir_fc2", dir="."):
os.makedirs(os.path.join("abcdefж", "klm"))
os.makedirs(os.path.join("abcaha", "klm"))
with open("abcxyz", "w") as fh, open("abcdefж/klm/test", "w") as fh2:
fh.write("test")
fh2.write("test")
expected_outputs = (
("prog subcommand --r ", ["abcxyz", "abcdefж/", "abcaha/"]),
("prog subcommand --w abcdefж/klm/t", ["abcdefж/klm/test "]),
)
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd)), set(output))
def test_directory_completion(self):
completer = DirectoriesCompleter()
def c(prefix):
return set(completer(prefix))
with TempDir(prefix="test_dir", dir="."):
# Create some temporary dirs and files (files must be ignored)
os.makedirs(os.path.join("abc", "baz"))
os.makedirs(os.path.join("abb", "baz"))
os.makedirs(os.path.join("abc", "faz"))
os.makedirs(os.path.join("def", "baz"))
with open("abc1", "w") as fp1:
with open("def1", "w") as fp2:
fp1.write("A test")
fp2.write("Another test")
# Test completions
self.assertEqual(c("a"), set(["abb/", "abc/"]))
self.assertEqual(c("ab"), set(["abc/", "abb/"]))
self.assertEqual(c("abc"), set(["abc/"]))
self.assertEqual(c("abc/"), set(["abc/baz/", "abc/faz/"]))
self.assertEqual(c("d"), set(["def/"]))
self.assertEqual(c("def/"), set(["def/baz/"]))
self.assertEqual(c("e"), set([]))
self.assertEqual(c("def/k"), set([]))
return
def test_default_completer(self):
def make_parser():
parser = ArgumentParser(add_help=False)
parser.add_argument("--one")
parser.add_argument("--many", nargs="+")
return parser
with TempDir(prefix="test_dir_dc", dir="."):
os.mkdir("test")
expected_outputs = (
("prog --one ", ["test/"]),
("prog --many ", ["test/"]),
("prog --many test/ ", ["test/", "--one", "--many"]),
)
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd)), set(output))
def test_subparsers(self):
def make_parser():
parser = ArgumentParser()
parser.add_argument("--age", type=int)
sub = parser.add_subparsers()
eggs = sub.add_parser("eggs")
eggs.add_argument("type", choices=["on a boat", "with a goat", "in the rain", "on a train"])
spam = sub.add_parser("spam")
spam.add_argument("type", choices=["ham", "iberico"])
return parser
expected_outputs = (
("prog ", ["--help", "eggs", "-h", "spam", "--age"]),
("prog --age 1 eggs", ["eggs "]),
(
"prog --age 2 eggs ",
[r"on\ a\ train", r"with\ a\ goat", r"on\ a\ boat", r"in\ the\ rain", "--help", "-h"],
),
("prog eggs ", [r"on\ a\ train", r"with\ a\ goat", r"on\ a\ boat", r"in\ the\ rain", "--help", "-h"]),
('prog eggs "on a', ["on a train", "on a boat"]),
("prog eggs on\\ a", [r"on\ a\ train", r"on\ a\ boat"]),
("prog spam ", ["iberico", "ham", "--help", "-h"]),
)
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd)), set(output))
self.assertEqual(set(self.run_completer(make_parser(), cmd, exclude=["-h"])), set(output) - set(["-h"]))
self.assertEqual(
set(self.run_completer(make_parser(), cmd, exclude=["-h", "--help"])),
set(output) - set(["-h", "--help"]),
)
def test_non_ascii(self):
def make_parser():
parser = ArgumentParser()
parser.add_argument(
"--книга",
choices=[
"Трудно быть богом",
"Парень из преисподней",
"Понедельник начинается в субботу",
],
)
return parser
expected_outputs = (
("prog ", ["--книга", "-h", "--help"]),
(
"prog --книга ",
[r"Трудно\ быть\ богом", r"Парень\ из\ преисподней", r"Понедельник\ начинается\ в\ субботу"],
),
("prog --книга П", [r"Парень\ из\ преисподней", r"Понедельник\ начинается\ в\ субботу"]),
("prog --книга Пу", [""]),
)
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd)), set(output))
def test_custom_validator(self):
def make_parser():
parser = ArgumentParser()
parser.add_argument("var", choices=["bus", "car"])
parser.add_argument("value", choices=["orange", "apple"])
return parser
expected_outputs = (
("prog ", ["-h", "--help"]),
("prog bu", [""]),
("prog bus ", ["-h", "--help"]),
("prog bus appl", [""]),
("prog bus apple ", ["-h", "--help"]),
)
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd, validator=lambda x, y: False)), set(output))
def test_different_validators(self):
def make_parser():
parser = ArgumentParser()
parser.add_argument("var", choices=["bus", "car"])
parser.add_argument("value", choices=["orange", "apple"])
return parser
validators = (
lambda x, y: False,
lambda x, y: True,
lambda x, y: x.startswith(y),
)
expected_outputs = (
("prog ", ["-h", "--help"], validators[0]),
("prog ", ["bus", "car", "-h", "--help"], validators[1]),
("prog bu", ["bus", "car"], validators[1]),
("prog bus ", ["apple", "orange", "-h", "--help"], validators[1]),
("prog bus appl", ["apple "], validators[2]),
("prog bus cappl", [""], validators[2]),
("prog bus pple ", ["-h", "--help"], validators[2]),
)
for cmd, output, validator in expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd, validator=validator)), set(output))
def test_readline_entry_point(self):
def get_readline_completions(completer, text):
completions = []
for i in range(9999):
completion = completer.rl_complete(text, i)
if completion is None:
break
completions.append(completion)
return completions
parser = ArgumentParser()
parser.add_argument("rover", choices=["sojourner", "spirit", "opportunity", "curiosity"])
parser.add_argument("antenna", choices=["low gain", "high gain"])
completer = CompletionFinder(parser)
self.assertEqual(
get_readline_completions(completer, ""), ["-h", "--help", "sojourner", "spirit", "opportunity", "curiosity"]
)
self.assertEqual(get_readline_completions(completer, "s"), ["sojourner", "spirit"])
self.assertEqual(get_readline_completions(completer, "x"), [])
def test_display_completions(self):
parser = ArgumentParser()
parser.add_argument(
"rover", choices=["sojourner", "spirit", "opportunity", "curiosity"], help="help for rover "
)
parser.add_argument("antenna", choices=["low gain", "high gain"], help="help for antenna")
sub = parser.add_subparsers()
p = sub.add_parser("list")
p.add_argument("-o", "--oh", help="ttt")
p.add_argument("-c", "--ch", help="ccc")
sub2 = p.add_subparsers()
sub2.add_parser("cat", help="list cat")
sub2.add_parser("dog", help="list dog")
completer = CompletionFinder(parser)
completer.rl_complete("", 0)
disp = completer.get_display_completions()
self.assertEqual("help for rover ", disp.get("spirit", ""))
self.assertEqual("help for rover ", disp.get("sojourner", ""))
self.assertEqual("", disp.get("low gain", ""))
def test_display_completions_with_aliases(self):
parser = ArgumentParser()
parser.add_subparsers().add_parser("a", aliases=["b", "c"], help="abc help")
# empty
completer = CompletionFinder(parser)
completer.rl_complete("", 0)
disp = completer.get_display_completions()
self.assertEqual(
{
"a": "abc help",
"b": "abc help",
"c": "abc help",
"-h": "show this help message and exit",
"--help": "show this help message and exit",
},
disp,
)
# a
completer = CompletionFinder(parser)
completer.rl_complete("a", 0)
disp = completer.get_display_completions()
self.assertEqual({"a": "abc help"}, disp)
# b
completer = CompletionFinder(parser)
completer.rl_complete("b", 0)
disp = completer.get_display_completions()
self.assertEqual({"b": "abc help"}, disp)
# c
completer = CompletionFinder(parser)
completer.rl_complete("c", 0)
disp = completer.get_display_completions()
self.assertEqual({"c": "abc help"}, disp)
def test_nargs_one_or_more(self):
def make_parser():
parser = ArgumentParser()
parser.add_argument("h1", choices=["c", "d"])
parser.add_argument("var", choices=["bus", "car"], nargs="+")
parser.add_argument("value", choices=["orange", "apple"])
parser.add_argument("end", choices=["end"])
return parser
expected_outputs = (
("prog ", ["c", "d", "-h", "--help"]),
("prog c ", ["bus", "car", "-h", "--help"]),
("prog c bu", ["bus "]),
("prog c bus ", ["bus", "car", "apple", "orange", "-h", "--help"]),
("prog c bus car ", ["bus", "car", "apple", "orange", "-h", "--help"]),
("prog c bus appl", ["apple "]),
# No way to know which completers to run past this point.
("prog c bus apple ", ["bus", "car", "apple", "orange", "end", "-h", "--help"]),
("prog c bus car apple ", ["bus", "car", "apple", "orange", "end", "-h", "--help"]),
("prog c bus car apple end ", ["bus", "car", "apple", "orange", "end", "-h", "--help"]),
)
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd)), set(output))
def test_nargs_zero_or_more(self):
def make_parser():
parser = ArgumentParser()
# default="foo" is necessary to stop argparse trying to validate []
parser.add_argument("foo", choices=["foo"], nargs="*", default="foo")
parser.add_argument("bar", choices=["bar"])
return parser
expected_outputs = (
("prog ", ["foo", "bar", "-h", "--help"]),
("prog foo ", ["foo", "bar", "-h", "--help"]),
("prog foo bar ", ["foo", "bar", "-h", "--help"]),
("prog foo foo bar ", ["foo", "bar", "-h", "--help"]),
)
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd)), set(output))
def test_nargs_optional(self):
def make_parser():
parser = ArgumentParser()
parser.add_argument("foo", choices=["foo"], nargs="?")
parser.add_argument("bar", choices=["bar"])
return parser
expected_outputs = (
("prog ", ["foo", "bar", "-h", "--help"]),
("prog foo ", ["foo", "bar", "-h", "--help"]),
("prog foo bar ", ["-h", "--help"]),
("prog bar ", ["foo", "bar", "-h", "--help"]),
)
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd)), set(output))
def test_optional_nargs(self):
def make_parser():
parser = ArgumentParser()
parser.add_argument("--foo", choices=["foo1", "foo2"], nargs=2)
parser.add_argument("--bar", choices=["bar1", "bar2"], nargs="?")
parser.add_argument("--baz", choices=["baz1", "baz2"], nargs="*")
parser.add_argument("--qux", choices=["qux1", "qux2"], nargs="+")
parser.add_argument("--foobar", choices=["pos", "--opt"], nargs=argparse.REMAINDER)
return parser
options = ["--foo", "--bar", "--baz", "--qux", "--foobar", "-h", "--help"]
expected_outputs = (
("prog ", options),
("prog --foo ", ["foo1", "foo2"]),
("prog --foo foo1 ", ["foo1", "foo2"]),
("prog --foo foo1 foo2 ", options),
("prog --bar ", ["bar1", "bar2"] + options),
("prog --bar bar1 ", options),
("prog --baz ", ["baz1", "baz2"] + options),
("prog --baz baz1 ", ["baz1", "baz2"] + options),
("prog --qux ", ["qux1", "qux2"]),
("prog --qux qux1 ", ["qux1", "qux2"] + options),
("prog --foobar ", ["pos", "--opt"]),
("prog --foobar pos ", ["pos", "--opt"]),
("prog --foobar --", ["--opt "]),
("prog --foobar --opt ", ["pos", "--opt"]),
)
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd)), set(output))
def test_positional_remainder(self):
def make_parser():
parser = ArgumentParser()
parser.add_argument("--foo", choices=["foo1", "foo2"])
parser.add_argument("remainder", choices=["pos", "--opt"], nargs=argparse.REMAINDER)
return parser
options = ["--foo", "-h", "--help"]
expected_outputs = (
("prog ", ["pos", "--opt"] + options),
("prog --foo foo1 ", ["pos", "--opt"] + options),
("prog pos ", ["pos", "--opt"]),
("prog -- ", ["pos", "--opt"]),
("prog -- --opt ", ["pos", "--opt"]),
)
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd)), set(output))
def test_skipped_completer(self):
parser = ArgumentParser(add_help=False)
parser.add_argument("--foo", choices=["--bar"])
self.assertEqual(self.run_completer(parser, "prog --foo --"), ["--foo "])
def test_optional_long_short_filtering(self):
def make_parser():
parser = ArgumentParser()
parser.add_argument("--foo")
parser.add_argument("-b", "--bar")
parser.add_argument("--baz", "--xyz")
parser.add_argument("-t")
parser.add_argument("-z", "--zzz")
parser.add_argument("-x")
return parser
long_opts = "--foo --bar --baz --xyz --zzz --help -x -t".split()
short_opts = "-b -t -x -z -h --foo --baz --xyz".split()
expected_outputs = (
("prog ", {"long": long_opts, "short": short_opts, True: long_opts + short_opts, False: [""]}),
("prog --foo", {"long": ["--foo "], "short": ["--foo "], True: ["--foo "], False: ["--foo "]}),
(
"prog --b",
{
"long": ["--bar", "--baz"],
"short": ["--bar", "--baz"],
True: ["--bar", "--baz"],
False: ["--bar", "--baz"],
},
),
("prog -z -x", {"long": ["-x "], "short": ["-x "], True: ["-x "], False: ["-x "]}),
)
for cmd, outputs in expected_outputs:
for always_complete_options, output in outputs.items():
result = self.run_completer(make_parser(), cmd, always_complete_options=always_complete_options)
self.assertEqual(set(result), set(output))
def test_exclusive(self):
def make_parser():
parser = ArgumentParser(add_help=False)
parser.add_argument("--foo", action="store_true")
group = parser.add_mutually_exclusive_group()
group.add_argument("--bar", action="store_true")
group.add_argument("--no-bar", action="store_true")
return parser
expected_outputs = (
("prog ", ["--foo", "--bar", "--no-bar"]),
("prog --foo ", ["--foo", "--bar", "--no-bar"]),
("prog --bar ", ["--foo", "--bar"]),
("prog --foo --no-bar ", ["--foo", "--no-bar"]),
)
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd)), set(output))
def test_mixed_optional_positional(self):
def make_parser():
parser = ArgumentParser(add_help=False)
parser.add_argument("name", choices=["name1", "name2"])
group = parser.add_mutually_exclusive_group()
group.add_argument("--get", action="store_true")
group.add_argument("--set", action="store_true")
return parser
expected_outputs = (
("prog ", ["--get", "--set", "name1", "name2"]),
("prog --", ["--get", "--set"]),
("prog -- ", ["name1", "name2"]),
("prog --get ", ["--get", "name1", "name2"]),
("prog --get name1 ", ["--get "]),
)
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(make_parser(), cmd)), set(output))
def test_append_space(self):
def make_parser():
parser = ArgumentParser(add_help=False)
parser.add_argument("foo", choices=["bar"])
return parser
self.assertEqual(self.run_completer(make_parser(), "prog "), ["bar "])
self.assertEqual(self.run_completer(make_parser(), "prog ", append_space=False), ["bar"])
def test_exclusive_class(self):
parser = ArgumentParser(add_help=False)
parser.add_argument("--foo", dest="types", action="append_const", const=str)
parser.add_argument("--bar", dest="types", action="append", choices=["bar1", "bar2"])
parser.add_argument("--baz", choices=["baz1", "baz2"])
parser.add_argument("--no-bar", action="store_true")
completer = ExclusiveCompletionFinder(parser, always_complete_options=True)
expected_outputs = (
("prog ", ["--foo", "--bar", "--baz", "--no-bar"]),
("prog --baz ", ["baz1", "baz2"]),
("prog --baz baz1 ", ["--foo", "--bar", "--no-bar"]),
("prog --foo --no-bar ", ["--foo", "--bar", "--baz"]),
("prog --foo --bar bar1 ", ["--foo", "--bar", "--baz", "--no-bar"]),
)
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(parser, cmd, completer=completer)), set(output))
def test_escape_special_chars(self):
def make_parser():
parser = ArgumentParser(add_help=False)
parser.add_argument("-1", choices=["bar<$>baz"])
parser.add_argument("-2", choices=[r"\* "])
parser.add_argument("-3", choices=["\"'"])
return parser
self.assertEqual(set(self.run_completer(make_parser(), "prog -1 ")), {r"bar\<\$\>baz "})
self.assertEqual(set(self.run_completer(make_parser(), "prog -2 ")), {r"\\\*\ "})
self.assertEqual(set(self.run_completer(make_parser(), "prog -3 ")), {r"\"\' "})
self.assertEqual(set(self.run_completer(make_parser(), 'prog -3 "')), {r"\"'"})
self.assertEqual(set(self.run_completer(make_parser(), "prog -3 '")), {"\"'\\''"})
self.assertEqual(set(self.run_completer(make_parser(), "prog -1 ", shell="tcsh")), {"bar<$>baz "})
# The trailing space won't actually work correctly in tcsh.
self.assertEqual(set(self.run_completer(make_parser(), "prog -2 ", shell="tcsh")), {r"\* "})
self.assertEqual(set(self.run_completer(make_parser(), "prog -3 ", shell="tcsh")), {"\"' "})
self.assertEqual(set(self.run_completer(make_parser(), 'prog -3 "', shell="tcsh")), {"\"'"})
self.assertEqual(set(self.run_completer(make_parser(), "prog -3 '", shell="tcsh")), {"\"'"})
def test_shellcode_utility(self):
with NamedTemporaryFile() as fh:
sc = shellcode(["prog"], use_defaults=True, shell="bash", complete_arguments=None)
fh.write(sc.encode())
fh.flush()
subprocess.check_call(["bash", "-n", fh.name])
with NamedTemporaryFile() as fh:
sc = shellcode(["prog", "prog2"], use_defaults=False, shell="bash", complete_arguments=["-o", "nospace"])
fh.write(sc.encode())
fh.flush()
subprocess.check_call(["bash", "-n", fh.name])
with NamedTemporaryFile() as fh:
sc = shellcode(
["prog"],
use_defaults=True,
shell="bash",
complete_arguments=None,
argcomplete_script="~/.bash_completion.d/prog.py",
)
fh.write(sc.encode())
fh.flush()
subprocess.check_call(["bash", "-n", fh.name])
sc = shellcode(["prog"], use_defaults=False, shell="tcsh", complete_arguments=["-o", "nospace"])
sc = shellcode(["prog"], use_defaults=False, shell="woosh", complete_arguments=["-o", "nospace"])
sc = shellcode(["prog"], shell="fish")
sc = shellcode(["prog"], shell="fish", argcomplete_script="~/.bash_completion.d/prog.py")
def test_option_help(self):
os.environ["_ARGCOMPLETE_DFS"] = "\t"
os.environ["_ARGCOMPLETE_SUPPRESS_SPACE"] = "1"
p = ArgumentParser()
p.add_argument("--foo", help="foo" + IFS + "help")
p.add_argument("--bar", "--bar2", help="bar help")
subparsers = p.add_subparsers()
subparsers.add_parser("subcommand", help="subcommand help")
subparsers.add_parser("subcommand 2", help="subcommand 2 help")
completions = self.run_completer(p, "prog --f", shell="fish")
self.assertEqual(set(completions), {"--foo\tfoo help"})
completions = self.run_completer(p, "prog --b", shell="fish")
self.assertEqual(set(completions), {"--bar\tbar help", "--bar2\tbar help"})
completions = self.run_completer(p, "prog sub", shell="fish")
self.assertEqual(set(completions), {"subcommand\tsubcommand help", "subcommand 2\tsubcommand 2 help"})
os.environ["_ARGCOMPLETE_DFS"] = "invalid"
self.assertRaises(Exception, self.run_completer, p, "prog --b", shell="fish")
class TestArgcompleteREPL(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def run_completer(self, parser, completer, command, point=None, **kwargs):
cword_prequote, cword_prefix, cword_suffix, comp_words, first_colon_pos = split_line(command)
completions = completer._get_completions(comp_words, cword_prefix, cword_prequote, first_colon_pos)
return completions
def test_repl_multiple_complete(self):
p = ArgumentParser()
p.add_argument("--foo")
p.add_argument("--bar")
c = CompletionFinder(p, always_complete_options=True)
completions = self.run_completer(p, c, "prog ")
assert set(completions) == set(["-h", "--help", "--foo", "--bar"])
completions = self.run_completer(p, c, "prog --")
assert set(completions) == set(["--help", "--foo", "--bar"])
def test_repl_parse_after_complete(self):
p = ArgumentParser()
p.add_argument("--foo", required=True)
p.add_argument("bar", choices=["bar"])
c = CompletionFinder(p, always_complete_options=True)
completions = self.run_completer(p, c, "prog ")
assert set(completions) == set(["-h", "--help", "--foo", "bar"])
args = p.parse_args(["--foo", "spam", "bar"])
assert args.foo == "spam"
assert args.bar == "bar"
# Both options are required - check the parser still enforces this.
with self.assertRaises(SystemExit):
p.parse_args(["--foo", "spam"])
with self.assertRaises(SystemExit):
p.parse_args(["bar"])
def test_repl_subparser_parse_after_complete(self):
p = ArgumentParser()
sp = p.add_subparsers().add_parser("foo")
sp.add_argument("bar", choices=["bar"])
c = CompletionFinder(p, always_complete_options=True)
completions = self.run_completer(p, c, "prog foo ")
assert set(completions) == set(["-h", "--help", "bar"])
args = p.parse_args(["foo", "bar"])
assert args.bar == "bar"
# "bar" is required - check the parser still enforces this.
with self.assertRaises(SystemExit):
p.parse_args(["foo"])
def test_repl_subcommand(self):
p = ArgumentParser()
p.add_argument("--foo")
p.add_argument("--bar")
s = p.add_subparsers()
s.add_parser("list")
s.add_parser("set")
show = s.add_parser("show")
def abc():
pass
show.add_argument("--test")
ss = show.add_subparsers()
de = ss.add_parser("depth")
de.set_defaults(func=abc)
c = CompletionFinder(p, always_complete_options=True)
expected_outputs = (
("prog ", ["-h", "--help", "--foo", "--bar", "list", "show", "set"]),
("prog li", ["list "]),
("prog s", ["show", "set"]),
("prog show ", ["--test", "depth", "-h", "--help"]),
("prog show d", ["depth "]),
("prog show depth ", ["-h", "--help"]),
)
for cmd, output in expected_outputs:
self.assertEqual(set(self.run_completer(p, c, cmd)), set(output))
def test_repl_reuse_parser_with_positional(self):
p = ArgumentParser()
p.add_argument("foo", choices=["aa", "bb", "cc"])
p.add_argument("bar", choices=["d", "e"])
c = CompletionFinder(p, always_complete_options=True)