robin/laufey

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

Justin M. KeyesMerge #40865 from justinmk/fixcif907614088

master
47.7 KiB1444 linesraw
1local t = require('test.testutil')
2local n = require('test.functional.testnvim')()
3local Screen = require('test.functional.ui.screen')
4local tt = require('test.functional.testterm')
5
6local describe, it, before_each, pending, finally =
7  t.describe, t.it, t.before_each, t.pending, t.finally
8local clear = n.clear
9local eq = t.eq
10local eval = n.eval
11local feed_command = n.feed_command
12local feed = n.feed
13local insert = n.insert
14local neq = t.neq
15local next_msg = n.next_msg
16local testprg = n.testprg
17local ok = t.ok
18local source = n.source
19local write_file = t.write_file
20local mkdir = t.mkdir
21local rmdir = n.rmdir
22local assert_alive = n.assert_alive
23local command = n.command
24local fn = n.fn
25local retry = t.retry
26local api = n.api
27local NIL = vim.NIL
28local poke_eventloop = n.poke_eventloop
29local get_pathsep = n.get_pathsep
30local pathroot = n.pathroot
31local exec_lua = n.exec_lua
32local nvim_set = n.nvim_set
33local expect_twostreams = n.expect_twostreams
34local expect_msg_seq = n.expect_msg_seq
35local pcall_err = t.pcall_err
36local matches = t.matches
37local skip = t.skip
38local is_os = t.is_os
39
40describe('jobs', function()
41  local channel
42
43  before_each(function()
44    clear()
45
46    channel = api.nvim_get_chan_info(0).id
47    api.nvim_set_var('channel', channel)
48    source([[
49    function! Normalize(data) abort
50      " Windows: remove ^M and term escape sequences
51      return type([]) == type(a:data)
52        \ ? mapnew(a:data, 'substitute(substitute(v:val, "\r", "", "g"), "\x1b\\%(\\]\\d\\+;.\\{-}\x07\\|\\[.\\{-}[\x40-\x7E]\\)", "", "g")')
53        \ : a:data
54    endfunction
55    function! OnEvent(id, data, event) dict
56      let userdata = get(self, 'user')
57      let data     = Normalize(a:data)
58      " If Normalize() made non-empty data empty, doesn't send a notification.
59      if type([]) == type(data) && len(data) == 1 && !empty(a:data[0]) && empty(data[0])
60        return
61      endif
62      call rpcnotify(g:channel, a:event, userdata, data)
63    endfunction
64    let g:job_opts = {
65    \ 'on_stdout': function('OnEvent'),
66    \ 'on_exit': function('OnEvent'),
67    \ 'user': 0
68    \ }
69    ]])
70  end)
71
72  it('validation', function()
73    matches(
74      "E475: Invalid argument: job cannot have both 'pty' and 'rpc' options set",
75      pcall_err(command, "call jobstart(['cat', '-'], { 'pty': v:true, 'rpc': v:true })")
76    )
77    matches(
78      'E475: Invalid argument: expected valid directory',
79      pcall_err(command, "call jobstart(['cat', '-'], { 'cwd': 9313843 })")
80    )
81    matches(
82      'E475: Invalid argument: expected valid directory',
83      pcall_err(command, "call jobstart(['cat', '-'], { 'cwd': 'bogusssssss/bogus' })")
84    )
85    matches(
86      "E475: Invalid argument: 'term' must be Boolean",
87      pcall_err(command, "call jobstart(['cat', '-'], { 'term': 'bogus' })")
88    )
89    matches(
90      "E475: Invalid argument: 'term' must be Boolean",
91      pcall_err(command, "call jobstart(['cat', '-'], { 'term': 1 })")
92    )
93    command('set modified')
94    matches(
95      vim.pesc('jobstart(...,{term=true}) requires unmodified buffer'),
96      pcall_err(command, "call jobstart(['cat', '-'], { 'term': v:true })")
97    )
98
99    -- Non-failure cases:
100    command('set nomodified')
101    command("call jobstart(['cat', '-'], { 'term': v:true })")
102    command("call jobstart(['cat', '-'], { 'term': v:false })")
103  end)
104
105  it('jobstart(term=true) accepts width/height (#33904)', function()
106    local buf = api.nvim_create_buf(false, true)
107    exec_lua(function()
108      vim.api.nvim_buf_call(buf, function()
109        vim.fn.jobstart({
110          vim.v.progpath,
111          '--clean',
112          '--headless',
113          '+lua tty = vim.uv.new_tty(1, false) print(tty:get_winsize()) tty:close()',
114        }, {
115          term = true,
116          width = 11,
117          height = 12,
118          env = { VIMRUNTIME = os.getenv('VIMRUNTIME') },
119        })
120      end)
121    end)
122    retry(nil, nil, function()
123      eq({ '11 12' }, api.nvim_buf_get_lines(buf, 0, 1, false))
124    end)
125  end)
126
127  it('must specify env option as a dict', function()
128    command('let g:job_opts.env = v:true')
129    local _, err = pcall(function()
130      if is_os('win') then
131        command("let j = jobstart('set', g:job_opts)")
132      else
133        command("let j = jobstart('env', g:job_opts)")
134      end
135    end)
136    matches('E475: Invalid argument: env', err)
137  end)
138
139  it('append environment #env', function()
140    command("let $VAR = 'abc'")
141    command("let $TOTO = 'goodbye world'")
142    command("let g:job_opts.env = {'TOTO': 'hello world'}")
143    if is_os('win') then
144      command([[call jobstart('echo %TOTO% %VAR%', g:job_opts)]])
145    else
146      command([[call jobstart('echo $TOTO $VAR', g:job_opts)]])
147    end
148
149    expect_msg_seq({
150      { 'notification', 'stdout', { 0, { 'hello world abc' } } },
151      { 'notification', 'stdout', { 0, { '', '' } } },
152    }, {
153      { 'notification', 'stdout', { 0, { 'hello world abc', '' } } },
154      { 'notification', 'stdout', { 0, { '' } } },
155    })
156  end)
157
158  it('append environment with pty #env', function()
159    command("let $VAR = 'abc'")
160    command("let $TOTO = 'goodbye world'")
161    command('let g:job_opts.pty = v:true')
162    command("let g:job_opts.env = {'TOTO': 'hello world'}")
163    if is_os('win') then
164      command([[call jobstart('echo %TOTO% %VAR%', g:job_opts)]])
165    else
166      command([[call jobstart('echo $TOTO $VAR', g:job_opts)]])
167    end
168    expect_msg_seq({
169      { 'notification', 'stdout', { 0, { 'hello world abc' } } },
170      { 'notification', 'stdout', { 0, { '', '' } } },
171    }, {
172      { 'notification', 'stdout', { 0, { 'hello world abc', '' } } },
173      { 'notification', 'stdout', { 0, { '' } } },
174    })
175  end)
176
177  it('replace environment #env', function()
178    command("let $VAR = 'abc'")
179    command("let $TOTO = 'goodbye world'")
180    command("let g:job_opts.env = {'TOTO': 'hello world'}")
181    command('let g:job_opts.clear_env = 1')
182
183    -- libuv ensures that certain "required" environment variables are
184    -- preserved if the user doesn't provide them in a custom environment
185    -- https://github.com/libuv/libuv/blob/635e0ce6073c5fbc96040e336b364c061441b54b/src/win/process.c#L672
186    -- https://github.com/libuv/libuv/blob/635e0ce6073c5fbc96040e336b364c061441b54b/src/win/process.c#L48-L60
187    --
188    -- Rather than expecting a completely empty environment, ensure that $VAR
189    -- is *not* in the environment but $TOTO is.
190    if is_os('win') then
191      command([[call jobstart('echo %TOTO% %VAR%', g:job_opts)]])
192      expect_msg_seq({
193        { 'notification', 'stdout', { 0, { 'hello world %VAR%', '' } } },
194      })
195    else
196      command('set shell=/bin/sh')
197      command([[call jobstart('echo $TOTO $VAR', g:job_opts)]])
198      expect_msg_seq({
199        { 'notification', 'stdout', { 0, { 'hello world', '' } } },
200      })
201    end
202  end)
203
204  it('handles case-insensitively matching #env vars', function()
205    command("let $TOTO = 'abc'")
206    -- Since $Toto is being set in the job, it should take precedence over the
207    -- global $TOTO on Windows
208    command("let g:job_opts = {'env': {'Toto': 'def'}, 'stdout_buffered': v:true}")
209    if is_os('win') then
210      command([[let j = jobstart('set | find /I "toto="', g:job_opts)]])
211    else
212      command([[let j = jobstart('env | grep -i toto=', g:job_opts)]])
213    end
214    command('call jobwait([j])')
215    command('let g:output = Normalize(g:job_opts.stdout)')
216    local actual = eval('g:output')
217    local expected
218    if is_os('win') then
219      -- Toto is normalized to TOTO so we can detect duplicates, and because
220      -- Windows doesn't care about case
221      expected = { 'TOTO=def', '' }
222    else
223      expected = { 'TOTO=abc', 'Toto=def', '' }
224    end
225    table.sort(actual)
226    table.sort(expected)
227    eq(expected, actual)
228  end)
229
230  it('uses &shell and &shellcmdflag if passed a string', function()
231    command("let $VAR = 'abc'")
232    if is_os('win') then
233      command("let j = jobstart('echo %VAR%', g:job_opts)")
234    else
235      command("let j = jobstart('echo $VAR', g:job_opts)")
236    end
237    eq({ 'notification', 'stdout', { 0, { 'abc', '' } } }, next_msg())
238    eq({ 'notification', 'stdout', { 0, { '' } } }, next_msg())
239    eq({ 'notification', 'exit', { 0, 0 } }, next_msg())
240  end)
241
242  it('changes to given / directory', function()
243    command("let g:job_opts.cwd = '/'")
244    if is_os('win') then
245      command("let j = jobstart('cd', g:job_opts)")
246    else
247      command("let j = jobstart('pwd', g:job_opts)")
248    end
249    eq({ 'notification', 'stdout', { 0, { pathroot(), '' } } }, next_msg())
250    eq({ 'notification', 'stdout', { 0, { '' } } }, next_msg())
251    eq({ 'notification', 'exit', { 0, 0 } }, next_msg())
252  end)
253
254  local function test_job_cwd()
255    local dir = eval('resolve(tempname())'):gsub('/', get_pathsep())
256    mkdir(dir)
257    finally(function()
258      rmdir(dir)
259    end)
260    command("let g:job_opts.cwd = '" .. dir .. "'")
261    if is_os('win') then
262      command("let j = jobstart('cd', g:job_opts)")
263    else
264      command("let j = jobstart('pwd', g:job_opts)")
265    end
266    expect_msg_seq(
267      {
268        { 'notification', 'stdout', { 0, { dir, '' } } },
269        { 'notification', 'stdout', { 0, { '' } } },
270        { 'notification', 'exit', { 0, 0 } },
271      },
272      -- Alternative sequence:
273      {
274        { 'notification', 'stdout', { 0, { dir } } },
275        { 'notification', 'stdout', { 0, { '', '' } } },
276        { 'notification', 'stdout', { 0, { '' } } },
277        { 'notification', 'exit', { 0, 0 } },
278      }
279    )
280  end
281
282  it('changes to given `cwd` directory', function()
283    test_job_cwd()
284  end)
285
286  it('changes to given `cwd` directory with pty', function()
287    command('let g:job_opts.pty = v:true')
288    test_job_cwd()
289  end)
290
291  it('fails to change to invalid `cwd`', function()
292    local dir = eval('resolve(tempname())."-bogus"')
293    local _, err = pcall(function()
294      command("let g:job_opts.cwd = '" .. dir .. "'")
295      if is_os('win') then
296        command("let j = jobstart('cd', g:job_opts)")
297      else
298        command("let j = jobstart('pwd', g:job_opts)")
299      end
300    end)
301    matches('E475: Invalid argument: expected valid directory$', err)
302  end)
303
304  it('error on non-executable `cwd`', function()
305    skip(is_os('win'), 'N/A for Windows')
306
307    local dir = 'Xtest_not_executable_dir'
308    mkdir(dir)
309    finally(function()
310      rmdir(dir)
311    end)
312    fn.setfperm(dir, 'rw-------')
313
314    matches(
315      '^Vim%(call%):E903: Process failed to start: permission denied: .*',
316      pcall_err(command, ("call jobstart(['pwd'], {'cwd': '%s'})"):format(dir))
317    )
318  end)
319
320  it('error log and exit status 122 on non-executable `cwd`', function()
321    skip(is_os('win'), 'N/A for Windows')
322
323    local logfile = 'Xchdir_fail_log'
324    clear({ env = { NVIM_LOG_FILE = logfile } })
325
326    local dir = 'Xtest_not_executable_dir'
327    mkdir(dir)
328    finally(function()
329      rmdir(dir)
330      n.check_close()
331      os.remove(logfile)
332    end)
333    fn.setfperm(dir, 'rw-------')
334
335    n.exec(([[
336      let s:chan = jobstart(['pwd'], {'cwd': '%s', 'pty': v:true})
337      let g:status = jobwait([s:chan], 1000)[0]
338    ]]):format(dir))
339    eq(122, eval('g:status'))
340    t.assert_log(('chdir%%(%s%%) failed: permission denied'):format(dir), logfile, 100)
341  end)
342
343  it('returns 0 when it fails to start', function()
344    eq('', eval('v:errmsg'))
345    feed_command('let g:test_jobid = jobstart([])')
346    eq(0, eval('g:test_jobid'))
347    eq('E474:', string.match(eval('v:errmsg'), 'E%d*:'))
348  end)
349
350  it('returns -1 when target is not executable #5465', function()
351    local function new_job()
352      return eval([[jobstart('')]])
353    end
354    local executable_jobid = new_job()
355
356    local exe = is_os('win') and './test/functional/fixtures'
357      or './test/functional/fixtures/non_executable.txt'
358    eq(
359      "Vim:E475: Invalid value for argument cmd: '" .. exe .. "' is not executable",
360      pcall_err(eval, "jobstart(['" .. exe .. "'])")
361    )
362    eq('', eval('v:errmsg'))
363    -- Non-executable job should not increment the job ids. #5465
364    eq(executable_jobid + 1, new_job())
365  end)
366
367  it('invokes callbacks when the job writes and exits', function()
368    command("let g:job_opts.on_stderr  = function('OnEvent')")
369    command([[call jobstart(has('win32') ? 'echo:' : 'echo', g:job_opts)]])
370    expect_twostreams({
371      { 'notification', 'stdout', { 0, { '', '' } } },
372      { 'notification', 'stdout', { 0, { '' } } },
373    }, { { 'notification', 'stderr', { 0, { '' } } } })
374    eq({ 'notification', 'exit', { 0, 0 } }, next_msg())
375  end)
376
377  it('interactive commands', function()
378    command("let j = jobstart(['cat', '-'], g:job_opts)")
379    neq(0, eval('j'))
380    command('call jobsend(j, "abc\\n")')
381    eq({ 'notification', 'stdout', { 0, { 'abc', '' } } }, next_msg())
382    command('call jobsend(j, "123\\nxyz\\n")')
383    expect_msg_seq(
384      { { 'notification', 'stdout', { 0, { '123', 'xyz', '' } } } },
385      -- Alternative sequence:
386      {
387        { 'notification', 'stdout', { 0, { '123', '' } } },
388        { 'notification', 'stdout', { 0, { 'xyz', '' } } },
389      }
390    )
391    command('call jobsend(j, [123, "xyz", ""])')
392    expect_msg_seq(
393      { { 'notification', 'stdout', { 0, { '123', 'xyz', '' } } } },
394      -- Alternative sequence:
395      {
396        { 'notification', 'stdout', { 0, { '123', '' } } },
397        { 'notification', 'stdout', { 0, { 'xyz', '' } } },
398      }
399    )
400    command('call jobstop(j)')
401    eq({ 'notification', 'stdout', { 0, { '' } } }, next_msg())
402    eq({ 'notification', 'exit', { 0, 143 } }, next_msg())
403  end)
404
405  it('preserves NULs', function()
406    -- Make a file with NULs in it.
407    local filename = t.tmpname()
408    write_file(filename, 'abc\0def\n')
409
410    command("let j = jobstart(['cat', '" .. filename .. "'], g:job_opts)")
411    eq({ 'notification', 'stdout', { 0, { 'abc\ndef', '' } } }, next_msg())
412    eq({ 'notification', 'stdout', { 0, { '' } } }, next_msg())
413    eq({ 'notification', 'exit', { 0, 0 } }, next_msg())
414    os.remove(filename)
415
416    -- jobsend() preserves NULs.
417    command("let j = jobstart(['cat', '-'], g:job_opts)")
418    command([[call jobsend(j, ["123\n456",""])]])
419    eq({ 'notification', 'stdout', { 0, { '123\n456', '' } } }, next_msg())
420    command('call jobstop(j)')
421  end)
422
423  it('emits partial lines (does NOT buffer data lacking newlines)', function()
424    command("let j = jobstart(['cat', '-'], g:job_opts)")
425    command('call jobsend(j, "abc\\nxyz")')
426    eq({ 'notification', 'stdout', { 0, { 'abc', 'xyz' } } }, next_msg())
427    command('call jobstop(j)')
428    eq({ 'notification', 'stdout', { 0, { '' } } }, next_msg())
429    eq({ 'notification', 'exit', { 0, 143 } }, next_msg())
430  end)
431
432  it('preserves newlines', function()
433    command("let j = jobstart(['cat', '-'], g:job_opts)")
434    command('call jobsend(j, "a\\n\\nc\\n\\n\\n\\nb\\n\\n")')
435    eq({ 'notification', 'stdout', { 0, { 'a', '', 'c', '', '', '', 'b', '', '' } } }, next_msg())
436  end)
437
438  it('preserves NULs', function()
439    command("let j = jobstart(['cat', '-'], g:job_opts)")
440    command('call jobsend(j, ["\n123\n", "abc\\nxyz\n", ""])')
441    eq({ 'notification', 'stdout', { 0, { '\n123\n', 'abc\nxyz\n', '' } } }, next_msg())
442    command('call jobstop(j)')
443    eq({ 'notification', 'stdout', { 0, { '' } } }, next_msg())
444    eq({ 'notification', 'exit', { 0, 143 } }, next_msg())
445  end)
446
447  it('avoids sending final newline', function()
448    command("let j = jobstart(['cat', '-'], g:job_opts)")
449    command('call jobsend(j, ["some data", "without\nfinal nl"])')
450    eq({ 'notification', 'stdout', { 0, { 'some data', 'without\nfinal nl' } } }, next_msg())
451    command('call jobstop(j)')
452    eq({ 'notification', 'stdout', { 0, { '' } } }, next_msg())
453    eq({ 'notification', 'exit', { 0, 143 } }, next_msg())
454  end)
455
456  it('closes the job streams with jobclose', function()
457    command("let j = jobstart(['cat', '-'], g:job_opts)")
458    command('call jobclose(j, "stdin")')
459    eq({ 'notification', 'stdout', { 0, { '' } } }, next_msg())
460    eq({ 'notification', 'exit', { 0, 0 } }, next_msg())
461  end)
462
463  it('disallows jobsend on a job that closed stdin', function()
464    command("let j = jobstart(['cat', '-'], g:job_opts)")
465    command('call jobclose(j, "stdin")')
466    eq(
467      false,
468      pcall(function()
469        command('call jobsend(j, ["some data"])')
470      end)
471    )
472
473    command("let g:job_opts.stdin = 'null'")
474    command("let j = jobstart(['cat', '-'], g:job_opts)")
475    eq(
476      false,
477      pcall(function()
478        command('call jobsend(j, ["some data"])')
479      end)
480    )
481  end)
482
483  it('disallows jobsend on a non-existent job', function()
484    eq(false, pcall(eval, "jobsend(-1, 'lol')"))
485    eq(0, eval('jobstop(-1)'))
486  end)
487
488  it('jobstop twice on the stopped or exited job return 0', function()
489    command("let j = jobstart(['cat', '-'], g:job_opts)")
490    neq(0, eval('j'))
491    eq(1, eval('jobstop(j)'))
492    eq(0, eval('jobstop(j)'))
493  end)
494
495  it('will not leak memory if we leave a job running', function()
496    command("call jobstart(['cat', '-'], g:job_opts)")
497  end)
498
499  it('can get the pid value using getpid', function()
500    command("let j =  jobstart(['cat', '-'], g:job_opts)")
501    local pid = eval('jobpid(j)')
502    neq(NIL, api.nvim_get_proc(pid))
503    command('call jobstop(j)')
504    eq({ 'notification', 'stdout', { 0, { '' } } }, next_msg())
505    eq({ 'notification', 'exit', { 0, 143 } }, next_msg())
506    eq(NIL, api.nvim_get_proc(pid))
507  end)
508
509  it('disposed on Nvim exit', function()
510    -- Start a child process which doesn't die on stdin close.
511    local j = n.fn.jobstart({ n.nvim_prog, '--clean', '--headless' })
512    local pid = n.fn.jobpid(j)
513    eq('number', type(api.nvim_get_proc(pid).pid))
514    clear()
515    eq(NIL, api.nvim_get_proc(pid))
516  end)
517
518  it('can survive Nvim exit with "detach"', function()
519    local j = n.fn.jobstart({ n.nvim_prog, '--clean', '--headless' }, { detach = true })
520    local pid = n.fn.jobpid(j)
521    eq('number', type(api.nvim_get_proc(pid).pid))
522    clear()
523    -- Still alive.
524    eq('number', type(api.nvim_get_proc(pid).pid))
525    -- Clean up after ourselves.
526    eq(0, vim.uv.kill(pid, 'sigkill'))
527  end)
528
529  it('can pass user data to the callback', function()
530    command('let g:job_opts.user = {"n": 5, "s": "str", "l": [1]}')
531    command([[call jobstart('echo foo', g:job_opts)]])
532    local data = { n = 5, s = 'str', l = { 1 } }
533    expect_msg_seq(
534      {
535        { 'notification', 'stdout', { data, { 'foo', '' } } },
536        { 'notification', 'stdout', { data, { '' } } },
537      },
538      -- Alternative sequence:
539      {
540        { 'notification', 'stdout', { data, { 'foo' } } },
541        { 'notification', 'stdout', { data, { '', '' } } },
542        { 'notification', 'stdout', { data, { '' } } },
543      }
544    )
545    eq({ 'notification', 'exit', { data, 0 } }, next_msg())
546  end)
547
548  it('can omit data callbacks', function()
549    command('unlet g:job_opts.on_stdout')
550    command('let g:job_opts.user = 5')
551    command([[call jobstart('echo foo', g:job_opts)]])
552    eq({ 'notification', 'exit', { 5, 0 } }, next_msg())
553  end)
554
555  it('can omit exit callback', function()
556    command('unlet g:job_opts.on_exit')
557    command('let g:job_opts.user = 5')
558    command([[call jobstart('echo foo', g:job_opts)]])
559    expect_msg_seq(
560      {
561        { 'notification', 'stdout', { 5, { 'foo', '' } } },
562        { 'notification', 'stdout', { 5, { '' } } },
563      },
564      -- Alternative sequence:
565      {
566        { 'notification', 'stdout', { 5, { 'foo' } } },
567        { 'notification', 'stdout', { 5, { '', '' } } },
568        { 'notification', 'stdout', { 5, { '' } } },
569      }
570    )
571  end)
572
573  it('will pass return code with the exit event', function()
574    command('let g:job_opts.user = 5')
575    command("call jobstart('exit 55', g:job_opts)")
576    eq({ 'notification', 'stdout', { 5, { '' } } }, next_msg())
577    eq({ 'notification', 'exit', { 5, 55 } }, next_msg())
578  end)
579
580  it('can receive dictionary functions', function()
581    source([[
582    let g:dict = {'id': 10}
583    function g:dict.on_exit(id, code, event)
584      call rpcnotify(g:channel, a:event, a:code, self.id)
585    endfunction
586    call jobstart('exit 45', g:dict)
587    ]])
588    eq({ 'notification', 'exit', { 45, 10 } }, next_msg())
589  end)
590
591  it('can redefine callbacks being used by a job', function()
592    local screen = Screen.new()
593    source([[
594      function! g:JobHandler(job_id, data, event)
595      endfunction
596
597      let g:callbacks = {
598      \ 'on_stdout': function('g:JobHandler'),
599      \ 'on_stderr': function('g:JobHandler'),
600      \ 'on_exit': function('g:JobHandler')
601      \ }
602      let job = jobstart(['cat', '-'], g:callbacks)
603    ]])
604    poke_eventloop()
605    source([[
606      function! g:JobHandler(job_id, data, event)
607      endfunction
608    ]])
609
610    eq('', eval('v:errmsg'))
611  end)
612
613  it('requires funcrefs for script-local (s:) functions', function()
614    local screen = Screen.new(60, 5)
615
616    -- Pass job callback names _without_ `function(...)`.
617    source([[
618      function! s:OnEvent(id, data, event) dict
619        let g:job_result = get(self, 'user')
620      endfunction
621      let s:job = jobstart('echo "foo"', {
622        \ 'on_stdout': 's:OnEvent',
623        \ 'on_stderr': 's:OnEvent',
624        \ 'on_exit':   's:OnEvent',
625        \ })
626    ]])
627
628    screen:expect { any = '{9:E120: Using <SID> not in a script context: s:OnEvent}' }
629  end)
630
631  it('does not repeat output with slow output handlers', function()
632    source([[
633      let d = {'data': []}
634      function! d.on_stdout(job, data, event) dict
635        call add(self.data, Normalize(a:data))
636        sleep 200m
637      endfunction
638      function! d.on_exit(job, data, event) dict
639        let g:exit_data = copy(self.data)
640      endfunction
641      if has('win32')
642        let cmd = 'for /L %I in (1,1,5) do @(echo %I& ping -n 2 127.0.0.1 > nul)'
643      else
644        let cmd = ['sh', '-c', 'for i in 1 2 3 4 5; do echo $i; sleep 0.1; done']
645      endif
646      let g:id = jobstart(cmd, d)
647      sleep 1500m
648      call jobwait([g:id])
649    ]])
650
651    local expected = { '1', '2', '3', '4', '5', '' }
652    local chunks = eval('d.data')
653    -- check nothing was received after exit, including EOF
654    eq(eval('g:exit_data'), chunks)
655    local received = { '' }
656    for i, chunk in ipairs(chunks) do
657      if i < #chunks then
658        -- if chunks got joined, a spurious [''] callback was not sent
659        neq({ '' }, chunk)
660      else
661        -- but EOF callback is still sent
662        eq({ '' }, chunk)
663      end
664      received[#received] = received[#received] .. chunk[1]
665      for j = 2, #chunk do
666        received[#received + 1] = chunk[j]
667      end
668    end
669    eq(expected, received)
670  end)
671
672  it('does not invoke callbacks recursively', function()
673    source([[
674      let d = {'data': []}
675      function! d.on_stdout(job, data, event) dict
676        " if callbacks were invoked recursively, this would cause on_stdout
677        " to be invoked recursively and the data reversed on the call stack
678        sleep 200m
679        call add(self.data, Normalize(a:data))
680      endfunction
681      function! d.on_exit(job, data, event) dict
682        let g:exit_data = copy(self.data)
683      endfunction
684      if has('win32')
685        let cmd = 'for /L %I in (1,1,5) do @(echo %I& ping -n 2 127.0.0.1 > nul)'
686      else
687        let cmd = ['sh', '-c', 'for i in 1 2 3 4 5; do echo $i; sleep 0.1; done']
688      endif
689      let g:id = jobstart(cmd, d)
690      sleep 1500m
691      call jobwait([g:id])
692    ]])
693
694    local expected = { '1', '2', '3', '4', '5', '' }
695    local chunks = eval('d.data')
696    -- check nothing was received after exit, including EOF
697    eq(eval('g:exit_data'), chunks)
698    local received = { '' }
699    for i, chunk in ipairs(chunks) do
700      if i < #chunks then
701        -- if chunks got joined, a spurious [''] callback was not sent
702        neq({ '' }, chunk)
703      else
704        -- but EOF callback is still sent
705        eq({ '' }, chunk)
706      end
707      received[#received] = received[#received] .. chunk[1]
708      for j = 2, #chunk do
709        received[#received + 1] = chunk[j]
710      end
711    end
712    eq(expected, received)
713  end)
714
715  it('jobstart() works with partial functions', function()
716    source([[
717    function PrintArgs(a1, a2, id, data, event)
718      " Windows: remove ^M
719      let normalized = mapnew(a:data, 'substitute(v:val, "\r", "", "g")')
720      call rpcnotify(g:channel, '1', a:a1,  a:a2, normalized, a:event)
721    endfunction
722    let Callback = function('PrintArgs', ["foo", "bar"])
723    let g:job_opts = {'on_stdout': Callback}
724    call jobstart('echo some text', g:job_opts)
725    ]])
726    expect_msg_seq(
727      { { 'notification', '1', { 'foo', 'bar', { 'some text', '' }, 'stdout' } } },
728      -- Alternative sequence:
729      {
730        { 'notification', '1', { 'foo', 'bar', { 'some text' }, 'stdout' } },
731        { 'notification', '1', { 'foo', 'bar', { '', '' }, 'stdout' } },
732      }
733    )
734  end)
735
736  it('jobstart() works with closures', function()
737    source([[
738      fun! MkFun()
739          let a1 = 'foo'
740          let a2 = 'bar'
741          return {id, data, event -> rpcnotify(g:channel, '1', a1, a2, Normalize(data), event)}
742      endfun
743      let g:job_opts = {'on_stdout': MkFun()}
744      call jobstart('echo some text', g:job_opts)
745    ]])
746    expect_msg_seq(
747      { { 'notification', '1', { 'foo', 'bar', { 'some text', '' }, 'stdout' } } },
748      -- Alternative sequence:
749      {
750        { 'notification', '1', { 'foo', 'bar', { 'some text' }, 'stdout' } },
751        { 'notification', '1', { 'foo', 'bar', { '', '' }, 'stdout' } },
752      }
753    )
754  end)
755
756  it('jobstart() works when closure passed directly to `jobstart`', function()
757    source([[
758      let g:job_opts = {'on_stdout': {id, data, event -> rpcnotify(g:channel, '1', 'foo', 'bar', Normalize(data), event)}}
759      call jobstart('echo some text', g:job_opts)
760    ]])
761    expect_msg_seq(
762      { { 'notification', '1', { 'foo', 'bar', { 'some text', '' }, 'stdout' } } },
763      -- Alternative sequence:
764      {
765        { 'notification', '1', { 'foo', 'bar', { 'some text' }, 'stdout' } },
766        { 'notification', '1', { 'foo', 'bar', { '', '' }, 'stdout' } },
767      }
768    )
769  end)
770
771  it('lists passed to callbacks are freed if not stored #25891', function()
772    if not exec_lua('return pcall(require, "ffi")') then
773      pending('N/A: missing LuaJIT FFI')
774    end
775
776    source([[
777      let g:stdout = ''
778      func AppendStrOnEvent(id, data, event)
779        let g:stdout ..= join(a:data, "\n")
780      endfunc
781      let g:job_opts = {'on_stdout': function('AppendStrOnEvent')}
782    ]])
783    local job = eval([[jobstart(['cat', '-'], g:job_opts)]])
784
785    exec_lua(function()
786      local ffi = require('ffi')
787      ffi.cdef([[
788        typedef struct listvar_S list_T;
789        list_T *gc_first_list;
790        list_T *tv_list_alloc(ptrdiff_t len);
791        void tv_list_free(list_T *const l);
792      ]])
793      _G.L = ffi.C.tv_list_alloc(1)
794      _G.L_val = ffi.cast('uintptr_t', _G.L)
795      assert(ffi.cast('uintptr_t', ffi.C.gc_first_list) == _G.L_val)
796    end)
797
798    local str_all = ''
799    for _, str in ipairs({ 'LINE1\nLINE2\nLINE3\n', 'LINE4\n', 'LINE5\nLINE6\n' }) do
800      str_all = str_all .. str
801      api.nvim_chan_send(job, str)
802      retry(nil, 1000, function()
803        eq(str_all, api.nvim_get_var('stdout'))
804      end)
805    end
806
807    exec_lua(function()
808      local ffi = require('ffi')
809      assert(ffi.cast('uintptr_t', ffi.C.gc_first_list) == _G.L_val)
810      ffi.C.tv_list_free(_G.L)
811      assert(ffi.cast('uintptr_t', ffi.C.gc_first_list) ~= _G.L_val)
812    end)
813  end)
814
815  it('jobstart() environment: $NVIM, $NVIM_LISTEN_ADDRESS #11009', function()
816    local function get_child_env(envname, env)
817      return exec_lua(
818        [[
819        local envname, env = ...
820        local join = function(s) return vim.fn.join(s, '') end
821        local stdout = {}
822        local stderr = {}
823        local opt = {
824          env = env,
825          stdout_buffered = true,
826          stderr_buffered = true,
827          on_stderr = function(chan, data, name) stderr = data end,
828          on_stdout = function(chan, data, name) stdout = data end,
829        }
830        local j1 = vim.fn.jobstart({ vim.v.progpath, '-es', '-V1',('+echo "%s="..getenv("%s")'):format(envname, envname), '+qa!' }, opt)
831        vim.fn.jobwait({ j1 }, 10000)
832        return join({ join(stdout), join(stderr) })
833      ]],
834        envname,
835        env
836      )
837    end
838
839    local addr = eval('v:servername')
840    ok((addr):len() > 0)
841    -- $NVIM is _not_ defined in the top-level Nvim process.
842    eq('', eval('$NVIM'))
843    -- jobstart() shares its v:servername with the child via $NVIM.
844    eq('NVIM=' .. addr, get_child_env('NVIM'))
845    -- $NVIM_LISTEN_ADDRESS is unset by server_init in the child.
846    eq('NVIM_LISTEN_ADDRESS=v:null', get_child_env('NVIM_LISTEN_ADDRESS'))
847    eq(
848      'NVIM_LISTEN_ADDRESS=v:null',
849      get_child_env('NVIM_LISTEN_ADDRESS', { NVIM_LISTEN_ADDRESS = 'Xtest_jobstart_env' })
850    )
851    -- User can explicitly set $NVIM_LOG_FILE, $VIM, $VIMRUNTIME.
852    eq(
853      'NVIM_LOG_FILE=Xtest_jobstart_env',
854      get_child_env('NVIM_LOG_FILE', { NVIM_LOG_FILE = 'Xtest_jobstart_env' })
855    )
856    os.remove('Xtest_jobstart_env')
857  end)
858
859  describe('jobwait()', function()
860    before_each(function()
861      if is_os('win') then
862        n.set_shell_powershell()
863      end
864    end)
865
866    it('returns a list of status codes', function()
867      source([[
868      call rpcnotify(g:channel, 'wait', jobwait(has('win32') ? [
869      \  jobstart('Start-Sleep -Milliseconds 100; exit 4'),
870      \  jobstart('Start-Sleep -Milliseconds 300; exit 5'),
871      \  jobstart('Start-Sleep -Milliseconds 500; exit 6'),
872      \  jobstart('Start-Sleep -Milliseconds 700; exit 7')
873      \  ] : [
874      \  jobstart('sleep 0.10; exit 4'),
875      \  jobstart('sleep 0.110; exit 5'),
876      \  jobstart('sleep 0.210; exit 6'),
877      \  jobstart('sleep 0.310; exit 7')
878      \  ]))
879      ]])
880      eq({ 'notification', 'wait', { { 4, 5, 6, 7 } } }, next_msg())
881    end)
882
883    it('will run callbacks while waiting', function()
884      source([[
885      let g:dict = {}
886      let g:jobs = []
887      let g:exits = []
888      function g:dict.on_stdout(id, code, event) abort
889        call add(g:jobs, a:id)
890      endfunction
891      function g:dict.on_exit(id, code, event) abort
892        if a:code != 5
893          throw 'Error!'
894        endif
895        call add(g:exits, a:id)
896      endfunction
897      call jobwait(has('win32') ? [
898      \  jobstart('Start-Sleep -Milliseconds 100; exit 5', g:dict),
899      \  jobstart('Start-Sleep -Milliseconds 300; exit 5', g:dict),
900      \  jobstart('Start-Sleep -Milliseconds 500; exit 5', g:dict),
901      \  jobstart('Start-Sleep -Milliseconds 700; exit 5', g:dict)
902      \  ] : [
903      \  jobstart('sleep 0.010; exit 5', g:dict),
904      \  jobstart('sleep 0.030; exit 5', g:dict),
905      \  jobstart('sleep 0.050; exit 5', g:dict),
906      \  jobstart('sleep 0.070; exit 5', g:dict)
907      \  ])
908      call rpcnotify(g:channel, 'wait', sort(g:jobs), sort(g:exits))
909      ]])
910      eq({ 'notification', 'wait', { { 3, 4, 5, 6 }, { 3, 4, 5, 6 } } }, next_msg())
911    end)
912
913    it('will return status codes in the order of passed ids', function()
914      source([[
915      call rpcnotify(g:channel, 'wait', jobwait(has('win32') ? [
916      \  jobstart('Start-Sleep -Milliseconds 700; exit 4'),
917      \  jobstart('Start-Sleep -Milliseconds 500; exit 5'),
918      \  jobstart('Start-Sleep -Milliseconds 300; exit 6'),
919      \  jobstart('Start-Sleep -Milliseconds 100; exit 7')
920      \  ] : [
921      \  jobstart('sleep 0.070; exit 4'),
922      \  jobstart('sleep 0.050; exit 5'),
923      \  jobstart('sleep 0.030; exit 6'),
924      \  jobstart('sleep 0.010; exit 7')
925      \  ]))
926      ]])
927      eq({ 'notification', 'wait', { { 4, 5, 6, 7 } } }, next_msg())
928    end)
929
930    it('will return -3 for invalid job ids', function()
931      source([[
932      call rpcnotify(g:channel, 'wait', jobwait([
933      \  -10,
934      \  jobstart((has('win32') ? 'Start-Sleep -Milliseconds 100' : 'sleep 0.01').'; exit 5'),
935      \  ]))
936      ]])
937      eq({ 'notification', 'wait', { { -3, 5 } } }, next_msg())
938    end)
939
940    it('will return -2 when interrupted without timeout', function()
941      feed_command(
942        'call rpcnotify(g:channel, "ready") | '
943          .. 'call rpcnotify(g:channel, "wait", '
944          .. 'jobwait([jobstart("'
945          .. (is_os('win') and 'Start-Sleep 10' or 'sleep 10')
946          .. '; exit 55")]))'
947      )
948      eq({ 'notification', 'ready', {} }, next_msg())
949      feed('<c-c>')
950      eq({ 'notification', 'wait', { { -2 } } }, next_msg())
951    end)
952
953    it('will return -2 when interrupted with timeout', function()
954      feed_command(
955        'call rpcnotify(g:channel, "ready") | '
956          .. 'call rpcnotify(g:channel, "wait", '
957          .. 'jobwait([jobstart("'
958          .. (is_os('win') and 'Start-Sleep 10' or 'sleep 10')
959          .. '; exit 55")], 10000))'
960      )
961      eq({ 'notification', 'ready', {} }, next_msg())
962      feed('<c-c>')
963      eq({ 'notification', 'wait', { { -2 } } }, next_msg())
964    end)
965
966    it('can be called recursively', function()
967      source([[
968      let g:opts = {}
969      let g:counter = 0
970      function g:opts.on_stdout(id, msg, _event)
971        if self.state == 0
972          if self.counter < 10
973            call Run()
974          endif
975          let self.state = 1
976          call jobsend(a:id, "line1\n")
977        elseif self.state == 1
978          let self.state = 2
979          call jobsend(a:id, "line2\n")
980        elseif self.state == 2
981          let self.state = 3
982          call jobsend(a:id, "line3\n")
983        elseif self.state == 3
984          let self.state = 4
985          call rpcnotify(g:channel, 'w', printf('job %d closed', self.counter))
986          call jobclose(a:id, 'stdin')
987        endif
988      endfunction
989      function g:opts.on_exit(...)
990        call rpcnotify(g:channel, 'w', printf('job %d exited', self.counter))
991      endfunction
992      function Run()
993        let g:counter += 1
994        let j = copy(g:opts)
995        let j.state = 0
996        let j.counter = g:counter
997        call jobwait([
998        \   jobstart('echo ready; cat -', j),
999        \ ])
1000      endfunction
1001      ]])
1002      feed_command('call Run()')
1003      local r
1004      for i = 10, 1, -1 do
1005        r = next_msg()
1006        eq('job ' .. i .. ' closed', r[3][1])
1007        r = next_msg()
1008        eq('job ' .. i .. ' exited', r[3][1])
1009      end
1010      eq(10, api.nvim_eval('g:counter'))
1011    end)
1012
1013    describe('with timeout argument', function()
1014      it('will return -1 if the wait timed out', function()
1015        source([[
1016        call rpcnotify(g:channel, 'wait', jobwait([
1017        \  jobstart((has('win32') ? 'Start-Sleep 10' : 'sleep 10').'; exit 5'),
1018        \  ], 100))
1019        ]])
1020        eq({ 'notification', 'wait', { { -1 } } }, next_msg())
1021      end)
1022
1023      it('can pass 0 to check if a job exists', function()
1024        source([[
1025        call rpcnotify(g:channel, 'wait', jobwait(has('win32') ? [
1026        \  jobstart('Start-Sleep -Milliseconds 50; exit 4'),
1027        \  jobstart('Start-Sleep -Milliseconds 300; exit 5'),
1028        \  ] : [
1029        \  jobstart('sleep 0.05; exit 4'),
1030        \  jobstart('sleep 0.3; exit 5'),
1031        \  ], 0))
1032        ]])
1033        eq({ 'notification', 'wait', { { -1, -1 } } }, next_msg())
1034      end)
1035    end)
1036
1037    it('hides cursor and flushes messages before blocking', function()
1038      local screen = Screen.new(50, 6)
1039      command([[let g:id = jobstart([v:progpath, '--clean', '--headless'])]])
1040      source([[
1041        func PrintAndWait()
1042          echon "aaa\nbbb"
1043          call jobwait([g:id], 300)
1044          echon "\nccc"
1045        endfunc
1046      ]])
1047      feed(':call PrintAndWait()')
1048      screen:expect([[
1049                                                          |
1050        {1:~                                                 }|*4
1051        :call PrintAndWait()^                              |
1052      ]])
1053      feed('<CR>')
1054      screen:expect {
1055        grid = [[
1056                                                          |
1057        {1:~                                                 }|*2
1058        {3:                                                  }|
1059        aaa                                               |
1060        bbb                                               |
1061      ]],
1062        timeout = 100,
1063      }
1064      screen:expect([[
1065                                                          |
1066        {3:                                                  }|
1067        aaa                                               |
1068        bbb                                               |
1069        ccc                                               |
1070        {6:Press ENTER or type command to continue}^           |
1071      ]])
1072      feed('<CR>')
1073      fn.jobstop(api.nvim_get_var('id'))
1074    end)
1075
1076    it('does not set UI busy with zero timeout #31712', function()
1077      local screen = Screen.new(50, 6)
1078      command([[let g:id = jobstart(['sleep', '0.3'])]])
1079      local busy = 0
1080      screen._handle_busy_start = (function(orig)
1081        return function()
1082          orig(screen)
1083          busy = busy + 1
1084        end
1085      end)(screen._handle_busy_start)
1086      source([[
1087        func PrintAndPoll()
1088          echon "aaa\nbbb"
1089          call jobwait([g:id], 0)
1090          echon "\nccc"
1091        endfunc
1092      ]])
1093      feed_command('call PrintAndPoll()')
1094      screen:expect([[
1095                                                          |
1096        {3:                                                  }|
1097        aaa                                               |
1098        bbb                                               |
1099        ccc                                               |
1100        {6:Press ENTER or type command to continue}^           |
1101      ]])
1102      feed('<CR>')
1103      fn.jobstop(api.nvim_get_var('id'))
1104      eq(0, busy)
1105    end)
1106  end)
1107
1108  pending('exit event follows stdout, stderr', function()
1109    command("let g:job_opts.on_stderr  = function('OnEvent')")
1110    command("let j = jobstart(['cat', '-'], g:job_opts)")
1111    api.nvim_eval('jobsend(j, "abcdef")')
1112    api.nvim_eval('jobstop(j)')
1113    expect_msg_seq(
1114      {
1115        { 'notification', 'stdout', { 0, { 'abcdef' } } },
1116        { 'notification', 'stdout', { 0, { '' } } },
1117        { 'notification', 'stderr', { 0, { '' } } },
1118      },
1119      -- Alternative sequence:
1120      {
1121        { 'notification', 'stderr', { 0, { '' } } },
1122        { 'notification', 'stdout', { 0, { 'abcdef' } } },
1123        { 'notification', 'stdout', { 0, { '' } } },
1124      },
1125      -- Alternative sequence:
1126      {
1127        { 'notification', 'stdout', { 0, { 'abcdef' } } },
1128        { 'notification', 'stderr', { 0, { '' } } },
1129        { 'notification', 'stdout', { 0, { '' } } },
1130      }
1131    )
1132    eq({ 'notification', 'exit', { 0, 143 } }, next_msg())
1133  end)
1134
1135  it('does not crash when repeatedly failing to start shell', function()
1136    source([[
1137      set shell=nosuchshell
1138      func! DoIt()
1139        call jobstart('true')
1140        call jobstart('true')
1141      endfunc
1142    ]])
1143    -- The crash only triggered if both jobs are cleaned up on the same event
1144    -- loop tick. This is also prevented by try-block, so feed must be used.
1145    feed_command('call DoIt()')
1146    feed('<cr>') -- press RETURN
1147    assert_alive()
1148  end)
1149
1150  it('jobstop() kills entire process tree #6530', function()
1151    -- XXX: Using `nvim` isn't a good test, it reaps its children on exit.
1152    -- local c = 'call jobstart([v:progpath, "-u", "NONE", "-i", "NONE", "--headless"])'
1153    -- local j = eval("jobstart([v:progpath, '-u', 'NONE', '-i', 'NONE', '--headless', '-c', '"
1154    --                ..c.."', '-c', '"..c.."'])")
1155
1156    -- Create child with several descendants.
1157    if is_os('win') then
1158      source([[
1159      function! s:formatprocs(pid, prefix)
1160        let result = ''
1161        let result .= a:prefix . printf("%-24.24s%6s %12.12s %s\n",
1162              \                         s:procs[a:pid]['name'],
1163              \                         a:pid,
1164              \                         s:procs[a:pid]['Session Name'],
1165              \                         s:procs[a:pid]['Session'])
1166        if has_key(s:procs[a:pid], 'children')
1167          for pid in s:procs[a:pid]['children']
1168            let result .= s:formatprocs(pid, a:prefix . '  ')
1169          endfor
1170        endif
1171        return result
1172      endfunction
1173
1174      function! PsTree() abort
1175        let s:procs = {}
1176        for proc in map(
1177              \       map(
1178              \         systemlist('tasklist /NH'),
1179              \         'substitute(v:val, "\r", "", "")'),
1180              \       'split(v:val, "\\s\\+")')
1181          if len(proc) == 6
1182            let s:procs[proc[1]] .. ']]' .. [[= {'name': proc[0],
1183                  \               'Session Name': proc[2],
1184                  \               'Session': proc[3]}
1185          endif
1186        endfor
1187        for pid in keys(s:procs)
1188          let children = nvim_get_proc_children(str2nr(pid))
1189          if !empty(children)
1190            let s:procs[pid]['children'] = children
1191            for cpid in children
1192              let s:procs[printf('%d', cpid)]['parent'] = str2nr(pid)
1193            endfor
1194          endif
1195        endfor
1196        let result = ''
1197        for pid in sort(keys(s:procs), {i1, i2 -> i1 - i2})
1198          if !has_key(s:procs[pid], 'parent')
1199            let result .= s:formatprocs(pid, '')
1200          endif
1201        endfor
1202        return result
1203      endfunction
1204      ]])
1205    end
1206    local sleep_cmd = (is_os('win') and 'ping -n 31 127.0.0.1' or 'sleep 30')
1207    local j = eval("jobstart('" .. sleep_cmd .. ' | ' .. sleep_cmd .. ' | ' .. sleep_cmd .. "')")
1208    local ppid = fn.jobpid(j)
1209    local children
1210    if is_os('win') then
1211      local status, result = pcall(retry, nil, nil, function()
1212        children = api.nvim_get_proc_children(ppid)
1213        -- On Windows conhost.exe may exist, and
1214        -- e.g. vctip.exe might appear.  #10783
1215        ok(#children >= 3 and #children <= 5)
1216      end)
1217      if not status then
1218        print('')
1219        print(eval('PsTree()'))
1220        error(result)
1221      end
1222    else
1223      retry(nil, nil, function()
1224        children = api.nvim_get_proc_children(ppid)
1225        eq(3, #children)
1226      end)
1227    end
1228    -- Assert that nvim_get_proc() sees the children.
1229    for _, child_pid in ipairs(children) do
1230      local info = api.nvim_get_proc(child_pid)
1231      -- eq((is_os('win') and 'nvim.exe' or 'nvim'), info.name)
1232      eq(ppid, info.ppid)
1233    end
1234    -- Kill the root of the tree.
1235    eq(1, fn.jobstop(j))
1236    -- Assert that the children were killed.
1237    retry(nil, nil, function()
1238      for _, child_pid in ipairs(children) do
1239        eq(NIL, api.nvim_get_proc(child_pid))
1240      end
1241    end)
1242  end)
1243
1244  it('jobstop on same id before stopped', function()
1245    command('let j = jobstart(["cat", "-"], g:job_opts)')
1246    neq(0, eval('j'))
1247
1248    eq({ 1, 0 }, eval('[jobstop(j), jobstop(j)]'))
1249  end)
1250
1251  describe('running tty-test program', function()
1252    local function next_chunk()
1253      local rv
1254      while true do
1255        local msg = next_msg()
1256        local data = msg[3][2]
1257        for i = 1, #data do
1258          data[i] = data[i]:gsub('\n', '\000')
1259        end
1260        rv = table.concat(data, '\n')
1261        if is_os('win') then
1262          -- ConPTY injects its own terminal escapes (init/teardown CSI+OSC) and pads redraw rows
1263          -- with trailing spaces around tty-test's plain output.
1264          rv = rv:gsub('\27%[[%d;?]*[%a~]', ''):gsub('\27%][^\7]*\7', '')
1265          rv = rv:gsub('[%s]+$', '')
1266        end
1267        rv = rv:gsub('\r\n$', ''):gsub('^\r\n', '')
1268        if rv ~= '' then
1269          break
1270        end
1271      end
1272      return rv
1273    end
1274
1275    local j
1276    local function send(str)
1277      -- check no nvim_chan_free double free with pty job (#14198)
1278      api.nvim_chan_send(j, str)
1279    end
1280
1281    before_each(function()
1282      -- Redefine Normalize() so that TTY data is not munged.
1283      source([[
1284      function! Normalize(data) abort
1285        return a:data
1286      endfunction
1287      ]])
1288      insert(testprg('tty-test'))
1289      command('let g:job_opts.pty = 1')
1290      command('let exec = [expand("<cfile>:p")]')
1291      command('let j = jobstart(exec, g:job_opts)')
1292      j = eval 'j'
1293      eq('tty ready', next_chunk())
1294    end)
1295
1296    it('echoing input', function()
1297      send('test')
1298      eq('test', next_chunk())
1299    end)
1300
1301    it('resizing window', function()
1302      command('call jobresize(j, 40, 10)')
1303      -- Windows: ConPTY emits a full screen redraw, so prior content ("tty ready") may prefix the new line.
1304      matches('rows: 10, cols: 40$', next_chunk())
1305      command('call jobresize(j, 10, 40)')
1306      matches('rows: 40, cols: 10$', next_chunk())
1307    end)
1308
1309    it('jobclose() sends SIGHUP', function()
1310      skip(is_os('win'), 'N/A: SIGHUP is a POSIX signal')
1311      command('call jobclose(j)')
1312      local msg = next_msg()
1313      msg = (msg[2] == 'stdout') and next_msg() or msg -- Skip stdout, if any.
1314      eq({ 'notification', 'exit', { 0, 42 } }, msg)
1315    end)
1316
1317    it('jobstart() does not keep ptmx file descriptor open', function()
1318      -- Start another job (using libuv)
1319      command('let g:job_opts.pty = 0')
1320      local other_jobid = eval("jobstart(['cat', '-'], g:job_opts)")
1321      local other_pid = eval('jobpid(' .. other_jobid .. ')')
1322
1323      -- Other job doesn't block first job from receiving SIGHUP on jobclose()
1324      command('call jobclose(j)')
1325      -- Have to wait so that the SIGHUP can be processed by tty-test on time.
1326      -- Can't wait for the next message in case this test fails, if it fails
1327      -- there won't be any more messages, and the test would hang.
1328      vim.uv.sleep(100)
1329      local err = pcall_err(command, 'call jobpid(j)')
1330      eq('Vim(call):E900: Invalid channel id', err)
1331
1332      -- cleanup
1333      eq(other_pid, eval('jobpid(' .. other_jobid .. ')'))
1334      command('call jobstop(' .. other_jobid .. ')')
1335    end)
1336  end)
1337
1338  it('does not close the same handle twice on exit #25086', function()
1339    local filename = string.format('%s.lua', t.tmpname())
1340    write_file(
1341      filename,
1342      [[
1343      vim.api.nvim_create_autocmd('VimLeavePre', {
1344        callback = function()
1345          local id = vim.fn.jobstart('sleep 0')
1346          vim.fn.jobwait({id})
1347        end,
1348      })
1349    ]]
1350    )
1351
1352    local screen = tt.setup_child_nvim({
1353      '--cmd',
1354      'set notermguicolors',
1355      '-i',
1356      'NONE',
1357      '-u',
1358      filename,
1359    })
1360    -- Wait for startup to complete, so that all terminal responses are received.
1361    screen:expect([[
1362      ^                                                  |
1363      ~                                                 |*3
1364      {2:[No Name]                       0,0-1          All}|
1365                                                        |
1366      {5:-- TERMINAL --}                                    |
1367    ]])
1368
1369    feed(':q<CR>')
1370    screen:expect([[
1371      ^                                                  |
1372      [Process exited 0]                                |
1373                                                        |*4
1374      {5:-- TERMINAL --}                                    |
1375    ]])
1376  end)
1377
1378  it('uses real pipes for stdin/stdout #35984', function()
1379    if is_os('win') then
1380      return -- Not applicable for Windows.
1381    end
1382
1383    -- this fails on linux if we used socketpair() for stdin and stdout,
1384    -- which libuv does if you ask to create stdio streams for you
1385    local val = exec_lua(function()
1386      local output
1387      local job = vim.fn.jobstart('wc /dev/stdin > /dev/stdout', {
1388        stdout_buffered = true,
1389        on_stdout = function(_, data, _)
1390          output = data
1391        end,
1392      })
1393      vim.fn.chansend(job, 'foo\nbar baz\n')
1394      vim.fn.chanclose(job, 'stdin')
1395      vim.fn.jobwait({ job })
1396      return output
1397    end)
1398    eq(2, #val, val)
1399    eq({ '2', '3', '12', '/dev/stdin' }, vim.split(val[1], '%s+', { trimempty = true }))
1400    eq('', val[2])
1401  end)
1402end)
1403
1404describe('pty process teardown', function()
1405  local screen
1406  before_each(function()
1407    clear()
1408    screen = Screen.new(30, 6)
1409    screen:expect([[
1410      ^                              |
1411      {1:~                             }|*4
1412                                    |
1413    ]])
1414  end)
1415
1416  it('does not prevent/delay exit. #4798 #4900', function()
1417    skip(fn.executable('sleep') == 0, 'missing "sleep" command')
1418    -- Use a nested nvim (in :term) to test without --headless.
1419    fn.jobstart({
1420      n.nvim_prog,
1421      '-u',
1422      'NONE',
1423      '-i',
1424      'NONE',
1425      '--cmd',
1426      nvim_set,
1427      -- Use :term again in the _nested_ nvim to get a PTY process.
1428      -- Use `sleep` to simulate a long-running child of the PTY.
1429      '+terminal',
1430      '+!(sleep 300 &)',
1431      '+qa',
1432    }, {
1433      term = true,
1434      env = { VIMRUNTIME = os.getenv('VIMRUNTIME') },
1435    })
1436
1437    -- Exiting should terminate all descendants (PTY, its children, ...).
1438    screen:expect([[
1439      ^                              |
1440      [Process exited 0]            |
1441                                    |*4
1442    ]])
1443  end)
1444end)