system_spec.lua 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. -- Tests for system() and :! shell.
  2. local t = require('test.testutil')
  3. local n = require('test.functional.testnvim')()
  4. local Screen = require('test.functional.ui.screen')
  5. local assert_alive = n.assert_alive
  6. local testprg = n.testprg
  7. local eq, call, clear, eval, feed_command, feed, api =
  8. t.eq, n.call, n.clear, n.eval, n.feed_command, n.feed, n.api
  9. local command = n.command
  10. local insert = n.insert
  11. local expect = n.expect
  12. local exc_exec = n.exc_exec
  13. local os_kill = n.os_kill
  14. local pcall_err = t.pcall_err
  15. local is_os = t.is_os
  16. local function create_file_with_nuls(name)
  17. return function()
  18. feed('ipart1<C-V>000part2<C-V>000part3<ESC>:w ' .. name .. '<CR>')
  19. eval('1') -- wait for the file to be created
  20. end
  21. end
  22. local function delete_file(name)
  23. return function()
  24. eval("delete('" .. name .. "')")
  25. end
  26. end
  27. describe('system()', function()
  28. before_each(clear)
  29. describe('command passed as a List', function()
  30. it('throws error if cmd[0] is not executable', function()
  31. eq(
  32. "Vim:E475: Invalid value for argument cmd: 'this-should-not-exist' is not executable",
  33. pcall_err(call, 'system', { 'this-should-not-exist' })
  34. )
  35. eq(-1, eval('v:shell_error'))
  36. end)
  37. it('parameter validation does NOT modify v:shell_error', function()
  38. -- 1. Call system() with invalid parameters.
  39. -- 2. Assert that v:shell_error was NOT set.
  40. feed_command('call system({})')
  41. eq('E475: Invalid argument: expected String or List', eval('v:errmsg'))
  42. eq(0, eval('v:shell_error'))
  43. feed_command('call system([])')
  44. eq('E474: Invalid argument', eval('v:errmsg'))
  45. eq(0, eval('v:shell_error'))
  46. -- Provoke a non-zero v:shell_error.
  47. eq(
  48. "Vim:E475: Invalid value for argument cmd: 'this-should-not-exist' is not executable",
  49. pcall_err(call, 'system', { 'this-should-not-exist' })
  50. )
  51. local old_val = eval('v:shell_error')
  52. eq(-1, old_val)
  53. -- 1. Call system() with invalid parameters.
  54. -- 2. Assert that v:shell_error was NOT modified.
  55. feed_command('call system({})')
  56. eq(old_val, eval('v:shell_error'))
  57. feed_command('call system([])')
  58. eq(old_val, eval('v:shell_error'))
  59. end)
  60. it('quotes arguments correctly #5280', function()
  61. local out =
  62. call('system', { testprg('printargs-test'), [[1]], [[2 "3]], [[4 ' 5]], [[6 ' 7']] })
  63. eq(0, eval('v:shell_error'))
  64. eq([[arg1=1;arg2=2 "3;arg3=4 ' 5;arg4=6 ' 7';]], out)
  65. out = call('system', { testprg('printargs-test'), [['1]], [[2 "3]] })
  66. eq(0, eval('v:shell_error'))
  67. eq([[arg1='1;arg2=2 "3;]], out)
  68. out = call('system', { testprg('printargs-test'), 'A\nB' })
  69. eq(0, eval('v:shell_error'))
  70. eq('arg1=A\nB;', out)
  71. end)
  72. it('calls executable in $PATH', function()
  73. if 0 == eval("executable('python3')") then
  74. pending('missing `python3`')
  75. end
  76. eq('foo\n', eval([[system(['python3', '-c', 'print("foo")'])]]))
  77. eq(0, eval('v:shell_error'))
  78. end)
  79. it('does NOT run in shell', function()
  80. if is_os('win') then
  81. eq(
  82. '%PATH%\n',
  83. eval(
  84. "system(['powershell', '-NoProfile', '-NoLogo', '-ExecutionPolicy', 'RemoteSigned', '-Command', 'Write-Output', '%PATH%'])"
  85. )
  86. )
  87. else
  88. eq('* $PATH %PATH%\n', eval("system(['echo', '*', '$PATH', '%PATH%'])"))
  89. end
  90. end)
  91. end)
  92. it('sets v:shell_error', function()
  93. if is_os('win') then
  94. eval([[system("cmd.exe /c exit")]])
  95. eq(0, eval('v:shell_error'))
  96. eval([[system("cmd.exe /c exit 1")]])
  97. eq(1, eval('v:shell_error'))
  98. eval([[system("cmd.exe /c exit 5")]])
  99. eq(5, eval('v:shell_error'))
  100. eval([[system('this-should-not-exist')]])
  101. eq(1, eval('v:shell_error'))
  102. else
  103. eval([[system("sh -c 'exit'")]])
  104. eq(0, eval('v:shell_error'))
  105. eval([[system("sh -c 'exit 1'")]])
  106. eq(1, eval('v:shell_error'))
  107. eval([[system("sh -c 'exit 5'")]])
  108. eq(5, eval('v:shell_error'))
  109. eval([[system('this-should-not-exist')]])
  110. eq(127, eval('v:shell_error'))
  111. end
  112. end)
  113. describe('executes shell function', function()
  114. local screen
  115. before_each(function()
  116. screen = Screen.new()
  117. end)
  118. if is_os('win') then
  119. local function test_more()
  120. eq('root = true', eval([[get(split(system('"more" ".editorconfig"'), "\n"), 0, '')]]))
  121. end
  122. local function test_shell_unquoting()
  123. eval([[system('"ping" "-n" "1" "127.0.0.1"')]])
  124. eq(0, eval('v:shell_error'))
  125. eq('"a b"\n', eval([[system('cmd /s/c "cmd /s/c "cmd /s/c "echo "a b""""')]]))
  126. eq(
  127. '"a b"\n',
  128. eval(
  129. [[system('powershell -NoProfile -NoLogo -ExecutionPolicy RemoteSigned -Command Write-Output ''\^"a b\^"''')]]
  130. )
  131. )
  132. end
  133. it('with shell=cmd.exe', function()
  134. command('set shell=cmd.exe')
  135. eq('""\n', eval([[system('echo ""')]]))
  136. eq('"a b"\n', eval([[system('echo "a b"')]]))
  137. eq('a \nb\n', eval([[system('echo a & echo b')]]))
  138. eq('a \n', eval([[system('echo a 2>&1')]]))
  139. test_more()
  140. eval([[system('cd "C:\Program Files"')]])
  141. eq(0, eval('v:shell_error'))
  142. test_shell_unquoting()
  143. end)
  144. it('with shell=cmd', function()
  145. command('set shell=cmd')
  146. eq('"a b"\n', eval([[system('echo "a b"')]]))
  147. test_more()
  148. test_shell_unquoting()
  149. end)
  150. it('with shell=$COMSPEC', function()
  151. local comspecshell = eval("fnamemodify($COMSPEC, ':t')")
  152. if comspecshell == 'cmd.exe' then
  153. command('set shell=$COMSPEC')
  154. eq('"a b"\n', eval([[system('echo "a b"')]]))
  155. test_more()
  156. test_shell_unquoting()
  157. else
  158. pending('$COMSPEC is not cmd.exe: ' .. comspecshell)
  159. end
  160. end)
  161. it('with powershell', function()
  162. n.set_shell_powershell()
  163. eq('a\nb\n', eval([[system('Write-Output a b')]]))
  164. eq('C:\\\n', eval([[system('cd c:\; (Get-Location).Path')]]))
  165. eq('a b\n', eval([[system('Write-Output "a b"')]]))
  166. end)
  167. end
  168. it('powershell w/ UTF-8 text #13713', function()
  169. if not n.has_powershell() then
  170. pending('powershell not found', function() end)
  171. return
  172. end
  173. n.set_shell_powershell()
  174. eq('ああ\n', eval([[system('Write-Output "ああ"')]]))
  175. -- Sanity test w/ default encoding
  176. -- * on Windows, expected to default to Western European enc
  177. -- * on Linux, expected to default to UTF8
  178. command([[let &shellcmdflag = '-NoLogo -NoProfile -ExecutionPolicy RemoteSigned -Command ']])
  179. eq(is_os('win') and '??\n' or 'ああ\n', eval([[system('Write-Output "ああ"')]]))
  180. end)
  181. it('`echo` and waits for its return', function()
  182. feed(':call system("echo")<cr>')
  183. screen:expect([[
  184. ^ |
  185. {1:~ }|*12
  186. :call system("echo") |
  187. ]])
  188. end)
  189. it('prints verbose information', function()
  190. api.nvim_set_option_value('shell', 'fake_shell', {})
  191. api.nvim_set_option_value('shellcmdflag', 'cmdflag', {})
  192. screen:try_resize(72, 14)
  193. feed(':4verbose echo system("echo hi")<cr>')
  194. if is_os('win') then
  195. screen:expect { any = [[Executing command: "'fake_shell' 'cmdflag' '"echo hi"'"]] }
  196. else
  197. screen:expect { any = [[Executing command: "'fake_shell' 'cmdflag' 'echo hi'"]] }
  198. end
  199. feed('<cr>')
  200. end)
  201. it('self and total time recorded separately', function()
  202. local tempfile = t.tmpname()
  203. feed(':function! AlmostNoSelfTime()<cr>')
  204. feed('echo system("echo hi")<cr>')
  205. feed('endfunction<cr>')
  206. feed(':profile start ' .. tempfile .. '<cr>')
  207. feed(':profile func AlmostNoSelfTime<cr>')
  208. feed(':call AlmostNoSelfTime()<cr>')
  209. feed(':profile dump<cr>')
  210. feed(':edit ' .. tempfile .. '<cr>')
  211. local command_total_time = tonumber(n.fn.split(n.fn.getline(7))[2])
  212. local command_self_time = tonumber(n.fn.split(n.fn.getline(7))[3])
  213. t.neq(nil, command_total_time)
  214. t.neq(nil, command_self_time)
  215. end)
  216. it('`yes` interrupted with CTRL-C', function()
  217. feed(
  218. ':call system("'
  219. .. (is_os('win') and 'for /L %I in (1,0,2) do @echo y' or 'yes')
  220. .. '")<cr>'
  221. )
  222. screen:expect([[
  223. |
  224. {1:~ }|*12
  225. ]] .. (is_os('win') and [[
  226. :call system("for /L %I in (1,0,2) do @echo y") |]] or [[
  227. :call system("yes") |]]))
  228. feed('foo<c-c>')
  229. screen:expect([[
  230. ^ |
  231. {1:~ }|*12
  232. Type :qa and press <Enter> to exit Nvim |
  233. ]])
  234. end)
  235. it('`yes` interrupted with mapped CTRL-C', function()
  236. command('nnoremap <C-C> i')
  237. feed(
  238. ':call system("'
  239. .. (is_os('win') and 'for /L %I in (1,0,2) do @echo y' or 'yes')
  240. .. '")<cr>'
  241. )
  242. screen:expect([[
  243. |
  244. {1:~ }|*12
  245. ]] .. (is_os('win') and [[
  246. :call system("for /L %I in (1,0,2) do @echo y") |]] or [[
  247. :call system("yes") |]]))
  248. feed('foo<c-c>')
  249. screen:expect([[
  250. ^ |
  251. {1:~ }|*12
  252. {5:-- INSERT --} |
  253. ]])
  254. end)
  255. end)
  256. describe('passing no input', function()
  257. it('returns the program output', function()
  258. if is_os('win') then
  259. eq('echoed\n', eval('system("echo echoed")'))
  260. else
  261. eq('echoed', eval('system("printf echoed")'))
  262. end
  263. end)
  264. it('to backgrounded command does not crash', function()
  265. -- This is indeterminate, just exercise the codepath. May get E5677.
  266. feed_command(
  267. 'call system(has("win32") ? "start /b /wait cmd /c echo echoed" : "printf echoed &")'
  268. )
  269. local v_errnum = string.match(eval('v:errmsg'), '^E%d*:')
  270. if v_errnum then
  271. eq('E5677:', v_errnum)
  272. end
  273. assert_alive()
  274. end)
  275. end)
  276. describe('passing input', function()
  277. it('returns the program output', function()
  278. eq('input', eval('system("cat -", "input")'))
  279. end)
  280. it('to backgrounded command does not crash', function()
  281. -- This is indeterminate, just exercise the codepath. May get E5677.
  282. feed_command('call system(has("win32") ? "start /b /wait more" : "cat - &", "input")')
  283. local v_errnum = string.match(eval('v:errmsg'), '^E%d*:')
  284. if v_errnum then
  285. eq('E5677:', v_errnum)
  286. end
  287. assert_alive()
  288. end)
  289. it('works with an empty string', function()
  290. eq('test\n', eval('system("echo test", "")'))
  291. assert_alive()
  292. end)
  293. end)
  294. describe('passing a lot of input', function()
  295. it('returns the program output', function()
  296. local input = {}
  297. -- write more than 1mb of data, which should be enough to overcome
  298. -- the os buffer limit and force multiple event loop iterations to write
  299. -- everything
  300. for _ = 1, 0xffff do
  301. input[#input + 1] = '01234567890ABCDEFabcdef'
  302. end
  303. input = table.concat(input, '\n')
  304. api.nvim_set_var('input', input)
  305. eq(input, eval('system("cat -", g:input)'))
  306. end)
  307. end)
  308. describe('Number input', function()
  309. it('is treated as a buffer id', function()
  310. command("put ='text in buffer 1'")
  311. eq('\ntext in buffer 1\n', eval('system("cat", 1)'))
  312. eq('Vim(echo):E86: Buffer 42 does not exist', exc_exec('echo system("cat", 42)'))
  313. end)
  314. end)
  315. describe('with output containing NULs', function()
  316. local fname = 'Xtest_functional_vimscript_system_nuls'
  317. before_each(create_file_with_nuls(fname))
  318. after_each(delete_file(fname))
  319. it('replaces NULs by SOH characters', function()
  320. eq('part1\001part2\001part3\n', eval([[system('"cat" "]] .. fname .. [["')]]))
  321. end)
  322. end)
  323. describe('input passed as List', function()
  324. it('joins List items with linefeed characters', function()
  325. eq('line1\nline2\nline3', eval("system('cat -', ['line1', 'line2', 'line3'])"))
  326. end)
  327. -- Notice that NULs are converted to SOH when the data is read back. This
  328. -- is inconsistent and is a good reason for the existence of the
  329. -- `systemlist()` function, where input and output map to the same
  330. -- characters(see the following tests with `systemlist()` below)
  331. describe('with linefeed characters inside List items', function()
  332. it('converts linefeed characters to NULs', function()
  333. eq(
  334. 'l1\001p2\nline2\001a\001b\nl3',
  335. eval([[system('cat -', ["l1\np2", "line2\na\nb", 'l3'])]])
  336. )
  337. end)
  338. end)
  339. describe('with leading/trailing whitespace characters on items', function()
  340. it('preserves whitespace, replacing linefeeds by NULs', function()
  341. eq(
  342. 'line \nline2\001\n\001line3',
  343. eval([[system('cat -', ['line ', "line2\n", "\nline3"])]])
  344. )
  345. end)
  346. end)
  347. end)
  348. it("with a program that doesn't close stdout will exit properly after passing input", function()
  349. local out = eval(string.format("system('%s', 'clip-data')", testprg('streams-test')))
  350. assert(out:sub(0, 5) == 'pid: ', out)
  351. os_kill(out:match('%d+'))
  352. end)
  353. end)
  354. describe('systemlist()', function()
  355. -- Similar to `system()`, but returns List instead of String.
  356. before_each(clear)
  357. it('sets v:shell_error', function()
  358. if is_os('win') then
  359. eval([[systemlist("cmd.exe /c exit")]])
  360. eq(0, eval('v:shell_error'))
  361. eval([[systemlist("cmd.exe /c exit 1")]])
  362. eq(1, eval('v:shell_error'))
  363. eval([[systemlist("cmd.exe /c exit 5")]])
  364. eq(5, eval('v:shell_error'))
  365. eval([[systemlist('this-should-not-exist')]])
  366. eq(1, eval('v:shell_error'))
  367. else
  368. eval([[systemlist("sh -c 'exit'")]])
  369. eq(0, eval('v:shell_error'))
  370. eval([[systemlist("sh -c 'exit 1'")]])
  371. eq(1, eval('v:shell_error'))
  372. eval([[systemlist("sh -c 'exit 5'")]])
  373. eq(5, eval('v:shell_error'))
  374. eval([[systemlist('this-should-not-exist')]])
  375. eq(127, eval('v:shell_error'))
  376. end
  377. end)
  378. describe('executes shell function', function()
  379. local screen
  380. before_each(function()
  381. screen = Screen.new()
  382. end)
  383. it('`echo` and waits for its return', function()
  384. feed(':call systemlist("echo")<cr>')
  385. screen:expect([[
  386. ^ |
  387. {1:~ }|*12
  388. :call systemlist("echo") |
  389. ]])
  390. end)
  391. it('`yes` interrupted with CTRL-C', function()
  392. feed(':call systemlist("yes | xargs")<cr>')
  393. screen:expect([[
  394. |
  395. {1:~ }|*12
  396. :call systemlist("yes | xargs") |
  397. ]])
  398. feed('<c-c>')
  399. screen:expect([[
  400. ^ |
  401. {1:~ }|*12
  402. Type :qa and press <Enter> to exit Nvim |
  403. ]])
  404. end)
  405. end)
  406. describe('passing string with linefeed characters as input', function()
  407. it('splits the output on linefeed characters', function()
  408. eq({ 'abc', 'def', 'ghi' }, eval([[systemlist("cat -", "abc\ndef\nghi")]]))
  409. end)
  410. end)
  411. describe('passing a lot of input', function()
  412. it('returns the program output', function()
  413. local input = {}
  414. for _ = 1, 0xffff do
  415. input[#input + 1] = '01234567890ABCDEFabcdef'
  416. end
  417. api.nvim_set_var('input', input)
  418. eq(input, eval('systemlist("cat -", g:input)'))
  419. end)
  420. end)
  421. describe('with output containing NULs', function()
  422. local fname = 'Xtest_functional_vimscript_systemlist_nuls'
  423. before_each(function()
  424. command('set ff=unix')
  425. create_file_with_nuls(fname)()
  426. end)
  427. after_each(delete_file(fname))
  428. it('replaces NULs by newline characters', function()
  429. eq({ 'part1\npart2\npart3' }, eval([[systemlist('"cat" "]] .. fname .. [["')]]))
  430. end)
  431. end)
  432. describe('input passed as List', function()
  433. it('joins list items with linefeed characters', function()
  434. eq({ 'line1', 'line2', 'line3' }, eval("systemlist('cat -', ['line1', 'line2', 'line3'])"))
  435. end)
  436. -- Unlike `system()` which uses SOH to represent NULs, with `systemlist()`
  437. -- input and output are the same.
  438. describe('with linefeed characters inside list items', function()
  439. it('converts linefeed characters to NULs', function()
  440. eq(
  441. { 'l1\np2', 'line2\na\nb', 'l3' },
  442. eval([[systemlist('cat -', ["l1\np2", "line2\na\nb", 'l3'])]])
  443. )
  444. end)
  445. end)
  446. describe('with leading/trailing whitespace characters on items', function()
  447. it('preserves whitespace, replacing linefeeds by NULs', function()
  448. eq(
  449. { 'line ', 'line2\n', '\nline3' },
  450. eval([[systemlist('cat -', ['line ', "line2\n", "\nline3"])]])
  451. )
  452. end)
  453. end)
  454. end)
  455. describe('handles empty lines', function()
  456. it('in the middle', function()
  457. eq({ 'line one', '', 'line two' }, eval("systemlist('cat',['line one','','line two'])"))
  458. end)
  459. it('in the beginning', function()
  460. eq({ '', 'line one', 'line two' }, eval("systemlist('cat',['','line one','line two'])"))
  461. end)
  462. end)
  463. describe('when keepempty option is', function()
  464. it('0, ignores trailing newline', function()
  465. eq({ 'aa', 'bb' }, eval("systemlist('cat',['aa','bb'],0)"))
  466. eq({ 'aa', 'bb' }, eval("systemlist('cat',['aa','bb',''],0)"))
  467. end)
  468. it('1, preserves trailing newline', function()
  469. eq({ 'aa', 'bb' }, eval("systemlist('cat',['aa','bb'],1)"))
  470. eq({ 'aa', 'bb', '' }, eval("systemlist('cat',['aa','bb',''],2)"))
  471. end)
  472. end)
  473. it("with a program that doesn't close stdout will exit properly after passing input", function()
  474. local out = eval(string.format("systemlist('%s', 'clip-data')", testprg('streams-test')))
  475. assert(out[1]:sub(0, 5) == 'pid: ', out)
  476. os_kill(out[1]:match('%d+'))
  477. end)
  478. it('powershell w/ UTF-8 text #13713', function()
  479. if not n.has_powershell() then
  480. pending('powershell not found', function() end)
  481. return
  482. end
  483. n.set_shell_powershell()
  484. eq({ is_os('win') and 'あ\r' or 'あ' }, eval([[systemlist('Write-Output あ')]]))
  485. -- Sanity test w/ default encoding
  486. -- * on Windows, expected to default to Western European enc
  487. -- * on Linux, expected to default to UTF8
  488. command([[let &shellcmdflag = '-NoLogo -NoProfile -ExecutionPolicy RemoteSigned -Command ']])
  489. eq({ is_os('win') and '?\r' or 'あ' }, eval([[systemlist('Write-Output あ')]]))
  490. end)
  491. end)
  492. describe('shell :!', function()
  493. before_each(clear)
  494. it(':{range}! with powershell filter/redirect #16271 #19250', function()
  495. local screen = Screen.new(500, 8)
  496. local found = n.set_shell_powershell(true)
  497. insert([[
  498. 3
  499. 1
  500. 4
  501. 2]])
  502. if is_os('win') then
  503. feed(':4verbose %!sort /R<cr>')
  504. screen:expect {
  505. any = [[Executing command: .?& { Get%-Content .* | & sort /R } 2>&1 | %%{ "$_" } | Out%-File .*; exit $LastExitCode"]],
  506. }
  507. else
  508. feed(':4verbose %!sort -r<cr>')
  509. screen:expect {
  510. any = [[Executing command: .?& { Get%-Content .* | & sort %-r } 2>&1 | %%{ "$_" } | Out%-File .*; exit $LastExitCode"]],
  511. }
  512. end
  513. feed('<CR>')
  514. if found then
  515. -- Not using fake powershell, so we can test the result.
  516. expect([[
  517. 4
  518. 3
  519. 2
  520. 1]])
  521. end
  522. end)
  523. it(':{range}! without redirecting to buffer', function()
  524. local screen = Screen.new(500, 10)
  525. insert([[
  526. 3
  527. 1
  528. 4
  529. 2]])
  530. feed(':4verbose %w !sort<cr>')
  531. if is_os('win') then
  532. screen:expect {
  533. any = [[Executing command: .?sort %< .*]],
  534. }
  535. else
  536. screen:expect {
  537. any = [[Executing command: .?%(sort%) %< .*]],
  538. }
  539. end
  540. feed('<CR>')
  541. n.set_shell_powershell(true)
  542. feed(':4verbose %w !sort<cr>')
  543. screen:expect {
  544. any = [[Executing command: .?& { Get%-Content .* | & sort }]],
  545. }
  546. feed('<CR>')
  547. n.expect_exit(command, 'qall!')
  548. end)
  549. end)