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
|
#!/usr/bin/env python3
import os
import sys
import time
import json
import yaml
import queue
import argparse
import threading
import subprocess
from collections import OrderedDict
from shells import BashShell, FishShell, ZshShell
# =============================================================================
# Script configuration
# =============================================================================
SHELLS = ['bash', 'fish', 'zsh']
TMUX_SESSION_PREFIX = 'crazy-complete-test'
TESTS_INFILE = 'tests.yaml'
TESTS_OUTFILE = 'tests.new.yaml'
CRAZY_COMPLETE = '../../crazy-complete'
COMPLETIONS_OUTDIR = 'output'
# =============================================================================
# Switch to the script's directory
# =============================================================================
os.chdir(os.path.dirname(os.path.abspath(__file__)))
# =============================================================================
# Commandline parser
# =============================================================================
argp = argparse.ArgumentParser()
argp.add_argument('-f', '--fast', action='store_true', default=False,
help='Enable fast testing mode. For tests where the input matches the expected output, these tests will always pass')
argp.add_argument('-d', '--driver', default='pyte', choices=['pyte', 'tmux'],
help='Select driver for tests')
argp.add_argument('-t', '--threads', default=1, type=int,
help='Set the number of threads per shell')
opts = argp.parse_args()
# =============================================================================
# Helper functions
# =============================================================================
def print_err(*args):
print(*args, file=sys.stderr)
def run(args, env=None):
result = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env)
if result.returncode != 0:
raise Exception("Command %r failed: %s" % (args, result.stderr))
return result.stdout
def indent(string, num_spaces):
lines = string.split('\n')
indented_lines = [((' ' * num_spaces) + line) if line.strip() else line for line in lines]
return '\n'.join(indented_lines)
def make_yaml_block_string(s):
return "|\n%s" % indent(s, 2)
def test_to_yaml(test):
r = OrderedDict()
r['number'] = str(test['number'])
r['definition_file'] = json.dumps(test['definition_file'])
r['description'] = json.dumps(test['description'])
if 'comment' in test:
r['comment'] = json.dumps(test['comment'])
r['send'] = json.dumps(test['send'])
if test.get('bash_tabs', 1) != 1:
r['bash_tabs'] = str(test['bash_tabs'])
r['bash_expected'] = make_yaml_block_string(test['bash_result'])
if test.get('fish_tabs', 1) != 1:
r['fish_tabs'] = str(test['fish_tabs'])
r['fish_expected'] = make_yaml_block_string(test['fish_result'])
if test.get('zsh_tabs', 1) != 1:
r['zsh_tabs'] = str(test['zsh_tabs'])
r['zsh_expected'] = make_yaml_block_string(test['zsh_result'])
return '\n'.join('%s: %s' % key_value for key_value in r.items())
# =============================================================================
# Import driver depending on command line arguments
# =============================================================================
if opts.driver == 'pyte':
try:
from pyte_driver import PyteTerminal
except ImportError as e:
print_err(e)
print_err('Please install the missing modules.')
print_err('Alternatively, you can use --driver=tmux if you have tmux installed')
sys.exit(2)
elif opts.driver == 'tmux':
from tmux_driver import TmuxTerminal
# =============================================================================
# Ensure all dependencies are available
# =============================================================================
for program in SHELLS:
try:
run(['sh', '-c', f'type {program}'])
except Exception:
print_err(f'Program `{program}` not found')
sys.exit(2)
if not os.path.exists('/usr/share/bash-completion/bash_completion'):
print_err('File `/usr/share/bash-completion/bash_completion` not found. Is `bash-completion` installed?')
sys.exit(2)
# =============================================================================
# Test code
# =============================================================================
class Tests:
def __init__(self, tests):
self.definition_files = tests.pop(0)
self.tests = tests
def enumerate_tests(self):
number = 1
for test in self.tests:
test['number'] = number
number += 1
def add_empty_expected(self):
for test in self.tests:
test.setdefault('bash_expected', '')
test.setdefault('fish_expected', '')
test.setdefault('zsh_expected', '')
def strip_expected(self):
for test in self.tests:
for key in ['bash_expected', 'fish_expected', 'zsh_expected']:
test[key] = test[key].strip()
def find_test_by_number(self, num):
for test in self.tests:
if test['number'] == num:
return test
raise Exception(f"No test with number {num} found")
def write_tests_file(self, outfile):
r = []
files = ''
for file, args in self.definition_files.items():
files += '%s: %s\n' % (file, json.dumps(args))
r += [files.strip()]
for test in self.tests:
r += [test_to_yaml(test)]
r = '\n---\n'.join(r)
with open(outfile, 'w') as fh:
fh.write(r)
def generate_completion_files(self):
try:
os.mkdir(COMPLETIONS_OUTDIR)
except FileExistsError:
if not os.path.isdir(COMPLETIONS_OUTDIR):
raise NotADirectoryError(COMPLETIONS_OUTDIR) from None
print_err('Generating completion files ...')
for file, args in self.definition_files.items():
for shell in SHELLS:
cmd = [CRAZY_COMPLETE, '--debug', '--zsh-compdef=False']
for arg in args['args']:
cmd += [arg.replace('$shell', shell)]
cmd += ['-o', f'{COMPLETIONS_OUTDIR}/{file}.{shell}']
cmd += [shell, args['definition_file']]
print_err('Running', ' '.join(cmd))
run(cmd)
def tests_worker_thread(thread_id, shell, input_queue, result_queue):
if opts.driver == 'tmux':
term = TmuxTerminal(f'{TMUX_SESSION_PREFIX}-{shell}-{thread_id}')
elif opts.driver == 'pyte':
term = PyteTerminal()
term_shell = {
'bash': BashShell,
'fish': FishShell,
'zsh': ZshShell
}[shell](term)
old_definition_file = None
while True:
try:
test = input_queue.get_nowait()
except queue.Empty:
break
if old_definition_file != test['definition_file']:
old_definition_file = test['definition_file']
try:
term_shell.stop()
except Exception:
pass
completion_file = '%s/%s.%s' % (COMPLETIONS_OUTDIR, test['definition_file'], shell)
term_shell.start()
term.resize_window(80, 100)
term_shell.set_prompt()
term_shell.init_completion()
term_shell.load_completion(completion_file)
time.sleep(1.5)
output = term.complete(
test['send'],
test.get(shell+'_tabs', 1),
test[shell+'_expected'],
opts.fast)
result = {
'number': test['number'],
'shell': shell,
'result': output
}
result_queue.put(result)
try:
term_shell.stop()
except Exception:
pass
class Tester():
def __init__(self, tests):
self.tests = tests
self.result_queue = queue.Queue()
self.input_queues = {}
self.threads = []
self.num_failed = 0
def run(self):
for shell in SHELLS:
self.input_queues[shell] = queue.Queue()
for test in self.tests.tests:
self.input_queues[shell].put(test)
for thread_id in range(opts.threads):
for shell in SHELLS:
thread = threading.Thread(
target=tests_worker_thread,
args=(thread_id, shell, self.input_queues[shell], self.result_queue)
)
thread.start()
self.threads.append(thread)
while self.threads_are_running():
self.eat_queue()
time.sleep(0.1)
self.eat_queue()
def threads_are_running(self):
for thread in self.threads:
if thread.is_alive():
return True
return False
def eat_queue(self):
while not self.result_queue.empty():
self.process_result(self.result_queue.get())
def process_result(self, result):
test = self.tests.find_test_by_number(result['number'])
shell = result['shell']
shell_result_key = '%s_result' % shell
shell_expected_key = '%s_expected' % shell
test[shell_result_key] = result['result']
if test[shell_result_key] != test[shell_expected_key]:
self.num_failed += 1
print_err("Test #%02d (%-4s - %s) failed" % (test['number'], shell, test['description']))
else:
print_err("Test #%02d (%-4s - %s) OK" % (test['number'], shell, test['description']))
# =============================================================================
# Main
# =============================================================================
with open(TESTS_INFILE, 'r') as fh:
tests = Tests(list(yaml.safe_load_all(fh)))
tests.enumerate_tests()
tests.add_empty_expected()
tests.strip_expected()
tests.generate_completion_files()
tester = Tester(tests)
tester.run()
tests.write_tests_file(TESTS_OUTFILE)
if tester.num_failed:
print_err(f'{tester.num_failed} tests failed.')
print_err(f'Use diff or vimdiff on `{TESTS_INFILE}` and `{TESTS_OUTFILE}` for further details')
if opts.threads > 2:
print_err('NOTE:')
print_err(' A high value for -t|--threads may cause that tests fail.')
print_err(' Consider running this script again with `-t 1`.')
sys.exit(1)
else:
print_err("All tests passed")
sys.exit(0)
|