robin/laufey

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

Justin M. KeyesMerge #40865 from justinmk/fixcif907614088

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