test: more tidying

This commit is contained in:
Lewis Russell 2023-10-05 17:11:47 +01:00 committed by Lewis Russell
parent 2929386210
commit ff01d34daa
8 changed files with 151 additions and 270 deletions

View File

@ -99,7 +99,9 @@ stylua-check: stylua
.PHONY: stylua-run
stylua-run: stylua
./stylua lua/**/*.lua lua/*.lua
./stylua \
lua/**/*.lua lua/*.lua \
test/*.lua test/**/*.lua
.PHONY: build
build: gen_help stylua-run

View File

@ -4,10 +4,10 @@ local setup_gitsigns = helpers.setup_gitsigns
local feed = helpers.feed
local test_file = helpers.test_file
local edit = helpers.edit
local command = helpers.command
local command = helpers.api.nvim_command
local check = helpers.check
local exec_lua = helpers.exec_lua
local fn = helpers.funcs
local fn = helpers.fn
local system = fn.system
local test_config = helpers.test_config
local clear = helpers.clear

View File

@ -1,13 +1,10 @@
local pretty = require('pl.pretty')
local global_helpers = require('test.helpers')
-- Colors are disabled by default. #15610
local colors = require('term.colors')
return function(options)
local busted = require('busted')
local handler = require('busted.outputHandlers.base')()
local colors = require('term.colors')
local pretty = require('pl.pretty')
--- @type table<string,fun(s:string): string>
local c = {
succ = function(s)
return colors.bright(colors.green(s))
@ -49,14 +46,13 @@ return function(options)
.. c.time('(%.2f ms total)')
.. '\n\n'
local globalTeardown = c.sect('--------') .. ' Global test environment teardown.\n'
local suiteEndString = c.sect('========')
.. ' '
.. c.nmbr('%d')
.. ' %s from '
.. c.nmbr('%d')
.. ' test %s ran. '
.. c.time('(%.2f ms total)')
.. '\n'
local suiteEndString = string.format(
'%s %s %%s from %s test %%s ran. %s\n',
c.sect('========'),
c.nmbr('%d'),
c.nmbr('%d'),
c.time('(%.2f ms total)')
)
local successStatus = c.succ('PASSED ') .. ' ' .. c.nmbr('%d') .. ' %s.\n'
local timeString = c.time('%.2f ms')
@ -151,30 +147,29 @@ return function(options)
end
local getSummary = function(status, count)
local string = ''
local footer = summaryStrings[status].footer
if count > 0 and footer then
local tests = (count == 1 and 'TEST' or 'TESTS')
local errors = (count == 1 and 'ERROR' or 'ERRORS')
string = footer:format(count, status == 'error' and errors or tests)
return footer:format(count, status == 'error' and errors or tests)
end
return string
return ''
end
local getSummaryString = function()
local tests = (successCount == 1 and 'test' or 'tests')
local string = successStatus:format(successCount, tests)
return table.concat({
successStatus:format(successCount, tests),
string = string .. getTestList('skipped', skippedCount, handler.pendings, pendingDescription)
string = string .. getTestList('failure', failureCount, handler.failures, failureDescription)
string = string .. getTestList('error', errorCount, handler.errors, failureDescription)
getTestList('skipped', skippedCount, handler.pendings, pendingDescription),
getTestList('failure', failureCount, handler.failures, failureDescription),
getTestList('error', errorCount, handler.errors, failureDescription),
string = string .. ((skippedCount + failureCount + errorCount) > 0 and '\n' or '')
string = string .. getSummary('skipped', skippedCount)
string = string .. getSummary('failure', failureCount)
string = string .. getSummary('error', errorCount)
return string
((skippedCount + failureCount + errorCount) > 0 and '\n' or ''),
getSummary('skipped', skippedCount),
getSummary('failure', failureCount),
getSummary('error', errorCount),
})
end
handler.suiteReset = function()
@ -212,14 +207,11 @@ return function(options)
handler.suiteEnd = function(suite, _count, _total)
local elapsedTime_ms = getElapsedTime(suite)
local tests = (testCount == 1 and 'test' or 'tests')
local files = (fileCount == 1 and 'file' or 'files')
local tests = testCount == 1 and 'test' or 'tests'
local files = fileCount == 1 and 'file' or 'files'
io.write(globalTeardown)
io.write(suiteEndString:format(testCount, tests, fileCount, files, elapsedTime_ms))
io.write(getSummaryString())
if failureCount > 0 or errorCount > 0 then
io.write(global_helpers.read_nvim_log(nil, true))
end
io.flush()
return nil, true
@ -234,7 +226,7 @@ return function(options)
handler.fileEnd = function(file)
local elapsedTime_ms = getElapsedTime(file)
local tests = (fileTestCount == 1 and 'test' or 'tests')
local tests = fileTestCount == 1 and 'test' or 'tests'
fileCount = fileCount + 1
io.write(
fileEndString:format(fileTestCount, tests, vim.fs.normalize(file.name), elapsedTime_ms)
@ -244,8 +236,7 @@ return function(options)
end
handler.testStart = function(element, _parent)
local testid = _G._nvim_test_id or ''
local desc = ('%s %s'):format(testid, handler.getFullName(element))
local desc = (' %s'):format(handler.getFullName(element))
io.write(runString:format(desc))
io.flush()
@ -258,7 +249,7 @@ return function(options)
end
handler.testEnd = function(element, _parent, status, _debug)
local string
local string --- @type string
fileTestCount = fileTestCount + 1
testCount = testCount + 1

View File

@ -6,7 +6,7 @@ local edit = helpers.edit
local eq = helpers.eq
local setup_test_repo = helpers.setup_test_repo
local cleanup = helpers.cleanup
local command = helpers.command
local command = helpers.api.nvim_command
local test_config = helpers.test_config
local match_debug_messages = helpers.match_debug_messages
local match_dag = helpers.match_dag
@ -19,8 +19,8 @@ helpers.env()
local function get_bufs()
local bufs = {}
for _, b in ipairs(helpers.meths.list_bufs()) do
bufs[b.id] = helpers.meths.buf_get_name(b)
for _, b in ipairs(helpers.api.nvim_list_bufs()) do
bufs[b.id] = helpers.api.nvim_buf_get_name(b)
end
return bufs
end
@ -31,7 +31,7 @@ describe('gitdir_watcher', function()
-- Make gitisigns available
exec_lua('package.path = ...', package.path)
command('cd ' .. helpers.funcs.system({ 'dirname', os.tmpname() }))
command('cd ' .. helpers.fn.system({ 'dirname', os.tmpname() }))
end)
after_each(function()
@ -47,7 +47,9 @@ describe('gitdir_watcher', function()
match_debug_messages({
'attach(1): Attaching (trigger=BufReadPost)',
np('run_job: git .* config user.name'),
np('run_job: git .* rev%-parse %-%-show%-toplevel %-%-absolute%-git%-dir %-%-abbrev%-ref HEAD'),
np(
'run_job: git .* rev%-parse %-%-show%-toplevel %-%-absolute%-git%-dir %-%-abbrev%-ref HEAD'
),
np('run_job: git .* ls%-files .* ' .. vim.pesc(test_file)),
n('watch_gitdir(1): Watching git dir'),
np('run_job: git .* show :0:dummy.txt'),
@ -68,7 +70,9 @@ describe('gitdir_watcher', function()
})
match_debug_messages({
np('run_job: git .* rev%-parse %-%-show%-toplevel %-%-absolute%-git%-dir %-%-abbrev%-ref HEAD'),
np(
'run_job: git .* rev%-parse %-%-show%-toplevel %-%-absolute%-git%-dir %-%-abbrev%-ref HEAD'
),
np('run_job: git .* ls%-files .* ' .. vim.pesc(test_file)),
np('run_job: git .* diff %-%-name%-status %-C %-%-cached'),
n('handle_moved(1): File moved to dummy.txt2'),
@ -93,7 +97,9 @@ describe('gitdir_watcher', function()
})
match_debug_messages({
p('run_job: git .* rev%-parse %-%-show%-toplevel %-%-absolute%-git%-dir %-%-abbrev%-ref HEAD'),
p(
'run_job: git .* rev%-parse %-%-show%-toplevel %-%-absolute%-git%-dir %-%-abbrev%-ref HEAD'
),
np('run_job: git .* ls%-files .* ' .. vim.pesc(test_file2)),
np('run_job: git .* diff %-%-name%-status %-C %-%-cached'),
n('handle_moved(1): File moved to dummy.txt3'),
@ -116,7 +122,9 @@ describe('gitdir_watcher', function()
})
match_debug_messages({
p('run_job: git .* rev%-parse %-%-show%-toplevel %-%-absolute%-git%-dir %-%-abbrev%-ref HEAD'),
p(
'run_job: git .* rev%-parse %-%-show%-toplevel %-%-absolute%-git%-dir %-%-abbrev%-ref HEAD'
),
np('run_job: git .* ls%-files .* ' .. vim.pesc(test_file3)),
np('run_job: git .* diff %-%-name%-status %-C %-%-cached'),
np('run_job: git .* ls%-files .* ' .. vim.pesc(test_file)),

View File

@ -4,14 +4,13 @@ local Screen = require('test.screen')
local helpers = require('test.gs_helpers')
local clear = helpers.clear
local command = helpers.command
local exec_capture = helpers.exec_capture
local command = helpers.api.nvim_command
local feed = helpers.feed
local insert = helpers.insert
local exec_lua = helpers.exec_lua
local split = vim.split
local get_buf_var = helpers.curbufmeths.get_var
local fn = helpers.funcs
local get_buf_var = helpers.api.nvim_buf_get_var
local fn = helpers.fn
local system = fn.system
local expectf = helpers.expectf
local write_to_file = helpers.write_to_file
@ -87,7 +86,9 @@ describe('gitsigns (with screen)', function()
match_dag({
'attach(1): Attaching (trigger=BufReadPost)',
p('run_job: git .* config user.name'),
p('run_job: git .* rev%-parse %-%-show%-toplevel %-%-absolute%-git%-dir %-%-abbrev%-ref HEAD'),
p(
'run_job: git .* rev%-parse %-%-show%-toplevel %-%-absolute%-git%-dir %-%-abbrev%-ref HEAD'
),
p(
'run_job: git .* ls%-files %-%-stage %-%-others %-%-exclude%-standard %-%-eol '
.. vim.pesc(test_file)
@ -118,7 +119,9 @@ describe('gitsigns (with screen)', function()
match_debug_messages({
'attach(1): Attaching (trigger=BufReadPost)',
np('run_job: git .* config user.name'),
np('run_job: git .* rev%-parse %-%-show%-toplevel %-%-absolute%-git%-dir %-%-abbrev%-ref HEAD'),
np(
'run_job: git .* rev%-parse %-%-show%-toplevel %-%-absolute%-git%-dir %-%-abbrev%-ref HEAD'
),
n('new: Not in git repo'),
n('attach(1): Empty git obj'),
})
@ -130,7 +133,9 @@ describe('gitsigns (with screen)', function()
match_debug_messages({
n('attach(1): Attaching (trigger=BufWritePost)'),
np('run_job: git .* config user.name'),
np('run_job: git .* rev%-parse %-%-show%-toplevel %-%-absolute%-git%-dir %-%-abbrev%-ref HEAD'),
np(
'run_job: git .* rev%-parse %-%-show%-toplevel %-%-absolute%-git%-dir %-%-abbrev%-ref HEAD'
),
n('new: Not in git repo'),
n('attach(1): Empty git obj'),
})
@ -145,7 +150,7 @@ describe('gitsigns (with screen)', function()
it('can setup mappings', function()
edit(test_file)
expectf(function()
local res = split(exec_capture('nmap <buffer>'), '\n')
local res = split(helpers.api.nvim_exec('nmap <buffer>', true), '\n')
table.sort(res)
-- Check all keymaps get set
@ -181,7 +186,9 @@ describe('gitsigns (with screen)', function()
match_debug_messages({
'attach(1): Attaching (trigger=BufReadPost)',
np('run_job: git .* config user.name'),
np('run_job: git .* rev%-parse %-%-show%-toplevel %-%-absolute%-git%-dir %-%-abbrev%-ref HEAD'),
np(
'run_job: git .* rev%-parse %-%-show%-toplevel %-%-absolute%-git%-dir %-%-abbrev%-ref HEAD'
),
np('run_job: git .* ls%-files .*/dummy_ignored.txt'),
n('attach(1): Cannot resolve file in repo'),
})
@ -195,7 +202,9 @@ describe('gitsigns (with screen)', function()
match_debug_messages({
'attach(1): Attaching (trigger=BufNewFile)',
np('run_job: git .* config user.name'),
np('run_job: git .* rev%-parse %-%-show%-toplevel %-%-absolute%-git%-dir %-%-abbrev%-ref HEAD'),
np(
'run_job: git .* rev%-parse %-%-show%-toplevel %-%-absolute%-git%-dir %-%-abbrev%-ref HEAD'
),
np(
'run_job: git .* ls%-files %-%-stage %-%-others %-%-exclude%-standard %-%-eol '
.. vim.pesc(newfile)
@ -214,8 +223,8 @@ describe('gitsigns (with screen)', function()
n('attach(1): Not a path'),
})
helpers.pcall_err(get_buf_var, 'gitsigns_head')
helpers.pcall_err(get_buf_var, 'gitsigns_status_dict')
helpers.pcall_err(get_buf_var, 0, 'gitsigns_head')
helpers.pcall_err(get_buf_var, 0, 'gitsigns_status_dict')
end)
it('can run copen', function()
@ -232,18 +241,15 @@ describe('gitsigns (with screen)', function()
feed('oline2<esc>')
expectf(function()
eq(
eq({
{
{
head = '@@ -1,1 +1,2 @@',
type = 'change',
lines = { '-This', '+line1This', '+line2' },
added = { count = 2, start = 1, lines = { 'line1This', 'line2' } },
removed = { count = 1, start = 1, lines = { 'This' } },
},
head = '@@ -1,1 +1,2 @@',
type = 'change',
lines = { '-This', '+line1This', '+line2' },
added = { count = 2, start = 1, lines = { 'line1This', 'line2' } },
removed = { count = 1, start = 1, lines = { 'This' } },
},
exec_lua([[return require'gitsigns'.get_hunks()]])
)
}, exec_lua([[return require'gitsigns'.get_hunks()]]))
end)
end)
end)
@ -336,7 +342,9 @@ describe('gitsigns (with screen)', function()
match_debug_messages({
'attach(1): Attaching (trigger=BufReadPost)',
np('run_job: git .* config user.name'),
np('run_job: git .* rev%-parse %-%-show%-toplevel %-%-absolute%-git%-dir %-%-abbrev%-ref HEAD'),
np(
'run_job: git .* rev%-parse %-%-show%-toplevel %-%-absolute%-git%-dir %-%-abbrev%-ref HEAD'
),
np('run_job: git .* rev%-parse %-%-short HEAD'),
np('run_job: git .* %-%-git%-dir .* %-%-stage %-%-others %-%-exclude%-standard %-%-eol.*'),
n('attach(1): User on_attach() returned false'),
@ -451,7 +459,9 @@ describe('gitsigns (with screen)', function()
match_debug_messages({
'attach(1): Attaching (trigger=BufNewFile)',
np('run_job: git .* config user.name'),
np('run_job: git .* rev%-parse %-%-show%-toplevel %-%-absolute%-git%-dir %-%-abbrev%-ref HEAD'),
np(
'run_job: git .* rev%-parse %-%-show%-toplevel %-%-absolute%-git%-dir %-%-abbrev%-ref HEAD'
),
np('run_job: git .* ls%-files .*'),
n('attach(1): Not a file'),
})
@ -460,7 +470,9 @@ describe('gitsigns (with screen)', function()
local messages = {
'attach(1): Attaching (trigger=BufWritePost)',
np('run_job: git .* config user.name'),
np('run_job: git .* rev%-parse %-%-show%-toplevel %-%-absolute%-git%-dir %-%-abbrev%-ref HEAD'),
np(
'run_job: git .* rev%-parse %-%-show%-toplevel %-%-absolute%-git%-dir %-%-abbrev%-ref HEAD'
),
np('run_job: git .* ls%-files .*'),
n('watch_gitdir(1): Watching git dir'),
np('run_job: git .* show :0:newfile.txt'),
@ -648,10 +660,12 @@ describe('gitsigns (with screen)', function()
helpers.exc_exec('vimgrep ben ' .. scratch .. '/*')
screen:expect({
messages = { {
kind = 'quickfix',
content = { { '(1 of 2): hello ben' } },
} },
messages = {
{
kind = 'quickfix',
content = { { '(1 of 2): hello ben' } },
},
},
})
match_debug_messages({
@ -673,7 +687,7 @@ describe('gitsigns (with screen)', function()
-- SHA is not deterministic so just check it can be cast as a hex value
expectf(function()
helpers.neq(nil, tonumber('0x' .. get_buf_var('gitsigns_head')))
helpers.neq(nil, tonumber('0x' .. get_buf_var(0, 'gitsigns_head')))
end)
end)
@ -712,10 +726,12 @@ describe('gitsigns (with screen)', function()
feed('x')
screen:expect({ grid = [[
screen:expect({
grid = [[
{2:~ }^orem ipsum |
{6:~ }|
]] })
]],
})
end)
it('handle #521', function()

View File

@ -7,8 +7,8 @@ local M = helpers
local exec_lua = helpers.exec_lua
local matches = helpers.matches
local eq = helpers.eq
local get_buf_var = helpers.curbufmeths.get_var
local system = helpers.funcs.system
local buf_get_var = helpers.api.nvim_buf_get_var
local system = helpers.fn.system
M.scratch = os.getenv('PJ_ROOT') .. '/scratch'
M.gitdir = M.scratch .. '/.git'
@ -142,7 +142,7 @@ function M.expectf(cond, interval)
end
function M.edit(path)
helpers.command('edit ' .. path)
helpers.api.nvim_command('edit ' .. path)
end
--- @param path string
@ -273,16 +273,16 @@ end
--- @param status table<string,string|integer>
local function check_status(status)
local fn = helpers.funcs
local fn = helpers.fn
if next(status) == nil then
eq(0, fn.exists('b:gitsigns_head'), 'b:gitsigns_head is unexpectedly set')
eq(0, fn.exists('b:gitsigns_status_dict'), 'b:gitsigns_status_dict is unexpectedly set')
else
eq(1, fn.exists('b:gitsigns_head'), 'b:gitsigns_head is not set')
eq(status.head, get_buf_var('gitsigns_head'), 'b:gitsigns_head does not match')
eq(status.head, buf_get_var(0, 'gitsigns_head'), 'b:gitsigns_head does not match')
--- @type table<string,string|integer>
local bstatus = get_buf_var('gitsigns_status_dict')
local bstatus = buf_get_var(0, 'gitsigns_status_dict')
for _, i in ipairs({ 'added', 'changed', 'removed', 'head' }) do
eq(status[i], bstatus[i], string.format("status['%s'] did not match gitsigns_status_dict", i))
@ -299,12 +299,12 @@ end
local function check_signs(signs, extmarks)
local buf_signs = {} --- @type string[]
if extmarks then
local buf_marks = helpers.curbufmeths.get_extmarks(-1, 0, -1, { details = true })
local buf_marks = helpers.api.nvim_buf_get_extmarks(0, -1, 0, -1, { details = true })
for _, s in ipairs(buf_marks) do
buf_signs[#buf_signs + 1] = s[4].sign_hl_group
end
else
local buf_vimsigns = helpers.funcs.sign_getplaced('%', { group = '*' })[1].signs
local buf_vimsigns = helpers.fn.sign_getplaced('%', { group = '*' })[1].signs
for _, s in ipairs(buf_vimsigns) do
buf_signs[#buf_signs + 1] = s.name
end

View File

@ -7,10 +7,7 @@ assert:set_parameter('TableFormatLevel', 100)
local M = {}
-- sleeps the test runner (_not_ the nvim instance)
function M.sleep(ms)
luv.sleep(ms)
end
M.sleep = luv.sleep
M.eq = assert.are.same
M.neq = assert.are_not.same
@ -31,49 +28,6 @@ function M.matches(pat, actual)
error(string.format('Pattern does not match.\nPattern:\n%s\nActual:\n%s', pat, actual))
end
--- Reads text lines from `filename` into a table.
---
--- filename: path to file
--- start: start line (1-indexed), negative means "lines before end" (tail)
--- @param filename string
--- @param start? integer
--- @return string[]?
local function read_file_list(filename, start)
local lnum = start or 1
local tail = lnum < 0
local maxlines = tail and math.abs(lnum) or nil
local file = io.open(filename, 'r')
if not file then
return
end
-- There is no need to read more than the last 2MB of the log file, so seek
-- to that.
local file_size = file:seek('end')
local offset = file_size - 2000000
if offset < 0 then
offset = 0
end
file:seek('set', offset)
local lines = {} --- @type string[]
local i = 1
local line = file:read('*l')
while line do
if i >= start then
table.insert(lines, line)
if #lines > maxlines then
table.remove(lines, 1)
end
end
i = i + 1
line = file:read('*l')
end
file:close()
return lines
end
--- @generic R
--- @param fn fun(...): R
--- @param ... any arguments
@ -125,7 +79,6 @@ end
--- @param ... any arguments
--- @return R
local function pcall_err_withfile(fn, ...)
assert(type(fn) == 'function')
local status, rv = M.pcall(fn, ...)
if status == true then
error('expected failure, but got success')
@ -190,41 +143,14 @@ function M.dedent(str, leave_indent)
return str
end
-- Gets the (tail) contents of `logfile`.
-- Also moves the file to "${NVIM_LOG_FILE}.displayed" on CI environments.
function M.read_nvim_log(logfile)
logfile = logfile or os.getenv('NVIM_LOG_FILE') or '.nvimlog'
local keep = 10
local lines = read_file_list(logfile, -keep) or {}
local log = (
('-'):rep(78)
.. '\n'
.. string.format('$NVIM_LOG_FILE: %s\n', logfile)
.. (#lines > 0 and '(last ' .. tostring(keep) .. ' lines)\n' or '(empty)\n')
)
for _, line in ipairs(lines) do
log = log .. line .. '\n'
end
log = log .. ('-'):rep(78) .. '\n'
return log
end
local runtime_set = 'set runtimepath^=./build/lib/nvim/'
local nvim_prog = os.getenv('NVIM_PRG') or 'nvim'
-- Default settings for the test session.
local nvim_set = table.concat({
'set',
'shortmess+=IS',
'background=light',
'noswapfile',
'noautoindent',
'startofline',
'laststatus=1',
'undodir=.',
'directory=.',
'viewdir=.',
'backupdir=.',
'belloff=',
'wildoptions-=pum',
'joinspaces',
'noshowcmd',
@ -233,20 +159,14 @@ local nvim_set = table.concat({
'redrawdebug=invalid',
}, ' ')
local nvim_argv = {
nvim_prog,
local nvim_cmd = {
os.getenv('NVIM_PRG') or 'nvim',
'-u',
'NONE',
'-i',
'NONE',
'--cmd',
runtime_set,
'--cmd',
nvim_set,
'--cmd',
'mapclear',
'--cmd',
'mapclear!',
'--embed',
'--headless',
}
@ -259,23 +179,6 @@ function M.get_session()
return session
end
--- @param method string
--- @param ... any
--- @return any[]
local function request(method, ...)
assert(session)
local status, rv = session:request(method, ...)
if not status then
if loop_running then
last_error = rv[2]
session:stop()
else
error(rv[2])
end
end
return rv
end
--- @param lsession NvimSession
--- @param ... any
--- @return string
@ -322,33 +225,51 @@ function M.run_session(lsession, request_cb, notification_cb, timeout)
return lsession.eof_err
end
--- Executes an ex-command. VimL errors manifest as client (lua) errors, but
--- v:errmsg will not be updated.
--- @param cmd string
function M.command(cmd)
request('nvim_command', cmd)
function M.create_callindex(func)
return setmetatable({}, {
--- @param tbl table<string,function>
--- @param arg1 string
--- @return function
__index = function(tbl, arg1)
local ret = function(...)
return func(arg1, ...)
end
tbl[arg1] = ret
return ret
end,
})
end
--- Evaluates a VimL expression.
--- Fails on VimL error, but does not update v:errmsg.
--- @param expr string
--- @return any[]
function M.eval(expr)
return request('nvim_eval', expr)
end
-- Trick LuaLS that M.api has the type of vim.api. vim.api is set to nil in
-- preload.lua so M.api gets the second term
--- Executes a VimL function via RPC.
--- Fails on VimL error, but does not update v:errmsg.
--- @param name string
--- @param ... any
--- @return any[]
function M.call(name, ...)
return request('nvim_call_function', name, { ... })
M.api = vim.api
or M.create_callindex(function(...)
assert(session)
local status, rv = session:request(...)
if not status then
if loop_running then
last_error = rv[2]
session:stop()
else
error(rv[2])
end
end
return rv
end)
M.fn = vim.fn
or M.create_callindex(function(name, ...)
return M.api.nvim_call_function(name, { ... })
end)
function M.exec_lua(code, ...)
return M.api.nvim_exec_lua(code, { ... })
end
-- Checks that the Nvim session did not terminate.
local function assert_alive()
assert(2 == M.eval('1+1'), 'crash? request failed')
assert(2 == M.api.nvim_eval('1+1'), 'crash? request failed')
end
--- Sends user input to Nvim.
@ -356,7 +277,7 @@ end
--- @param input string
local function nvim_feed(input)
while #input > 0 do
local written = request('nvim_input', input)
local written = M.api.nvim_input(input)
if written == nil then
assert_alive()
error('crash? (nvim_input returned nil)')
@ -403,7 +324,7 @@ end
--- Starts a new global Nvim session.
function M.clear()
check_close()
local child_stream = ProcessStream.spawn(nvim_argv)
local child_stream = ProcessStream.spawn(nvim_cmd)
session = Session.new(child_stream)
local status, info = session:request('nvim_get_api_info')
@ -434,76 +355,19 @@ function M.insert(...)
nvim_feed('<ESC>')
end
function M.create_callindex(func)
return setmetatable({}, {
--- @param tbl table<string,function>
--- @param arg1 string
--- @return function
__index = function(tbl, arg1)
local ret = function(...)
return func(arg1, ...)
end
tbl[arg1] = ret
return ret
end,
})
end
function M.nvim(method, ...)
return request('nvim_' .. method, ...)
end
function M.buffer(method, ...)
return request('nvim_buf_' .. method, ...)
end
function M.window(method, ...)
return request('nvim_win_' .. method, ...)
end
function M.curbuf(method, ...)
if not method then
return M.nvim('get_current_buf')
end
return M.buffer(method, 0, ...)
end
function M.curwin(method, ...)
if not method then
return M.nvim('get_current_win')
end
return M.window(method, 0, ...)
end
M.funcs = M.create_callindex(M.call)
M.meths = M.create_callindex(M.nvim)
M.bufmeths = M.create_callindex(M.buffer)
M.winmeths = M.create_callindex(M.window)
M.curbufmeths = M.create_callindex(M.curbuf)
M.curwinmeths = M.create_callindex(M.curwin)
function M.exc_exec(cmd)
M.command(([[
M.api.nvim_command(([[
try
execute "%s"
catch
let g:__exception = v:exception
endtry
]]):format(cmd:gsub('\n', '\\n'):gsub('[\\"]', '\\%0')))
local ret = M.eval('get(g:, "__exception", 0)')
M.command('unlet! g:__exception')
local ret = M.api.nvim_eval('get(g:, "__exception", 0)')
M.api.nvim_command('unlet! g:__exception')
return ret
end
function M.exec_capture(code)
-- return module.meths.exec2(code, { output = true }).output
return M.meths.exec(code, true)
end
function M.exec_lua(code, ...)
return M.meths.exec_lua(code, { ... })
end
--- @param after_each fun(block:fun())
function M.after_each(after_each)
after_each(function()

View File

@ -3,7 +3,7 @@ local helpers = require('test.gs_helpers')
local clear = helpers.clear
local exec_lua = helpers.exec_lua
local command = helpers.command
local command = helpers.api.nvim_command
local cleanup = helpers.cleanup
local test_config = helpers.test_config