job_spec.lua 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097
  1. local helpers = require('test.functional.helpers')(after_each)
  2. local clear, eq, eval, exc_exec, feed_command, feed, insert, neq, next_msg, nvim,
  3. nvim_dir, ok, source, write_file, mkdir, rmdir = helpers.clear,
  4. helpers.eq, helpers.eval, helpers.exc_exec, helpers.feed_command, helpers.feed,
  5. helpers.insert, helpers.neq, helpers.next_msg, helpers.nvim,
  6. helpers.nvim_dir, helpers.ok, helpers.source,
  7. helpers.write_file, helpers.mkdir, helpers.rmdir
  8. local command = helpers.command
  9. local funcs = helpers.funcs
  10. local os_kill = helpers.os_kill
  11. local retry = helpers.retry
  12. local meths = helpers.meths
  13. local NIL = helpers.NIL
  14. local poke_eventloop = helpers.poke_eventloop
  15. local iswin = helpers.iswin
  16. local get_pathsep = helpers.get_pathsep
  17. local pathroot = helpers.pathroot
  18. local nvim_set = helpers.nvim_set
  19. local expect_twostreams = helpers.expect_twostreams
  20. local expect_msg_seq = helpers.expect_msg_seq
  21. local pcall_err = helpers.pcall_err
  22. local Screen = require('test.functional.ui.screen')
  23. describe('jobs', function()
  24. local channel
  25. before_each(function()
  26. clear()
  27. channel = nvim('get_api_info')[1]
  28. nvim('set_var', 'channel', channel)
  29. source([[
  30. function! Normalize(data) abort
  31. " Windows: remove ^M and term escape sequences
  32. return type([]) == type(a:data)
  33. \ ? map(a:data, 'substitute(substitute(v:val, "\r", "", "g"), "\x1b\\%(\\]\\d\\+;.\\{-}\x07\\|\\[.\\{-}[\x40-\x7E]\\)", "", "g")')
  34. \ : a:data
  35. endfunction
  36. function! OnEvent(id, data, event) dict
  37. let userdata = get(self, 'user')
  38. let data = Normalize(a:data)
  39. call rpcnotify(g:channel, a:event, userdata, data)
  40. endfunction
  41. let g:job_opts = {
  42. \ 'on_stdout': function('OnEvent'),
  43. \ 'on_exit': function('OnEvent'),
  44. \ 'user': 0
  45. \ }
  46. ]])
  47. end)
  48. it('must specify env option as a dict', function()
  49. command("let g:job_opts.env = v:true")
  50. local _, err = pcall(function()
  51. if iswin() then
  52. nvim('command', "let j = jobstart('set', g:job_opts)")
  53. else
  54. nvim('command', "let j = jobstart('env', g:job_opts)")
  55. end
  56. end)
  57. ok(string.find(err, "E475: Invalid argument: env") ~= nil)
  58. end)
  59. it('append environment #env', function()
  60. nvim('command', "let $VAR = 'abc'")
  61. nvim('command', "let $TOTO = 'goodbye world'")
  62. nvim('command', "let g:job_opts.env = {'TOTO': 'hello world'}")
  63. if iswin() then
  64. nvim('command', [[call jobstart('echo %TOTO% %VAR%', g:job_opts)]])
  65. else
  66. nvim('command', [[call jobstart('echo $TOTO $VAR', g:job_opts)]])
  67. end
  68. expect_msg_seq({
  69. {'notification', 'stdout', {0, {'hello world abc', ''}}},
  70. })
  71. end)
  72. it('append environment with pty #env', function()
  73. nvim('command', "let $VAR = 'abc'")
  74. nvim('command', "let $TOTO = 'goodbye world'")
  75. nvim('command', "let g:job_opts.pty = v:true")
  76. nvim('command', "let g:job_opts.env = {'TOTO': 'hello world'}")
  77. if iswin() then
  78. nvim('command', [[call jobstart('echo %TOTO% %VAR%', g:job_opts)]])
  79. else
  80. nvim('command', [[call jobstart('echo $TOTO $VAR', g:job_opts)]])
  81. end
  82. expect_msg_seq({
  83. {'notification', 'stdout', {0, {'hello world abc', ''}}},
  84. })
  85. end)
  86. it('replace environment #env', function()
  87. nvim('command', "let $VAR = 'abc'")
  88. nvim('command', "let $TOTO = 'goodbye world'")
  89. nvim('command', "let g:job_opts.env = {'TOTO': 'hello world'}")
  90. nvim('command', "let g:job_opts.clear_env = 1")
  91. -- libuv ensures that certain "required" environment variables are
  92. -- preserved if the user doesn't provide them in a custom environment
  93. -- https://github.com/libuv/libuv/blob/635e0ce6073c5fbc96040e336b364c061441b54b/src/win/process.c#L672
  94. -- https://github.com/libuv/libuv/blob/635e0ce6073c5fbc96040e336b364c061441b54b/src/win/process.c#L48-L60
  95. --
  96. -- Rather than expecting a completely empty environment, ensure that $VAR
  97. -- is *not* in the environment but $TOTO is.
  98. if iswin() then
  99. nvim('command', [[call jobstart('echo %TOTO% %VAR%', g:job_opts)]])
  100. expect_msg_seq({
  101. {'notification', 'stdout', {0, {'hello world %VAR%', ''}}}
  102. })
  103. else
  104. nvim('command', "set shell=/bin/sh")
  105. nvim('command', [[call jobstart('echo $TOTO $VAR', g:job_opts)]])
  106. expect_msg_seq({
  107. {'notification', 'stdout', {0, {'hello world', ''}}}
  108. })
  109. end
  110. end)
  111. it('handles case-insensitively matching #env vars', function()
  112. nvim('command', "let $TOTO = 'abc'")
  113. -- Since $Toto is being set in the job, it should take precedence over the
  114. -- global $TOTO on Windows
  115. nvim('command', "let g:job_opts = {'env': {'Toto': 'def'}, 'stdout_buffered': v:true}")
  116. if iswin() then
  117. nvim('command', [[let j = jobstart('set | find /I "toto="', g:job_opts)]])
  118. else
  119. nvim('command', [[let j = jobstart('env | grep -i toto=', g:job_opts)]])
  120. end
  121. nvim('command', "call jobwait([j])")
  122. nvim('command', "let g:output = Normalize(g:job_opts.stdout)")
  123. local actual = eval('g:output')
  124. local expected
  125. if iswin() then
  126. -- Toto is normalized to TOTO so we can detect duplicates, and because
  127. -- Windows doesn't care about case
  128. expected = {'TOTO=def', ''}
  129. else
  130. expected = {'TOTO=abc', 'Toto=def', ''}
  131. end
  132. table.sort(actual)
  133. table.sort(expected)
  134. eq(expected, actual)
  135. end)
  136. it('uses &shell and &shellcmdflag if passed a string', function()
  137. nvim('command', "let $VAR = 'abc'")
  138. if iswin() then
  139. nvim('command', "let j = jobstart('echo %VAR%', g:job_opts)")
  140. else
  141. nvim('command', "let j = jobstart('echo $VAR', g:job_opts)")
  142. end
  143. eq({'notification', 'stdout', {0, {'abc', ''}}}, next_msg())
  144. eq({'notification', 'stdout', {0, {''}}}, next_msg())
  145. eq({'notification', 'exit', {0, 0}}, next_msg())
  146. end)
  147. it('changes to given / directory', function()
  148. nvim('command', "let g:job_opts.cwd = '/'")
  149. if iswin() then
  150. nvim('command', "let j = jobstart('cd', g:job_opts)")
  151. else
  152. nvim('command', "let j = jobstart('pwd', g:job_opts)")
  153. end
  154. eq({'notification', 'stdout',
  155. {0, {pathroot(), ''}}}, next_msg())
  156. eq({'notification', 'stdout', {0, {''}}}, next_msg())
  157. eq({'notification', 'exit', {0, 0}}, next_msg())
  158. end)
  159. it('changes to given `cwd` directory', function()
  160. local dir = eval("resolve(tempname())"):gsub("/", get_pathsep())
  161. mkdir(dir)
  162. nvim('command', "let g:job_opts.cwd = '" .. dir .. "'")
  163. if iswin() then
  164. nvim('command', "let j = jobstart('cd', g:job_opts)")
  165. else
  166. nvim('command', "let j = jobstart('pwd', g:job_opts)")
  167. end
  168. expect_msg_seq(
  169. { {'notification', 'stdout', {0, {dir, ''} } },
  170. {'notification', 'stdout', {0, {''} } },
  171. {'notification', 'exit', {0, 0} }
  172. },
  173. -- Alternative sequence:
  174. { {'notification', 'stdout', {0, {dir} } },
  175. {'notification', 'stdout', {0, {'', ''} } },
  176. {'notification', 'stdout', {0, {''} } },
  177. {'notification', 'exit', {0, 0} }
  178. }
  179. )
  180. rmdir(dir)
  181. end)
  182. it('fails to change to invalid `cwd`', function()
  183. local dir = eval('resolve(tempname())."-bogus"')
  184. local _, err = pcall(function()
  185. nvim('command', "let g:job_opts.cwd = '" .. dir .. "'")
  186. if iswin() then
  187. nvim('command', "let j = jobstart('cd', g:job_opts)")
  188. else
  189. nvim('command', "let j = jobstart('pwd', g:job_opts)")
  190. end
  191. end)
  192. ok(string.find(err, "E475: Invalid argument: expected valid directory$") ~= nil)
  193. end)
  194. it('produces error when using non-executable `cwd`', function()
  195. if iswin() then return end -- N/A for Windows
  196. local dir = 'Xtest_not_executable_dir'
  197. mkdir(dir)
  198. funcs.setfperm(dir, 'rw-------')
  199. eq('Vim(call):E475: Invalid argument: expected valid directory',
  200. pcall_err(nvim, 'command', "call jobstart('pwd', {'cwd': '"..dir.."'})"))
  201. rmdir(dir)
  202. end)
  203. it('returns 0 when it fails to start', function()
  204. eq("", eval("v:errmsg"))
  205. feed_command("let g:test_jobid = jobstart([])")
  206. eq(0, eval("g:test_jobid"))
  207. eq("E474:", string.match(eval("v:errmsg"), "E%d*:"))
  208. end)
  209. it('returns -1 when target is not executable #5465', function()
  210. local function new_job()
  211. return eval([[jobstart('')]])
  212. end
  213. local executable_jobid = new_job()
  214. local exe = iswin() and './test/functional/fixtures' or './test/functional/fixtures/non_executable.txt'
  215. eq("Vim:E475: Invalid value for argument cmd: '"..exe.."' is not executable",
  216. pcall_err(eval, "jobstart(['"..exe.."'])"))
  217. eq("", eval("v:errmsg"))
  218. -- Non-executable job should not increment the job ids. #5465
  219. eq(executable_jobid + 1, new_job())
  220. end)
  221. it('invokes callbacks when the job writes and exits', function()
  222. nvim('command', "let g:job_opts.on_stderr = function('OnEvent')")
  223. nvim('command', [[call jobstart(has('win32') ? 'echo:' : 'echo', g:job_opts)]])
  224. expect_twostreams({{'notification', 'stdout', {0, {'', ''}}},
  225. {'notification', 'stdout', {0, {''}}}},
  226. {{'notification', 'stderr', {0, {''}}}})
  227. eq({'notification', 'exit', {0, 0}}, next_msg())
  228. end)
  229. it('allows interactive commands', function()
  230. nvim('command', "let j = jobstart(['cat', '-'], g:job_opts)")
  231. neq(0, eval('j'))
  232. nvim('command', 'call jobsend(j, "abc\\n")')
  233. eq({'notification', 'stdout', {0, {'abc', ''}}}, next_msg())
  234. nvim('command', 'call jobsend(j, "123\\nxyz\\n")')
  235. expect_msg_seq(
  236. { {'notification', 'stdout', {0, {'123', 'xyz', ''}}}
  237. },
  238. -- Alternative sequence:
  239. { {'notification', 'stdout', {0, {'123', ''}}},
  240. {'notification', 'stdout', {0, {'xyz', ''}}}
  241. }
  242. )
  243. nvim('command', 'call jobsend(j, [123, "xyz", ""])')
  244. expect_msg_seq(
  245. { {'notification', 'stdout', {0, {'123', 'xyz', ''}}}
  246. },
  247. -- Alternative sequence:
  248. { {'notification', 'stdout', {0, {'123', ''}}},
  249. {'notification', 'stdout', {0, {'xyz', ''}}}
  250. }
  251. )
  252. nvim('command', "call jobstop(j)")
  253. eq({'notification', 'stdout', {0, {''}}}, next_msg())
  254. eq({'notification', 'exit', {0, 143}}, next_msg())
  255. end)
  256. it('preserves NULs', function()
  257. -- Make a file with NULs in it.
  258. local filename = helpers.tmpname()
  259. write_file(filename, "abc\0def\n")
  260. nvim('command', "let j = jobstart(['cat', '"..filename.."'], g:job_opts)")
  261. eq({'notification', 'stdout', {0, {'abc\ndef', ''}}}, next_msg())
  262. eq({'notification', 'stdout', {0, {''}}}, next_msg())
  263. eq({'notification', 'exit', {0, 0}}, next_msg())
  264. os.remove(filename)
  265. -- jobsend() preserves NULs.
  266. nvim('command', "let j = jobstart(['cat', '-'], g:job_opts)")
  267. nvim('command', [[call jobsend(j, ["123\n456",""])]])
  268. eq({'notification', 'stdout', {0, {'123\n456', ''}}}, next_msg())
  269. nvim('command', "call jobstop(j)")
  270. end)
  271. it("will not buffer data if it doesn't end in newlines", function()
  272. if helpers.isCI('travis') and os.getenv('CC') == 'gcc-4.9'
  273. and helpers.is_os('mac') then
  274. -- XXX: Hangs Travis macOS since e9061117a5b8f195c3f26a5cb94e18ddd7752d86.
  275. pending("[Hangs on Travis macOS. #5002]")
  276. end
  277. nvim('command', "let j = jobstart(['cat', '-'], g:job_opts)")
  278. nvim('command', 'call jobsend(j, "abc\\nxyz")')
  279. eq({'notification', 'stdout', {0, {'abc', 'xyz'}}}, next_msg())
  280. nvim('command', "call jobstop(j)")
  281. eq({'notification', 'stdout', {0, {''}}}, next_msg())
  282. eq({'notification', 'exit', {0, 143}}, next_msg())
  283. end)
  284. it('preserves newlines', function()
  285. nvim('command', "let j = jobstart(['cat', '-'], g:job_opts)")
  286. nvim('command', 'call jobsend(j, "a\\n\\nc\\n\\n\\n\\nb\\n\\n")')
  287. eq({'notification', 'stdout',
  288. {0, {'a', '', 'c', '', '', '', 'b', '', ''}}}, next_msg())
  289. end)
  290. it('preserves NULs', function()
  291. nvim('command', "let j = jobstart(['cat', '-'], g:job_opts)")
  292. nvim('command', 'call jobsend(j, ["\n123\n", "abc\\nxyz\n", ""])')
  293. eq({'notification', 'stdout', {0, {'\n123\n', 'abc\nxyz\n', ''}}},
  294. next_msg())
  295. nvim('command', "call jobstop(j)")
  296. eq({'notification', 'stdout', {0, {''}}}, next_msg())
  297. eq({'notification', 'exit', {0, 143}}, next_msg())
  298. end)
  299. it('avoids sending final newline', function()
  300. nvim('command', "let j = jobstart(['cat', '-'], g:job_opts)")
  301. nvim('command', 'call jobsend(j, ["some data", "without\nfinal nl"])')
  302. eq({'notification', 'stdout', {0, {'some data', 'without\nfinal nl'}}},
  303. next_msg())
  304. nvim('command', "call jobstop(j)")
  305. eq({'notification', 'stdout', {0, {''}}}, next_msg())
  306. eq({'notification', 'exit', {0, 143}}, next_msg())
  307. end)
  308. it('closes the job streams with jobclose', function()
  309. nvim('command', "let j = jobstart(['cat', '-'], g:job_opts)")
  310. nvim('command', 'call jobclose(j, "stdin")')
  311. eq({'notification', 'stdout', {0, {''}}}, next_msg())
  312. eq({'notification', 'exit', {0, 0}}, next_msg())
  313. end)
  314. it("disallows jobsend on a job that closed stdin", function()
  315. nvim('command', "let j = jobstart(['cat', '-'], g:job_opts)")
  316. nvim('command', 'call jobclose(j, "stdin")')
  317. eq(false, pcall(function()
  318. nvim('command', 'call jobsend(j, ["some data"])')
  319. end))
  320. command("let g:job_opts.stdin = 'null'")
  321. nvim('command', "let j = jobstart(['cat', '-'], g:job_opts)")
  322. eq(false, pcall(function()
  323. nvim('command', 'call jobsend(j, ["some data"])')
  324. end))
  325. end)
  326. it('disallows jobsend on a non-existent job', function()
  327. eq(false, pcall(eval, "jobsend(-1, 'lol')"))
  328. eq(0, eval('jobstop(-1)'))
  329. end)
  330. it('jobstop twice on the stopped or exited job return 0', function()
  331. nvim('command', "let j = jobstart(['cat', '-'], g:job_opts)")
  332. neq(0, eval('j'))
  333. eq(1, eval("jobstop(j)"))
  334. eq(0, eval("jobstop(j)"))
  335. end)
  336. it('will not leak memory if we leave a job running', function()
  337. nvim('command', "call jobstart(['cat', '-'], g:job_opts)")
  338. end)
  339. it('can get the pid value using getpid', function()
  340. nvim('command', "let j = jobstart(['cat', '-'], g:job_opts)")
  341. local pid = eval('jobpid(j)')
  342. neq(NIL, meths.get_proc(pid))
  343. nvim('command', 'call jobstop(j)')
  344. eq({'notification', 'stdout', {0, {''}}}, next_msg())
  345. eq({'notification', 'exit', {0, 143}}, next_msg())
  346. eq(NIL, meths.get_proc(pid))
  347. end)
  348. it("do not survive the exit of nvim", function()
  349. -- use sleep, which doesn't die on stdin close
  350. nvim('command', "let g:j = jobstart(has('win32') ? ['ping', '-n', '1001', '127.0.0.1'] : ['sleep', '1000'], g:job_opts)")
  351. local pid = eval('jobpid(g:j)')
  352. neq(NIL, meths.get_proc(pid))
  353. clear()
  354. eq(NIL, meths.get_proc(pid))
  355. end)
  356. it('can survive the exit of nvim with "detach"', function()
  357. nvim('command', 'let g:job_opts.detach = 1')
  358. nvim('command', "let g:j = jobstart(has('win32') ? ['ping', '-n', '1001', '127.0.0.1'] : ['sleep', '1000'], g:job_opts)")
  359. local pid = eval('jobpid(g:j)')
  360. neq(NIL, meths.get_proc(pid))
  361. clear()
  362. neq(NIL, meths.get_proc(pid))
  363. -- clean up after ourselves
  364. eq(0, os_kill(pid))
  365. end)
  366. it('can pass user data to the callback', function()
  367. nvim('command', 'let g:job_opts.user = {"n": 5, "s": "str", "l": [1]}')
  368. nvim('command', [[call jobstart('echo foo', g:job_opts)]])
  369. local data = {n = 5, s = 'str', l = {1}}
  370. expect_msg_seq(
  371. { {'notification', 'stdout', {data, {'foo', ''}}},
  372. {'notification', 'stdout', {data, {''}}},
  373. },
  374. -- Alternative sequence:
  375. { {'notification', 'stdout', {data, {'foo'}}},
  376. {'notification', 'stdout', {data, {'', ''}}},
  377. {'notification', 'stdout', {data, {''}}},
  378. }
  379. )
  380. eq({'notification', 'exit', {data, 0}}, next_msg())
  381. end)
  382. it('can omit data callbacks', function()
  383. nvim('command', 'unlet g:job_opts.on_stdout')
  384. nvim('command', 'let g:job_opts.user = 5')
  385. nvim('command', [[call jobstart('echo foo', g:job_opts)]])
  386. eq({'notification', 'exit', {5, 0}}, next_msg())
  387. end)
  388. it('can omit exit callback', function()
  389. nvim('command', 'unlet g:job_opts.on_exit')
  390. nvim('command', 'let g:job_opts.user = 5')
  391. nvim('command', [[call jobstart('echo foo', g:job_opts)]])
  392. expect_msg_seq(
  393. { {'notification', 'stdout', {5, {'foo', ''} } },
  394. {'notification', 'stdout', {5, {''} } },
  395. },
  396. -- Alternative sequence:
  397. { {'notification', 'stdout', {5, {'foo'} } },
  398. {'notification', 'stdout', {5, {'', ''} } },
  399. {'notification', 'stdout', {5, {''} } },
  400. }
  401. )
  402. end)
  403. it('will pass return code with the exit event', function()
  404. nvim('command', 'let g:job_opts.user = 5')
  405. nvim('command', "call jobstart('exit 55', g:job_opts)")
  406. eq({'notification', 'stdout', {5, {''}}}, next_msg())
  407. eq({'notification', 'exit', {5, 55}}, next_msg())
  408. end)
  409. it('can receive dictionary functions', function()
  410. source([[
  411. let g:dict = {'id': 10}
  412. function g:dict.on_exit(id, code, event)
  413. call rpcnotify(g:channel, a:event, a:code, self.id)
  414. endfunction
  415. call jobstart('exit 45', g:dict)
  416. ]])
  417. eq({'notification', 'exit', {45, 10}}, next_msg())
  418. end)
  419. it('can redefine callbacks being used by a job', function()
  420. local screen = Screen.new()
  421. screen:attach()
  422. screen:set_default_attr_ids({
  423. [1] = {bold=true, foreground=Screen.colors.Blue},
  424. })
  425. source([[
  426. function! g:JobHandler(job_id, data, event)
  427. endfunction
  428. let g:callbacks = {
  429. \ 'on_stdout': function('g:JobHandler'),
  430. \ 'on_stderr': function('g:JobHandler'),
  431. \ 'on_exit': function('g:JobHandler')
  432. \ }
  433. let job = jobstart(['cat', '-'], g:callbacks)
  434. ]])
  435. poke_eventloop()
  436. source([[
  437. function! g:JobHandler(job_id, data, event)
  438. endfunction
  439. ]])
  440. eq("", eval("v:errmsg"))
  441. end)
  442. it('requires funcrefs for script-local (s:) functions', function()
  443. local screen = Screen.new(60, 5)
  444. screen:attach()
  445. screen:set_default_attr_ids({
  446. [1] = {bold = true, foreground = Screen.colors.Blue1},
  447. [2] = {foreground = Screen.colors.Grey100, background = Screen.colors.Red},
  448. [3] = {bold = true, foreground = Screen.colors.SeaGreen4}
  449. })
  450. -- Pass job callback names _without_ `function(...)`.
  451. source([[
  452. function! s:OnEvent(id, data, event) dict
  453. let g:job_result = get(self, 'user')
  454. endfunction
  455. let s:job = jobstart('echo "foo"', {
  456. \ 'on_stdout': 's:OnEvent',
  457. \ 'on_stderr': 's:OnEvent',
  458. \ 'on_exit': 's:OnEvent',
  459. \ })
  460. ]])
  461. screen:expect{any="{2:E120: Using <SID> not in a script context: s:OnEvent}"}
  462. end)
  463. it('does not repeat output with slow output handlers', function()
  464. source([[
  465. let d = {'data': []}
  466. function! d.on_stdout(job, data, event) dict
  467. call add(self.data, Normalize(a:data))
  468. sleep 200m
  469. endfunction
  470. function! d.on_exit(job, data, event) dict
  471. let g:exit_data = copy(self.data)
  472. endfunction
  473. if has('win32')
  474. let cmd = 'for /L %I in (1,1,5) do @(echo %I& ping -n 2 127.0.0.1 > nul)'
  475. else
  476. let cmd = ['sh', '-c', 'for i in 1 2 3 4 5; do echo $i; sleep 0.1; done']
  477. endif
  478. let g:id = jobstart(cmd, d)
  479. sleep 1500m
  480. call jobwait([g:id])
  481. ]])
  482. local expected = {'1', '2', '3', '4', '5', ''}
  483. local chunks = eval('d.data')
  484. -- check nothing was received after exit, including EOF
  485. eq(eval('g:exit_data'), chunks)
  486. local received = {''}
  487. for i, chunk in ipairs(chunks) do
  488. if i < #chunks then
  489. -- if chunks got joined, a spurious [''] callback was not sent
  490. neq({''}, chunk)
  491. else
  492. -- but EOF callback is still sent
  493. eq({''}, chunk)
  494. end
  495. received[#received] = received[#received]..chunk[1]
  496. for j = 2, #chunk do
  497. received[#received+1] = chunk[j]
  498. end
  499. end
  500. eq(expected, received)
  501. end)
  502. it('does not invoke callbacks recursively', function()
  503. source([[
  504. let d = {'data': []}
  505. function! d.on_stdout(job, data, event) dict
  506. " if callbacks were invoked recursively, this would cause on_stdout
  507. " to be invoked recursively and the data reversed on the call stack
  508. sleep 200m
  509. call add(self.data, Normalize(a:data))
  510. endfunction
  511. function! d.on_exit(job, data, event) dict
  512. let g:exit_data = copy(self.data)
  513. endfunction
  514. if has('win32')
  515. let cmd = 'for /L %I in (1,1,5) do @(echo %I& ping -n 2 127.0.0.1 > nul)'
  516. else
  517. let cmd = ['sh', '-c', 'for i in 1 2 3 4 5; do echo $i; sleep 0.1; done']
  518. endif
  519. let g:id = jobstart(cmd, d)
  520. sleep 1500m
  521. call jobwait([g:id])
  522. ]])
  523. local expected = {'1', '2', '3', '4', '5', ''}
  524. local chunks = eval('d.data')
  525. -- check nothing was received after exit, including EOF
  526. eq(eval('g:exit_data'), chunks)
  527. local received = {''}
  528. for i, chunk in ipairs(chunks) do
  529. if i < #chunks then
  530. -- if chunks got joined, a spurious [''] callback was not sent
  531. neq({''}, chunk)
  532. else
  533. -- but EOF callback is still sent
  534. eq({''}, chunk)
  535. end
  536. received[#received] = received[#received]..chunk[1]
  537. for j = 2, #chunk do
  538. received[#received+1] = chunk[j]
  539. end
  540. end
  541. eq(expected, received)
  542. end)
  543. it('jobstart() works with partial functions', function()
  544. source([[
  545. function PrintArgs(a1, a2, id, data, event)
  546. " Windows: remove ^M
  547. let normalized = map(a:data, 'substitute(v:val, "\r", "", "g")')
  548. call rpcnotify(g:channel, '1', a:a1, a:a2, normalized, a:event)
  549. endfunction
  550. let Callback = function('PrintArgs', ["foo", "bar"])
  551. let g:job_opts = {'on_stdout': Callback}
  552. call jobstart('echo some text', g:job_opts)
  553. ]])
  554. expect_msg_seq(
  555. { {'notification', '1', {'foo', 'bar', {'some text', ''}, 'stdout'}},
  556. },
  557. -- Alternative sequence:
  558. { {'notification', '1', {'foo', 'bar', {'some text'}, 'stdout'}},
  559. {'notification', '1', {'foo', 'bar', {'', ''}, 'stdout'}},
  560. }
  561. )
  562. end)
  563. it('jobstart() works with closures', function()
  564. source([[
  565. fun! MkFun()
  566. let a1 = 'foo'
  567. let a2 = 'bar'
  568. return {id, data, event -> rpcnotify(g:channel, '1', a1, a2, Normalize(data), event)}
  569. endfun
  570. let g:job_opts = {'on_stdout': MkFun()}
  571. call jobstart('echo some text', g:job_opts)
  572. ]])
  573. expect_msg_seq(
  574. { {'notification', '1', {'foo', 'bar', {'some text', ''}, 'stdout'}},
  575. },
  576. -- Alternative sequence:
  577. { {'notification', '1', {'foo', 'bar', {'some text'}, 'stdout'}},
  578. {'notification', '1', {'foo', 'bar', {'', ''}, 'stdout'}},
  579. }
  580. )
  581. end)
  582. it('jobstart() works when closure passed directly to `jobstart`', function()
  583. source([[
  584. let g:job_opts = {'on_stdout': {id, data, event -> rpcnotify(g:channel, '1', 'foo', 'bar', Normalize(data), event)}}
  585. call jobstart('echo some text', g:job_opts)
  586. ]])
  587. expect_msg_seq(
  588. { {'notification', '1', {'foo', 'bar', {'some text', ''}, 'stdout'}},
  589. },
  590. -- Alternative sequence:
  591. { {'notification', '1', {'foo', 'bar', {'some text'}, 'stdout'}},
  592. {'notification', '1', {'foo', 'bar', {'', ''}, 'stdout'}},
  593. }
  594. )
  595. end)
  596. describe('jobwait', function()
  597. before_each(function()
  598. if iswin() then
  599. helpers.set_shell_powershell()
  600. end
  601. end)
  602. it('returns a list of status codes', function()
  603. source([[
  604. call rpcnotify(g:channel, 'wait', jobwait(has('win32') ? [
  605. \ jobstart('Start-Sleep -Milliseconds 100; exit 4'),
  606. \ jobstart('Start-Sleep -Milliseconds 300; exit 5'),
  607. \ jobstart('Start-Sleep -Milliseconds 500; exit 6'),
  608. \ jobstart('Start-Sleep -Milliseconds 700; exit 7')
  609. \ ] : [
  610. \ jobstart('sleep 0.10; exit 4'),
  611. \ jobstart('sleep 0.110; exit 5'),
  612. \ jobstart('sleep 0.210; exit 6'),
  613. \ jobstart('sleep 0.310; exit 7')
  614. \ ]))
  615. ]])
  616. eq({'notification', 'wait', {{4, 5, 6, 7}}}, next_msg())
  617. end)
  618. it('will run callbacks while waiting', function()
  619. source([[
  620. let g:dict = {}
  621. let g:jobs = []
  622. let g:exits = []
  623. function g:dict.on_stdout(id, code, event) abort
  624. call add(g:jobs, a:id)
  625. endfunction
  626. function g:dict.on_exit(id, code, event) abort
  627. if a:code != 5
  628. throw 'Error!'
  629. endif
  630. call add(g:exits, a:id)
  631. endfunction
  632. call jobwait(has('win32') ? [
  633. \ jobstart('Start-Sleep -Milliseconds 100; exit 5', g:dict),
  634. \ jobstart('Start-Sleep -Milliseconds 300; exit 5', g:dict),
  635. \ jobstart('Start-Sleep -Milliseconds 500; exit 5', g:dict),
  636. \ jobstart('Start-Sleep -Milliseconds 700; exit 5', g:dict)
  637. \ ] : [
  638. \ jobstart('sleep 0.010; exit 5', g:dict),
  639. \ jobstart('sleep 0.030; exit 5', g:dict),
  640. \ jobstart('sleep 0.050; exit 5', g:dict),
  641. \ jobstart('sleep 0.070; exit 5', g:dict)
  642. \ ])
  643. call rpcnotify(g:channel, 'wait', sort(g:jobs), sort(g:exits))
  644. ]])
  645. eq({'notification', 'wait',
  646. {{3,4,5,6}, {3,4,5,6}}}, next_msg())
  647. end)
  648. it('will return status codes in the order of passed ids', function()
  649. source([[
  650. call rpcnotify(g:channel, 'wait', jobwait(has('win32') ? [
  651. \ jobstart('Start-Sleep -Milliseconds 700; exit 4'),
  652. \ jobstart('Start-Sleep -Milliseconds 500; exit 5'),
  653. \ jobstart('Start-Sleep -Milliseconds 300; exit 6'),
  654. \ jobstart('Start-Sleep -Milliseconds 100; exit 7')
  655. \ ] : [
  656. \ jobstart('sleep 0.070; exit 4'),
  657. \ jobstart('sleep 0.050; exit 5'),
  658. \ jobstart('sleep 0.030; exit 6'),
  659. \ jobstart('sleep 0.010; exit 7')
  660. \ ]))
  661. ]])
  662. eq({'notification', 'wait', {{4, 5, 6, 7}}}, next_msg())
  663. end)
  664. it('will return -3 for invalid job ids', function()
  665. source([[
  666. call rpcnotify(g:channel, 'wait', jobwait([
  667. \ -10,
  668. \ jobstart((has('win32') ? 'Start-Sleep -Milliseconds 100' : 'sleep 0.01').'; exit 5'),
  669. \ ]))
  670. ]])
  671. eq({'notification', 'wait', {{-3, 5}}}, next_msg())
  672. end)
  673. it('will return -2 when interrupted without timeout', function()
  674. feed_command('call rpcnotify(g:channel, "ready") | '..
  675. 'call rpcnotify(g:channel, "wait", '..
  676. 'jobwait([jobstart("'..
  677. (iswin() and 'Start-Sleep 10' or 'sleep 10')..
  678. '; exit 55")]))')
  679. eq({'notification', 'ready', {}}, next_msg())
  680. feed('<c-c>')
  681. eq({'notification', 'wait', {{-2}}}, next_msg())
  682. end)
  683. it('will return -2 when interrupted with timeout', function()
  684. feed_command('call rpcnotify(g:channel, "ready") | '..
  685. 'call rpcnotify(g:channel, "wait", '..
  686. 'jobwait([jobstart("'..
  687. (iswin() and 'Start-Sleep 10' or 'sleep 10')..
  688. '; exit 55")], 10000))')
  689. eq({'notification', 'ready', {}}, next_msg())
  690. feed('<c-c>')
  691. eq({'notification', 'wait', {{-2}}}, next_msg())
  692. end)
  693. it('can be called recursively', function()
  694. if helpers.pending_win32(pending) then return end -- TODO: Need `cat`.
  695. source([[
  696. let g:opts = {}
  697. let g:counter = 0
  698. function g:opts.on_stdout(id, msg, _event)
  699. if self.state == 0
  700. if self.counter < 10
  701. call Run()
  702. endif
  703. let self.state = 1
  704. call jobsend(a:id, "line1\n")
  705. elseif self.state == 1
  706. let self.state = 2
  707. call jobsend(a:id, "line2\n")
  708. elseif self.state == 2
  709. let self.state = 3
  710. call jobsend(a:id, "line3\n")
  711. elseif self.state == 3
  712. let self.state = 4
  713. call rpcnotify(g:channel, 'w', printf('job %d closed', self.counter))
  714. call jobclose(a:id, 'stdin')
  715. endif
  716. endfunction
  717. function g:opts.on_exit(...)
  718. call rpcnotify(g:channel, 'w', printf('job %d exited', self.counter))
  719. endfunction
  720. function Run()
  721. let g:counter += 1
  722. let j = copy(g:opts)
  723. let j.state = 0
  724. let j.counter = g:counter
  725. call jobwait([
  726. \ jobstart('echo ready; cat -', j),
  727. \ ])
  728. endfunction
  729. ]])
  730. feed_command('call Run()')
  731. local r
  732. for i = 10, 1, -1 do
  733. r = next_msg()
  734. eq('job '..i..' closed', r[3][1])
  735. r = next_msg()
  736. eq('job '..i..' exited', r[3][1])
  737. end
  738. eq(10, nvim('eval', 'g:counter'))
  739. end)
  740. describe('with timeout argument', function()
  741. it('will return -1 if the wait timed out', function()
  742. source([[
  743. call rpcnotify(g:channel, 'wait', jobwait([
  744. \ jobstart((has('win32') ? 'Start-Sleep 10' : 'sleep 10').'; exit 5'),
  745. \ ], 100))
  746. ]])
  747. eq({'notification', 'wait', {{-1}}}, next_msg())
  748. end)
  749. it('can pass 0 to check if a job exists', function()
  750. source([[
  751. call rpcnotify(g:channel, 'wait', jobwait(has('win32') ? [
  752. \ jobstart('Start-Sleep -Milliseconds 50; exit 4'),
  753. \ jobstart('Start-Sleep -Milliseconds 300; exit 5'),
  754. \ ] : [
  755. \ jobstart('sleep 0.05; exit 4'),
  756. \ jobstart('sleep 0.3; exit 5'),
  757. \ ], 0))
  758. ]])
  759. eq({'notification', 'wait', {{-1, -1}}}, next_msg())
  760. end)
  761. end)
  762. end)
  763. pending('exit event follows stdout, stderr', function()
  764. nvim('command', "let g:job_opts.on_stderr = function('OnEvent')")
  765. nvim('command', "let j = jobstart(['cat', '-'], g:job_opts)")
  766. nvim('eval', 'jobsend(j, "abcdef")')
  767. nvim('eval', 'jobstop(j)')
  768. expect_msg_seq(
  769. { {'notification', 'stdout', {0, {'abcdef'}}},
  770. {'notification', 'stdout', {0, {''}}},
  771. {'notification', 'stderr', {0, {''}}},
  772. },
  773. -- Alternative sequence:
  774. { {'notification', 'stderr', {0, {''}}},
  775. {'notification', 'stdout', {0, {'abcdef'}}},
  776. {'notification', 'stdout', {0, {''}}},
  777. },
  778. -- Alternative sequence:
  779. { {'notification', 'stdout', {0, {'abcdef'}}},
  780. {'notification', 'stderr', {0, {''}}},
  781. {'notification', 'stdout', {0, {''}}},
  782. }
  783. )
  784. eq({'notification', 'exit', {0, 143}}, next_msg())
  785. end)
  786. it('cannot have both rpc and pty options', function()
  787. command("let g:job_opts.pty = v:true")
  788. command("let g:job_opts.rpc = v:true")
  789. local _, err = pcall(command, "let j = jobstart(['cat', '-'], g:job_opts)")
  790. ok(string.find(err, "E475: Invalid argument: job cannot have both 'pty' and 'rpc' options set") ~= nil)
  791. end)
  792. it('does not crash when repeatedly failing to start shell', function()
  793. source([[
  794. set shell=nosuchshell
  795. func! DoIt()
  796. call jobstart('true')
  797. call jobstart('true')
  798. endfunc
  799. ]])
  800. -- The crash only triggered if both jobs are cleaned up on the same event
  801. -- loop tick. This is also prevented by try-block, so feed must be used.
  802. feed_command("call DoIt()")
  803. feed('<cr>') -- press RETURN
  804. eq(2,eval('1+1'))
  805. end)
  806. it('jobstop() kills entire process tree #6530', function()
  807. -- XXX: Using `nvim` isn't a good test, it reaps its children on exit.
  808. -- local c = 'call jobstart([v:progpath, "-u", "NONE", "-i", "NONE", "--headless"])'
  809. -- local j = eval("jobstart([v:progpath, '-u', 'NONE', '-i', 'NONE', '--headless', '-c', '"
  810. -- ..c.."', '-c', '"..c.."'])")
  811. -- Create child with several descendants.
  812. if iswin() then
  813. source([[
  814. function! s:formatprocs(pid, prefix)
  815. let result = ''
  816. let result .= a:prefix . printf("%-24.24s%6s %12.12s %s\n",
  817. \ s:procs[a:pid]['name'],
  818. \ a:pid,
  819. \ s:procs[a:pid]['Session Name'],
  820. \ s:procs[a:pid]['Session'])
  821. if has_key(s:procs[a:pid], 'children')
  822. for pid in s:procs[a:pid]['children']
  823. let result .= s:formatprocs(pid, a:prefix . ' ')
  824. endfor
  825. endif
  826. return result
  827. endfunction
  828. function! PsTree() abort
  829. let s:procs = {}
  830. for proc in map(
  831. \ map(
  832. \ systemlist('tasklist /NH'),
  833. \ 'substitute(v:val, "\r", "", "")'),
  834. \ 'split(v:val, "\\s\\+")')
  835. if len(proc) == 6
  836. let s:procs[proc[1]] ..']]'..[[= {'name': proc[0],
  837. \ 'Session Name': proc[2],
  838. \ 'Session': proc[3]}
  839. endif
  840. endfor
  841. for pid in keys(s:procs)
  842. let children = nvim_get_proc_children(str2nr(pid))
  843. if !empty(children)
  844. let s:procs[pid]['children'] = children
  845. for cpid in children
  846. let s:procs[printf('%d', cpid)]['parent'] = str2nr(pid)
  847. endfor
  848. endif
  849. endfor
  850. let result = ''
  851. for pid in sort(keys(s:procs), {i1, i2 -> i1 - i2})
  852. if !has_key(s:procs[pid], 'parent')
  853. let result .= s:formatprocs(pid, '')
  854. endif
  855. endfor
  856. return result
  857. endfunction
  858. ]])
  859. end
  860. local sleep_cmd = (iswin()
  861. and 'ping -n 31 127.0.0.1'
  862. or 'sleep 30')
  863. local j = eval("jobstart('"..sleep_cmd..' | '..sleep_cmd..' | '..sleep_cmd.."')")
  864. local ppid = funcs.jobpid(j)
  865. local children
  866. if iswin() then
  867. local status, result = pcall(retry, nil, nil, function()
  868. children = meths.get_proc_children(ppid)
  869. -- On Windows conhost.exe may exist, and
  870. -- e.g. vctip.exe might appear. #10783
  871. ok(#children >= 3 and #children <= 5)
  872. end)
  873. if not status then
  874. print('')
  875. print(eval('PsTree()'))
  876. error(result)
  877. end
  878. else
  879. retry(nil, nil, function()
  880. children = meths.get_proc_children(ppid)
  881. eq(3, #children)
  882. end)
  883. end
  884. -- Assert that nvim_get_proc() sees the children.
  885. for _, child_pid in ipairs(children) do
  886. local info = meths.get_proc(child_pid)
  887. -- eq((iswin() and 'nvim.exe' or 'nvim'), info.name)
  888. eq(ppid, info.ppid)
  889. end
  890. -- Kill the root of the tree.
  891. eq(1, funcs.jobstop(j))
  892. -- Assert that the children were killed.
  893. retry(nil, nil, function()
  894. for _, child_pid in ipairs(children) do
  895. eq(NIL, meths.get_proc(child_pid))
  896. end
  897. end)
  898. end)
  899. it('jobstop on same id before stopped', function()
  900. nvim('command', 'let j = jobstart(["cat", "-"], g:job_opts)')
  901. neq(0, eval('j'))
  902. eq({1, 0}, eval('[jobstop(j), jobstop(j)]'))
  903. end)
  904. describe('running tty-test program', function()
  905. if helpers.pending_win32(pending) then return end
  906. local function next_chunk()
  907. local rv
  908. while true do
  909. local msg = next_msg()
  910. local data = msg[3][2]
  911. for i = 1, #data do
  912. data[i] = data[i]:gsub('\n', '\000')
  913. end
  914. rv = table.concat(data, '\n')
  915. rv = rv:gsub('\r\n$', ''):gsub('^\r\n', '')
  916. if rv ~= '' then
  917. break
  918. end
  919. end
  920. return rv
  921. end
  922. local j
  923. local function send(str)
  924. -- check no nvim_chan_free double free with pty job (#14198)
  925. meths.chan_send(j, str)
  926. end
  927. before_each(function()
  928. -- Redefine Normalize() so that TTY data is not munged.
  929. source([[
  930. function! Normalize(data) abort
  931. return a:data
  932. endfunction
  933. ]])
  934. local ext = iswin() and '.exe' or ''
  935. insert(nvim_dir..'/tty-test'..ext) -- Full path to tty-test.
  936. nvim('command', 'let g:job_opts.pty = 1')
  937. nvim('command', 'let exec = [expand("<cfile>:p")]')
  938. nvim('command', "let j = jobstart(exec, g:job_opts)")
  939. j = eval'j'
  940. eq('tty ready', next_chunk())
  941. end)
  942. it('echoing input', function()
  943. send('test')
  944. eq('test', next_chunk())
  945. end)
  946. it('resizing window', function()
  947. nvim('command', 'call jobresize(j, 40, 10)')
  948. eq('rows: 10, cols: 40', next_chunk())
  949. nvim('command', 'call jobresize(j, 10, 40)')
  950. eq('rows: 40, cols: 10', next_chunk())
  951. end)
  952. it('jobclose() sends SIGHUP', function()
  953. nvim('command', 'call jobclose(j)')
  954. local msg = next_msg()
  955. msg = (msg[2] == 'stdout') and next_msg() or msg -- Skip stdout, if any.
  956. eq({'notification', 'exit', {0, 42}}, msg)
  957. end)
  958. it('jobstart() does not keep ptmx file descriptor open', function()
  959. -- Start another job (using libuv)
  960. command('let g:job_opts.pty = 0')
  961. local other_jobid = eval("jobstart(['cat', '-'], g:job_opts)")
  962. local other_pid = eval('jobpid(' .. other_jobid .. ')')
  963. -- Other job doesn't block first job from recieving SIGHUP on jobclose()
  964. command('call jobclose(j)')
  965. -- Have to wait so that the SIGHUP can be processed by tty-test on time.
  966. -- Can't wait for the next message in case this test fails, if it fails
  967. -- there won't be any more messages, and the test would hang.
  968. helpers.sleep(100)
  969. local err = exc_exec('call jobpid(j)')
  970. eq('Vim(call):E900: Invalid channel id', err)
  971. -- cleanup
  972. eq(other_pid, eval('jobpid(' .. other_jobid .. ')'))
  973. command('call jobstop(' .. other_jobid .. ')')
  974. end)
  975. end)
  976. end)
  977. describe("pty process teardown", function()
  978. local screen
  979. before_each(function()
  980. clear()
  981. screen = Screen.new(30, 6)
  982. screen:attach()
  983. screen:expect([[
  984. ^ |
  985. ~ |
  986. ~ |
  987. ~ |
  988. ~ |
  989. |
  990. ]])
  991. end)
  992. it("does not prevent/delay exit. #4798 #4900", function()
  993. if helpers.pending_win32(pending) then return end
  994. -- Use a nested nvim (in :term) to test without --headless.
  995. feed_command(":terminal '"..helpers.nvim_prog
  996. .."' -u NONE -i NONE --cmd '"..nvim_set.."' "
  997. -- Use :term again in the _nested_ nvim to get a PTY process.
  998. -- Use `sleep` to simulate a long-running child of the PTY.
  999. .."+terminal +'!(sleep 300 &)' +qa")
  1000. -- Exiting should terminate all descendants (PTY, its children, ...).
  1001. screen:expect([[
  1002. ^ |
  1003. [Process exited 0] |
  1004. |
  1005. |
  1006. |
  1007. |
  1008. ]])
  1009. end)
  1010. end)