Debian Codegraph @

testing/test_argcomplete.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 from pathlib import Path
5 import subprocess
6 import sys
7
8 from _pytest.monkeypatch import MonkeyPatch
9 import pytest
10
11
12 # Test for _argcomplete but not specific for any application.
13
14
15 def equal_with_bash(prefix, ffc, fc, out=None):
16 res = ffc(prefix)
17 res_bash = set(fc(prefix))
18 retval = set(res) == res_bash
19 if out:
20 out.write(f"equal_with_bash({prefix}) {retval} {res}\n")
21 if not retval:
22 out.write(" python - bash: %s\n" % (set(res) - res_bash))
23 out.write(" bash - python: %s\n" % (res_bash - set(res)))
24 return retval
25
26
27 # Copied from argcomplete.completers as import from there.
28 # Also pulls in argcomplete.__init__ which opens filedescriptor 9.
29 # This gives an OSError at the end of testrun.
30
31
32 def _wrapcall(*args, **kargs):
33 try:
34 return subprocess.check_output(*args, **kargs).decode().splitlines()
35 except subprocess.CalledProcessError:
36 return []
37
38
39 class FilesCompleter:
40 """File completer class, optionally takes a list of allowed extensions."""
41
42 def __init__(self, allowednames=(), directories=True):
43 # Fix if someone passes in a string instead of a list
44 if type(allowednames) is str:
45 allowednames = [allowednames]
46
47 self.allowednames = [x.lstrip("*").lstrip(".") for x in allowednames]
48 self.directories = directories
49
50 def __call__(self, prefix, **kwargs):
51 completion = []
52 if self.allowednames:
53 if self.directories:
54 files = _wrapcall(["bash", "-c", f"compgen -A directory -- '{prefix}'"])
55 completion += [f + "/" for f in files]
56 for x in self.allowednames:
57 completion += _wrapcall(
58 ["bash", "-c", f"compgen -A file -X '!*.{x}' -- '{prefix}'"]
59 )
60 else:
61 completion += _wrapcall(["bash", "-c", f"compgen -A file -- '{prefix}'"])
62
63 anticomp = _wrapcall(["bash", "-c", f"compgen -A directory -- '{prefix}'"])
64
65 completion = list(set(completion) - set(anticomp))
66
67 if self.directories:
68 completion += [f + "/" for f in anticomp]
69 return completion
70
71
72 class TestArgComplete:
73 @pytest.mark.skipif("sys.platform in ('win32', 'darwin')")
74 def test_compare_with_compgen(
75 self, tmp_path: Path, monkeypatch: MonkeyPatch
76 ) -> None:
77 from _pytest._argcomplete import FastFilesCompleter
78
79 ffc = FastFilesCompleter()
80 fc = FilesCompleter()
81
82 monkeypatch.chdir(tmp_path)
83
84 assert equal_with_bash("", ffc, fc, out=sys.stdout)
85
86 tmp_path.cwd().joinpath("data").touch()
87
88 for x in ["d", "data", "doesnotexist", ""]:
89 assert equal_with_bash(x, ffc, fc, out=sys.stdout)
90
91 @pytest.mark.skipif("sys.platform in ('win32', 'darwin')")
92 def test_remove_dir_prefix(self):
93 """This is not compatible with compgen but it is with bash itself: ls /usr/<TAB>."""
94 from _pytest._argcomplete import FastFilesCompleter
95
96 ffc = FastFilesCompleter()
97 fc = FilesCompleter()
98 for x in "/usr/".split():
99 assert not equal_with_bash(x, ffc, fc, out=sys.stdout)