robin/laufey

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

Justin M. KeyesMerge #41114 from epithet/default-ruler-as-expressiondab5fab948

master
33.3 KiB1198 linesraw
1local uv = vim.uv
2local t = require('test.testutil')
3---@type test.harness
4local harness = require('test.harness')
5
6local Session = require('test.client.session')
7local uv_stream = require('test.client.uv_stream')
8local SocketStream = uv_stream.SocketStream
9local ProcStream = uv_stream.ProcStream
10
11local check_cores = t.check_cores
12local check_logs = t.check_logs
13local dedent = t.dedent
14local eq = t.eq
15local is_os = t.is_os
16local ok = t.ok
17local sleep = uv.sleep
18
19--- Functions executing in the current nvim session/process being tested.
20local M = {}
21
22M.runtime_set = 'set runtimepath^=' .. t.paths.test_build_dir .. '/lib/nvim'
23
24M.nvim_prog = (os.getenv('NVIM_PRG') or t.paths.test_build_dir .. '/bin/nvim')
25-- Default settings for the test session.
26M.nvim_set = (
27  'set shortmess+=IS background=light noswapfile noautoindent startofline'
28  .. ' laststatus=1 undodir=. directory=. viewdir=. backupdir=.'
29  .. " belloff= wildoptions-=pum joinspaces noshowcmd noruler nomore redrawdebug=invalid shada=!,'100,<50,s10,h"
30  .. [[ statusline=%<%f\ %{%nvim_eval_statusline('%h%w%m%r',\ {'maxwidth':\ 30}).width\ >\ 0\ ?\ '%h%w%m%r\ '\ :\ ''%}%=%{%\ &showcmdloc\ ==\ 'statusline'\ ?\ '%-10.S\ '\ :\ ''\ %}%{%\ exists('b:keymap_name')\ ?\ '<'..b:keymap_name..'>\ '\ :\ ''\ %}%{%\ &ruler\ ?\ &rulerformat\ :\ ''\ %}]]
31  .. ' rulerformat=%18(%l,%c%V%=%P%)'
32)
33M.nvim_argv = {
34  M.nvim_prog,
35  '-u',
36  'NONE',
37  '-i',
38  'NONE',
39  -- XXX: find treesitter parsers.
40  '--cmd',
41  M.runtime_set,
42  '--cmd',
43  M.nvim_set,
44  -- Remove default user commands and mappings.
45  '--cmd',
46  'comclear | mapclear | mapclear!',
47  -- Make screentest work after changing to the new default color scheme
48  -- Source 'vim' color scheme without side effects
49  -- TODO: rewrite tests
50  '--cmd',
51  'lua dofile("runtime/colors/vim.lua")',
52  '--cmd',
53  'unlet g:colors_name',
54  '--embed',
55}
56if os.getenv('OSV_PORT') then
57  table.insert(M.nvim_argv, '--cmd')
58  table.insert(
59    M.nvim_argv,
60    string.format(
61      "lua require('osv').launch({ port = %s, blocking = true })",
62      os.getenv('OSV_PORT')
63    )
64  )
65end
66
67-- Directory containing nvim.
68M.nvim_dir = M.nvim_prog:gsub('[/\\][^/\\]+$', '')
69if M.nvim_dir == M.nvim_prog then
70  M.nvim_dir = '.'
71end
72
73local prepend_argv --- @type string[]?
74
75if os.getenv('VALGRIND') then
76  local log_file = os.getenv('VALGRIND_LOG') or 'valgrind-%p.log'
77  prepend_argv = {
78    'valgrind',
79    '-q',
80    '--tool=memcheck',
81    '--leak-check=yes',
82    '--track-origins=yes',
83    '--show-possibly-lost=no',
84    '--suppressions=src/.valgrind.supp',
85    '--log-file=' .. log_file,
86  }
87  if os.getenv('GDB') then
88    table.insert(prepend_argv, '--vgdb=yes')
89    table.insert(prepend_argv, '--vgdb-error=0')
90  end
91elseif os.getenv('GDB') then
92  local gdbserver_port = os.getenv('GDBSERVER_PORT') or '7777'
93  prepend_argv = { 'gdbserver', 'localhost:' .. gdbserver_port }
94end
95
96if prepend_argv then
97  local new_nvim_argv = {} --- @type string[]
98  local len = #prepend_argv
99  for i = 1, len do
100    new_nvim_argv[i] = prepend_argv[i]
101  end
102  for i = 1, #M.nvim_argv do
103    new_nvim_argv[i + len] = M.nvim_argv[i]
104  end
105  M.nvim_argv = new_nvim_argv
106  M.prepend_argv = prepend_argv
107end
108
109local session --- @type test.Session?
110local sessions = {} --- @type table<test.Session, true>
111local sigpipe_handler --- @type uv.uv_signal_t?
112local loop_running --- @type boolean?
113local last_error --- @type string?
114local method_error --- @type string?
115
116if not is_os('win') then
117  sigpipe_handler = assert(uv.new_signal())
118  uv.signal_start(sigpipe_handler, 'sigpipe', function()
119    print('warning: got SIGPIPE signal. Likely related to a crash in nvim')
120  end)
121end
122
123function M.get_session()
124  return session
125end
126
127function M.set_session(s)
128  session = s
129end
130
131--- @param method string
132--- @param ... any
133--- @return any
134function M.request(method, ...)
135  assert(session, 'no Nvim session')
136  assert(not session.eof_err, 'RPC request after Nvim EOF')
137  local status, rv = session:request(method, ...)
138  if not status then
139    if loop_running then
140      --- @type string
141      last_error = rv[2]
142      session:stop()
143    else
144      error(rv[2])
145    end
146  end
147  return rv
148end
149
150--- @param method string
151--- @param ... any
152--- @return any
153function M.request_lua(method, ...)
154  return M.exec_lua([[return vim.api[...](select(2, ...))]], method, ...)
155end
156
157--- @param timeout? integer
158--- @return string?
159function M.next_msg(timeout)
160  assert(session)
161  return session:next_message(timeout or 10000)
162end
163
164function M.expect_twostreams(msgs1, msgs2)
165  local pos1, pos2 = 1, 1
166  while pos1 <= #msgs1 or pos2 <= #msgs2 do
167    local msg = M.next_msg()
168    if pos1 <= #msgs1 and pcall(eq, msgs1[pos1], msg) then
169      pos1 = pos1 + 1
170    elseif pos2 <= #msgs2 then
171      eq(msgs2[pos2], msg)
172      pos2 = pos2 + 1
173    else
174      -- already failed, but show the right error message
175      eq(msgs1[pos1], msg)
176    end
177  end
178end
179
180-- Expects a sequence of next_msg() results. If multiple sequences are
181-- passed they are tried until one succeeds, in order of shortest to longest.
182--
183-- Can be called with positional args (list of sequences only):
184--    expect_msg_seq(seq1, seq2, ...)
185-- or keyword args:
186--    expect_msg_seq{ignore={...}, seqs={seq1, seq2, ...}}
187--
188-- ignore:      List of ignored event names.
189-- seqs:        List of one or more potential event sequences.
190function M.expect_msg_seq(...)
191  if select('#', ...) < 1 then
192    error('need at least 1 argument')
193  end
194  local arg1 = select(1, ...)
195  if (arg1['seqs'] and select('#', ...) > 1) or type(arg1) ~= 'table' then
196    error('invalid args')
197  end
198  local ignore = arg1['ignore'] and arg1['ignore'] or {}
199  --- @type string[]
200  local seqs = arg1['seqs'] and arg1['seqs'] or { ... }
201  if type(ignore) ~= 'table' then
202    error("'ignore' arg must be a list of strings")
203  end
204  table.sort(seqs, function(a, b) -- Sort ascending, by (shallow) length.
205    return #a < #b
206  end)
207
208  local actual_seq = {}
209  local nr_ignored = 0
210  local final_error = ''
211  local function cat_err(err1, err2)
212    if err1 == nil then
213      return err2
214    end
215    return string.format('%s\n%s\n%s', err1, string.rep('=', 78), err2)
216  end
217  local msg_timeout = M.load_adjust(10000) -- Big timeout for ASAN/valgrind.
218  for anum = 1, #seqs do
219    local expected_seq = seqs[anum]
220    -- Collect enough messages to compare the next expected sequence.
221    while #actual_seq < #expected_seq do
222      local msg = M.next_msg(msg_timeout)
223      local msg_type = msg and msg[2] or nil
224      if msg == nil then
225        error(
226          cat_err(
227            final_error,
228            string.format(
229              'got %d messages (ignored %d), expected %d',
230              #actual_seq,
231              nr_ignored,
232              #expected_seq
233            )
234          )
235        )
236      elseif vim.tbl_contains(ignore, msg_type) then
237        nr_ignored = nr_ignored + 1
238      else
239        table.insert(actual_seq, msg)
240      end
241    end
242    local status, result = pcall(eq, expected_seq, actual_seq)
243    if status then
244      return result
245    end
246    local message = result
247    if type(result) == 'table' then
248      -- 'eq' returns several things
249      --- @type string
250      message = result.message
251    end
252    final_error = cat_err(final_error, message)
253  end
254  error(final_error)
255end
256
257local function call_and_stop_on_error(lsession, ...)
258  local status, result = Session.safe_pcall(...) -- luacheck: ignore
259  if not status then
260    lsession:stop()
261    last_error = result
262    return ''
263  end
264  return result
265end
266
267function M.set_method_error(err)
268  method_error = err
269end
270
271--- Runs the event loop of the given session.
272---
273--- @param lsession test.Session
274--- @param request_cb function?
275--- @param notification_cb function?
276--- @param setup_cb function?
277--- @param timeout integer
278--- @return [integer, string]
279function M.run_session(lsession, request_cb, notification_cb, setup_cb, timeout)
280  local on_request --- @type function?
281  local on_notification --- @type function?
282  local on_setup --- @type function?
283
284  if request_cb then
285    function on_request(method, args)
286      method_error = nil
287      local result = call_and_stop_on_error(lsession, request_cb, method, args)
288      if method_error ~= nil then
289        return method_error, true
290      end
291      return result
292    end
293  end
294
295  if notification_cb then
296    function on_notification(method, args)
297      call_and_stop_on_error(lsession, notification_cb, method, args)
298    end
299  end
300
301  if setup_cb then
302    function on_setup()
303      call_and_stop_on_error(lsession, setup_cb)
304    end
305  end
306
307  loop_running = true
308  lsession:run(on_request, on_notification, on_setup, timeout)
309  loop_running = false
310  if last_error then
311    local err = last_error
312    last_error = nil
313    error(err)
314  end
315
316  return lsession.eof_err
317end
318
319--- Runs the event loop of the current global session.
320function M.run(request_cb, notification_cb, setup_cb, timeout)
321  assert(session)
322  return M.run_session(session, request_cb, notification_cb, setup_cb, timeout)
323end
324
325function M.stop()
326  if loop_running then
327    assert(session):stop()
328  end
329end
330
331-- Use for commands which expect nvim to quit.
332-- The first argument can also be a timeout.
333function M.expect_exit(fn_or_timeout, ...)
334  if type(fn_or_timeout) == 'function' then
335    t.matches(vim.pesc(Session.eof_err_msg), t.pcall_err(fn_or_timeout, ...))
336  else
337    t.matches(
338      vim.pesc(Session.eof_err_msg),
339      t.pcall_err(function(timeout, fn, ...)
340        fn(...)
341        assert(session)
342        while session:next_message(timeout) do
343        end
344        if session.eof_err then
345          error(session.eof_err[2])
346        end
347      end, fn_or_timeout, ...)
348    )
349  end
350  M.check_close()
351end
352
353--- Executes a Vimscript function via Lua.
354--- Fails on Vimscript error, but does not update v:errmsg.
355--- @param name string
356--- @param ... any
357--- @return any
358function M.call_lua(name, ...)
359  return M.exec_lua([[return vim.call(...)]], name, ...)
360end
361
362--- Sends user input to Nvim.
363--- Does not fail on Vimscript error, but v:errmsg will be updated.
364--- @param input string
365local function nvim_feed(input)
366  while #input > 0 do
367    local written = M.request('nvim_input', input)
368    if written == nil then
369      M.assert_alive()
370      error('crash? (nvim_input returned nil)')
371    end
372    input = input:sub(written + 1)
373  end
374end
375
376--- @param ... string
377function M.feed(...)
378  for _, v in ipairs({ ... }) do
379    nvim_feed(v)
380  end
381end
382
383---@param ... string[]?
384---@return string[]
385function M.merge_args(...)
386  local i = 1
387  local argv = {} --- @type string[]
388  for anum = 1, select('#', ...) do
389    --- @type string[]?
390    local args = select(anum, ...)
391    if args then
392      for _, arg in ipairs(args) do
393        argv[i] = arg
394        i = i + 1
395      end
396    end
397  end
398  return argv
399end
400
401--- Removes Nvim startup args from `args` matching items in `args_rm`.
402---
403--- - Special case: "-u", "-i", "--cmd" are treated specially: their "values" are also removed.
404--- - Special case: "runtimepath" will remove only { '--cmd', 'set runtimepath^=…', }
405---
406--- Example:
407---     args={'--headless', '-u', 'NONE'}
408---     args_rm={'--cmd', '-u'}
409--- Result:
410---     {'--headless'}
411---
412--- All matching cases are removed.
413---
414--- Example:
415---     args={'--cmd', 'foo', '-N', '--cmd', 'bar'}
416---     args_rm={'--cmd', '-u'}
417--- Result:
418---     {'-N'}
419--- @param args string[]
420--- @param args_rm string[]
421--- @return string[]
422local function remove_args(args, args_rm)
423  local new_args = {} --- @type string[]
424  local skip_following = { '-u', '-i', '-c', '--cmd', '-s', '--listen' }
425  if not args_rm or #args_rm == 0 then
426    return { unpack(args) }
427  end
428  for _, v in ipairs(args_rm) do
429    assert(type(v) == 'string')
430  end
431  local last = ''
432  for _, arg in ipairs(args) do
433    if vim.tbl_contains(skip_following, last) then
434      last = ''
435    elseif vim.tbl_contains(args_rm, arg) then
436      last = arg
437    elseif arg == M.runtime_set and vim.tbl_contains(args_rm, 'runtimepath') then
438      table.remove(new_args) -- Remove the preceding "--cmd".
439      last = ''
440    else
441      table.insert(new_args, arg)
442    end
443  end
444  return new_args
445end
446
447function M.check_close(noblock)
448  if not session then
449    return
450  end
451
452  local s = session
453  s:close(nil, noblock)
454  sessions[s] = nil
455  session = nil
456end
457
458local function close_extra_sessions(test_id, noblock)
459  for s in pairs(sessions) do
460    if s ~= session and (test_id == nil or (s.data and s.data.test_id == test_id)) then
461      if not s.closed then
462        s:close(nil, noblock)
463      end
464      sessions[s] = nil
465    end
466  end
467end
468
469-- Creates a new Session connected by domain socket (named pipe) or TCP.
470function M.connect(file_or_address)
471  local addr, port = string.match(file_or_address, '(.*):(%d+)')
472  local stream = (addr and port) and SocketStream.connect(addr, port)
473    or SocketStream.open(file_or_address)
474  local s = Session.new(stream)
475  s.data = { test_id = _G._nvim_test_id }
476  sessions[s] = true
477  return s
478end
479
480--- Starts a new, global Nvim session and clears the current one.
481---
482--- Note:
483--- - Use `new_session()` to start a session without replacing the current one.
484--- - Use `spawn_wait()` to start Nvim without connecting a RPC session.
485---
486--- Parameters are interpreted as startup args, OR a map with these keys:
487--- - args:       List: Args appended to the default `nvim_argv` set.
488--- - args_rm:    List: Args removed from the default set. All cases are
489---               removed, e.g. args_rm={'--cmd'} removes all cases of "--cmd"
490---               (and its value) from the default set.
491--- - env:        Map: Defines the environment of the new session.
492---
493--- Example:
494--- ```
495--- clear('-e')
496--- clear{args={'-e'}, args_rm={'-i'}, env={TERM=term}}
497--- ```
498---
499--- @param ... string Nvim CLI args
500--- @return test.Session
501--- @overload fun(opts: test.session.Opts): test.Session
502function M.clear(...)
503  M.set_session(M.new_session(false, ...))
504  return M.get_session()
505end
506
507local n_processes = 0
508
509--- Starts a new Nvim process with the given args and returns a msgpack-RPC session.
510---
511--- Does not replace the current global session, unlike `clear()`.
512---
513--- @param keep boolean (default: false) Don't close the current global session.
514--- @param ... string Nvim CLI args
515--- @return test.Session
516--- @overload fun(keep: boolean, opts: test.session.Opts): test.Session
517function M.new_session(keep, ...)
518  local test_id = _G._nvim_test_id
519  if not keep and session ~= nil then
520    local s = session
521    -- Don't block for the previous session's exit if it's from a different test.
522    s:close(nil, s.data and s.data.test_id ~= test_id)
523    sessions[s] = nil
524    session = nil
525  end
526
527  local argv, env, io_extra = M._new_argv(...)
528
529  local proc = ProcStream.spawn(argv, env, io_extra, function(closed)
530    n_processes = n_processes - 1
531    local delta = 0
532    if closed then
533      uv.update_time() -- Update cached value of uv.now() (libuv: uv_now()).
534      delta = uv.now() - closed
535    end
536    if delta > 500 then
537      print(
538        ('\nNvim session %s took %d milliseconds to exit\n'):format(test_id, delta)
539          .. 'This indicates a likely problem with the test even if it passed!'
540      )
541      io.stdout:flush()
542    end
543  end, true)
544  n_processes = n_processes + 1
545
546  local new_session = Session.new(proc)
547  sessions[new_session] = true
548  -- Make it possible to check whether two sessions are from the same test.
549  new_session.data = { test_id = test_id }
550  return new_session
551end
552
553harness.on_suite_end(function()
554  M.check_close(true)
555  -- Some tests create extra sessions without replacing the global one.
556  -- Close any that individual tests did not clean up before the runner exits.
557  close_extra_sessions(nil, true)
558
559  local timed_out = false
560  local timer = assert(vim.uv.new_timer())
561  timer:start(10000, 0, function()
562    timed_out = true
563  end)
564  while n_processes > 0 and not timed_out do
565    uv.run('once')
566  end
567  timer:close()
568  if sigpipe_handler and not sigpipe_handler:is_closing() then
569    sigpipe_handler:close()
570  end
571  -- Drain close callbacks queued by explicit Session/ProcStream cleanup before
572  -- Nvim checks the runner loop for active handles.
573  for _ = 1, 10 do
574    uv.run('nowait')
575  end
576  if timed_out then
577    print(('warning: %d dangling Nvim processes'):format(n_processes))
578    io.stdout:flush()
579  end
580end)
581
582--- Starts a (non-RPC, `--headless --listen "Tx"`) Nvim process, waits for exit, and returns result.
583---
584--- @param ... string Nvim CLI args, or `test.session.Opts` table.
585--- @return test.ProcStream
586--- @overload fun(opts: test.session.Opts): test.ProcStream
587function M.spawn_wait(...)
588  local opts = type(...) == 'string' and { args = { ... } } or ...
589  opts.args_rm = opts.args_rm and opts.args_rm or {}
590  table.insert(opts.args_rm, '--embed')
591  local argv, env, io_extra = M._new_argv(opts)
592  local proc = ProcStream.spawn(argv, env, io_extra)
593  proc.collect_text = true
594  proc:read_start()
595  proc:wait()
596  proc:close()
597  return proc
598end
599
600--- @class test.session.Opts
601--- Nvim CLI args
602--- @field args? string[]
603--- Remove these args from the default `nvim_argv` args set. Ignored if `merge=false`.
604--- @field args_rm? string[]
605--- (default: true) Merge `args` with the default set. Else use only the provided `args`.
606--- @field merge? boolean
607--- Environment variables
608--- @field env? table<string,string>
609--- Used for stdin_fd, see `:help ui-option`
610--- @field io_extra? uv.uv_pipe_t
611
612--- @private
613---
614--- Builds an argument list for use in `new_session()`, `clear()`, and `spawn_wait()`.
615---
616--- @param ... string Nvim CLI args, or `test.session.Opts` table.
617--- @return string[]
618--- @return string[]?
619--- @return uv.uv_pipe_t?
620--- @overload fun(opts: test.session.Opts): string[], string[]?, uv.uv_pipe_t?
621function M._new_argv(...)
622  --- @type test.session.Opts|string
623  local opts = select(1, ...)
624  local merge = type(opts) ~= 'table' and true or opts.merge ~= false
625
626  local args = merge and { unpack(M.nvim_argv) } or { M.nvim_prog }
627  if merge then
628    table.insert(args, '--headless')
629    if _G._nvim_test_id then
630      -- Set the server name to the test-id for logging. #8519
631      table.insert(args, '--listen')
632      table.insert(args, _G._nvim_test_id)
633    end
634  end
635
636  local new_args --- @type string[]
637  local io_extra --- @type uv.uv_pipe_t?
638  local env --- @type string[]? List of "key=value" env vars.
639
640  if type(opts) ~= 'table' then
641    new_args = { ... }
642  else
643    args = merge and remove_args(args, opts.args_rm) or args
644    if opts.env then
645      local env_opt = {} --- @type table<string,string>
646      for k, v in pairs(opts.env) do
647        assert(type(k) == 'string')
648        assert(type(v) == 'string')
649        env_opt[k] = v
650      end
651      -- Set these from the environment unless the caller defined them.
652      for _, k in ipairs({
653        'ASAN_OPTIONS',
654        'GCOV_ERROR_FILE',
655        'HOME',
656        'LD_LIBRARY_PATH',
657        'MSAN_OPTIONS',
658        'NVIM_TEST',
659        'NVIM_LOG_FILE',
660        'NVIM_RPLUGIN_MANIFEST',
661        'PATH',
662        'TMPDIR',
663        'TSAN_OPTIONS',
664        'VIMRUNTIME',
665        'XDG_DATA_DIRS',
666      }) do
667        if not env_opt[k] then
668          env_opt[k] = os.getenv(k)
669        end
670      end
671      env = {}
672      for k, v in pairs(env_opt) do
673        env[#env + 1] = k .. '=' .. v
674      end
675    end
676    new_args = opts.args or {}
677    io_extra = opts.io_extra
678  end
679  for _, arg in ipairs(new_args) do
680    table.insert(args, arg)
681  end
682  return args, env, io_extra
683end
684
685--- Dedents string arguments and inserts the resulting text into the current buffer.
686--- @param ... string
687function M.insert(...)
688  nvim_feed('i')
689  for _, v in ipairs({ ... }) do
690    local escaped = v:gsub('<', '<lt>')
691    nvim_feed(dedent(escaped))
692  end
693  nvim_feed('<ESC>')
694end
695
696--- @deprecated Use `command()` or `feed()` instead.
697---
698--- Executes an ex-command by user input. Because nvim_input() is used, Vimscript
699--- errors will not manifest as client (lua) errors. Use command() for that.
700--- @param ... string
701function M.feed_command(...)
702  for _, v in ipairs({ ... }) do
703    if v:sub(1, 1) ~= '/' then
704      -- not a search command, prefix with colon
705      nvim_feed(':')
706    end
707    nvim_feed(v:gsub('<', '<lt>'))
708    nvim_feed('<CR>')
709  end
710end
711
712-- @deprecated use nvim_exec2()
713function M.source(code)
714  M.exec(dedent(code))
715end
716
717function M.has_powershell()
718  return M.eval('executable("pwsh")') == 1
719end
720
721--- Sets Nvim shell to powershell.
722---
723--- @param fake boolean? Use a fake if powershell is not found on the system.
724--- @returns true if powershell was found on the system, else false.
725function M.set_shell_powershell(fake)
726  local found = M.has_powershell()
727  if not fake then
728    assert(found)
729  end
730  local shell = found and 'pwsh' or M.testprg('pwsh-test')
731  local cmd = 'Remove-Item -Force '
732    .. table.concat(
733      is_os('win') and { 'alias:cat', 'alias:echo', 'alias:sleep', 'alias:sort', 'alias:tee' }
734        or { 'alias:echo' },
735      ','
736    )
737    .. ';'
738  M.exec([[
739    let &shell = ']] .. shell .. [['
740    set shellquote= shellxquote=
741    let &shellcmdflag = '-NoLogo -NoProfile -ExecutionPolicy RemoteSigned -Command '
742    let &shellcmdflag .= '[Console]::InputEncoding=[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new();'
743    let &shellcmdflag .= '$PSDefaultParameterValues[''Out-File:Encoding'']=''utf8'';'
744    let &shellcmdflag .= ']] .. cmd .. [['
745    let &shellredir = '2>&1 | %%{ "$_" } | Out-File %s; exit $LastExitCode'
746    let &shellpipe  = '> %s 2>&1'
747  ]])
748  return found
749end
750
751---@param func function
752---@return table<string,function>
753function M.create_callindex(func)
754  return setmetatable({}, {
755    --- @param tbl table<any,function>
756    --- @param arg1 string
757    --- @return function
758    __index = function(tbl, arg1)
759      local ret = function(...)
760        return func(arg1, ...)
761      end
762      tbl[arg1] = ret
763      return ret
764    end,
765  })
766end
767
768--- @param method string
769--- @param ... any
770function M.nvim_async(method, ...)
771  assert(session, 'no Nvim session')
772  assert(not session.eof_err, 'sending notification after EOF from Nvim')
773  session:notify(method, ...)
774end
775
776--- Executes a Vimscript function via RPC.
777--- Fails on Vimscript error, but does not update v:errmsg.
778--- @param name string
779--- @param ... any
780--- @return any
781function M.call(name, ...)
782  return M.request('nvim_call_function', name, { ... })
783end
784
785M.async_meths = M.create_callindex(M.nvim_async)
786
787M.rpc = {
788  fn = M.create_callindex(M.call),
789  api = M.create_callindex(M.request),
790}
791
792M.lua = {
793  fn = M.create_callindex(M.call_lua),
794  api = M.create_callindex(M.request_lua),
795}
796
797M.describe_lua_and_rpc = function(describe)
798  return function(what, tests)
799    local function d(flavour)
800      describe(string.format('%s (%s)', what, flavour), function(...)
801        return tests(M[flavour].api, ...)
802      end)
803    end
804
805    d('rpc')
806    d('lua')
807  end
808end
809
810--- add for typing. The for loop after will overwrite this
811M.api = vim.api
812M.fn = vim.fn
813
814for name, fns in pairs(M.rpc) do
815  --- @diagnostic disable-next-line:no-unknown
816  M[name] = fns
817end
818
819-- Executes an ex-command. Vimscript errors manifest as client (lua) errors, but
820-- v:errmsg will not be updated.
821M.command = M.api.nvim_command
822
823-- Evaluates a Vimscript expression.
824-- Fails on Vimscript error, but does not update v:errmsg.
825M.eval = M.api.nvim_eval
826
827function M.poke_eventloop()
828  -- Execute 'nvim_eval' (a deferred function) to
829  -- force at least one main_loop iteration
830  M.api.nvim_eval('1')
831end
832
833function M.buf_lines(bufnr)
834  return M.exec_lua('return vim.api.nvim_buf_get_lines((...), 0, -1, false)', bufnr)
835end
836
837---@see buf_lines()
838function M.curbuf_contents()
839  M.poke_eventloop() -- Before inspecting the buffer, do whatever.
840  return table.concat(M.api.nvim_buf_get_lines(0, 0, -1, true), '\n')
841end
842
843function M.expect(contents)
844  return eq(dedent(contents), M.curbuf_contents())
845end
846
847function M.expect_any(contents)
848  contents = dedent(contents)
849  return ok(nil ~= string.find(M.curbuf_contents(), contents, 1, true))
850end
851
852-- Checks that the Nvim session did not terminate.
853function M.assert_alive()
854  assert(2 == M.eval('1+1'), 'crash? request failed')
855end
856
857-- Asserts that buffer is loaded and visible in the current tabpage.
858function M.assert_visible(bufnr, visible)
859  assert(type(visible) == 'boolean')
860  eq(visible, M.api.nvim_buf_is_loaded(bufnr))
861  if visible then
862    assert(
863      -1 ~= M.fn.bufwinnr(bufnr),
864      'expected buffer to be visible in current tabpage: ' .. tostring(bufnr)
865    )
866  else
867    assert(
868      -1 == M.fn.bufwinnr(bufnr),
869      'expected buffer NOT visible in current tabpage: ' .. tostring(bufnr)
870    )
871  end
872end
873
874local start_dir = assert(uv.cwd())
875
876function M.rmdir(path)
877  local ret, _ = pcall(vim.fs.rm, path, { recursive = true, force = true })
878  local did_cd = false
879  if not ret and is_os('win') then
880    -- Maybe "Permission denied"; try again after changing the nvim
881    -- process to the top-level directory.
882    ret, _ = pcall(function()
883      M.fn.chdir(start_dir)
884      vim.fs.rm(path, { recursive = true, force = true })
885    end)
886    did_cd = true
887  end
888  -- During teardown, the nvim process may not exit quickly enough, then rmdir()
889  -- will fail (on Windows).
890  if not ret then -- Try again.
891    sleep(1000)
892    vim.fs.rm(path, { recursive = true, force = true })
893  end
894  if did_cd then
895    -- Try to restore CWD in case rmdir() is used within a test. Needs pcall: #38278
896    pcall(M.command, 'cd -')
897  end
898end
899
900function M.exec(code)
901  M.api.nvim_exec2(code, {})
902end
903
904--- @param code string
905--- @return string
906function M.exec_capture(code)
907  return M.api.nvim_exec2(code, { output = true }).output
908end
909
910--- Execute Lua code in the wrapped Nvim session.
911---
912--- When `code` is passed as a function, it is converted into Lua byte code.
913---
914--- Direct upvalues are copied over, however upvalues contained
915--- within nested functions are not. Upvalues are also copied back when `code`
916--- finishes executing. See `:help lua-upvalue`.
917---
918--- Only types which can be serialized can be transferred over, e.g:
919--- `table`, `number`, `boolean`, `string`.
920---
921--- `code` runs with a different environment and thus will have a different global
922--- environment. See `:help lua-environments`.
923---
924--- Example:
925--- ```lua
926--- local upvalue1 = 'upvalue1'
927--- exec_lua(function(a, b, c)
928---   print(upvalue1, a, b, c)
929---   (function()
930---     print(upvalue2)
931---   end)()
932--- end, 'a', 'b', 'c'
933--- ```
934--- Prints:
935--- ```
936--- upvalue1 a b c
937--- nil
938--- ```
939---
940--- Not supported:
941--- ```lua
942--- local a = vim.uv.new_timer()
943--- exec_lua(function()
944---   print(a) -- Error: a is of type 'userdata' which cannot be serialized.
945--- end)
946--- ```
947--- @param code string|function
948--- @param ... any
949--- @return any
950function M.exec_lua(code, ...)
951  if type(code) == 'string' then
952    return M.api.nvim_exec_lua(code, { ... })
953  end
954
955  assert(session, 'no Nvim session')
956  return require('test.functional.testnvim.exec_lua')(session, 2, code, ...)
957end
958
959--- Runs `cmd` via `vim.system()` in the Nvim-under-test and returns its result.
960---
961--- Asserts the child process is gone afterward, polling to absorb the brief lag between the
962--- exit-handler and nvim_get_proc() reporting it (seen on Windows).
963---
964--- @param cmd string[]
965--- @param opts? vim.SystemOpts
966--- @param async? boolean  Wait via the on_exit callback instead of a blocking `obj:wait()`.
967--- @return vim.SystemCompleted
968local function system(cmd, opts, async)
969  return M.exec_lua(function()
970    local res --- @type vim.SystemCompleted?
971    local obj
972    if async then
973      local done = false
974      obj = vim.system(cmd, opts, function(o)
975        done = true
976        res = o
977      end)
978      assert(
979        vim.wait(10000, function()
980          return done
981        end),
982        'process did not exit'
983      )
984    else
985      obj = vim.system(cmd, opts)
986      if opts and opts.timeout then
987        -- Minor delay before calling wait() so the timeout uv timer can have a headstart over the
988        -- internal call to vim.wait() in wait().
989        vim.wait(10)
990      end
991      res = obj:wait()
992    end
993
994    -- Assert that the process terminated.
995    -- XXX: Poll bc nvim_get_proc() can briefly lag the exit callback (on Windows): `uv_close`
996    -- completes on a later tick, thus the PID is still briefly resolvable.
997    assert(
998      vim.wait(1000, function()
999        return not vim.api.nvim_get_proc(obj.pid)
1000      end),
1001      'process still exists'
1002    )
1003
1004    return res
1005  end)
1006end
1007
1008--- Runs `cmd` via `vim.system()` in the Nvim-under-test and waits (synchronously) for it to exit.
1009function M.system_sync(cmd, opts)
1010  return system(cmd, opts, false)
1011end
1012
1013--- Like `system_sync()` but waits via the `vim.system()` on_exit callback.
1014function M.system_async(cmd, opts)
1015  return system(cmd, opts, true)
1016end
1017
1018--- Benchmarks `fn` in the Nvim-under-test: runs it `opts.n` times, timing each run in-session, then reports.
1019---
1020--- Note: see `testutil.bench()` to run in the test-runner process.
1021---
1022--- @param body string  Lua source executed each iteration; the iteration index is available as `i`.
1023--- @param opts { n: integer, label?: string, unit?: 'ms'|'us', warmup?: integer }
1024--- @return table stats  See `testutil.bench_report()`.
1025function M.bench(body, opts)
1026  local samples = M.exec_lua(
1027    [[
1028    local body, n, warmup = ...
1029    local fn = assert(loadstring('local i = ...\n' .. body))
1030    for i = 1, warmup do
1031      fn(i)
1032    end
1033    local samples = {}
1034    for i = 1, n do
1035      local t0 = vim.uv.hrtime()
1036      fn(i)
1037      samples[i] = vim.uv.hrtime() - t0
1038    end
1039    return samples
1040  ]],
1041    body,
1042    opts.n,
1043    opts.warmup or 100
1044  )
1045  return t.bench_report(samples, opts)
1046end
1047
1048function M.get_pathsep()
1049  return is_os('win') and '\\' or '/'
1050end
1051
1052--- Gets the filesystem root dir, namely "/" or "C:/".
1053function M.pathroot()
1054  local pathsep = package.config:sub(1, 1)
1055  return is_os('win') and (M.nvim_dir:sub(1, 2) .. pathsep) or '/'
1056end
1057
1058--- Gets the full `…/build/bin/{name}` path of a test program produced by
1059--- `test/functional/fixtures/CMakeLists.txt`.
1060---
1061--- @param name (string) Name of the test program.
1062function M.testprg(name)
1063  local ext = is_os('win') and '.exe' or ''
1064  return ('%s/%s%s'):format(M.nvim_dir, name, ext)
1065end
1066
1067--- Returns a valid, platform-independent Nvim listen address.
1068--- Useful for communicating with child instances.
1069---
1070--- @return string
1071function M.new_pipename()
1072  -- HACK: Start a server temporarily, get the name, then stop it.
1073  --
1074  -- XXX: If a (still-alive) Nvim process is using an old "--listen nvim.<PID>.<counter>" pipename,
1075  -- and the OS reuses the PID, then serverstart() may generate a duplicate name (bc of PID reuse).
1076  -- Retry serverstart() to force an incremented <counter>.
1077  local ok = false
1078  local pipename ---@type string
1079  for _ = 1, 100 do
1080    ok, pipename = pcall(M.eval, 'serverstart()')
1081    if ok then
1082      break
1083    end
1084    sleep(20) -- Avoid hot loop; give stale process time to exit.
1085  end
1086  assert(ok, pipename)
1087  M.fn.serverstop(pipename)
1088  -- Remove the pipe so that trying to connect to it without a server listening
1089  -- will be an error instead of a hang.
1090  os.remove(pipename)
1091  return pipename
1092end
1093
1094--- @param provider string
1095--- @return string|boolean?
1096function M.missing_provider(provider)
1097  if provider == 'ruby' or provider == 'perl' then
1098    --- @type string?
1099    local e = M.exec_lua("return {require('vim.provider." .. provider .. "').detect()}")[2]
1100    return e ~= '' and e or false
1101  elseif provider == 'node' then
1102    --- @type string?
1103    local e = M.fn['provider#node#Detect']()[2]
1104    return e ~= '' and e or false
1105  elseif provider == 'python' then
1106    return M.exec_lua([[return {require('vim.provider.python').detect_by_module('neovim')}]])[2]
1107  end
1108  assert(false, 'Unknown provider: ' .. provider)
1109end
1110
1111local load_factor = 1
1112if t.is_ci() then
1113  -- Compute load factor only once (but outside of any tests).
1114  M.clear()
1115  M.request('nvim_command', 'source test/old/testdir/load.vim')
1116  load_factor = M.request('nvim_eval', 'g:test_load_factor')
1117end
1118
1119--- @param num number
1120--- @return number
1121function M.load_adjust(num)
1122  return math.ceil(num * load_factor)
1123end
1124
1125--- @param ctx table<string,any>
1126--- @return table
1127function M.parse_context(ctx)
1128  local parsed = {} --- @type table<string,any>
1129  for _, item in ipairs({ 'regs', 'jumps', 'bufs', 'gvars' }) do
1130    --- @param v any
1131    parsed[item] = vim.tbl_filter(function(v)
1132      return type(v) == 'table'
1133    end, M.call('msgpackparse', ctx[item]))
1134  end
1135  parsed['bufs'] = parsed['bufs'][1]
1136  --- @param v any
1137  return vim.tbl_map(function(v)
1138    if #v == 0 then
1139      return nil
1140    end
1141    return v
1142  end, parsed)
1143end
1144
1145function M.add_builddir_to_rtp()
1146  -- Add runtime from build dir for doc/tags (used with :help).
1147  M.command(string.format([[set rtp+=%s/runtime]], t.paths.test_build_dir))
1148end
1149
1150--- Create folder with non existing parents
1151---
1152--- TODO(justinmk): lift this and `t.mkdir()` into vim.fs.
1153---
1154--- @param path string
1155--- @return boolean?
1156function M.mkdir_p(path)
1157  return os.execute(
1158    (is_os('win') and 'mkdir ' .. string.gsub(path, '/', '\\') or 'mkdir -p ' .. path)
1159  )
1160end
1161
1162local testid = (function()
1163  local id = 0
1164  return function()
1165    id = id + 1
1166    return id
1167  end
1168end)()
1169
1170return function()
1171  if harness.is_defining() then
1172    harness.before_each(function()
1173      local id = ('T%d'):format(testid())
1174      _G._nvim_test_id = id
1175    end)
1176
1177    harness.after_each(function()
1178      close_extra_sessions(_G._nvim_test_id, true)
1179      if not vim.endswith(_G._nvim_test_id, 'x') then
1180        -- Use a different test ID for skipped tests as well as Nvim instances spawned
1181        -- between this after_each() and the next before_each() (e.g. in setup()).
1182        _G._nvim_test_id = _G._nvim_test_id .. 'x'
1183      end
1184      check_logs()
1185      check_cores('build/bin/nvim')
1186      if session then
1187        local msg = session:next_message(0)
1188        if msg then
1189          if msg[1] == 'notification' and msg[2] == 'nvim_error_event' then
1190            error(msg[3][2])
1191          end
1192        end
1193      end
1194    end)
1195  end
1196
1197  return M
1198end