robin/laufey

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

zeertzjqMerge pull request #40160 from janlazo/vim-9.0.20828b51e50cdc

master
10.9 KiB403 linesraw
1" Functions shared by several tests.
2
3" Only load this script once.
4if exists('*PythonProg')
5  finish
6endif
7
8source view_util.vim
9
10" {Nvim}
11" Filepath captured from output may be truncated, like this:
12"   /home/va...estdir/X-test-tmpdir/nvimxbXN4i/10
13" Get last 2 segments, then combine with $TMPDIR.
14func! Fix_truncated_tmpfile(fname)
15  " sanity check
16  if $TMPDIR ==# ''
17    throw '$TMPDIR is empty'
18  endif
19  let tmpdir_tail = fnamemodify(substitute($TMPDIR, '[\/]\+$', '', 'g'), ':t')
20  if tmpdir_tail ==# ''
21    throw 'empty tmpdir_tail'
22  endif
23  if a:fname !~# tmpdir_tail
24    throw printf('$TMPDIR (%s) not in fname: %s', tmpdir_tail, a:fname)
25  endif
26  let last2segments = matchstr(a:fname, '[\/][^\/]\+[\/][^\/]\+$')
27  return $TMPDIR.last2segments
28endfunc
29
30" Get the name of the Python executable.
31" Also keeps it in s:python.
32func PythonProg()
33  " This test requires the Python command to run the test server.
34  " This most likely only works on Unix and Windows.
35  if has('unix')
36    " We also need the job feature or the pkill command to make sure the server
37    " can be stopped.
38    if !(has('job') || executable('pkill'))
39      return ''
40    endif
41    if executable('python3')
42      let s:python = 'python3'
43    elseif executable('python')
44      let s:python = 'python'
45    else
46      return ''
47    end
48  elseif has('win32')
49    " Use Python Launcher for Windows (py.exe) if available.
50    " NOTE: if you get a "Python was not found" error, disable the Python
51    " shortcuts in "Windows menu / Settings / Manage App Execution Aliases".
52    if executable('py.exe')
53      let s:python = 'py.exe'
54    elseif executable('python.exe')
55      let s:python = 'python.exe'
56    else
57      return ''
58    endif
59  else
60    return ''
61  endif
62  return s:python
63endfunc
64
65" Run "cmd".  Returns the job if using a job.
66func RunCommand(cmd)
67  " Running an external command can occasionally be slow or fail.
68  let g:test_is_flaky = 1
69
70  let job = 0
71  if has('job')
72    let job = job_start(a:cmd, {"stoponexit": "hup"})
73    call job_setoptions(job, {"stoponexit": "kill"})
74  elseif has('win32')
75    exe 'silent !start cmd /D /c start "test_channel" ' . a:cmd
76  else
77    exe 'silent !' . a:cmd . '&'
78  endif
79  return job
80endfunc
81
82" Read the port number from the Xportnr file.
83func GetPort()
84  let l = []
85  " with 200 it sometimes failed, with 400 is rarily failed
86  for i in range(600)
87    try
88      let l = readfile("Xportnr")
89    catch
90    endtry
91    if len(l) >= 1
92      break
93    endif
94    sleep 10m
95  endfor
96  call delete("Xportnr")
97
98  if len(l) == 0
99    " Can't make the connection, give up.
100    return 0
101  endif
102  return l[0]
103endfunc
104
105" Run a Python server for "cmd" and call "testfunc".
106" Always kills the server before returning.
107func RunServer(cmd, testfunc, args)
108  " The Python program writes the port number in Xportnr.
109  call delete("Xportnr")
110
111  if len(a:args) == 1
112    let arg = ' ' . a:args[0]
113  else
114    let arg = ''
115  endif
116  let pycmd = s:python . " " . a:cmd . arg
117
118  try
119    let g:currentJob = RunCommand(pycmd)
120
121    " Wait for some time for the port number to be there.
122    let port = GetPort()
123    if port == 0
124      call assert_report(strftime("%H:%M:%S") .. " Can't start " .. a:cmd)
125      return
126    endif
127
128    call call(function(a:testfunc), [port])
129  catch /E901.*Address family for hostname not supported/
130    throw 'Skipped: Invalid network setup ("' .. v:exception .. '" in ' .. v:throwpoint .. ')'
131  catch
132    call assert_report('Caught exception: "' . v:exception . '" in ' . v:throwpoint)
133  finally
134    call s:kill_server(a:cmd)
135  endtry
136endfunc
137
138func s:kill_server(cmd)
139  if has('job')
140    if exists('g:currentJob')
141      call job_stop(g:currentJob)
142      unlet g:currentJob
143    endif
144  elseif has('win32')
145    let cmd = substitute(a:cmd, ".py", '', '')
146    call system('taskkill /IM ' . s:python . ' /T /F /FI "WINDOWTITLE eq ' . cmd . '"')
147  else
148    call system("pkill -f " . a:cmd)
149  endif
150endfunc
151
152" Wait for up to five seconds for "expr" to become true.  "expr" can be a
153" stringified expression to evaluate, or a funcref without arguments.
154" Using a lambda works best.  Example:
155"	call WaitFor({-> status == "ok"})
156"
157" A second argument can be used to specify a different timeout in msec.
158"
159" When successful the time slept is returned.
160" When running into the timeout an exception is thrown, thus the function does
161" not return.
162func WaitFor(expr, ...)
163  let timeout = get(a:000, 0, 5000)
164  let slept = s:WaitForCommon(a:expr, v:null, timeout)
165  if slept < 0
166    throw 'WaitFor() timed out after ' . timeout . ' msec'
167  endif
168  return slept
169endfunc
170
171" Wait for up to five seconds for "assert" to return zero.  "assert" must be a
172" (lambda) function containing one assert function.  Example:
173"	call WaitForAssert({-> assert_equal("dead", job_status(job)})
174"
175" A second argument can be used to specify a different timeout in msec.
176"
177" Return zero for success, one for failure (like the assert function).
178func WaitForAssert(assert, ...)
179  let timeout = get(a:000, 0, 5000)
180  if s:WaitForCommon(v:null, a:assert, timeout) < 0
181    return 1
182  endif
183  return 0
184endfunc
185
186" Common implementation of WaitFor() and WaitForAssert().
187" Either "expr" or "assert" is not v:null
188" Return the waiting time for success, -1 for failure.
189func s:WaitForCommon(expr, assert, timeout)
190  " using reltime() is more accurate, but not always available
191  let slept = 0
192  if exists('*reltimefloat')
193    let start = reltime()
194  endif
195
196  while 1
197    if type(a:expr) == v:t_func
198      let success = a:expr()
199    elseif type(a:assert) == v:t_func
200      let success = a:assert() == 0
201    else
202      let success = eval(a:expr)
203    endif
204    if success
205      return slept
206    endif
207
208    if slept >= a:timeout
209      break
210    endif
211    if type(a:assert) == v:t_func
212      " Remove the error added by the assert function.
213      call remove(v:errors, -1)
214    endif
215
216    sleep 1m
217    if exists('*reltimefloat')
218      let slept = float2nr(reltimefloat(reltime(start)) * 1000)
219    else
220      let slept += 1
221    endif
222  endwhile
223
224  return -1  " timed out
225endfunc
226
227
228" Wait for up to a given milliseconds.
229" With the +timers feature this waits for key-input by getchar(), Resume()
230" feeds key-input and resumes process. Return time waited in milliseconds.
231" Without +timers it uses simply :sleep.
232func Standby(msec)
233  if has('timers') && exists('*reltimefloat')
234    let start = reltime()
235    let g:_standby_timer = timer_start(a:msec, function('s:feedkeys'))
236    call getchar()
237    return float2nr(reltimefloat(reltime(start)) * 1000)
238  else
239    execute 'sleep ' a:msec . 'm'
240    return a:msec
241  endif
242endfunc
243
244func Resume()
245  if exists('g:_standby_timer')
246    call timer_stop(g:_standby_timer)
247    call s:feedkeys(0)
248    unlet g:_standby_timer
249  endif
250endfunc
251
252func s:feedkeys(timer)
253  call feedkeys('x', 'nt')
254endfunc
255
256" Get $VIMPROG to run the Vim executable.
257" The Makefile writes it as the first line in the "vimcmd" file.
258" Falls back to the Vim executable in the src directory.
259" Nvim: uses $NVIM_TEST_ARG0.
260func GetVimProg()
261  if !empty($NVIM_TEST_ARG0)
262    if has('win32')
263      return substitute($NVIM_TEST_ARG0, '/', '\\', 'g')
264    else
265      return $NVIM_TEST_ARG0
266    endif
267  endif
268  " echo 'Cannot read the "vimcmd" file, falling back to ../vim.'
269
270  " Probably the script was sourced instead of running "make".
271  " We assume Vim was just build in the src directory then.
272  return v:progpath
273endfunc
274
275let g:valgrind_cnt = 1
276
277" Get the command to run Vim, with -u NONE and --headless arguments.
278" If there is an argument use it instead of "NONE".
279func GetVimCommand(...)
280  if a:0 == 0
281    let name = 'NONE'
282  else
283    let name = a:1
284  endif
285  let cmd = GetVimProg()
286  let cmd = substitute(cmd, '-u \f\+', '-u ' . name, '')
287  if cmd !~ '-u '. name
288    let cmd = cmd . ' -u ' . name
289  endif
290  let cmd .= ' --headless -i NONE'
291  let cmd = substitute(cmd, 'VIMRUNTIME=\S\+', '', '')
292
293  " If using valgrind, make sure every run uses a different log file.
294  if cmd =~ 'valgrind.*--log-file='
295    let cmd = substitute(cmd, '--log-file=\(\S*\)', '--log-file=\1.' . g:valgrind_cnt, '')
296    let g:valgrind_cnt += 1
297  endif
298
299  return cmd
300endfunc
301
302" Return one when it looks like the tests are run with valgrind, which means
303" that everything is much slower.
304func RunningWithValgrind()
305  return GetVimCommand() =~ '\<valgrind\>'
306endfunc
307
308" Get the command to run Vim, with --clean instead of "-u NONE".
309func GetVimCommandClean()
310  let cmd = GetVimCommand()
311  let cmd = substitute(cmd, '-u NONE', '--clean', '')
312  let cmd = substitute(cmd, '--headless', '', '')
313
314  " Force using utf-8, Vim may pick up something else from the environment.
315  " let cmd ..= ' --cmd "set enc=utf8" '
316
317  " Optionally run Vim under valgrind
318  " let cmd = 'valgrind --tool=memcheck --leak-check=yes --num-callers=25 --log-file=valgrind ' . cmd
319
320  return cmd
321endfunc
322
323" Get the command to run Vim, with --clean, and force to run in terminal so it
324" won't start a new GUI.
325func GetVimCommandCleanTerm()
326  " Add -v to have gvim run in the terminal (if possible)
327  return GetVimCommandClean() .. ' -v '
328endfunc
329
330" Run Vim, using the "vimcmd" file and "-u NORC".
331" "before" is a list of Vim commands to be executed before loading plugins.
332" "after" is a list of Vim commands to be executed after loading plugins.
333" Plugins are not loaded, unless 'loadplugins' is set in "before".
334" Return 1 if Vim could be executed.
335func RunVim(before, after, arguments)
336  return RunVimPiped(a:before, a:after, a:arguments, '')
337endfunc
338
339func RunVimPiped(before, after, arguments, pipecmd)
340  let cmd = GetVimCommand()
341  let args = ''
342  if len(a:before) > 0
343    call writefile(a:before, 'Xbefore.vim')
344    let args .= ' --cmd "so Xbefore.vim"'
345  endif
346  if len(a:after) > 0
347    call writefile(a:after, 'Xafter.vim')
348    let args .= ' -S Xafter.vim'
349  endif
350
351  " Optionally run Vim under valgrind
352  " let cmd = 'valgrind --tool=memcheck --leak-check=yes --num-callers=25 --log-file=valgrind ' . cmd
353
354  let $NVIM_LOG_FILE = exists($NVIM_LOG_FILE) ? $NVIM_LOG_FILE : 'Xnvim.log'
355  " Nvim does not support -Z flag, remove it.
356  exe "silent !" .. a:pipecmd .. ' ' ..  cmd .. args .. ' ' .. a:arguments->substitute('-Z', '', 'g')
357
358  if len(a:before) > 0
359    call delete('Xbefore.vim')
360  endif
361  if len(a:after) > 0
362    call delete('Xafter.vim')
363  endif
364  return 1
365endfunc
366
367func IsRoot()
368  if !has('unix')
369    return v:false
370  elseif $USER == 'root' || system('id -un') =~ '\<root\>'
371    return v:true
372  endif
373  return v:false
374endfunc
375
376" Get all messages but drop the maintainer entry.
377func GetMessages()
378  redir => result
379  redraw | messages
380  redir END
381  let msg_list = split(result, "\n")
382  " if msg_list->len() > 0 && msg_list[0] =~ 'Messages maintainer:'
383  "   return msg_list[1:]
384  " endif
385  return msg_list
386endfunc
387
388" Run the list of commands in 'cmds' and look for 'errstr' in exception.
389" Note that assert_fails() cannot be used in some places and this function
390" can be used.
391func AssertException(cmds, errstr)
392  let save_exception = ''
393  try
394    for cmd in a:cmds
395      exe cmd
396    endfor
397  catch
398    let save_exception = v:exception
399  endtry
400  call assert_match(a:errstr, save_exception)
401endfunc
402
403" vim: shiftwidth=2 sts=2 expandtab