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