robin/laufey

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

Justin M. KeyesMerge #40865 from justinmk/fixcif907614088

master
18.5 KiB604 linesraw
1local t = require('test.testutil')
2local n = require('test.functional.testnvim')()
3
4local describe, it, before_each, finally = t.describe, t.it, t.before_each, t.finally
5local clear, eq, eval, next_msg, ok, source = n.clear, t.eq, n.eval, n.next_msg, t.ok, n.source
6local command, fn, api = n.command, n.fn, n.api
7local feed = n.feed
8local exec_lua = n.exec_lua
9local matches = t.matches
10local sleep = vim.uv.sleep
11local get_session, set_session = n.get_session, n.set_session
12local nvim_prog = n.nvim_prog
13local is_os = t.is_os
14local retry = t.retry
15local expect_twostreams = n.expect_twostreams
16local assert_alive = n.assert_alive
17local pcall_err = t.pcall_err
18local skip = t.skip
19
20describe('channels', function()
21  local init = [[
22    function! Normalize(data) abort
23      " Windows: remove ^M
24      return type([]) == type(a:data)
25        \ ? mapnew(a:data, 'substitute(v:val, "\r", "", "g")')
26        \ : a:data
27    endfunction
28    function! OnEvent(id, data, event) dict
29      call rpcnotify(1, a:event, a:id, a:data)
30    endfunction
31  ]]
32  before_each(function()
33    clear()
34    source(init)
35  end)
36
37  it('can connect to socket', function()
38    local server = n.new_session(true)
39    set_session(server)
40    local address = fn.serverlist()[1]
41    local client = n.new_session(true)
42    set_session(client)
43    source(init)
44
45    api.nvim_set_var('address', address)
46    command("let g:id = sockconnect('pipe', address, {'on_data':'OnEvent'})")
47    local id = eval('g:id')
48    ok(id > 0)
49
50    command("call chansend(g:id, msgpackdump([[2,'nvim_set_var',['code',23]]]))")
51    set_session(server)
52    retry(nil, 1000, function()
53      eq(23, api.nvim_get_var('code'))
54    end)
55    set_session(client)
56
57    command("call chansend(g:id, msgpackdump([[0,0,'nvim_eval',['2+3']]]))")
58
59    local res = eval('msgpackdump([[1,0,v:null,5]])')
60    eq({ '\148\001\n\192\005' }, res)
61    eq({ 'notification', 'data', { id, res } }, next_msg())
62    command("call chansend(g:id, msgpackdump([[2,'nvim_command',['quit']]]))")
63    eq({ 'notification', 'data', { id, { '' } } }, next_msg())
64  end)
65
66  it('emits ChanClose when RPC socket reaches EOF', function()
67    local client = get_session()
68    local server = n.new_session(true)
69    finally(function()
70      set_session(client)
71      if server then
72        server:close()
73      end
74    end)
75    set_session(server)
76    local address = fn.serverlist()[1]
77    set_session(client)
78
79    api.nvim_set_var('address', address)
80    exec_lua(function()
81      _G.closed_event = nil
82      vim.api.nvim_create_autocmd('ChanClose', {
83        callback = function()
84          _G.closed_event = vim.deepcopy(vim.v.event.info)
85        end,
86      })
87    end)
88    command("let g:id = sockconnect('pipe', address, {'rpc': v:true})")
89    local id = eval('g:id')
90    ok(id > 0)
91    eq(5, eval("rpcrequest(g:id, 'nvim_eval', '2+3')"))
92
93    server:close()
94    server = nil
95    set_session(client)
96    retry(nil, 3000, function()
97      local info = exec_lua(function()
98        return _G.closed_event
99      end)
100      eq(id, info.id)
101      eq('socket', info.stream)
102      eq('rpc', info.mode)
103    end)
104  end)
105
106  it('dont crash due to garbage in rpc #23781', function()
107    local client = get_session()
108    local server = n.new_session(true)
109    set_session(server)
110    local address = fn.serverlist()[1]
111    set_session(client)
112
113    api.nvim_set_var('address', address)
114    command("let g:id = sockconnect('pipe', address, {'on_data':'OnEvent'})")
115    local id = eval('g:id')
116    ok(id > 0)
117
118    command("call chansend(g:id, 'F')")
119    eq({ 'notification', 'data', { id, { '' } } }, next_msg())
120    set_session(server)
121    assert_alive()
122
123    set_session(client)
124    command('call chanclose(g:id)')
125    command("let g:id = sockconnect('pipe', address, {'on_data':'OnEvent'})")
126    id = eval('g:id')
127    ok(id > 0)
128
129    command("call chansend(g:id, msgpackdump([[2, 'redraw', 'F']], 'B')[:-4])")
130    set_session(server)
131    assert_alive()
132    set_session(client)
133    command("call chansend(g:id, 'F')")
134    eq({ 'notification', 'data', { id, { '' } } }, next_msg())
135
136    set_session(server)
137    assert_alive()
138    set_session(client)
139    command('call chanclose(g:id)')
140    server:close()
141  end)
142
143  it('can use stdio channel', function()
144    source([[
145      let g:job_opts = {
146      \ 'on_stdout': function('OnEvent'),
147      \ 'on_stderr': function('OnEvent'),
148      \ 'on_exit': function('OnEvent'),
149      \ }
150    ]])
151    api.nvim_set_var('nvim_prog', nvim_prog)
152    api.nvim_set_var(
153      'code',
154      [[
155      function! OnEvent(id, data, event) dict
156        let text = string([a:id, a:data, a:event])
157        call chansend(g:x, text)
158
159        if a:data == ['']
160          call chansend(v:stderr, "*dies*")
161          quit
162        endif
163      endfunction
164      let g:x = stdioopen({'on_stdin':'OnEvent'})
165      call chansend(x, "hello")
166    ]]
167    )
168    command(
169      "let g:id = jobstart([ g:nvim_prog, '-u', 'NONE', '-i', 'NONE', '--cmd', 'set noswapfile', '--headless', '--cmd', g:code], g:job_opts)"
170    )
171    local id = eval('g:id')
172    ok(id > 0)
173
174    eq({ 'notification', 'stdout', { id, { 'hello' } } }, next_msg())
175
176    command("call chansend(id, 'howdy')")
177    eq({ 'notification', 'stdout', { id, { "[1, ['howdy'], 'stdin']" } } }, next_msg())
178
179    command('call chansend(id, 0z686f6c61)')
180    eq({ 'notification', 'stdout', { id, { "[1, ['hola'], 'stdin']" } } }, next_msg())
181
182    command("call chanclose(id, 'stdin')")
183    expect_twostreams({
184      { 'notification', 'stdout', { id, { "[1, [''], 'stdin']" } } },
185      { 'notification', 'stdout', { id, { '' } } },
186    }, {
187      { 'notification', 'stderr', { id, { '*dies*' } } },
188      { 'notification', 'stderr', { id, { '' } } },
189    })
190    eq({ 'notification', 'exit', { 3, 0 } }, next_msg())
191  end)
192
193  it('can use stdio channel and on_print callback', function()
194    source([[
195      let g:job_opts = {
196      \ 'on_stdout': function('OnEvent'),
197      \ 'on_stderr': function('OnEvent'),
198      \ 'on_exit': function('OnEvent'),
199      \ }
200    ]])
201    api.nvim_set_var('nvim_prog', nvim_prog)
202    api.nvim_set_var(
203      'code',
204      [[
205      function! OnStdin(id, data, event) dict
206        echo string([a:id, a:data, a:event])
207        if a:data == ['']
208          quit
209        endif
210      endfunction
211      function! OnPrint(text) dict
212        call chansend(g:x, ['OnPrint:' .. a:text])
213      endfunction
214      let g:x = stdioopen({'on_stdin': funcref('OnStdin'), 'on_print':'OnPrint'})
215      call chansend(x, "hello")
216    ]]
217    )
218    command(
219      "let g:id = jobstart([ g:nvim_prog, '-u', 'NONE', '-i', 'NONE', '--cmd', 'set noswapfile', '--headless', '--cmd', g:code], g:job_opts)"
220    )
221    local id = eval('g:id')
222    ok(id > 0)
223
224    eq({ 'notification', 'stdout', { id, { 'hello' } } }, next_msg())
225
226    command("call chansend(id, 'howdy')")
227    eq({ 'notification', 'stdout', { id, { "OnPrint:[1, ['howdy'], 'stdin']" } } }, next_msg())
228  end)
229
230  -- Helper to accumulate PTY stdout data until expected string is received.
231  -- PTY reads are non-atomic and may deliver data in chunks.
232  local function expect_stdout(id, expected)
233    local accumulated = ''
234    while #accumulated < #expected do
235      local msg = next_msg(1000)
236      if not msg then
237        break
238      end
239      eq('notification', msg[1])
240      eq('stdout', msg[2])
241      eq(id, msg[3][1])
242      accumulated = accumulated .. table.concat(msg[3][2], '\n')
243      -- Windows: strip terminal escapes injected by ConPTY (CSI/OSC).
244      accumulated = accumulated:gsub('\27%[[%d;?]*[%a~]', ''):gsub('\27%][^\7]*\7', '')
245    end
246    eq(expected, accumulated)
247  end
248
249  it('can use stdio channel with pty', function()
250    source([[
251      let g:job_opts = {
252      \ 'on_stdout': function('OnEvent'),
253      \ 'on_exit': function('OnEvent'),
254      \ 'pty': v:true,
255      \ }
256    ]])
257    api.nvim_set_var('nvim_prog', nvim_prog)
258    api.nvim_set_var(
259      'code',
260      [[
261      function! OnEvent(id, data, event) dict
262        let text = string([a:id, a:data, a:event])
263        call chansend(g:x, text)
264      endfunction
265      let g:x = stdioopen({'on_stdin':'OnEvent'})
266    ]]
267    )
268    command(
269      "let g:id = jobstart([ g:nvim_prog, '-u', 'NONE', '-i', 'NONE', '--cmd', 'set noswapfile', '--headless', '--cmd', g:code], g:job_opts)"
270    )
271    local id = eval('g:id')
272    ok(id > 0)
273
274    -- Windows ConPTY does not echo input to the master, unlike POSIX ptys.
275    local echo_text = is_os('win') and '' or 'TEXT\r\n'
276    local echo_blobs = is_os('win') and '' or 'Blobs!\r\n'
277
278    command("call chansend(id, 'TEXT\n')")
279    expect_stdout(id, echo_text .. "[1, ['TEXT', ''], 'stdin']")
280
281    command('call chansend(id, 0z426c6f6273210a)')
282    expect_stdout(id, echo_blobs .. "[1, ['Blobs!', ''], 'stdin']")
283
284    -- Windows: the assertions below depend on POSIX pty canonical-mode behavior (echo, backspace handling, EOT-as-EOF).
285    if is_os('win') then
286      return
287    end
288
289    command("call chansend(id, 'neovan')")
290    expect_stdout(id, 'neovan')
291    command("call chansend(id, '\127\127im\n')")
292    expect_stdout(id, "\b \b\b \bim\r\n[1, ['neovim', ''], 'stdin']")
293
294    command("call chansend(id, 'incomplet\004')")
295
296    local bsdlike = is_os('bsd') or is_os('mac')
297    local extra = bsdlike and '^D\008\008' or ''
298    expect_stdout(id, 'incomplet' .. extra .. "[1, ['incomplet'], 'stdin']")
299
300    command("call chansend(id, '\004')")
301    expect_stdout(id, extra .. "[1, [''], 'stdin']")
302
303    -- channel is still open
304    command("call chansend(id, 'hi again!\n')")
305    expect_stdout(id, 'hi again!\r\n')
306  end)
307
308  it('stdio channel can use rpc and stderr simultaneously', function()
309    source([[
310      let g:job_opts = {
311      \ 'on_stderr': function('OnEvent'),
312      \ 'on_exit': function('OnEvent'),
313      \ 'rpc': v:true,
314      \ }
315    ]])
316    api.nvim_set_var('nvim_prog', nvim_prog)
317    api.nvim_set_var(
318      'code',
319      [[
320      let id = stdioopen({'rpc':v:true})
321      call rpcnotify(id,"nvim_call_function", "rpcnotify", [1, "message", "hi there!", id])
322      call chansend(v:stderr, "trouble!")
323    ]]
324    )
325    command(
326      "let id = jobstart([ g:nvim_prog, '-u', 'NONE', '-i', 'NONE', '--cmd', 'set noswapfile', '--headless', '--cmd', g:code], g:job_opts)"
327    )
328    -- On Windows the stderr write may be delivered before the RPC notify.
329    local notif1 = { 'notification', 'message', { 'hi there!', 1 } }
330    local notif2 = { 'notification', 'stderr', { 3, { 'trouble!' } } }
331    n.expect_msg_seq({ notif1, notif2 }, { notif2, notif1 })
332
333    eq(30, eval("rpcrequest(id, 'nvim_eval', '[chansend(v:stderr, \"math??\"), 5*6][1]')"))
334    eq({ 'notification', 'stderr', { 3, { 'math??' } } }, next_msg())
335
336    local _, err =
337      pcall(command, "call rpcrequest(id, 'nvim_command', 'call chanclose(v:stderr, \"stdin\")')")
338    matches('E906: invalid stream for channel', err)
339
340    eq(1, eval("rpcrequest(id, 'nvim_eval', 'chanclose(v:stderr, \"stderr\")')"))
341    eq({ 'notification', 'stderr', { 3, { '' } } }, next_msg())
342
343    command("call rpcnotify(id, 'nvim_command', 'quit')")
344    eq({ 'notification', 'exit', { 3, 0 } }, next_msg())
345  end)
346
347  it('stdio channel works with stdout redirected to file #30509', function()
348    t.write_file(
349      'Xstdio_write.vim',
350      [[
351        let chan = stdioopen({})
352        call chansend(chan, 'foo')
353        call chansend(chan, 'bar')
354        qall!
355      ]]
356    )
357    local fd = assert(vim.uv.fs_open('Xstdio_redir', 'w', 420))
358    local exit_code, exit_signal
359    local handle = vim.uv.spawn(nvim_prog, {
360      args = { '-u', 'NONE', '-i', 'NONE', '--headless', '-S', 'Xstdio_write.vim' },
361      -- Simulate shell redirection: "nvim ... > Xstdio_redir". #30509
362      stdio = { nil, fd, nil },
363    }, function(code, signal)
364      vim.uv.stop()
365      exit_code, exit_signal = code, signal
366    end)
367    finally(function()
368      handle:close()
369      vim.uv.fs_close(fd)
370      os.remove('Xstdio_write.vim')
371      os.remove('Xstdio_redir')
372    end)
373    vim.uv.run('default')
374    eq({ 0, 0 }, { exit_code, exit_signal })
375    eq('foobar', t.read_file('Xstdio_redir'))
376  end)
377
378  it('can use buffered output mode', function()
379    skip(fn.executable('grep') == 0, 'missing "grep" command')
380    source([[
381      let g:job_opts = {
382      \ 'on_stdout': function('OnEvent'),
383      \ 'on_exit': function('OnEvent'),
384      \ 'stdout_buffered': v:true,
385      \ }
386    ]])
387    command("let id = jobstart(['grep', '^[0-9]'], g:job_opts)")
388    local id = eval('g:id')
389
390    command([[call chansend(id, "stuff\n10 PRINT \"NVIM\"\nxx")]])
391    sleep(10)
392    command([[call chansend(id, "xx\n20 GOTO 10\nzz\n")]])
393    command("call chanclose(id, 'stdin')")
394
395    eq({
396      'notification',
397      'stdout',
398      { id, { '10 PRINT "NVIM"', '20 GOTO 10', '' } },
399    }, next_msg())
400    eq({ 'notification', 'exit', { id, 0 } }, next_msg())
401
402    command("let id = jobstart(['grep', '^[0-9]'], g:job_opts)")
403    id = eval('g:id')
404
405    command([[call chansend(id, "is no number\nnot at all")]])
406    command("call chanclose(id, 'stdin')")
407
408    -- works correctly with no output
409    eq({ 'notification', 'stdout', { id, { '' } } }, next_msg())
410    eq({ 'notification', 'exit', { id, 1 } }, next_msg())
411  end)
412
413  it('can use buffered output mode with no stream callback', function()
414    skip(fn.executable('grep') == 0, 'missing "grep" command')
415    source([[
416      function! OnEvent(id, data, event) dict
417        call rpcnotify(1, a:event, a:id, a:data, self.stdout)
418      endfunction
419      let g:job_opts = {
420      \ 'on_exit': function('OnEvent'),
421      \ 'stdout_buffered': v:true,
422      \ }
423    ]])
424    command("let id = jobstart(['grep', '^[0-9]'], g:job_opts)")
425    local id = eval('g:id')
426
427    command([[call chansend(id, "stuff\n10 PRINT \"NVIM\"\nxx")]])
428    sleep(10)
429    command([[call chansend(id, "xx\n20 GOTO 10\nzz\n")]])
430    command("call chanclose(id, 'stdin')")
431
432    eq({
433      'notification',
434      'exit',
435      { id, 0, { '10 PRINT "NVIM"', '20 GOTO 10', '' } },
436    }, next_msg())
437
438    -- if dict is reused the new value is not stored,
439    -- but nvim also does not crash
440    command("let id = jobstart(['cat'], g:job_opts)")
441    id = eval('g:id')
442
443    command([[call chansend(id, "cat text\n")]])
444    sleep(10)
445    command("call chanclose(id, 'stdin')")
446
447    -- old value was not overwritten
448    eq({
449      'notification',
450      'exit',
451      { id, 0, { '10 PRINT "NVIM"', '20 GOTO 10', '' } },
452    }, next_msg())
453
454    -- and an error was thrown.
455    eq(
456      "E5210: dict key 'stdout' already set for buffered stream in channel " .. id,
457      eval('v:errmsg')
458    )
459
460    -- reset dictionary
461    source([[
462      let g:job_opts = {
463      \ 'on_exit': function('OnEvent'),
464      \ 'stdout_buffered': v:true,
465      \ }
466    ]])
467    command("let id = jobstart(['grep', '^[0-9]'], g:job_opts)")
468    id = eval('g:id')
469
470    command([[call chansend(id, "is no number\nnot at all")]])
471    command("call chanclose(id, 'stdin')")
472
473    -- works correctly with no output
474    eq({ 'notification', 'exit', { id, 1, { '' } } }, next_msg())
475  end)
476
477  it('ChanOpen works with vim.wait() from another autocommand #32706', function()
478    exec_lua([[
479      vim.api.nvim_create_autocmd('ChanOpen', {
480        callback = function(ev)
481          _G.chan = vim.v.event.info.id
482        end,
483      })
484      vim.api.nvim_create_autocmd('InsertEnter', {
485        buf = 0,
486        callback = function()
487          local chan = vim.fn.jobstart({ 'cat' })
488          _G.result = vim.wait(3000, function()
489            return _G.chan == chan
490          end)
491        end,
492      })
493    ]])
494    feed('i')
495    retry(nil, 4000, function()
496      eq(true, exec_lua('return _G.result'))
497    end)
498  end)
499
500  it('ChanInfo works with vim.wait() from another autocommand #32706', function()
501    exec_lua([[
502      vim.api.nvim_create_autocmd('ChanInfo', {
503        callback = function(ev)
504          _G.foo = vim.v.event.info.client.attributes.foo
505        end,
506      })
507      vim.api.nvim_create_autocmd('InsertEnter', {
508        buf = 0,
509        callback = function()
510          local chan = vim.fn.jobstart({ 'cat' })
511          _G.result = vim.wait(3000, function()
512            return _G.foo == 'bar'
513          end)
514        end,
515      })
516    ]])
517    feed('i')
518    api.nvim_set_client_info('test', {}, 'remote', {}, { foo = 'bar' })
519    retry(nil, 4000, function()
520      eq(true, exec_lua('return _G.result'))
521    end)
522  end)
523
524  describe('sockconnect() reports error when connection fails', function()
525    it('in "pipe" mode', function()
526      eq(
527        'Vim:connection failed: connection refused',
528        pcall_err(fn.sockconnect, 'pipe', n.new_pipename())
529      )
530    end)
531
532    it('in "tcp" mode', function()
533      eq(
534        'Vim:connection failed: connection refused',
535        pcall_err(fn.sockconnect, 'tcp', '127.0.0.1:0')
536      )
537    end)
538
539    it('with another connection accepted while polling #37807', function()
540      local server = api.nvim_get_vvar('servername')
541      local invalid_pipe = n.new_pipename()
542      exec_lua(function()
543        vim.defer_fn(function()
544          vim.uv.sleep(50) -- Block the uv event loop.
545          vim.fn.sockconnect('pipe', invalid_pipe)
546        end, 10)
547      end)
548      vim.uv.sleep(20)
549      -- The server uv event loop is currently blocked, so the connection will
550      -- be accepted when sockconnect() polls.
551      local other_session = n.connect(server)
552      eq({ true, { 1000 } }, { other_session:request('nvim_list_wins') })
553      other_session:close()
554      matches(
555        '^vim.schedule callback: Vim:connection failed: connection refused\n',
556        api.nvim_get_vvar('errmsg')
557      )
558    end)
559  end)
560
561  it('no stack-buffer-overflow with Nvim exit during connection #39387', function()
562    local nvim0 = n.get_session()
563    -- Need a valid pipe so that connecting to it doesn't fail immediately.
564    local server = fn.serverstart()
565    finally(function()
566      nvim0:close()
567    end)
568
569    n.set_session(n.new_session(true))
570    exec_lua(function()
571      vim.defer_fn(function()
572        vim.uv.sleep(50) -- Block the uv event loop.
573        vim.fn.sockconnect('pipe', server)
574      end, 10)
575    end)
576    vim.uv.sleep(20)
577    -- The server uv event loop is currently blocked, so the channel close will
578    -- be processed when sockconnect() polls.
579    n.check_close()
580  end)
581end)
582
583describe('loopback', function()
584  before_each(function()
585    clear()
586    command("let chan = sockconnect('pipe', v:servername, {'rpc': v:true})")
587  end)
588
589  it('does not crash when sending raw data', function()
590    eq(
591      "Vim(call):Can't send raw data to rpc channel",
592      pcall_err(command, "call chansend(chan, 'test')")
593    )
594    assert_alive()
595  end)
596
597  it('are released when closed', function()
598    local chans = eval('len(nvim_list_chans())')
599    command('call chanclose(chan)')
600    n.poke_eventloop() -- Process rpc_close_event().
601    -- Channel has been released after processing free_channel_event().
602    eq(chans - 1, eval('len(nvim_list_chans())'))
603  end)
604end)