robin/laufey

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

Justin M. KeyesMerge #40865 from justinmk/fixcif907614088

master
12.4 KiB364 linesraw
1-- Test suite for checking :lua* commands
2local t = require('test.testutil')
3local n = require('test.functional.testnvim')()
4local Screen = require('test.functional.ui.screen')
5
6local describe, it, before_each, after_each = t.describe, t.it, t.before_each, t.after_each
7local eq = t.eq
8local NIL = vim.NIL
9local eval = n.eval
10local feed = n.feed
11local clear = n.clear
12local matches = t.matches
13local api = n.api
14local exec_lua = n.exec_lua
15local exec_capture = n.exec_capture
16local fn = n.fn
17local source = n.source
18local dedent = t.dedent
19local command = n.command
20local pcall_err = t.pcall_err
21local write_file = t.write_file
22local remove_trace = t.remove_trace
23
24before_each(clear)
25
26describe(':lua', function()
27  it('works', function()
28    eq('', exec_capture('lua vim.api.nvim_buf_set_lines(1, 1, 2, false, {"TEST"})'))
29    eq({ '', 'TEST' }, api.nvim_buf_get_lines(0, 0, 100, false))
30    source([[
31      lua << EOF
32        vim.api.nvim_buf_set_lines(1, 1, 2, false, {"TSET"})
33      EOF]])
34    eq({ '', 'TSET' }, api.nvim_buf_get_lines(0, 0, 100, false))
35    source([[
36      lua << EOF
37        vim.api.nvim_buf_set_lines(1, 1, 2, false, {"SETT"})]])
38    eq({ '', 'SETT' }, api.nvim_buf_get_lines(0, 0, 100, false))
39    source([[
40      lua << EOF
41        vim.api.nvim_buf_set_lines(1, 1, 2, false, {"ETTS"})
42        vim.api.nvim_buf_set_lines(1, 2, 3, false, {"TTSE"})
43        vim.api.nvim_buf_set_lines(1, 3, 4, false, {"STTE"})
44      EOF]])
45    eq({ '', 'ETTS', 'TTSE', 'STTE' }, api.nvim_buf_get_lines(0, 0, 100, false))
46    matches(
47      '.*Vim%(lua%):E15: Invalid expression: .*',
48      pcall_err(
49        source,
50        [[
51      lua << eval EOF
52        {}
53      EOF
54    ]]
55      )
56    )
57  end)
58
59  it('throws catchable errors', function()
60    eq('Vim(lua):E471: Argument required', pcall_err(command, 'lua'))
61    eq(
62      [[Vim(lua):E5107: Lua: [string ":lua"]:0: unexpected symbol near ')']],
63      pcall_err(command, 'lua ()')
64    )
65    eq(
66      [[Vim(lua):E5108: Lua: [string ":lua"]:0: TEST]],
67      remove_trace(pcall_err(command, 'lua error("TEST")'))
68    )
69    eq(
70      [[Vim(lua):E5108: Lua: [string ":lua"]:0: Invalid buffer id: -10]],
71      remove_trace(pcall_err(command, 'lua vim.api.nvim_buf_set_lines(-10, 1, 1, false, {"TEST"})'))
72    )
73    eq({ '' }, api.nvim_buf_get_lines(0, 0, 100, false))
74  end)
75
76  it('works with nil errors', function()
77    eq([=[Vim(lua):E5108: Lua: nil]=], pcall_err(command, 'lua error(nil)'))
78  end)
79
80  it('works with errors with __tostring failure', function()
81    eq(
82      [=[Vim(lua):E5108: Lua: [UNPRINTABLE ERROR]]=],
83      pcall_err(command, 'lua error(setmetatable({}, {__tostring=error}))')
84    )
85  end)
86
87  it('works with printable errors', function()
88    eq([=[Vim(lua):E5108: Lua: false]=], pcall_err(command, 'lua error(false)'))
89    -- numbers get the location prefixed because numbers are almost strings (know the workplace rules)
90    eq([=[Vim(lua):E5108: Lua: [string ":lua"]:0: 39]=], pcall_err(command, 'lua error(39)'))
91    matches([=[Vim%(lua%):E5108: Lua: table: 0x%x+]=], pcall_err(command, 'lua error({})'))
92  end)
93
94  it('accepts embedded NLs without heredoc', function()
95    -- Such code is usually used for `:execute 'lua' {generated_string}`:
96    -- heredocs do not work in this case.
97    command([[
98      lua
99        vim.api.nvim_buf_set_lines(1, 1, 2, false, {"ETTS"})
100        vim.api.nvim_buf_set_lines(1, 2, 3, false, {"TTSE"})
101        vim.api.nvim_buf_set_lines(1, 3, 4, false, {"STTE"})
102    ]])
103    eq({ '', 'ETTS', 'TTSE', 'STTE' }, api.nvim_buf_get_lines(0, 0, 100, false))
104  end)
105
106  it('preserves global and not preserves local variables', function()
107    eq('', exec_capture('lua gvar = 42'))
108    eq('', exec_capture('lua local lvar = 100500'))
109    eq(NIL, fn.luaeval('lvar'))
110    eq(42, fn.luaeval('gvar'))
111  end)
112
113  it('works with long strings', function()
114    local s = ('x'):rep(100500)
115
116    eq(
117      'Vim(lua):E5107: Lua: [string ":lua"]:0: unfinished string near \'<eof>\'',
118      pcall_err(command, ('lua vim.api.nvim_buf_set_lines(1, 1, 2, false, {"%s})'):format(s))
119    )
120    eq({ '' }, api.nvim_buf_get_lines(0, 0, -1, false))
121
122    eq('', exec_capture(('lua vim.api.nvim_buf_set_lines(1, 1, 2, false, {"%s"})'):format(s)))
123    eq({ '', s }, api.nvim_buf_get_lines(0, 0, -1, false))
124  end)
125
126  it('can show multiline error messages', function()
127    local screen = Screen.new(40, 10)
128    screen:set_default_attr_ids({
129      [1] = { bold = true, foreground = Screen.colors.Blue1 },
130      [2] = { bold = true, reverse = true },
131      [3] = { foreground = Screen.colors.Grey100, background = Screen.colors.Red },
132      [4] = { bold = true, foreground = Screen.colors.SeaGreen4 },
133    })
134
135    feed(':lua error("fail\\nmuch error\\nsuch details")<cr>')
136    screen:expect([[
137                                              |
138      {2:                                        }|
139      {3:E5108: Lua: [string ":lua"]:1: fail}     |
140      {3:much error}                              |
141      {3:such details}                            |
142      {3:stack traceback:}                        |
143      {3:        [C]: in function 'error'}        |
144      {3:        [string ":lua"]:1: in main chunk}|
145                                              |
146      {4:Press ENTER or type command to continue}^ |
147    ]])
148    feed('<cr>')
149    screen:expect {
150      grid = [[
151      ^                                        |
152      {1:~                                       }|*8
153                                              |
154    ]],
155    }
156    eq(
157      'E5108: Lua: [string ":lua"]:1: fail\nmuch error\nsuch details',
158      remove_trace(eval('v:errmsg'))
159    )
160
161    local expected = 'Vim(lua):E5108: Lua: [string ":lua"]:0: some error\nin a\nAPI command'
162    eq(expected, remove_trace(pcall_err(command, 'lua error("some error\\nin a\\nAPI command")')))
163
164    feed(':messages<cr>')
165    screen:expect([[
166                                              |
167      {2:                                        }|
168      {3:E5108: Lua: [string ":lua"]:1: fail}     |
169      {3:much error}                              |
170      {3:such details}                            |
171      {3:stack traceback:}                        |
172      {3:        [C]: in function 'error'}        |
173      {3:        [string ":lua"]:1: in main chunk}|
174                                              |
175      {4:Press ENTER or type command to continue}^ |
176    ]])
177  end)
178
179  it('prints result of =expr', function()
180    exec_lua('x = 5')
181    eq('5', exec_capture(':lua =x'))
182    eq('5', exec_capture('=x'))
183    exec_lua('x = "5"')
184    eq('"5"', exec_capture(':lua =x'))
185    eq('"5"', exec_capture('=x'))
186    exec_lua("function x() return 'hello' end")
187    eq('"hello"', exec_capture(':lua = x()'))
188    exec_lua("function x() return 'hello ' end")
189    eq('"hello "', exec_capture(':lua = x()'))
190    exec_lua('x = {a = 1, b = 2}')
191    eq('{\n  a = 1,\n  b = 2\n}', exec_capture(':lua  =x'))
192    exec_lua(function()
193      function _G.x(success)
194        if success then
195          return true, 'Return value'
196        else
197          return false, nil, 'Error message'
198        end
199      end
200    end)
201    eq(
202      dedent [[
203      true
204      "Return value"]],
205      exec_capture(':lua  =x(true)')
206    )
207    eq(
208      dedent [[
209      false
210      nil
211      "Error message"]],
212      exec_capture('=x(false)')
213    )
214  end)
215
216  it('with range', function()
217    local screen = Screen.new(40, 10)
218    api.nvim_buf_set_lines(0, 0, 0, 0, { 'nonsense', 'function x() print "hello" end', 'x()' })
219
220    -- ":{range}lua" fails on invalid Lua code.
221    eq(
222      [[:{range}lua buffer=1: Vim(lua):E5107: Lua: ]]
223        .. [[[string ":{range}lua buffer=1"]:0: '=' expected near '<eof>']],
224      pcall_err(command, '1lua')
225    )
226
227    -- ":{range}lua" executes valid Lua code.
228    feed(':2,3lua<CR>')
229    screen:expect {
230      grid = [[
231        nonsense                                |
232        function x() print "hello" end          |
233        x()                                     |
234        ^                                        |
235        {1:~                                       }|*5
236        hello                                   |
237      ]],
238      attr_ids = {
239        [1] = { foreground = Screen.colors.Blue, bold = true },
240      },
241    }
242
243    -- ":{range}lua {code}" executes {code}, ignoring {range}
244    eq('', exec_capture('1lua gvar = 42'))
245    eq(42, fn.luaeval('gvar'))
246  end)
247end)
248
249describe(':luado command', function()
250  it('works', function()
251    api.nvim_buf_set_lines(0, 0, 1, false, { 'ABC', 'def', 'gHi' })
252    eq('', exec_capture('luado lines = (lines or {}) lines[#lines + 1] = {linenr, line}'))
253    eq({ 'ABC', 'def', 'gHi' }, api.nvim_buf_get_lines(0, 0, -1, false))
254    eq({ { 1, 'ABC' }, { 2, 'def' }, { 3, 'gHi' } }, fn.luaeval('lines'))
255
256    -- Automatic transformation of numbers
257    eq('', exec_capture('luado return linenr'))
258    eq({ '1', '2', '3' }, api.nvim_buf_get_lines(0, 0, -1, false))
259
260    eq('', exec_capture('luado return ("<%02x>"):format(line:byte())'))
261    eq({ '<31>', '<32>', '<33>' }, api.nvim_buf_get_lines(0, 0, -1, false))
262  end)
263
264  it('stops processing lines when suddenly out of lines', function()
265    api.nvim_buf_set_lines(0, 0, 1, false, { 'ABC', 'def', 'gHi' })
266    eq('', exec_capture('2,$luado runs = ((runs or 0) + 1) vim.api.nvim_command("%d")'))
267    eq({ '' }, api.nvim_buf_get_lines(0, 0, -1, false))
268    eq(1, fn.luaeval('runs'))
269
270    api.nvim_buf_set_lines(0, 0, -1, false, { 'one', 'two', 'three' })
271    eq('', exec_capture('luado vim.api.nvim_command("%d")'))
272    eq({ '' }, api.nvim_buf_get_lines(0, 0, -1, false))
273
274    api.nvim_buf_set_lines(0, 0, -1, false, { 'one', 'two', 'three' })
275    eq('', exec_capture('luado vim.api.nvim_command("1,2d")'))
276    eq({ 'three' }, api.nvim_buf_get_lines(0, 0, -1, false))
277
278    api.nvim_buf_set_lines(0, 0, -1, false, { 'one', 'two', 'three' })
279    eq('', exec_capture('luado vim.api.nvim_command("2,3d"); return "REPLACED"'))
280    eq({ 'REPLACED' }, api.nvim_buf_get_lines(0, 0, -1, false))
281
282    api.nvim_buf_set_lines(0, 0, -1, false, { 'one', 'two', 'three' })
283    eq('', exec_capture('2,3luado vim.api.nvim_command("1,2d"); return "REPLACED"'))
284    eq({ 'three' }, api.nvim_buf_get_lines(0, 0, -1, false))
285  end)
286
287  it('fails on errors', function()
288    eq(
289      [[Vim(luado):E5109: Lua: [string ":luado"]:0: unexpected symbol near ')']],
290      pcall_err(command, 'luado ()')
291    )
292    eq(
293      [[Vim(luado):E5111: Lua: [string ":luado"]:0: attempt to perform arithmetic on global 'liness' (a nil value)]],
294      pcall_err(command, 'luado return liness + 1')
295    )
296  end)
297
298  it('works with nil errors', function()
299    eq([=[Vim(luado):E5111: Lua: nil]=], pcall_err(command, 'luado error(nil)'))
300  end)
301
302  it('fails in sandbox when needed', function()
303    api.nvim_buf_set_lines(0, 0, 1, false, { 'ABC', 'def', 'gHi' })
304    eq(
305      'Vim(luado):E48: Not allowed in sandbox: sandbox luado runs = (runs or 0) + 1',
306      pcall_err(command, 'sandbox luado runs = (runs or 0) + 1')
307    )
308    eq(NIL, fn.luaeval('runs'))
309  end)
310
311  it('works with long strings', function()
312    local s = ('x'):rep(100500)
313
314    eq(
315      'Vim(luado):E5109: Lua: [string ":luado"]:0: unfinished string near \'<eof>\'',
316      pcall_err(command, ('luado return "%s'):format(s))
317    )
318    eq({ '' }, api.nvim_buf_get_lines(0, 0, -1, false))
319
320    eq('', exec_capture(('luado return "%s"'):format(s)))
321    eq({ s }, api.nvim_buf_get_lines(0, 0, -1, false))
322  end)
323end)
324
325describe(':luafile', function()
326  local fname = 'Xtest-functional-lua-commands-luafile'
327
328  after_each(function()
329    os.remove(fname)
330  end)
331
332  it('works', function()
333    write_file(
334      fname,
335      [[
336        vim.api.nvim_buf_set_lines(1, 1, 2, false, {"ETTS"})
337        vim.api.nvim_buf_set_lines(1, 2, 3, false, {"TTSE"})
338        vim.api.nvim_buf_set_lines(1, 3, 4, false, {"STTE"})
339    ]]
340    )
341    eq('', exec_capture('luafile ' .. fname))
342    eq({ '', 'ETTS', 'TTSE', 'STTE' }, api.nvim_buf_get_lines(0, 0, 100, false))
343  end)
344
345  it('correctly errors out', function()
346    write_file(fname, '()')
347    eq(
348      ("Vim(luafile):E5112: Lua chunk: %s:1: unexpected symbol near ')'"):format(fname),
349      pcall_err(command, 'luafile ' .. fname)
350    )
351    write_file(fname, 'vimm.api.nvim_buf_set_lines(1, 1, 2, false, {"ETTS"})')
352    eq(
353      ("Vim(luafile):E5113: Lua chunk: %s:1: attempt to index global 'vimm' (a nil value)"):format(
354        fname
355      ),
356      remove_trace(pcall_err(command, 'luafile ' .. fname))
357    )
358  end)
359
360  it('works with nil errors', function()
361    write_file(fname, 'error(nil)')
362    eq([=[Vim(luafile):E5113: Lua chunk: nil]=], pcall_err(command, 'luafile ' .. fname))
363  end)
364end)