robin/laufey

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

Justin M. KeyesMerge #40865 from justinmk/fixcif907614088

master
13.5 KiB423 linesraw
1local t = require('test.testutil')
2local n = require('test.functional.testnvim')()
3local Screen = require('test.functional.ui.screen')
4local describe, it, before_each = t.describe, t.it, t.before_each
5local uv = vim.uv
6
7local clear, command, testprg = n.clear, n.command, n.testprg
8local eval, eq, neq, retry = n.eval, t.eq, t.neq, t.retry
9local exec_lua = n.exec_lua
10local matches = t.matches
11local ok = t.ok
12local feed = n.feed
13local api = n.api
14local pcall_err = t.pcall_err
15local assert_alive = n.assert_alive
16local skip = t.skip
17local is_os = t.is_os
18
19describe('autocmd TermClose', function()
20  before_each(function()
21    clear()
22    api.nvim_set_option_value('shell', testprg('shell-test'), {})
23    command('set shellcmdflag=EXE shellredir= shellpipe= shellquote= shellxquote=')
24    command('autocmd! nvim.terminal TermClose')
25  end)
26
27  local function test_termclose_delete_own_buf()
28    -- The terminal process needs to keep running so that TermClose isn't triggered immediately.
29    api.nvim_set_option_value('shell', string.format('"%s" INTERACT', testprg('shell-test')), {})
30    command('terminal')
31    local termbuf = api.nvim_get_current_buf()
32    command(('autocmd TermClose * bdelete! %d'):format(termbuf))
33    matches(
34      '^TermClose Autocommands for "%*": Vim%(bdelete%):E937: Attempt to delete a buffer that is in use: term://',
35      pcall_err(command, 'bdelete!')
36    )
37    assert_alive()
38  end
39
40  it('TermClose deleting its own buffer, altbuf = buffer 1 #10386', function()
41    test_termclose_delete_own_buf()
42  end)
43
44  it('TermClose deleting its own buffer, altbuf NOT buffer 1 #10386', function()
45    command('edit foo1')
46    test_termclose_delete_own_buf()
47  end)
48
49  it('TermClose deleting all other buffers', function()
50    local oldbuf = api.nvim_get_current_buf()
51    -- The terminal process needs to keep running so that TermClose isn't triggered immediately.
52    api.nvim_set_option_value('shell', string.format('"%s" INTERACT', testprg('shell-test')), {})
53    command(('autocmd TermClose * bdelete! %d'):format(oldbuf))
54    command('horizontal terminal')
55    neq(oldbuf, api.nvim_get_current_buf())
56    command('bdelete!')
57    feed('<C-G>') -- This shouldn't crash due to having a 0-line buffer.
58    assert_alive()
59  end)
60
61  it('TermClose switching back to terminal buffer', function()
62    local buf = api.nvim_get_current_buf()
63    api.nvim_open_term(buf, {})
64    command(('autocmd TermClose * buffer %d | new'):format(buf))
65    eq(
66      'TermClose Autocommands for "*": Vim(buffer):E1546: Cannot switch to a closing buffer',
67      pcall_err(command, 'bwipe!')
68    )
69    assert_alive()
70  end)
71
72  it('triggers when fast-exiting terminal job stops', function()
73    command('autocmd TermClose * let g:test_termclose = 23')
74    command('terminal')
75    -- shell-test exits immediately.
76    retry(nil, nil, function()
77      neq(-1, eval('jobwait([&channel], 0)[0]'))
78    end)
79    retry(nil, nil, function()
80      eq(23, eval('g:test_termclose'))
81    end)
82  end)
83
84  it('triggers when long-running terminal job gets stopped', function()
85    api.nvim_set_option_value('shell', is_os('win') and 'cmd.exe' or 'sh', {})
86    command('autocmd TermClose * let g:test_termclose = 23')
87    command('terminal')
88    command('call jobstop(b:terminal_job_id)')
89    retry(nil, nil, function()
90      eq(23, eval('g:test_termclose'))
91    end)
92  end)
93
94  it('kills job trapping SIGTERM', function()
95    skip(is_os('win'), 'N/A for Windows')
96    api.nvim_set_option_value('shell', 'sh', {})
97    api.nvim_set_option_value('shellcmdflag', '-c', {})
98    command(
99      [[ let g:test_job = jobstart('trap "" TERM && echo 1 && sleep 60', { ]]
100        .. [[ 'on_stdout': {-> execute('let g:test_job_started = 1')}, ]]
101        .. [[ 'on_exit': {-> execute('let g:test_job_exited = 1')}}) ]]
102    )
103    retry(nil, nil, function()
104      eq(1, eval('get(g:, "test_job_started", 0)'))
105    end)
106
107    uv.update_time()
108    local start = uv.now()
109    command('call jobstop(g:test_job)')
110    retry(nil, nil, function()
111      eq(1, eval('get(g:, "test_job_exited", 0)'))
112    end)
113    uv.update_time()
114    local duration = uv.now() - start
115    -- Nvim begins SIGTERM after KILL_TIMEOUT_MS.
116    ok(duration >= 2000)
117    ok(duration <= 4000) -- Epsilon for slow CI
118  end)
119
120  it('kills PTY job trapping SIGHUP and SIGTERM', function()
121    skip(is_os('win'), 'N/A for Windows')
122    api.nvim_set_option_value('shell', 'sh', {})
123    api.nvim_set_option_value('shellcmdflag', '-c', {})
124    command(
125      [[ let g:test_job = jobstart('trap "" HUP TERM && echo 1 && sleep 60', { ]]
126        .. [[ 'pty': 1,]]
127        .. [[ 'on_stdout': {-> execute('let g:test_job_started = 1')}, ]]
128        .. [[ 'on_exit': {-> execute('let g:test_job_exited = 1')}}) ]]
129    )
130    retry(nil, nil, function()
131      eq(1, eval('get(g:, "test_job_started", 0)'))
132    end)
133
134    uv.update_time()
135    local start = uv.now()
136    command('call jobstop(g:test_job)')
137    retry(nil, nil, function()
138      eq(1, eval('get(g:, "test_job_exited", 0)'))
139    end)
140    uv.update_time()
141    local duration = uv.now() - start
142    -- Nvim begins SIGKILL after (2 * KILL_TIMEOUT_MS).
143    ok(duration >= 4000)
144    ok(duration <= 7000) -- Epsilon for slow CI
145  end)
146
147  it('reports the correct <abuf>', function()
148    command('set hidden')
149    command('set shellcmdflag=EXE')
150    command('autocmd TermClose * let g:abuf = expand("<abuf>")')
151    command('edit foo')
152    command('edit bar')
153    eq(2, eval('bufnr("%")'))
154
155    command('terminal ls')
156    retry(nil, nil, function()
157      eq(3, eval('bufnr("%")'))
158    end)
159
160    command('buffer 1')
161    retry(nil, nil, function()
162      eq(1, eval('bufnr("%")'))
163    end)
164
165    command('3bdelete!')
166    retry(nil, nil, function()
167      eq('3', eval('g:abuf'))
168    end)
169    feed('<c-c>')
170    n.poke_eventloop() -- Wait for input to be flushed
171    n.expect_exit(n.load_adjust(1000), feed, ':qa!<cr>')
172  end)
173
174  it('exposes v:event.status', function()
175    command('set shellcmdflag=EXIT')
176    command('autocmd TermClose * let g:status = v:event.status')
177
178    command('terminal 0')
179    retry(nil, nil, function()
180      eq(0, eval('g:status'))
181    end)
182
183    command('terminal 42')
184    retry(nil, nil, function()
185      eq(42, eval('g:status'))
186    end)
187
188    command('set shellcmdflag= | terminal INTERACT')
189    retry(nil, nil, function()
190      matches('^interact %$ ?$', api.nvim_buf_get_lines(0, 0, 1, true)[1])
191    end)
192    command('bwipe!')
193    eq(-1, eval('g:status'))
194  end)
195end)
196
197it('autocmd TermEnter, TermLeave', function()
198  clear()
199  command('let g:evs = []')
200  command('autocmd TermOpen  * call add(g:evs, ["TermOpen", mode()])')
201  command('autocmd TermClose * call add(g:evs, ["TermClose", mode()])')
202  command('autocmd TermEnter * call add(g:evs, ["TermEnter", mode()])')
203  command('autocmd TermLeave * call add(g:evs, ["TermLeave", mode()])')
204  command('terminal')
205
206  feed('i')
207  eq({ { 'TermOpen', 'n' }, { 'TermEnter', 't' } }, eval('g:evs'))
208  feed([[<C-\><C-n>]])
209  feed('A')
210  eq(
211    { { 'TermOpen', 'n' }, { 'TermEnter', 't' }, { 'TermLeave', 'n' }, { 'TermEnter', 't' } },
212    eval('g:evs')
213  )
214
215  -- TermLeave is also triggered by :quit.
216  command('split foo')
217  feed('<Ignore>') -- Add input to separate two RPC requests
218  command('wincmd w')
219  feed('i')
220  command('q!')
221  feed('<Ignore>') -- Add input to separate two RPC requests
222  eq({
223    { 'TermOpen', 'n' },
224    { 'TermEnter', 't' },
225    { 'TermLeave', 'n' },
226    { 'TermEnter', 't' },
227    { 'TermLeave', 'n' },
228    { 'TermEnter', 't' },
229    { 'TermClose', 't' },
230    { 'TermLeave', 'n' },
231  }, eval('g:evs'))
232end)
233
234describe('autocmd TextChangedT,WinResized', function()
235  before_each(clear)
236
237  it('TextChangedT works', function()
238    local screen = Screen.new(50, 7)
239    screen:set_default_attr_ids({
240      [1] = { bold = true },
241      [31] = { foreground = Screen.colors.Gray100, background = Screen.colors.DarkGreen },
242      [32] = {
243        foreground = Screen.colors.Gray100,
244        bold = true,
245        background = Screen.colors.DarkGreen,
246      },
247    })
248
249    local term, term_unfocused = exec_lua(function()
250      -- Split windows before opening terminals so TextChangedT doesn't fire an additional time due
251      -- to the inner terminal being resized (which is usually deferred too).
252      vim.cmd.vnew()
253      local term_unfocused = vim.api.nvim_open_term(0, {})
254      vim.cmd.wincmd 'p'
255      local term = vim.api.nvim_open_term(0, {})
256      vim.cmd.startinsert()
257      return term, term_unfocused
258    end)
259    eq('t', eval('mode()'))
260
261    exec_lua(function()
262      _G.n_triggered = 0
263      vim.api.nvim_create_autocmd('TextChanged', {
264        callback = function()
265          _G.n_triggered = _G.n_triggered + 1
266        end,
267      })
268      _G.t_triggered = 0
269      vim.api.nvim_create_autocmd('TextChangedT', {
270        callback = function()
271          _G.t_triggered = _G.t_triggered + 1
272        end,
273      })
274    end)
275
276    api.nvim_chan_send(term, 'a')
277    retry(nil, nil, function()
278      eq(1, exec_lua('return _G.t_triggered'))
279    end)
280    api.nvim_chan_send(term, 'b')
281    retry(nil, nil, function()
282      eq(2, exec_lua('return _G.t_triggered'))
283    end)
284
285    -- Not triggered by changes in a non-current terminal.
286    api.nvim_chan_send(term_unfocused, 'hello')
287    screen:expect([[
288      hello                    │ab^                      |
289                               │                        |*4
290      {31:[Scratch] [-]             }{32:[Scratch] [-]           }|
291      {1:-- TERMINAL --}                                    |
292    ]])
293    eq(2, exec_lua('return _G.t_triggered'))
294
295    -- Not triggered by unflushed redraws.
296    api.nvim__redraw({ valid = false, flush = false })
297    eq(2, exec_lua('return _G.t_triggered'))
298
299    -- Not triggered when not in terminal mode.
300    command('stopinsert')
301    eq('n', eval('mode()'))
302    eq(2, exec_lua('return _G.t_triggered'))
303    eq(0, exec_lua('return _G.n_triggered')) -- Nothing we did was in Normal mode yet.
304
305    api.nvim_chan_send(term, 'c')
306    screen:expect([[
307      hello                    │a^bc                     |
308                               │                        |*4
309      {31:[Scratch] [-]             }{32:[Scratch] [-]           }|
310                                                        |
311    ]])
312    eq(1, exec_lua('return _G.n_triggered')) -- Happened in Normal mode.
313  end)
314
315  it('no crash when deleting terminal buffer', function()
316    -- Using nvim_open_term over :terminal as the former can free the terminal immediately on
317    -- close, causing the crash.
318
319    -- WinResized
320    local buf1, term1 = exec_lua(function()
321      vim.cmd.new()
322      local buf = vim.api.nvim_get_current_buf()
323      local term = vim.api.nvim_open_term(0, {
324        on_input = function()
325          vim.cmd.wincmd '_'
326        end,
327      })
328      vim.api.nvim_create_autocmd('WinResized', {
329        once = true,
330        command = 'bwipeout!',
331      })
332      return buf, term
333    end)
334    feed('ii')
335    eq(false, api.nvim_buf_is_valid(buf1))
336    eq('n', eval('mode()'))
337    eq({}, api.nvim_get_chan_info(term1)) -- Channel should've been cleaned up.
338
339    -- TextChangedT
340    local buf2, term2 = exec_lua(function()
341      vim.cmd.new()
342      local buf = vim.api.nvim_get_current_buf()
343      local term = vim.api.nvim_open_term(0, {
344        on_input = function(_, chan)
345          vim.api.nvim_chan_send(chan, 'sup')
346        end,
347      })
348      vim.api.nvim_create_autocmd('TextChangedT', {
349        once = true,
350        command = 'bwipeout!',
351      })
352      return buf, term
353    end)
354    feed('ii')
355    -- refresh_terminal is deferred, so TextChangedT may not trigger immediately.
356    retry(nil, nil, function()
357      eq(false, api.nvim_buf_is_valid(buf2))
358    end)
359    eq('n', eval('mode()'))
360    eq({}, api.nvim_get_chan_info(term2)) -- Channel should've been cleaned up.
361  end)
362end)
363
364describe('no crash if :bwipe from TermClose is processed by', function()
365  local oldwin --- @type integer
366  local chan --- @type integer
367
368  before_each(function()
369    clear()
370    command('autocmd! nvim.terminal')
371    oldwin = api.nvim_get_current_win()
372    command('new')
373    local buf = api.nvim_get_current_buf()
374    chan = api.nvim_open_term(buf, {})
375    api.nvim_set_var('chan', chan)
376    command(('autocmd TermClose <buffer> bwipe! %d'):format(buf))
377    command('let g:done = 0')
378    feed('i')
379    eq({ mode = 't', blocking = false }, api.nvim_get_mode())
380  end)
381
382  --- @param event string Event name.
383  --- @param trigger_cmd string The Ex command to trigger the event.
384  local function test_case(event, trigger_cmd)
385    api.nvim_create_autocmd(
386      event,
387      { nested = true, once = true, command = 'sleep 40m | let g:done = 1' }
388    )
389    exec_lua(function()
390      vim.cmd(trigger_cmd)
391      vim.defer_fn(function()
392        vim.fn.chanclose(chan)
393      end, 25)
394    end)
395    retry(nil, 1000, function()
396      eq(1, api.nvim_get_var('done'))
397    end)
398    assert_alive()
399    eq({ mode = 'n', blocking = false }, api.nvim_get_mode())
400    eq({ oldwin }, api.nvim_list_wins())
401    feed('<Ignore>') -- Add input to separate two RPC requests.
402    -- Channel should have been released.
403    eq({}, api.nvim_get_chan_info(chan))
404  end
405
406  it('WinResized autocommand in Terminal mode', function()
407    test_case('WinResized', 'vsplit')
408  end)
409
410  it('TextChangedT autocommand in Terminal mode', function()
411    test_case('TextChangedT', [[call chansend(g:chan, "foo\r\nbar")]])
412  end)
413
414  it('TermRequest autocommand in Terminal mode', function()
415    test_case('TermRequest', [[call chansend(g:chan, "\x1b]11;?\x1b\\")]])
416  end)
417
418  it('TermRequest autocommand in Normal mode', function()
419    feed([[<C-\><C-N>]])
420    eq({ mode = 'nt', blocking = false }, api.nvim_get_mode())
421    test_case('TermRequest', [[call chansend(g:chan, "\x1b]11;?\x1b\\")]])
422  end)
423end)