robin/laufey

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

robinmerge: 9a29622b3b00ddb601

master
8.0 KiB247 linesraw
1-- Functions to test :terminal and the Nvim TUI.
2-- Starts a child process in a `:terminal` and sends bytes to the child via nvim_chan_send().
3-- Note: the global functional/testutil.lua test-session is _host_ session, _not_
4-- the child session.
5--
6-- - Use `setup_screen()` to test `:terminal` behavior with an arbitrary command.
7-- - Use `setup_child_nvim()` to test the Nvim TUI.
8--    - NOTE: Only use this if your test actually needs the full lifecycle/capabilities of the
9--    builtin Nvim TUI. Most tests should just use `Screen.new()` directly, or plain old API calls.
10
11local t = require('test.testutil')
12local n = require('test.functional.testnvim')()
13local Screen = require('test.functional.ui.screen')
14
15local testprg = n.testprg
16local exec_lua = n.exec_lua
17local api = n.api
18local nvim_prog = n.nvim_prog
19local retry = t.retry
20local eq = t.eq
21
22local M = {}
23
24function M.feed_data(data)
25  if type(data) == 'table' then
26    data = table.concat(data, '\n')
27  end
28  exec_lua('vim.api.nvim_chan_send(vim.b.terminal_job_id, ...)', data)
29end
30
31function M.feed_termcode(data)
32  M.feed_data('\027' .. data)
33end
34
35function M.feed_csi(data)
36  M.feed_termcode('[' .. data)
37end
38
39--- @param session test.Session
40--- @return fun(code: string, ...):any
41function M.make_lua_executor(session)
42  return function(code, ...)
43    local status, rv = session:request('nvim_exec_lua', code, { ... })
44    if not status then
45      session:stop()
46      error(rv[2])
47    end
48    return rv
49  end
50end
51
52-- some helpers for controlling the terminal. the codes were taken from
53-- infocmp xterm-256color which is less what libvterm understands
54-- civis/cnorm
55function M.hide_cursor()
56  M.feed_termcode('[?25l')
57end
58function M.show_cursor()
59  M.feed_termcode('[?25h')
60end
61-- smcup/rmcup
62function M.enter_altscreen()
63  M.feed_termcode('[?1049h')
64end
65function M.exit_altscreen()
66  M.feed_termcode('[?1049l')
67end
68-- character attributes
69function M.set_fg(num)
70  M.feed_termcode('[38;5;' .. num .. 'm')
71end
72function M.set_bg(num)
73  M.feed_termcode('[48;5;' .. num .. 'm')
74end
75function M.set_bold()
76  M.feed_termcode('[1m')
77end
78function M.set_italic()
79  M.feed_termcode('[3m')
80end
81function M.set_underline()
82  M.feed_termcode('[4m')
83end
84function M.set_underdouble()
85  M.feed_termcode('[4:2m')
86end
87function M.set_undercurl()
88  M.feed_termcode('[4:3m')
89end
90function M.set_reverse()
91  M.feed_termcode('[7m')
92end
93function M.set_strikethrough()
94  M.feed_termcode('[9m')
95end
96function M.clear_attrs()
97  M.feed_termcode('[0;10m')
98end
99-- mouse
100function M.enable_mouse()
101  M.feed_termcode('[?1002h')
102end
103function M.disable_mouse()
104  M.feed_termcode('[?1002l')
105end
106
107local default_command = { testprg('tty-test') }
108
109--- Runs `cmd` in a :terminal, and returns a `Screen` object.
110---
111---@param extra_rows? integer Extra rows to add to the default screen.
112---@param cmd? string|string[] Command to run in the terminal (default: `{ 'tty-test' }`)
113---@param cols? integer Create screen with this many columns (default: 50)
114---@param env? table Environment set on the `cmd` job.
115---@param screen_opts? table Options for `Screen.new()`.
116---@return test.functional.ui.screen # Screen attached to the global (not child) Nvim session.
117function M.setup_screen(extra_rows, cmd, cols, env, screen_opts)
118  extra_rows = extra_rows and extra_rows or 0
119  cmd = cmd and cmd or default_command
120  cols = cols and cols or 50
121
122  api.nvim_command('highlight StatusLineTerm ctermbg=2 ctermfg=0')
123  api.nvim_command('highlight StatusLineTermNC ctermbg=2 ctermfg=8')
124
125  local screen = Screen.new(cols, 7 + extra_rows, screen_opts or { rgb = false })
126  screen:add_extra_attr_ids({
127    [100] = { foreground = 12 },
128    [101] = { foreground = 15, background = 1 },
129    [102] = { foreground = 121 },
130    [103] = { foreground = 11 },
131    [104] = { foreground = 81 },
132    [105] = { underline = true, reverse = true },
133    [106] = { underline = true, reverse = true, bold = true },
134    [107] = { underline = true },
135    [108] = { background = 248, foreground = Screen.colors.Black },
136    [109] = { bold = true, background = 121, foreground = Screen.colors.Grey0 },
137    [110] = { fg_indexed = true, foreground = tonumber('0xe0e000') },
138    [111] = { fg_indexed = true, foreground = tonumber('0x4040ff') },
139    [112] = { foreground = 4 },
140    [113] = { foreground = Screen.colors.SeaGreen4 },
141    [114] = { undercurl = true },
142    [115] = { underdouble = true },
143    [116] = { underline = true, foreground = 12 },
144    [117] = { background = 1 },
145    [118] = { background = 1, reverse = true },
146    [119] = { background = 2, foreground = 8 },
147    [120] = { foreground = Screen.colors.Black, background = 2 },
148    [121] = { foreground = 130 },
149    [122] = { background = 46 },
150    [123] = { foreground = 2 },
151  })
152
153  api.nvim_command('enew')
154  api.nvim_call_function('jobstart', { cmd, { term = true, env = (env and env or nil) } })
155  api.nvim_input('<CR>')
156  local vim_errmsg = api.nvim_eval('v:errmsg')
157  if vim_errmsg and '' ~= vim_errmsg then
158    error(vim_errmsg)
159  end
160
161  api.nvim_command('setlocal scrollback=10')
162  api.nvim_command('startinsert')
163  api.nvim_input('<Ignore>') -- Add input to separate two RPC requests
164
165  -- tty-test puts the terminal into raw mode and echoes input. Tests work by
166  -- feeding termcodes to control the display and asserting by screen:expect.
167  if cmd == default_command and screen_opts == nil then
168    -- Wait for "tty ready" to be printed before each test or the terminal may
169    -- still be in canonical mode (will echo characters for example).
170    local empty_line = (' '):rep(cols)
171    local expected = {
172      'tty ready' .. (' '):rep(cols - 9),
173      '^' .. (' '):rep(cols),
174      empty_line,
175      empty_line,
176      empty_line,
177      empty_line,
178    }
179    for _ = 1, extra_rows do
180      table.insert(expected, empty_line)
181    end
182
183    table.insert(expected, '{5:-- TERMINAL --}' .. ((' '):rep(cols - 14)))
184    screen:expect(table.concat(expected, '|\n') .. '|')
185  else
186    -- This eval also acts as a poke_eventloop().
187    if 0 == api.nvim_eval("exists('b:terminal_job_id')") then
188      error('terminal job failed to start')
189    end
190  end
191  return screen
192end
193
194--- Spawns Nvim with `args` in a :terminal, and returns a `Screen` object.
195---
196--- @note Only use this if you actually need the full lifecycle/capabilities of the builtin Nvim
197--- TUI. Most tests should just use `Screen.new()` directly, or plain old API calls.
198---
199---@param args? string[] Args passed to child Nvim.
200---@param opts? table Options
201---@return test.functional.ui.screen # Screen attached to the global (not child) Nvim session.
202function M.setup_child_nvim(args, opts)
203  opts = opts or {}
204  local argv = { nvim_prog, unpack(args or {}) }
205
206  local env = t.shallowcopy(opts.env) or {}
207  env.VIMRUNTIME = env.VIMRUNTIME or os.getenv('VIMRUNTIME')
208  env.NVIM_TEST = env.NVIM_TEST or os.getenv('NVIM_TEST')
209  -- Child servers need the socket dir set by runner.lua.
210  env.XDG_RUNTIME_DIR = env.XDG_RUNTIME_DIR or os.getenv('XDG_RUNTIME_DIR')
211
212  return M.setup_screen(opts.extra_rows, argv, opts.cols, env)
213end
214
215--- FIXME: On Windows spaces at the end of a screen line may have wrong attrs.
216--- Remove this function when that's fixed.
217---
218--- @param screen test.functional.ui.screen
219function M.override_screen_expect_for_conpty(screen)
220  if not t.is_os('win') then
221    return
222  end
223  local orig_screen_expect = screen.expect
224  function screen.expect(self, expected, attr_ids, ...)
225    if type(expected) == 'string' then
226      expected = expected:gsub(' *%} +%|\n', '{MATCH: *}}{MATCH: *}|\n')
227      expected = expected:gsub('%}%^ +%|\n', '{MATCH:[ ^]*}}{MATCH:[ ^]*}|\n')
228    end
229    orig_screen_expect(self, expected, attr_ids, ...)
230  end
231end
232
233--- Asserts that the exit code of chan eventually matches the expected exit code
234---
235--- @param code integer expected exit code
236--- @param chan? integer channel id, defaults to current buffer's channel
237function M.expect_exitcode(code, chan)
238  chan = chan or api.nvim_get_option_value('channel', { buf = 0 }) or 0
239  eq(true, chan > 0, 'Expected a valid channel ID, but got: ' .. chan)
240
241  retry(nil, nil, function()
242    local info = api.nvim_get_chan_info(chan)
243    eq(code, info.exitcode)
244  end)
245end
246
247return M