Debian Codegraph @

test/tests/run.py

raw
1 #!/usr/bin/env python3
2
3 import os
4 import sys
5 import time
6 import json
7 import shlex
8 import yaml
9 import queue
10 import argparse
11 import threading
12 import subprocess
13 from collections import OrderedDict
14
15 from shells import BashShell, FishShell, ZshShell
16
17 # =============================================================================
18 # Script configuration
19 # =============================================================================
20
21 SHELLS = ['bash', 'fish', 'zsh']
22 TMUX_SESSION_PREFIX = 'crazy-complete-test'
23 TESTS_INFILE = 'tests.yaml'
24 TESTS_OUTFILE = 'tests.new.yaml'
25 CRAZY_COMPLETE = '../../crazy-complete'
26 COMPLETIONS_OUTDIR = 'output'
27 TEMP_DIR = 'tmp'
28 OUTPUT_WAIT = 5
29
30 # =============================================================================
31 # Switch to the script's directory
32 # =============================================================================
33
34 os.chdir(os.path.dirname(os.path.abspath(__file__)))
35 CURRENT_DIRECTORY = os.path.abspath(os.getcwd())
36
37 # =============================================================================
38 # Commandline parser
39 # =============================================================================
40
41 argp = argparse.ArgumentParser()
42 argp.add_argument('-f', '--fast', action='store_true', default=False,
43 help='Enable fast testing mode. For tests where the input matches the expected output, these tests will always pass')
44 argp.add_argument('-d', '--driver', default='tmux', choices=['pyte', 'tmux'],
45 help='Select driver for tests')
46 argp.add_argument('-t', '--threads', default=1, type=int,
47 help='Set the number of threads per shell')
48 argp.add_argument('-w', '--wait', default=OUTPUT_WAIT, type=float,
49 help='Set how many seconds to wait for terminal output')
50 argp.add_argument('-s', '--select', action='append',
51 help='Select tests by definition file')
52 opts = argp.parse_args()
53
54 OUTPUT_WAIT = opts.wait
55
56 # =============================================================================
57 # Helper functions
58 # =============================================================================
59
60 def print_err(*args):
61 print(*args, file=sys.stderr)
62
63 def run(args, env=None):
64 result = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env)
65
66 if result.returncode != 0:
67 raise Exception("Command %r failed: %s" % (args, result.stderr))
68
69 return result.stdout
70
71 def indent(string, num_spaces):
72 lines = string.split('\n')
73 indented_lines = [((' ' * num_spaces) + line) if line.strip() else line for line in lines]
74 return '\n'.join(indented_lines)
75
76 def make_yaml_block_string(s):
77 return "|\n%s" % indent(s, 2)
78
79 # =============================================================================
80 # Import driver depending on command line arguments
81 # =============================================================================
82
83 if opts.driver == 'tmux':
84 from tmux_driver import TmuxTerminal
85 elif opts.driver == 'pyte':
86 print_err("The `pyte` driver has been disabled because it does not implement the `kitty`")
87 print_err("protocol used by the Fish shell, causing tests to fail.")
88 sys.exit(2)
89
90 # =============================================================================
91 # Ensure all dependencies are available
92 # =============================================================================
93
94 for shell in SHELLS:
95 try:
96 run(['sh', '-c', f'type {shell}'])
97 except Exception:
98 print_err(f'Program `{shell}` not found')
99 sys.exit(2)
100
101 if not os.path.exists('/usr/share/bash-completion/bash_completion'):
102 print_err('File `/usr/share/bash-completion/bash_completion` not found. Is `bash-completion` installed?')
103 sys.exit(2)
104
105 # =============================================================================
106 # Test code
107 # =============================================================================
108
109 class Test:
110 def __init__(self, data):
111 self.number = data.get('number', None)
112 self.definition_file = data['definition_file']
113 self.description = data['description']
114 self.comment = data.get('comment', None)
115 self.send = data['send']
116 self.require_order = data.get('require_order', False)
117 self.bash_tabs = data.get('bash_tabs', 1)
118 self.fish_tabs = data.get('fish_tabs', 1)
119 self.zsh_tabs = data.get('zsh_tabs', 1)
120 self.bash_expected = data.get('bash_expected', '').strip()
121 self.fish_expected = data.get('fish_expected', '').strip()
122 self.zsh_expected = data.get('zsh_expected', '').strip()
123 self.bash_result = None
124 self.fish_result = None
125 self.zsh_result = None
126
127 def get_tabs(self, shell):
128 if shell == 'bash':
129 return self.bash_tabs
130 if shell == 'fish':
131 return self.fish_tabs
132 if shell == 'zsh':
133 return self.zsh_tabs
134 raise
135
136 def get_expected(self, shell):
137 if shell == 'bash':
138 return self.bash_expected
139 if shell == 'fish':
140 return self.fish_expected
141 if shell == 'zsh':
142 return self.zsh_expected
143
144 def get_result(self, shell):
145 if shell == 'bash':
146 return self.bash_result
147 if shell == 'fish':
148 return self.fish_result
149 if shell == 'zsh':
150 return self.zsh_result
151 raise
152
153 def set_result(self, shell, result):
154 if shell == 'bash':
155 self.bash_result = result
156 elif shell == 'fish':
157 self.fish_result = result
158 elif shell == 'zsh':
159 self.zsh_result = result
160 else:
161 raise
162
163 def passed(self, shell):
164 result = self.get_result(shell)
165 expected = self.get_expected(shell)
166
167 if self.require_order:
168 return result.split() == expected.split()
169 else:
170 return sorted(result.split()) == sorted(expected.split())
171
172 def to_yaml(self):
173 r = OrderedDict()
174
175 r['number'] = str(self.number)
176 r['definition_file'] = json.dumps(self.definition_file)
177 r['description'] = json.dumps(self.description)
178 if self.comment:
179 r['comment'] = json.dumps(self.comment)
180 r['send'] = json.dumps(self.send)
181 if self.require_order:
182 r['require_order'] = 'true'
183 if self.bash_tabs != 1:
184 r['bash_tabs'] = str(self.bash_tabs)
185 r['bash_expected'] = make_yaml_block_string(self.bash_result)
186 if self.fish_tabs != 1:
187 r['fish_tabs'] = str(self.fish_tabs)
188 r['fish_expected'] = make_yaml_block_string(self.fish_result)
189 if self.zsh_tabs != 1:
190 r['zsh_tabs'] = str(self.zsh_tabs)
191 r['zsh_expected'] = make_yaml_block_string(self.zsh_result)
192
193 return '\n'.join('%s: %s' % key_value for key_value in r.items())
194
195
196 class Tests:
197 def __init__(self, tests):
198 self.definition_files = tests.pop(0)
199 self.tests = [Test(data) for data in tests]
200
201 def enumerate_tests(self):
202 number = 1
203 for test in self.tests:
204 test.number = number
205 number += 1
206
207 def find_test_by_number(self, num):
208 for test in self.tests:
209 if test.number == num:
210 return test
211
212 raise Exception(f"No test with number {num} found")
213
214 def write_tests_file(self, outfile):
215 r = []
216
217 files = ''
218 for file, args in self.definition_files.items():
219 files += '%s: %s\n' % (file, json.dumps(args))
220 r += [files.strip()]
221
222 for test in self.tests:
223 r += [test.to_yaml()]
224
225 r = '\n---\n'.join(r)
226
227 with open(outfile, 'w') as fh:
228 fh.write(r)
229
230 def generate_completion_files(self):
231 try:
232 os.mkdir(COMPLETIONS_OUTDIR)
233 except FileExistsError:
234 if not os.path.isdir(COMPLETIONS_OUTDIR):
235 raise NotADirectoryError(COMPLETIONS_OUTDIR) from None
236
237 try:
238 os.mkdir(TEMP_DIR)
239 except FileExistsError:
240 if not os.path.isdir(TEMP_DIR):
241 raise NotADirectoryError(TEMP_DIR) from None
242
243 batch_file = '%s/%s' % (TEMP_DIR, 'batch.txt')
244 batch_commands = []
245
246 for file, args in self.definition_files.items():
247 definition_file = args['definition_file']
248 temp_definition_file = f'{TEMP_DIR}/{definition_file}'
249
250 with open(definition_file, 'r', encoding='UTF-8') as fh:
251 content = fh.read()
252 content = content.replace('%TEST_DIR%', CURRENT_DIRECTORY)
253
254 with open(temp_definition_file, 'w', encoding='UTF-8') as fh:
255 fh.write(content)
256
257 for shell in SHELLS:
258 cmd = ['--debug', '--zsh-compdef=False']
259 for arg in args['args']:
260 cmd += [arg.replace('$shell', shell)]
261 cmd += ['-o', f'{COMPLETIONS_OUTDIR}/{file}.{shell}']
262 cmd += [shell, temp_definition_file]
263 cmd = ' '.join(shlex.quote(arg) for arg in cmd)
264 batch_commands.append(cmd)
265
266 with open(batch_file, 'w', encoding='utf-8') as fh:
267 print_err("Writing batch file '%s' ..." % batch_file)
268 fh.write('\n'.join(batch_commands))
269
270 print_err('Running batch file ...')
271 args = [CRAZY_COMPLETE, '--batch', batch_file]
272 subprocess.run(args, check=True)
273 print_err('Finished running batch file ...')
274
275 def tests_worker_thread(thread_id, shell, input_queue, result_queue):
276 if opts.driver == 'tmux':
277 term = TmuxTerminal(f'{TMUX_SESSION_PREFIX}-{shell}-{thread_id}')
278 elif opts.driver == 'pyte':
279 term = PyteTerminal()
280
281 term_shell = {
282 'bash': BashShell,
283 'fish': FishShell,
284 'zsh': ZshShell
285 }[shell](term)
286
287 old_definition_file = None
288
289 while True:
290 try:
291 test = input_queue.get_nowait()
292 except queue.Empty:
293 break
294
295 if old_definition_file != test.definition_file:
296 old_definition_file = test.definition_file
297
298 try:
299 term_shell.stop()
300 except Exception:
301 pass
302 completion_file = '%s/%s.%s' % (COMPLETIONS_OUTDIR, test.definition_file, shell)
303 term_shell.start()
304 term.resize_window(80, 100)
305 term_shell.set_prompt()
306 term_shell.init_completion()
307 term_shell.load_completion(completion_file)
308 time.sleep(1.5)
309
310 output = term.complete(
311 test.send,
312 test.get_tabs(shell),
313 OUTPUT_WAIT,
314 test.get_expected(shell),
315 opts.fast)
316
317 result = {
318 'number': test.number,
319 'shell': shell,
320 'result': output
321 }
322
323 result_queue.put(result)
324
325 try:
326 term_shell.stop()
327 except Exception:
328 pass
329
330 class Tester():
331 def __init__(self, tests, selected):
332 self.tests = tests
333 self.selected = selected
334 self.result_queue = queue.Queue()
335 self.input_queues = {}
336 self.threads = []
337 self.num_failed = 0
338
339 def run(self):
340 for shell in SHELLS:
341 self.input_queues[shell] = queue.Queue()
342
343 for test in self.tests.tests:
344 if not self.selected or test.definition_file in self.selected:
345 self.input_queues[shell].put(test)
346 else:
347 test.set_result(shell, test.get_expected(shell))
348
349 for thread_id in range(opts.threads):
350 for shell in SHELLS:
351 thread = threading.Thread(
352 target=tests_worker_thread,
353 args=(thread_id, shell, self.input_queues[shell], self.result_queue)
354 )
355
356 thread.start()
357 self.threads.append(thread)
358
359 while self.threads_are_running():
360 self.eat_queue()
361 time.sleep(0.1)
362 self.eat_queue()
363
364 def threads_are_running(self):
365 for thread in self.threads:
366 if thread.is_alive():
367 return True
368 return False
369
370 def eat_queue(self):
371 while not self.result_queue.empty():
372 self.process_result(self.result_queue.get())
373
374 def process_result(self, result):
375 test = self.tests.find_test_by_number(result['number'])
376 shell = result['shell']
377 test.set_result(shell, result['result'])
378
379 if not test.passed(shell):
380 self.num_failed += 1
381 print_err("Test #%03d (%-4s - %s) failed" % (test.number, shell, test.description))
382 else:
383 print_err("Test #%03d (%-4s - %s) OK" % (test.number, shell, test.description))
384
385 # =============================================================================
386 # Main
387 # =============================================================================
388
389 with open(TESTS_INFILE, 'r') as fh:
390 tests = Tests(list(yaml.safe_load_all(fh)))
391
392 tests.enumerate_tests()
393 tests.generate_completion_files()
394 tester = Tester(tests, opts.select)
395 tester.run()
396 tests.write_tests_file(TESTS_OUTFILE)
397 if tester.num_failed:
398 print_err(f'{tester.num_failed} tests failed.')
399 print_err(f'Use diff or vimdiff on `{TESTS_INFILE}` and `{TESTS_OUTFILE}` for further details')
400 if opts.threads > 1:
401 print_err('NOTE:')
402 print_err(' A high value for -t|--threads may cause that tests fail.')
403 print_err(' Consider running this script again with `-t 1`.')
404 sys.exit(1)
405 else:
406 print_err("All tests passed")
407 sys.exit(0)