view src/testdir/runtest.vim @ 32936:c517845bd10e v9.0.1776

patch 9.0.1776: No support for stable Python 3 ABI Commit: https://github.com/vim/vim/commit/c13b3d1350b60b94fe87f0761ea31c0e7fb6ebf3 Author: Yee Cheng Chin <ychin.git@gmail.com> Date: Sun Aug 20 21:18:38 2023 +0200 patch 9.0.1776: No support for stable Python 3 ABI Problem: No support for stable Python 3 ABI Solution: Support Python 3 stable ABI Commits: 1) Support Python 3 stable ABI to allow mixed version interoperatbility Vim currently supports embedding Python for use with plugins, and the "dynamic" linking option allows the user to specify a locally installed version of Python by setting `pythonthreedll`. However, one caveat is that the Python 3 libs are not binary compatible across minor versions, and mixing versions can potentially be dangerous (e.g. let's say Vim was linked against the Python 3.10 SDK, but the user sets `pythonthreedll` to a 3.11 lib). Usually, nothing bad happens, but in theory this could lead to crashes, memory corruption, and other unpredictable behaviors. It's also difficult for the user to tell something is wrong because Vim has no way of reporting what Python 3 version Vim was linked with. For Vim installed via a package manager, this usually isn't an issue because all the dependencies would already be figured out. For prebuilt Vim binaries like MacVim (my motivation for working on this), AppImage, and Win32 installer this could potentially be an issue as usually a single binary is distributed. This is more tricky when a new Python version is released, as there's a chicken-and-egg issue with deciding what Python version to build against and hard to keep in sync when a new Python version just drops and we have a mix of users of different Python versions, and a user just blindly upgrading to a new Python could lead to bad interactions with Vim. Python 3 does have a solution for this problem: stable ABI / limited API (see https://docs.python.org/3/c-api/stable.html). The C SDK limits the API to a set of functions that are promised to be stable across versions. This pull request adds an ifdef config that allows us to turn it on when building Vim. Vim binaries built with this option should be safe to freely link with any Python 3 libraies without having the constraint of having to use the same minor version. Note: Python 2 has no such concept and this doesn't change how Python 2 integration works (not that there is going to be a new version of Python 2 that would cause compatibility issues in the future anyway). --- Technical details: ====== The stable ABI can be accessed when we compile with the Python 3 limited API (by defining `Py_LIMITED_API`). The Python 3 code (in `if_python3.c` and `if_py_both.h`) would now handle this and switch to limited API mode. Without it set, Vim will still use the full API as before so this is an opt-in change. The main difference is that `PyType_Object` is now an opaque struct that we can't directly create "static types" out of, and we have to create type objects as "heap types" instead. This is because the struct is not stable and changes from version to version (e.g. 3.8 added a `tp_vectorcall` field to it). I had to change all the types to be allocated on the heap instead with just a pointer to them. Other functions are also simply missing in limited API, or they are introduced too late (e.g. `PyUnicode_AsUTF8AndSize` in 3.10) to it that we need some other ways to do the same thing, so I had to abstract a few things into macros, and sometimes re-implement functions like `PyObject_NEW`. One caveat is that in limited API, `OutputType` (used for replacing `sys.stdout`) no longer inherits from `PyStdPrinter_Type` which I don't think has any real issue other than minor differences in how they convert to a string and missing a couple functions like `mode()` and `fileno()`. Also fixed an existing bug where `tp_basicsize` was set incorrectly for `BufferObject`, `TabListObject, `WinListObject`. Technically, there could be a small performance drop, there is a little more indirection with accessing type objects, and some APIs like `PyUnicode_AsUTF8AndSize` are missing, but in practice I didn't see any difference, and any well-written Python plugin should try to avoid excessing callbacks to the `vim` module in Python anyway. I only tested limited API mode down to Python 3.7, which seemes to compile and work fine. I haven't tried earlier Python versions. 2) Fix PyIter_Check on older Python vers / type##Ptr unused warning For PyIter_Check, older versions exposed them as either macros (used in full API), or a function (for use in limited API). A previous change exposed PyIter_Check to the dynamic build because Python just moved it to function-only in 3.10 anyway. Because of that, just make sure we always grab the function in dynamic builds in earlier versions since that's what Python eventually did anyway. 3) Move Py_LIMITED_API define to configure script Can now use --with-python-stable-abi flag to customize what stable ABI version to target. Can also use an env var to do so as well. 4) Show +python/dyn-stable in :version, and allow has() feature query Not sure if the "/dyn-stable" suffix would break things, or whether we should do it another way. Or just don't show it in version and rely on has() feature checking. 5) Documentation first draft. Still need to implement v:python3_version 6) Fix PyIter_Check build breaks when compiling against Python 3.8 7) Add CI coverage stable ABI on Linux/Windows / make configurable on Windows This adds configurable options for Windows make files (both MinGW and MSVC). CI will also now exercise both traditional full API and stable ABI for Linux and Windows in the matrix for coverage. Also added a "dynamic" option to Linux matrix as a drive-by change to make other scripting languages like Ruby / Perl testable under both static and dynamic builds. 8) Fix inaccuracy in Windows docs Python's own docs are confusing but you don't actually want to use `python3.dll` for the dynamic linkage. 9) Add generated autoconf file 10) Add v:python3_version support This variable indicates the version of Python3 that Vim was built against (PY_VERSION_HEX), and will be useful to check whether the Python library you are loading in dynamically actually fits it. When built with stable ABI, it will be the limited ABI version instead (`Py_LIMITED_API`), which indicates the minimum version of Python 3 the user should have, rather than the exact match. When stable ABI is used, we won't be exposing PY_VERSION_HEX in this var because it just doesn't seem necessary to do so (the whole point of stable ABI is the promise that it will work across versions), and I don't want to confuse the user with too many variables. Also, cleaned up some documentation, and added help tags. 11) Fix Python 3.7 compat issues Fix a couple issues when using limited API < 3.8 - Crash on exit: In Python 3.7, if a heap-allocated type is destroyed before all instances are, it would cause a crash later. This happens when we destroyed `OptionsType` before calling `Py_Finalize` when using the limited API. To make it worse, later versions changed the semantics and now each instance has a strong reference to its own type and the recommendation has changed to have each instance de-ref its own type and have its type in GC traversal. To avoid dealing with these cross-version variations, we just don't free the heap type. They are static types in non-limited-API anyway and are designed to last through the entirety of the app, and we also don't restart the Python runtime and therefore do not need it to have absolutely 0 leaks. See: - https://docs.python.org/3/whatsnew/3.8.html#changes-in-the-c-api - https://docs.python.org/3/whatsnew/3.9.html#changes-in-the-c-api - PyIter_Check: This function is not provided in limited APIs older than 3.8. Previously I was trying to mock it out using manual PyType_GetSlot() but it was brittle and also does not actually work properly for static types (it will generate a Python error). Just return false. It does mean using limited API < 3.8 is not recommended as you lose the functionality to handle iterators, but from playing with plugins I couldn't find it to be an issue. - Fix loading of PyIter_Check so it will be done when limited API < 3.8. Otherwise loading a 3.7 Python lib will fail even if limited API was specified to use it. 12) Make sure to only load `PyUnicode_AsUTF8AndSize` in needed in limited API We don't use this function unless limited API >= 3.10, but we were loading it regardless. Usually it's ok in Unix-like systems where Python just has a single lib that we load from, but in Windows where there is a separate python3.dll this would not work as the symbol would not have been exposed in this more limited DLL file. This makes it much clearer under what condition is this function needed. closes: #12032 Signed-off-by: Christian Brabandt <cb@256bit.org> Co-authored-by: Yee Cheng Chin <ychin.git@gmail.com>
author Christian Brabandt <cb@256bit.org>
date Sun, 20 Aug 2023 21:30:04 +0200
parents e5cd5e8627da
children 5eab5c00bb7c
line wrap: on
line source

" This script is sourced while editing the .vim file with the tests.
" When the script is successful the .res file will be created.
" Errors are appended to the test.log file.
"
" To execute only specific test functions, add a second argument.  It will be
" matched against the names of the Test_ function.  E.g.:
"	../vim -u NONE -S runtest.vim test_channel.vim open_delay
" The output can be found in the "messages" file.
"
" If the environment variable $TEST_FILTER is set then only test functions
" matching this pattern are executed.  E.g. for sh/bash:
"     export TEST_FILTER=Test_channel
" For csh:
"     setenv TEST_FILTER Test_channel
"
" If the environment variable $TEST_SKIP_PAT is set then test functions
" matching this pattern will be skipped.  It's the opposite of $TEST_FILTER.
"
" While working on a test you can make $TEST_NO_RETRY non-empty to not retry:
"     export TEST_NO_RETRY=yes
"
" To ignore failure for tests that are known to fail in a certain environment,
" set $TEST_MAY_FAIL to a comma separated list of function names.  E.g. for
" sh/bash:
"     export TEST_MAY_FAIL=Test_channel_one,Test_channel_other
" The failure report will then not be included in the test.log file and
" "make test" will not fail.
"
" The test script may contain anything, only functions that start with
" "Test_" are special.  These will be invoked and should contain assert
" functions.  See test_assert.vim for an example.
"
" It is possible to source other files that contain "Test_" functions.  This
" can speed up testing, since Vim does not need to restart.  But be careful
" that the tests do not interfere with each other.
"
" If an error cannot be detected properly with an assert function add the
" error to the v:errors list:
"   call add(v:errors, 'test foo failed: Cannot find xyz')
"
" If preparation for each Test_ function is needed, define a SetUp function.
" It will be called before each Test_ function.
"
" If cleanup after each Test_ function is needed, define a TearDown function.
" It will be called after each Test_ function.
"
" When debugging a test it can be useful to add messages to v:errors:
"	call add(v:errors, "this happened")


" Without the +eval feature we can't run these tests, bail out.
silent! while 0
  qa!
silent! endwhile

" In the GUI we can always change the screen size.
if has('gui_running')
  set columns=80 lines=25
endif

" Check that the screen size is at least 24 x 80 characters.
if &lines < 24 || &columns < 80
  let error = 'Screen size too small! Tests require at least 24 lines with 80 characters, got ' .. &lines .. ' lines with ' .. &columns .. ' characters'
  echoerr error
  split test.log
  $put =error
  write
  split messages
  call append(line('$'), '')
  call append(line('$'), 'From ' . expand('%') . ':')
  call append(line('$'), error)
  write
  qa!
endif

if has('reltime')
  let s:run_start_time = reltime()

  if !filereadable('starttime')
    " first test, store the overall test starting time
    let s:test_start_time = localtime()
    call writefile([string(s:test_start_time)], 'starttime')
  else
    " second or later test, read the overall test starting time
    let s:test_start_time = readfile('starttime')[0]->str2nr()
  endif
endif

" Always use forward slashes.
set shellslash

" Common with all tests on all systems.
source setup.vim

" Needed for RunningWithValgrind().
source shared.vim

" For consistency run all tests with 'nocompatible' set.
" This also enables use of line continuation.
set nocp viminfo+=nviminfo

" Use utf-8 by default, instead of whatever the system default happens to be.
" Individual tests can overrule this at the top of the file and use
" g:orig_encoding if needed.
let g:orig_encoding = &encoding
set encoding=utf-8

" REDIR_TEST_TO_NULL has a very permissive SwapExists autocommand which is for
" the test_name.vim file itself. Replace it here with a more restrictive one,
" so we still catch mistakes.
if has("win32")
  " replace any '/' directory separators by '\\'
  let s:test_script_fname = substitute(expand('%'), '/', '\\', 'g')
else
  let s:test_script_fname = expand('%')
endif

au! SwapExists * call HandleSwapExists()
func HandleSwapExists()
  if exists('g:ignoreSwapExists')
    if type(g:ignoreSwapExists) == v:t_string
      let v:swapchoice = g:ignoreSwapExists
    endif
    return
  endif
  " Ignore finding a swap file for the test script (the user might be
  " editing it and do ":make test_name") and the output file.
  " Report finding another swap file and chose 'q' to avoid getting stuck.
  if expand('<afile>') == 'messages' || expand('<afile>') =~ s:test_script_fname
    let v:swapchoice = 'e'
  else
    call assert_report('Unexpected swap file: ' .. v:swapname)
    let v:swapchoice = 'q'
  endif
endfunc

" Avoid stopping at the "hit enter" prompt
set nomore

" Output all messages in English.
lang mess C

" suppress menu translation
if has('gui_running') && exists('did_install_default_menus')
  source $VIMRUNTIME/delmenu.vim
  set langmenu=none
  source $VIMRUNTIME/menu.vim
endif

let s:srcdir = expand('%:p:h:h')

if has('win32')
  " avoid prompt that is long or contains a line break
  let $PROMPT = '$P$G'
  " On MS-Windows t_md and t_me are Vim specific escape sequences.
  let s:t_bold = "\x1b[1m"
  let s:t_normal = "\x1b[m"
else
  let s:t_bold = &t_md
  let s:t_normal = &t_me
endif

if has('mac')
  " In macOS, when starting a shell in a terminal, a bash deprecation warning
  " message is displayed. This breaks the terminal test. Disable the warning
  " message.
  let $BASH_SILENCE_DEPRECATION_WARNING = 1
endif


" Prepare for calling test_garbagecollect_now().
let v:testing = 1

" By default, copy each buffer line into allocated memory, so that valgrind can
" detect accessing memory before and after it.
call test_override('alloc_lines', 1)

" Support function: get the alloc ID by name.
function GetAllocId(name)
  exe 'split ' . s:srcdir . '/alloc.h'
  let top = search('typedef enum')
  if top == 0
    call add(v:errors, 'typedef not found in alloc.h')
  endif
  let lnum = search('aid_' . a:name . ',')
  if lnum == 0
    call add(v:errors, 'Alloc ID ' . a:name . ' not defined')
  endif
  close
  return lnum - top - 1
endfunc

if has('reltime')
  let g:func_start = reltime()
endif

" Get the list of swap files in the current directory.
func s:GetSwapFileList()
  let save_dir = &directory
  let &directory = '.'
  let files = swapfilelist()
  let &directory = save_dir

  " remove a match with runtest.vim
  let idx = indexof(files, 'v:val =~ "runtest.vim."')
  if idx >= 0
    call remove(files, idx)
  endif

  return files
endfunc

" A previous (failed) test run may have left swap files behind.  Delete them
" before running tests again, they might interfere.
for name in s:GetSwapFileList()
  call delete(name)
endfor
unlet name


" Invoked when a test takes too much time.
func TestTimeout(id)
  split test.log
  call append(line('$'), '')

  let text = 'Test timed out: ' .. g:testfunc
  if g:timeout_start > 0
    let text ..= strftime(' after %s seconds', localtime() - g:timeout_start)
  endif
  call append(line('$'), text)
  write
  call add(v:errors, text)

  cquit! 42
endfunc
let g:timeout_start = 0

func RunTheTest(test)
  let prefix = ''
  if has('reltime')
    let prefix = strftime('%M:%S', localtime() - s:test_start_time) .. ' '
    let g:func_start = reltime()
  endif
  echoconsole prefix .. 'Executing ' .. a:test

  if has('timers')
    " No test should take longer than 30 seconds.  If it takes longer we
    " assume we are stuck and need to break out.
    let test_timeout_timer =
          \ timer_start(RunningWithValgrind() ? 50000 : 30000, 'TestTimeout')
    let g:timeout_start = localtime()
  endif

  " Avoid stopping at the "hit enter" prompt
  set nomore

  " Avoid a three second wait when a message is about to be overwritten by the
  " mode message.
  set noshowmode

  " Clear any overrides, except "alloc_lines".
  call test_override('ALL', 0)

  " Some tests wipe out buffers.  To be consistent, always wipe out all
  " buffers.
  %bwipe!

  " The test may change the current directory. Save and restore the
  " directory after executing the test.
  let save_cwd = getcwd()

  if exists("*SetUp")
    try
      call SetUp()
    catch
      call add(v:errors, 'Caught exception in SetUp() before ' . a:test . ': ' . v:exception . ' @ ' . v:throwpoint)
    endtry
  endif

  au VimLeavePre * call EarlyExit(g:testfunc)
  if a:test =~ 'Test_nocatch_'
    " Function handles errors itself.  This avoids skipping commands after the
    " error.
    let g:skipped_reason = ''
    exe 'call ' . a:test
    if g:skipped_reason != ''
      call add(s:messages, '    Skipped')
      call add(s:skipped, 'SKIPPED ' . a:test . ': ' . g:skipped_reason)
    endif
  else
    try
      exe 'call ' . a:test
    catch /^\cskipped/
      call add(s:messages, '    Skipped')
      call add(s:skipped, 'SKIPPED ' . a:test . ': ' . substitute(v:exception, '^\S*\s\+', '',  ''))
    catch
      call add(v:errors, 'Caught exception in ' . a:test . ': ' . v:exception . ' @ ' . v:throwpoint)
    endtry
  endif
  au! VimLeavePre

  if a:test =~ '_terminal_'
    " Terminal tests sometimes hang, give extra information
    echoconsole 'After executing ' .. a:test
  endif

  " In case 'insertmode' was set and something went wrong, make sure it is
  " reset to avoid trouble with anything else.
  set noinsertmode

  if exists("*TearDown")
    try
      call TearDown()
    catch
      call add(v:errors, 'Caught exception in TearDown() after ' . a:test . ': ' . v:exception . ' @ ' . v:throwpoint)
    endtry
  endif

  if has('timers')
    call timer_stop(test_timeout_timer)
    let g:timeout_start = 0
  endif

  " Clear any autocommands and put back the catch-all for SwapExists.
  au!
  au SwapExists * call HandleSwapExists()

  " Check for and close any stray popup windows.
  if has('popupwin')
    call assert_equal([], popup_list(), 'Popup is still present')
    call popup_clear(1)
  endif

  if filereadable('guidialogfile')
    call add(v:errors, "Unexpected dialog: " .. readfile('guidialogfile')->join('<NL>'))
    call delete('guidialogfile')
  endif

  " Close any extra tab pages and windows and make the current one not modified.
  while tabpagenr('$') > 1
    let winid = win_getid()
    quit!
    if winid == win_getid()
      echoerr 'Could not quit window'
      break
    endif
  endwhile

  while 1
    let wincount = winnr('$')
    if wincount == 1
      break
    endif
    bwipe!
    if wincount == winnr('$')
      " Did not manage to close a window.
      only!
      break
    endif
  endwhile

  exe 'cd ' . save_cwd

  if a:test =~ '_terminal_'
    " Terminal tests sometimes hang, give extra information
    echoconsole 'Finished ' . a:test
  endif

  let message = 'Executed ' . a:test
  if has('reltime')
    let message ..= repeat(' ', 50 - len(message))
    let time = reltime(g:func_start)
    if reltimefloat(time) > 0.1
      let message = s:t_bold .. message
    endif
    let message ..= ' in ' .. reltimestr(time) .. ' seconds'
    if reltimefloat(time) > 0.1
      let message ..= s:t_normal
    endif
  endif
  call add(s:messages, message)
  let s:done += 1

  " close any split windows
  while winnr('$') > 1
    noswapfile bwipe!
  endwhile

  " May be editing some buffer, wipe it out.  Then we may end up in another
  " buffer, continue until we end up in an empty no-name buffer without a swap
  " file.
  while bufname() != '' || execute('swapname') !~ 'No swap file'
    let bn = bufnr()

    noswapfile bwipe!

    if bn == bufnr()
      " avoid getting stuck in the same buffer
      break
    endif
  endwhile

  " Check if the test has left any swap files behind.  Delete them before
  " running tests again, they might interfere.
  let swapfiles = s:GetSwapFileList()
  if len(swapfiles) > 0
    call add(s:messages, "Found swap files: " .. string(swapfiles))
    for name in swapfiles
      call delete(name)
    endfor
  endif
endfunc

function Delete_Xtest_Files()
  for file in glob('X*', v:false, v:true)
    if file ==? 'XfakeHOME'
      " Clean up files created by setup.vim
      call delete('XfakeHOME', 'rf')
      continue
    endif
    " call add(v:errors, file .. " exists when it shouldn't, trying to delete it!")
    call delete(file)
    if !empty(glob(file, v:false, v:true))
      " call add(v:errors, file .. " still exists after trying to delete it!")
      if has('unix')
        call system('rm -rf  ' .. file)
      endif
    endif
  endfor
endfunc

func AfterTheTest(func_name)
  if len(v:errors) > 0
    if match(s:may_fail_list, '^' .. a:func_name) >= 0
      let s:fail_expected += 1
      call add(s:errors_expected, 'Found errors in ' . g:testfunc . ':')
      call extend(s:errors_expected, v:errors)
    else
      let s:fail += 1
      call add(s:errors, 'Found errors in ' . g:testfunc . ':')
      call extend(s:errors, v:errors)
    endif
    let v:errors = []
  endif
endfunc

func EarlyExit(test)
  " It's OK for the test we use to test the quit detection.
  if a:test != 'Test_zz_quit_detected()'
    call add(v:errors, v:errmsg)
    call add(v:errors, 'Test caused Vim to exit: ' . a:test)
  endif

  call FinishTesting()
endfunc

" This function can be called by a test if it wants to abort testing.
func FinishTesting()
  call AfterTheTest('')
  call Delete_Xtest_Files()

  " Don't write viminfo on exit.
  set viminfo=

  if s:fail == 0 && s:fail_expected == 0
    " Success, create the .res file so that make knows it's done.
    exe 'split ' . fnamemodify(g:testname, ':r') . '.res'
    write
  endif

  if len(s:errors) > 0
    " Append errors to test.log
    split test.log
    call append(line('$'), '')
    call append(line('$'), 'From ' . g:testname . ':')
    call append(line('$'), s:errors)
    write
  endif

  if s:done == 0
    if s:filtered > 0
      if $TEST_FILTER != ''
        let message = "NO tests match $TEST_FILTER: '" .. $TEST_FILTER .. "'"
      else
        let message = "ALL tests match $TEST_SKIP_PAT: '" .. $TEST_SKIP_PAT .. "'"
      endif
    else
      let message = 'NO tests executed'
    endif
  else
    if s:filtered > 0
      call add(s:messages, "Filtered " .. s:filtered .. " tests with $TEST_FILTER and $TEST_SKIP_PAT")
    endif
    let message = 'Executed ' . s:done . (s:done > 1 ? ' tests' : ' test')
  endif
  if s:done > 0 && has('reltime')
    let message = s:t_bold .. message .. repeat(' ', 40 - len(message))
    let message ..= ' in ' .. reltimestr(reltime(s:run_start_time)) .. ' seconds'
    let message ..= s:t_normal
  endif
  echo message
  call add(s:messages, message)
  if s:fail > 0
    let message = s:fail . ' FAILED:'
    echo message
    call add(s:messages, message)
    call extend(s:messages, s:errors)
  endif
  if s:fail_expected > 0
    let message = s:fail_expected . ' FAILED (matching $TEST_MAY_FAIL):'
    echo message
    call add(s:messages, message)
    call extend(s:messages, s:errors_expected)
  endif

  " Add SKIPPED messages
  call extend(s:messages, s:skipped)

  " Append messages to the file "messages"
  split messages
  call append(line('$'), '')
  call append(line('$'), 'From ' . g:testname . ':')
  call append(line('$'), s:messages)
  write

  qall!
endfunc

" Source the test script.  First grab the file name, in case the script
" navigates away.  g:testname can be used by the tests.
let g:testname = expand('%')
let s:done = 0
let s:fail = 0
let s:fail_expected = 0
let s:errors = []
let s:errors_expected = []
let s:messages = []
let s:skipped = []
if expand('%') =~ 'test_vimscript.vim'
  " this test has intentional errors, don't use try/catch.
  source %
else
  try
    source %
  catch /^\cskipped/
    call add(s:messages, '    Skipped')
    call add(s:skipped, 'SKIPPED ' . expand('%') . ': ' . substitute(v:exception, '^\S*\s\+', '',  ''))
  catch
    let s:fail += 1
    call add(s:errors, 'Caught exception: ' . v:exception . ' @ ' . v:throwpoint)
  endtry
endif

" Delete the .res file, it may change behavior for completion
call delete(fnamemodify(g:testname, ':r') .. '.res')

" Locate Test_ functions and execute them.
redir @q
silent function /^Test_
redir END
let s:tests = split(substitute(@q, '\(function\|def\) \(\k*()\)', '\2', 'g'))

" If there is an extra argument filter the function names against it.
if argc() > 1
  let s:tests = filter(s:tests, 'v:val =~ argv(1)')
endif

" If the environment variable $TEST_FILTER is set then filter the function
" names against it.
let s:filtered = 0
if $TEST_FILTER != ''
  let s:filtered = len(s:tests)
  let s:tests = filter(s:tests, 'v:val =~ $TEST_FILTER')
  let s:filtered -= len(s:tests)
endif

let s:may_fail_list = []
if $TEST_MAY_FAIL != ''
  " Split the list at commas and add () to make it match g:testfunc.
  let s:may_fail_list = split($TEST_MAY_FAIL, ',')->map({i, v -> v .. '()'})
endif

" Execute the tests in alphabetical order.
for g:testfunc in sort(s:tests)
  if $TEST_SKIP_PAT != '' && g:testfunc =~ $TEST_SKIP_PAT
    call add(s:messages, g:testfunc .. ' matches $TEST_SKIP_PAT')
    let s:filtered += 1
    continue
  endif

  " Silence, please!
  set belloff=all
  let prev_error = ''
  let total_errors = []
  let g:run_nr = 1

  " A test can set g:test_is_flaky to retry running the test.
  let g:test_is_flaky = 0

  let starttime = strftime("%H:%M:%S")
  call RunTheTest(g:testfunc)

  " Repeat a flaky test.  Give up when:
  " - $TEST_NO_RETRY is not empty
  " - it fails again with the same message
  " - it fails five times (with a different message)
  if len(v:errors) > 0
        \ && $TEST_NO_RETRY == ''
        \ && g:test_is_flaky
    while 1
      call add(s:messages, 'Found errors in ' .. g:testfunc .. ':')
      call extend(s:messages, v:errors)

      let endtime = strftime("%H:%M:%S")
      call add(total_errors, $'Run {g:run_nr}, {starttime} - {endtime}:')
      call extend(total_errors, v:errors)

      if g:run_nr >= 5 || prev_error == v:errors[0]
        call add(total_errors, 'Flaky test failed too often, giving up')
        let v:errors = total_errors
        break
      endif

      call add(s:messages, 'Flaky test failed, running it again')

      " Flakiness is often caused by the system being very busy.  Sleep a
      " couple of seconds to have a higher chance of succeeding the second
      " time.
      sleep 2

      let prev_error = v:errors[0]
      let v:errors = []
      let g:run_nr += 1

      let starttime = strftime("%H:%M:%S")
      call RunTheTest(g:testfunc)

      if len(v:errors) == 0
        " Test passed on rerun.
        break
      endif
    endwhile
  endif

  call AfterTheTest(g:testfunc)
endfor

call FinishTesting()

" vim: shiftwidth=2 sts=2 expandtab