Debian Codegraph @

tests/CLICompletionTest.py

raw symbols SCIP
1 # ClusterShell bash-completion test suite
2 # Written by S. Thiell
3
4 """Unit test for the bash_completion.d/ scripts (clush, cluset).
5
6 The functional tests drive the real completion functions (_clush, _cluset)
7 inside a child bash that sources the system bash-completion library, then
8 assert on the resulting COMPREPLY array. They skip gracefully when bash, the
9 bash-completion library, or clush/cluset (the scripts shell out to them) are
10 unavailable. A separate class runs a 'bash -n' syntax check that needs only
11 bash.
12 """
13
14 import os
15 import shutil
16 import tempfile
17 import unittest
18
19 from subprocess import run, PIPE
20
21 # Anchor on this file: tests run via 'unittest discover -t .' from the repo
22 # root, but CWD must not be assumed.
23 _TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
24 _REPO_ROOT = os.path.dirname(_TESTS_DIR)
25 _COMPL_DIR = os.path.join(_REPO_ROOT, "bash_completion.d")
26
27 # The completion scripts under test.
28 _SCRIPTS = ("clush", "cluset")
29
30 # Locate the bash-completion runtime library (skip functional tests if absent).
31 _BC_LIB = next((p for p in ("/usr/share/bash-completion/bash_completion",
32 "/etc/bash_completion",
33 "/usr/local/share/bash-completion/bash_completion")
34 if os.access(p, os.R_OK)), None)
35
36 # Driver: source the bash-completion library and the completion script under
37 # test, populate the COMP_* variables, run the completion function and print
38 # COMPREPLY one entry per line.
39 _DRIVER = r'''
40 BC_LIB="$1"; SCRIPT="$2"; FUNC="$3"; shift 3
41 # /dev/null is the documented way to skip the user's ~/.bash_completion
42 BASH_COMPLETION_USER_FILE=/dev/null
43 . "$BC_LIB"
44 . "$SCRIPT"
45 COMP_WORDS=("$@")
46 COMP_CWORD=$(( ${#COMP_WORDS[@]} - 1 ))
47 COMP_LINE="${COMP_WORDS[*]}"
48 COMP_POINT=${#COMP_LINE}
49 COMPREPLY=()
50 # compopt warns when run outside readline; that diagnostic is harmless here.
51 "$FUNC" 2>/dev/null || true
52 ((${#COMPREPLY[@]})) && printf '%s\n' "${COMPREPLY[@]}" || true
53 '''
54
55 # Stub cluset printing fixed nodes/groups; shadows the real one via PATH.
56 _CLUSET_STUB = r'''#!/bin/bash
57 case "$1" in
58 --completion)
59 printf '%s\n' @stubsrc: @gpu
60 if [ $# -gt 1 ]; then printf '%s\n' stubnode1 stubnode2; fi
61 ;;
62 esac
63 '''
64
65
66 @unittest.skipUnless(shutil.which("bash"), "bash not found")
67 @unittest.skipUnless(_BC_LIB, "bash-completion library not installed")
68 @unittest.skipUnless(shutil.which("clush") and shutil.which("cluset"),
69 "clush/cluset not on PATH")
70 class CLICompletionTest(unittest.TestCase):
71 """Drive the bash completion functions in a child bash; check COMPREPLY."""
72
73 def _complete(self, script, func, *words, pathdir=None):
74 """Return the completion candidates for the given words; the last word
75 is the current word being completed (use '' for an empty word)."""
76 path = os.path.join(_COMPL_DIR, script)
77 self.assertTrue(os.path.isfile(path), path)
78 env = None
79 if pathdir:
80 env = dict(os.environ, PATH=pathdir + ":" + os.environ["PATH"])
81 proc = run(["bash", "-c", _DRIVER, "bash", _BC_LIB, path, func, *words],
82 stdout=PIPE, stderr=PIPE, timeout=30, env=env)
83 self.assertEqual(proc.returncode, 0, proc.stderr.decode())
84 return proc.stdout.decode().split("\n")[:-1] # drop trailing empty element
85
86 def _stub_cluset(self):
87 """Install the cluset stub in a temp dir; return it for pathdir."""
88 tmpdir = tempfile.mkdtemp()
89 self.addCleanup(shutil.rmtree, tmpdir)
90 stub = os.path.join(tmpdir, "cluset")
91 with open(stub, "w") as f:
92 f.write(_CLUSET_STUB)
93 os.chmod(stub, 0o755)
94 return tmpdir
95
96 def test_clush_dash_lists_options(self):
97 """clush: bare '-' completes to the option list"""
98 reply = self._complete("clush", "_clush", "clush", "-")
99 self.assertTrue(len(reply) > 1, reply)
100 self.assertIn("--diff ", reply)
101
102 def test_clush_noarg_flag_does_not_swallow_next_word(self):
103 """clush: a no-arg flag must not consume the following word (#619)"""
104 # -b/--diff are no-arg options; a trailing '-' must still complete to
105 # the option list. Before #619 the parser ate the next word and the
106 # completion came back empty.
107 for line in (("clush", "-b", "-"),
108 ("clush", "--diff", "-"),
109 ("clush", "-b", "-w", "node01", "-")):
110 reply = self._complete("clush", "_clush", *line)
111 self.assertIn("--diff ", reply, "%r -> %r" % (line, reply))
112
113 def test_clush_glued_short_option(self):
114 """clush: glued short option -wPREFIX completes with -w kept (#586)"""
115 reply = self._complete("clush", "_clush", "clush", "-wstub",
116 pathdir=self._stub_cluset())
117 self.assertEqual(reply, ["-wstubnode1 ", "-wstubnode2 "])
118 # glued no-arg flags cannot be completed (known limitation)
119 self.assertEqual(self._complete("clush", "_clush", "clush", "-bg"), [])
120
121 def test_clush_fixed_value_options(self):
122 """clush: --color and -R complete to their fixed value sets"""
123 self.assertEqual(self._complete("clush", "_clush", "clush", "--color", ""),
124 ["never ", "always ", "auto "])
125 self.assertEqual(self._complete("clush", "_clush", "clush", "-R", ""),
126 ["ssh ", "exec ", "rsh "])
127
128 def test_clush_command_completion_after_noarg_flag(self):
129 """clush: command completion works after a no-arg flag (#619)"""
130 tmpdir = tempfile.mkdtemp()
131 self.addCleanup(shutil.rmtree, tmpdir)
132 cmd = os.path.join(tmpdir, "cs-test-cmd-8f3a1")
133 open(cmd, "w").close()
134 os.chmod(cmd, 0o755)
135 for line in (("clush", "-b", "-w", "node01", "cs-test-cmd-"),
136 ("clush", "--diff", "-w", "node01", "cs-test-cmd-")):
137 reply = self._complete("clush", "_clush", *line, pathdir=tmpdir)
138 self.assertIn("cs-test-cmd-8f3a1", reply, "%r -> %r" % (line, reply))
139
140 def test_clush_copy_mode_completes_files(self):
141 """clush: copy mode completes file names"""
142 tmpdir = tempfile.mkdtemp()
143 self.addCleanup(shutil.rmtree, tmpdir)
144 fname = os.path.join(tmpdir, "cs-test-file-8f3a1")
145 open(fname, "w").close()
146 reply = self._complete("clush", "_clush", "clush", "-c",
147 os.path.join(tmpdir, "cs-test-file-"))
148 self.assertIn(fname, reply)
149
150 def test_clush_node_and_group_completion(self):
151 """clush: -w completes nodes and @groups, -g groups without @"""
152 tmpdir = self._stub_cluset()
153 reply = self._complete("clush", "_clush", "clush", "-b", "-w", "",
154 pathdir=tmpdir)
155 self.assertEqual(reply,
156 ["@stubsrc:", "@gpu ", "stubnode1 ", "stubnode2 "])
157 reply = self._complete("clush", "_clush", "clush", "-g", "",
158 pathdir=tmpdir)
159 self.assertEqual(reply, ["stubsrc:", "gpu "])
160
161 def test_cluset_dash_lists_options(self):
162 """cluset: bare '-' completes to the option list"""
163 reply = self._complete("cluset", "_cluset", "cluset", "-")
164 self.assertTrue(len(reply) > 1, reply)
165 self.assertIn("--fold ", reply)
166
167 def test_cluset_noarg_flag_does_not_swallow_next_word(self):
168 """cluset: a no-arg flag must not consume the following word"""
169 reply = self._complete("cluset", "_cluset", "cluset", "-G", "-e", "@",
170 pathdir=self._stub_cluset())
171 self.assertEqual(reply, ["@stubsrc:", "@gpu "])
172 reply = self._complete("cluset", "_cluset", "cluset", "-a", "")
173 self.assertIn("--fold ", reply)
174
175
176 @unittest.skipUnless(shutil.which("bash"), "bash not found")
177 class CLICompletionStaticTest(unittest.TestCase):
178 """Static syntax check for the completion scripts (needs only bash)."""
179
180 def test_bash_syntax(self):
181 """each completion script parses with 'bash -n'"""
182 for script in _SCRIPTS:
183 path = os.path.join(_COMPL_DIR, script)
184 self.assertTrue(os.path.isfile(path), path)
185 proc = run(["bash", "-n", path], stdout=PIPE, stderr=PIPE,
186 timeout=30)
187 self.assertEqual(proc.returncode, 0,
188 "bash -n failed for %s:\n%s"
189 % (path, proc.stderr.decode()))