robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 9a29622b3b00ddb601

master
20.3 KiB716 linesraw
1" This script is sourced while editing the .vim file with the tests.
2" When the script is successful the .res file will be created.
3" Errors are appended to the test.log file.
4"
5" To execute only specific test functions, add a second argument.  It will be
6" matched against the names of the Test_ function.  E.g.:
7"	../vim -u NONE -S runtest.vim test_channel.vim open_delay
8" The output can be found in the "messages" file.
9"
10" If the environment variable $TEST_FILTER is set then only test functions
11" matching this pattern are executed.  E.g. for sh/bash:
12"     export TEST_FILTER=Test_channel
13" For csh:
14"     setenv TEST_FILTER Test_channel
15"
16" If the environment variable $TEST_SKIP_PAT is set then test functions
17" matching this pattern will be skipped.  It's the opposite of $TEST_FILTER.
18"
19" While working on a test you can make $TEST_NO_RETRY non-empty to not retry:
20"     export TEST_NO_RETRY=yes
21"
22" To ignore failure for tests that are known to fail in a certain environment,
23" set $TEST_MAY_FAIL to a comma separated list of function names.  E.g. for
24" sh/bash:
25"     export TEST_MAY_FAIL=Test_channel_one,Test_channel_other
26" The failure report will then not be included in the test.log file and
27" "make test" will not fail.
28"
29" The test script may contain anything, only functions that start with
30" "Test_" are special.  These will be invoked and should contain assert
31" functions.  See test_assert.vim for an example.
32"
33" It is possible to source other files that contain "Test_" functions.  This
34" can speed up testing, since Vim does not need to restart.  But be careful
35" that the tests do not interfere with each other.
36"
37" If an error cannot be detected properly with an assert function add the
38" error to the v:errors list:
39"   call add(v:errors, 'test foo failed: Cannot find xyz')
40"
41" If preparation for each Test_ function is needed, define a SetUp function.
42" It will be called before each Test_ function.
43"
44" If cleanup after each Test_ function is needed, define a TearDown function.
45" It will be called after each Test_ function.
46"
47" When debugging a test it can be useful to add messages to v:errors:
48"	call add(v:errors, "this happened")
49
50
51" Without the +eval feature we can't run these tests, bail out.
52silent! while 0
53  qa!
54silent! endwhile
55
56" In the GUI we can always change the screen size.
57if has('gui_running')
58  if has('gui_gtk')
59    " to keep screendump size unchanged
60    set guifont=Monospace\ 10
61  endif
62  set columns=80 lines=25
63endif
64
65" Check that the screen size is at least 24 x 80 characters.
66if &lines < 24 || &columns < 80
67  let error = 'Screen size too small! Tests require at least 24 lines with 80 characters, got ' .. &lines .. ' lines with ' .. &columns .. ' characters'
68  echoerr error
69  split test.log
70  $put =error
71  write
72  split messages
73  call append(line('$'), '')
74  call append(line('$'), 'From ' . expand('%') . ':')
75  call append(line('$'), error)
76  write
77  qa!
78endif
79
80if has('reltime')
81  let s:run_start_time = reltime()
82
83  if !filereadable('starttime')
84    " first test, store the overall test starting time
85    let s:test_start_time = localtime()
86    call writefile([string(s:test_start_time)], 'starttime')
87  else
88    " second or later test, read the overall test starting time
89    let s:test_start_time = readfile('starttime')[0]->str2nr()
90  endif
91endif
92
93" Always use forward slashes.
94set shellslash
95
96" Common with all tests on all systems.
97source setup.vim
98
99" Needed for RunningWithValgrind().
100source shared.vim
101
102" Needed for the various Check commands
103source check.vim
104
105" For consistency run all tests with 'nocompatible' set.
106" This also enables use of line continuation.
107set nocp viminfo+=nviminfo
108
109" Use utf-8 by default, instead of whatever the system default happens to be.
110" Individual tests can overrule this at the top of the file and use
111" g:orig_encoding if needed.
112let g:orig_encoding = &encoding
113set encoding=utf-8
114
115" REDIR_TEST_TO_NULL has a very permissive SwapExists autocommand which is for
116" the test_name.vim file itself. Replace it here with a more restrictive one,
117" so we still catch mistakes.
118if has("win32")
119  " replace any '/' directory separators by '\\'
120  let s:test_script_fname = substitute(expand('%'), '/', '\\', 'g')
121else
122  let s:test_script_fname = expand('%')
123endif
124au! SwapExists * call HandleSwapExists()
125func HandleSwapExists()
126  if exists('g:ignoreSwapExists')
127    if type(g:ignoreSwapExists) == v:t_string
128      let v:swapchoice = g:ignoreSwapExists
129    endif
130    return
131  endif
132  " Ignore finding a swap file for the test script (the user might be
133  " editing it and do ":make test_name") and the output file.
134  " Report finding another swap file and chose 'q' to avoid getting stuck.
135  if expand('<afile>') == 'messages' || expand('<afile>') =~ s:test_script_fname
136    let v:swapchoice = 'e'
137  else
138    call assert_report('Unexpected swap file: ' .. v:swapname)
139    let v:swapchoice = 'q'
140  endif
141endfunc
142
143" Avoid stopping at the "hit enter" prompt
144set nomore
145
146" Output all messages in English.
147lang mess C
148
149" Nvim: append runtime from build dir, which contains the generated doc/tags.
150let &runtimepath ..= ',' .. expand($BUILD_DIR) .. '/runtime/'
151" Nvim: append libdir from build dir, which contains the bundled TS parsers.
152let &runtimepath ..= ',' .. expand($BUILD_DIR) .. '/lib/nvim/'
153" Nvim: load the ":helptags" module + parser now, because tests reset 'runtimepath'.
154lua pcall(vim.treesitter.language.add, 'vimdoc')
155
156let s:t_bold = &t_md
157let s:t_normal = &t_me
158if has('win32')
159  " avoid prompt that is long or contains a line break
160  let $PROMPT = '$P$G'
161endif
162
163if has('mac')
164  " In macOS, when starting a shell in a terminal, a bash deprecation warning
165  " message is displayed. This breaks the terminal test. Disable the warning
166  " message.
167  let $BASH_SILENCE_DEPRECATION_WARNING = 1
168endif
169
170
171" Prepare for calling test_garbagecollect_now().
172" Also avoids some delays in Insert mode completion.
173let v:testing = 1
174
175let s:has_ffi = luaeval('pcall(require, "ffi")')
176if s:has_ffi
177  lua << trim EOF
178    require('ffi').cdef([[
179      int starting;
180      bool test_disable_char_avail;
181    ]])
182  EOF
183endif
184
185" This can emulate test_override('starting') and test_override('char_avail')
186" if LuaJIT FFI is enabled.
187" Other flags are not supported.
188func Ntest_override(name, val)
189  if a:name !=# 'starting' && a:name != 'char_avail' && a:name !=# 'ALL'
190    throw 'Unexpected use of Ntest_override()'
191  endif
192  if !s:has_ffi
193    throw 'Skipped: missing LuaJIT FFI'
194  endif
195
196  if a:name ==# 'starting' || a:name ==# 'ALL'
197    if a:val
198      if !exists('s:save_starting')
199        let s:save_starting = luaeval('require("ffi").C.starting')
200      endif
201      lua require("ffi").C.starting = 0
202    elseif exists('s:save_starting')
203      exe 'lua require("ffi").C.starting =' s:save_starting
204      unlet s:save_starting
205    endif
206  endif
207
208  if a:name ==# 'char_avail' || a:name ==# 'ALL'
209    exe 'lua require("ffi").C.test_disable_char_avail =' a:val
210  endif
211endfunc
212
213" roughly equivalent to test_setmouse() in Vim
214func Ntest_setmouse(row, col)
215  call nvim_input_mouse('move', '', '', 0, a:row - 1, a:col - 1)
216  if state('m') == ''
217    call getchar(0)
218  endif
219endfunc
220
221" roughly equivalent to term_wait() in Vim
222func Nterm_wait(buf, time = 10)
223  execute $'sleep {a:time}m'
224endfunc
225
226" Support function: get the alloc ID by name.
227func GetAllocId(name)
228  exe 'split ' . s:srcdir . '/alloc.h'
229  let top = search('typedef enum')
230  if top == 0
231    call add(v:errors, 'typedef not found in alloc.h')
232  endif
233  let lnum = search('aid_' . a:name . ',')
234  if lnum == 0
235    call add(v:errors, 'Alloc ID ' . a:name . ' not defined')
236  endif
237  close
238  return lnum - top - 1
239endfunc
240
241" Get the list of swap files in the current directory.
242func s:GetSwapFileList()
243  let save_dir = &directory
244  let &directory = '.'
245  let files = swapfilelist()
246  let &directory = save_dir
247
248  " remove a match with runtest.vim
249  let idx = indexof(files, 'v:val =~ "runtest.vim."')
250  if idx >= 0
251    call remove(files, idx)
252  endif
253
254  return files
255endfunc
256
257" A previous (failed) test run may have left swap files behind.  Delete them
258" before running tests again, they might interfere.
259for name in s:GetSwapFileList()
260  call delete(name)
261endfor
262unlet! name
263
264
265" Invoked when a test takes too much time.
266func TestTimeout(id)
267  split test.log
268  call append(line('$'), '')
269
270  let text = 'Test timed out: ' .. g:testfunc
271  if g:timeout_start > 0
272    let text ..= strftime(' after %s seconds', localtime() - g:timeout_start)
273  endif
274  call append(line('$'), text)
275  write
276  call add(v:errors, text)
277
278  cquit! 42
279endfunc
280let g:timeout_start = 0
281
282func RunTheTest(test)
283  let prefix = ''
284  if has('reltime')
285    let prefix = strftime('%M:%S', localtime() - s:test_start_time) .. ' '
286    let g:func_start = reltime()
287  endif
288  echo prefix .. 'Executing ' .. a:test
289
290  if has('timers')
291    " No test should take longer than 45 seconds.  If it takes longer we
292    " assume we are stuck and need to break out.
293    let test_timeout_timer =
294          \ timer_start(RunningWithValgrind() ? 90000 : 45000, 'TestTimeout')
295    let g:timeout_start = localtime()
296  endif
297
298  " Avoid stopping at the "hit enter" prompt
299  set nomore
300
301  " Avoid a three second wait when a message is about to be overwritten by the
302  " mode message.
303  set noshowmode
304
305  " Some tests wipe out buffers.  To be consistent, always wipe out all
306  " buffers.
307  %bwipe!
308
309  " The test may change the current directory. Save and restore the
310  " directory after executing the test.
311  let save_cwd = getcwd()
312
313  " Align Nvim defaults to Vim.
314  source setup.vim
315
316  if exists("*SetUp")
317    try
318      call SetUp()
319    catch
320      call add(v:errors, 'Caught exception in SetUp() before ' . a:test . ': ' . v:exception . ' @ ' . v:throwpoint)
321    endtry
322  endif
323
324  let skipped = v:false
325
326  au VimLeavePre * call EarlyExit(g:testfunc)
327  if a:test =~ 'Test_nocatch_'
328    " Function handles errors itself.  This avoids skipping commands after the
329    " error.
330    let g:skipped_reason = ''
331    exe 'call ' . a:test
332    if g:skipped_reason != ''
333      call add(s:messages, '    Skipped')
334      call add(s:skipped, 'SKIPPED ' . a:test . ': ' . g:skipped_reason)
335      let skipped = v:true
336    endif
337  elseif !s:has_ffi && execute('func ' .. a:test[:-3])->match("\n[ 0-9]*call Ntest_override(") >= 0
338    call add(s:messages, '    Skipped')
339    call add(s:skipped, 'SKIPPED ' . a:test . ': missing LuaJIT FFI' . )
340    let skipped = v:true
341  else
342    try
343      exe 'call ' . a:test
344    catch /^\cskipped/
345      call add(s:messages, '    Skipped')
346      call add(s:skipped, 'SKIPPED ' . a:test . ': ' . substitute(v:exception, '^\S*\s\+', '',  ''))
347      let skipped = v:true
348    catch
349      call add(v:errors, 'Caught exception in ' . a:test . ': ' . v:exception . ' @ ' . v:throwpoint)
350    endtry
351  endif
352  au! VimLeavePre
353
354  if a:test =~ '_terminal_'
355    " Terminal tests sometimes hang, give extra information
356    echoconsole 'After executing ' .. a:test
357  endif
358
359  " In case 'insertmode' was set and something went wrong, make sure it is
360  " reset to avoid trouble with anything else.
361  set noinsertmode
362
363  if exists("*TearDown")
364    try
365      call TearDown()
366    catch
367      call add(v:errors, 'Caught exception in TearDown() after ' . a:test . ': ' . v:exception . ' @ ' . v:throwpoint)
368    endtry
369  endif
370
371  if has('timers')
372    call timer_stop(test_timeout_timer)
373    let g:timeout_start = 0
374  endif
375
376  " Clear any autocommands and put back the catch-all for SwapExists.
377  au!
378  au SwapExists * call HandleSwapExists()
379
380  " Close any stray popup windows
381  if has('popupwin')
382    call popup_clear()
383  endif
384
385  " Close any extra tab pages and windows and make the current one not modified.
386  while tabpagenr('$') > 1
387    let winid = win_getid()
388    quit!
389    if winid == win_getid()
390      echoerr 'Could not quit window'
391      break
392    endif
393  endwhile
394
395  while 1
396    let wincount = winnr('$')
397    if wincount == 1
398      break
399    endif
400    bwipe!
401    if wincount == winnr('$')
402      " Did not manage to close a window.
403      only!
404      break
405    endif
406  endwhile
407
408  exe 'cd ' . save_cwd
409
410  if a:test =~ '_terminal_'
411    " Terminal tests sometimes hang, give extra information
412    echoconsole 'Finished ' . a:test
413  endif
414
415  let message = 'Executed ' . a:test
416  if has('reltime')
417    let message ..= repeat(' ', 50 - len(message))
418    let time = reltime(g:func_start)
419    if reltimefloat(time) > 0.1
420      let message = s:t_bold .. message
421    endif
422    let message ..= ' in ' .. reltimestr(time) .. ' seconds'
423    if reltimefloat(time) > 0.1
424      let message ..= s:t_normal
425    endif
426  endif
427  call add(s:messages, message)
428  let s:done += 1
429
430  " close any split windows
431  while winnr('$') > 1
432    noswapfile bwipe!
433  endwhile
434
435  " May be editing some buffer, wipe it out.  Then we may end up in another
436  " buffer, continue until we end up in an empty no-name buffer without a swap
437  " file.
438  while bufname() != '' || execute('swapname') !~ 'No swap file'
439    let bn = bufnr()
440
441    noswapfile bwipe!
442
443    if bn == bufnr()
444      " avoid getting stuck in the same buffer
445      break
446    endif
447  endwhile
448
449  if !skipped
450    " Check if the test has left any swap files behind.  Delete them before
451    " running tests again, they might interfere.
452    let swapfiles = s:GetSwapFileList()
453    if len(swapfiles) > 0
454      call add(s:messages, "Found swap files: " .. string(swapfiles))
455      for name in swapfiles
456        call delete(name)
457      endfor
458    endif
459  endif
460endfunc
461
462function Delete_Xtest_Files()
463  for file in glob('X*', v:false, v:true)
464    if file ==? 'XfakeHOME'
465      " Clean up files created by setup.vim
466      call delete('XfakeHOME', 'rf')
467      continue
468    endif
469    " call add(v:errors, file .. " exists when it shouldn't, trying to delete it!")
470    call delete(file)
471    if !empty(glob(file, v:false, v:true))
472      " call add(v:errors, file .. " still exists after trying to delete it!")
473      if has('unix')
474        call system('rm -rf  ' .. file)
475      endif
476    endif
477  endfor
478endfunc
479
480func AfterTheTest(func_name)
481  if len(v:errors) > 0
482    if match(s:may_fail_list, '^' .. a:func_name) >= 0
483      let s:fail_expected += 1
484      call add(s:errors_expected, 'Found errors in ' . g:testfunc . ':')
485      call extend(s:errors_expected, v:errors)
486    else
487      let s:fail += 1
488      call add(s:errors, 'Found errors in ' . g:testfunc . ':')
489      call extend(s:errors, v:errors)
490    endif
491    let v:errors = []
492  endif
493endfunc
494
495func EarlyExit(test)
496  " It's OK for the test we use to test the quit detection.
497  if a:test != 'Test_zz_quit_detected()'
498    call add(v:errors, v:errmsg)
499    call add(v:errors, 'Test caused Vim to exit: ' . a:test)
500  endif
501
502  call FinishTesting()
503endfunc
504
505" This function can be called by a test if it wants to abort testing.
506func FinishTesting()
507  call AfterTheTest('')
508  call Delete_Xtest_Files()
509
510  " Don't write viminfo on exit.
511  set viminfo=
512
513  if s:fail == 0 && s:fail_expected == 0
514    " Success, create the .res file so that make knows it's done.
515    exe 'split ' . fnamemodify(g:testname, ':r') . '.res'
516    write
517  endif
518
519  if len(s:errors) > 0
520    " Append errors to test.log
521    split test.log
522    call append(line('$'), '')
523    call append(line('$'), 'From ' . g:testname . ':')
524    call append(line('$'), s:errors)
525    write
526  endif
527
528  if s:done == 0
529    if s:filtered > 0
530      if $TEST_FILTER != ''
531        let message = "NO tests match $TEST_FILTER: '" .. $TEST_FILTER .. "'"
532      else
533        let message = "ALL tests match $TEST_SKIP_PAT: '" .. $TEST_SKIP_PAT .. "'"
534      endif
535    else
536      let message = 'NO tests executed'
537    endif
538  else
539    if s:filtered > 0
540      call add(s:messages, "Filtered " .. s:filtered .. " tests with $TEST_FILTER and $TEST_SKIP_PAT")
541    endif
542    let message = 'Executed ' . s:done . (s:done > 1 ? ' tests' : ' test')
543  endif
544  if s:done > 0 && has('reltime')
545    let message = s:t_bold .. message .. repeat(' ', 40 - len(message))
546    let message ..= ' in ' .. reltimestr(reltime(s:run_start_time)) .. ' seconds'
547    let message ..= s:t_normal
548  endif
549  echo message
550  call add(s:messages, message)
551  if s:fail > 0
552    let message = s:fail . ' FAILED:'
553    echo message
554    call add(s:messages, message)
555    call extend(s:messages, s:errors)
556  endif
557  if s:fail_expected > 0
558    let message = s:fail_expected . ' FAILED (matching $TEST_MAY_FAIL):'
559    echo message
560    call add(s:messages, message)
561    call extend(s:messages, s:errors_expected)
562  endif
563
564  " Add SKIPPED messages
565  call extend(s:messages, s:skipped)
566
567  " Append messages to the file "messages"
568  split messages
569  call append(line('$'), '')
570  call append(line('$'), 'From ' . g:testname . ':')
571  call append(line('$'), s:messages)
572  write
573
574  qall!
575endfunc
576
577" Source the test script.  First grab the file name, in case the script
578" navigates away.  g:testname can be used by the tests.
579let g:testname = expand('%')
580let s:done = 0
581let s:fail = 0
582let s:fail_expected = 0
583let s:errors = []
584let s:errors_expected = []
585let s:messages = []
586let s:skipped = []
587if expand('%') =~ 'test_vimscript.vim'
588  " this test has intentional errors, don't use try/catch.
589  source %
590else
591  try
592    source %
593  catch /^\cskipped/
594    call add(s:messages, '    Skipped')
595    call add(s:skipped, 'SKIPPED ' . expand('%') . ': ' . substitute(v:exception, '^\S*\s\+', '',  ''))
596  catch
597    let s:fail += 1
598    call add(s:errors, 'Caught exception: ' . v:exception . ' @ ' . v:throwpoint)
599  endtry
600endif
601
602" Delete the .res file, it may change behavior for completion
603call delete(fnamemodify(g:testname, ':r') .. '.res')
604
605" Locate Test_ functions and execute them.
606redir @q
607silent function /^Test_
608redir END
609let s:tests = split(substitute(@q, 'function \(\k*()\)', '\1', 'g'))
610
611" If there is an extra argument filter the function names against it.
612if argc() > 1
613  let s:tests = filter(s:tests, 'v:val =~ argv(1)')
614endif
615
616" If the environment variable $TEST_FILTER is set then filter the function
617" names against it.
618let s:filtered = 0
619if $TEST_FILTER != ''
620  let s:filtered = len(s:tests)
621  let s:tests = filter(s:tests, 'v:val =~ $TEST_FILTER')
622  let s:filtered -= len(s:tests)
623endif
624
625let s:may_fail_list = []
626if $TEST_MAY_FAIL != ''
627  " Split the list at commas and add () to make it match g:testfunc.
628  let s:may_fail_list = split($TEST_MAY_FAIL, ',')->map({i, v -> v .. '()'})
629endif
630
631" Execute the tests in alphabetical order.
632for g:testfunc in sort(s:tests)
633  if $TEST_SKIP_PAT != '' && g:testfunc =~ $TEST_SKIP_PAT
634    call add(s:messages, g:testfunc .. ' matches $TEST_SKIP_PAT')
635    let s:filtered += 1
636    continue
637  endif
638
639  " Silence, please!
640  set belloff=all
641  let prev_error = ''
642  let total_errors = []
643  let g:run_nr = 1
644
645  " A test can set g:test_is_flaky to retry running the test.
646  let g:test_is_flaky = 0
647
648  let g:check_screendump_called = v:false
649
650  " A test can set g:max_run_nr to change the max retry count.
651  let g:max_run_nr = 5
652  if has('mac')
653    let g:max_run_nr = 10
654  endif
655
656  " By default, give up if the same error occurs.  A test can set
657  " g:giveup_same_error to 0 to not give up on the same error and keep trying.
658  let g:giveup_same_error = 1
659
660  let starttime = strftime("%H:%M:%S")
661  call RunTheTest(g:testfunc)
662
663  " Repeat a flaky test.  Give up when:
664  " - $TEST_NO_RETRY is not empty
665  " - it fails again with the same message
666  " - it fails five times (with a different message)
667  if len(v:errors) > 0
668        \ && $TEST_NO_RETRY == ''
669        \ && g:test_is_flaky
670    while 1
671      call add(s:messages, 'Found errors in ' .. g:testfunc .. ':')
672      call extend(s:messages, v:errors)
673
674      let endtime = strftime("%H:%M:%S")
675      if has('reltime')
676        let suffix = $' in{reltimestr(reltime(g:func_start))} seconds'
677      else
678        let suffix = ''
679      endif
680      call add(total_errors, $'Run {g:run_nr}, {starttime} - {endtime}{suffix}:')
681      call extend(total_errors, v:errors)
682
683      if g:run_nr >= g:max_run_nr || g:giveup_same_error && prev_error == v:errors[0]
684        call add(total_errors, 'Flaky test failed too often, giving up')
685        let v:errors = total_errors
686        break
687      endif
688
689      call add(s:messages, 'Flaky test failed, running it again')
690
691      " Flakiness is often caused by the system being very busy.  Sleep a
692      " couple of seconds to have a higher chance of succeeding the second
693      " time.
694      let delay = g:run_nr * 2
695      exe 'sleep' delay
696
697      let prev_error = v:errors[0]
698      let v:errors = []
699      let g:run_nr += 1
700
701      let starttime = strftime("%H:%M:%S")
702      call RunTheTest(g:testfunc)
703
704      if len(v:errors) == 0
705        " Test passed on rerun.
706        break
707      endif
708    endwhile
709  endif
710
711  call AfterTheTest(g:testfunc)
712endfor
713
714call FinishTesting()
715
716" vim: shiftwidth=2 sts=2 expandtab