robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
13.5 KiB375 linesraw
1-- Test for Vim overrides of lua built-ins
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 matches = t.matches
9local NIL = vim.NIL
10local feed = n.feed
11local clear = n.clear
12local fn = n.fn
13local api = n.api
14local command = n.command
15local write_file = t.write_file
16local exec_capture = n.exec_capture
17local exec_lua = n.exec_lua
18local pcall_err = t.pcall_err
19local is_os = t.is_os
20
21local fname = 'Xtest-functional-lua-overrides-luafile'
22
23before_each(clear)
24
25after_each(function()
26  os.remove(fname)
27end)
28
29describe('print', function()
30  it('returns nothing', function()
31    eq(NIL, fn.luaeval('print("abc")'))
32    eq(0, fn.luaeval('select("#", print("abc"))'))
33  end)
34  it('allows catching printed text with :execute', function()
35    eq('\nabc', fn.execute('lua print("abc")'))
36    eq('\nabc', fn.execute('luado print("abc")'))
37    eq('\nabc', fn.execute('call luaeval("print(\'abc\')")'))
38    write_file(fname, 'print("abc")')
39    eq('\nabc', fn.execute('luafile ' .. fname))
40
41    eq('abc', exec_capture('lua print("abc")'))
42    eq('abc', exec_capture('luado print("abc")'))
43    eq('abc', exec_capture('call luaeval("print(\'abc\')")'))
44    write_file(fname, 'print("abc")')
45    eq('abc', exec_capture('luafile ' .. fname))
46  end)
47  it('handles errors in __tostring', function()
48    write_file(
49      fname,
50      [[
51      local meta_nilerr = { __tostring = function() error(nil) end }
52      local meta_abcerr = { __tostring = function() error("abc") end }
53      local meta_tblout = { __tostring = function() return {"TEST"} end }
54      v_nilerr = setmetatable({}, meta_nilerr)
55      v_abcerr = setmetatable({}, meta_abcerr)
56      v_tblout = setmetatable({}, meta_tblout)
57    ]]
58    )
59    eq('', exec_capture('luafile ' .. fname))
60    -- TODO(bfredl): these look weird, print() should not use "E5114:" style errors..
61    eq(
62      'Vim(lua):E5108: Lua: E5114: Converting print argument #2: nil',
63      pcall_err(command, 'lua print("foo", v_nilerr, "bar")')
64    )
65    eq(
66      'Vim(lua):E5108: Lua: E5114: Converting print argument #2: Xtest-functional-lua-overrides-luafile:2: abc',
67      pcall_err(command, 'lua print("foo", v_abcerr, "bar")')
68    )
69    matches(
70      '^Vim%(lua%):E5108: Lua: E5114: Converting print argument #2: table: 0x%x+$',
71      pcall_err(command, 'lua print("foo", v_tblout, "bar")')
72    )
73  end)
74  it('coerces error values into strings', function()
75    write_file(
76      fname,
77      [[
78    function string_error() error("my mistake") end
79    function number_error() error(1234) end
80    function nil_error() error(nil) end
81    function table_error() error({message = "my mistake"}) end
82    function custom_error()
83      local err = {message = "my mistake", code = 11234}
84      setmetatable(err, {
85        __tostring = function(t)
86          return "Internal Error [" .. t.code .. "] " .. t.message
87        end
88      })
89      error(err)
90    end
91    function bad_custom_error()
92      local err = {message = "my mistake", code = 11234}
93      setmetatable(err, {
94        -- intentionally not a function, downstream programmer has made an mistake
95        __tostring = "Internal Error [" .. err.code .. "] " .. err.message
96      })
97      error(err)
98    end
99    ]]
100    )
101    eq('', exec_capture('luafile ' .. fname))
102    eq(
103      'Vim(lua):E5108: Lua: Xtest-functional-lua-overrides-luafile:1: my mistake',
104      pcall_err(command, 'lua string_error()')
105    )
106    eq(
107      'Vim(lua):E5108: Lua: Xtest-functional-lua-overrides-luafile:2: 1234',
108      pcall_err(command, 'lua number_error()')
109    )
110    eq('Vim(lua):E5108: Lua: nil', pcall_err(command, 'lua nil_error()'))
111    matches('^Vim%(lua%):E5108: Lua: table: 0x%x+$', pcall_err(command, 'lua table_error()'))
112    eq(
113      'Vim(lua):E5108: Lua: Internal Error [11234] my mistake',
114      pcall_err(command, 'lua custom_error()')
115    )
116    eq('Vim(lua):E5108: Lua: [UNPRINTABLE ERROR]', pcall_err(command, 'lua bad_custom_error()'))
117  end)
118  it('prints strings with NULs and NLs correctly', function()
119    api.nvim_set_option_value('more', true, {})
120    eq(
121      'abc ^@ def\nghi^@^@^@jkl\nTEST\n\n\nT\n',
122      exec_capture([[lua print("abc \0 def\nghi\0\0\0jkl\nTEST\n\n\nT\n")]])
123    )
124    eq(
125      'abc ^@ def\nghi^@^@^@jkl\nTEST\n\n\nT^@',
126      exec_capture([[lua print("abc \0 def\nghi\0\0\0jkl\nTEST\n\n\nT\0")]])
127    )
128    eq('T^@', exec_capture([[lua print("T\0")]]))
129    eq('T\n', exec_capture([[lua print("T\n")]]))
130  end)
131  it('prints empty strings correctly', function()
132    -- Regression: first test used to crash
133    eq('', exec_capture('lua print("")'))
134    eq(' def', exec_capture('lua print("", "def")'))
135    eq('abc ', exec_capture('lua print("abc", "")'))
136    eq('abc  def', exec_capture('lua print("abc", "", "def")'))
137  end)
138  it('defers printing in luv event handlers', function()
139    exec_lua(function(cmd)
140      function test()
141        local timer = vim.uv.new_timer()
142        local done = false
143        timer:start(10, 0, function()
144          print('very fast')
145          timer:close()
146          done = true
147        end)
148        -- be kind to slow travis OS X jobs:
149        -- loop until we know for sure the callback has been executed
150        while not done do
151          os.execute(cmd)
152          vim.uv.run('nowait') -- fake os_breakcheck()
153        end
154        print('very slow')
155        vim.api.nvim_command('sleep 1m') -- force deferred event processing
156      end
157    end, (is_os('win') and 'timeout 1') or 'sleep 0.1')
158    eq('very slow\nvery fast', exec_capture('lua test()'))
159  end)
160
161  it('blank line in message works', function()
162    local screen = Screen.new(40, 8)
163    feed([[:lua print('\na')<CR>]])
164    screen:expect {
165      grid = [[
166                                              |
167      {1:~                                       }|*3
168      {3:                                        }|
169                                              |
170      a                                       |
171      {6:Press ENTER or type command to continue}^ |
172    ]],
173    }
174    feed('<CR>')
175    feed([[:lua print('b\n\nc')<CR>]])
176    screen:expect {
177      grid = [[
178                                              |
179      {1:~                                       }|*2
180      {3:                                        }|
181      b                                       |
182                                              |
183      c                                       |
184      {6:Press ENTER or type command to continue}^ |
185    ]],
186    }
187  end)
188end)
189
190describe('_G.debug', function()
191  local screen --- @type test.functional.ui.screen
192
193  before_each(function()
194    screen = Screen.new()
195  end)
196
197  it('if broken, Nvim reports it instead of crashing #41504', function()
198    -- If user code breaks `_G.debug.traceback`, Nvim should function enough to allow ":qa!".
199    -- But `_G.debug=nil` panics immediately, and that is intentional/wontfix.
200    for _, override in ipairs({ 'debug.traceback = nil', '_G.debug = {}' }) do
201      clear()
202      eq(
203        true,
204        exec_lua(([[
205          %s
206          local called = false
207          -- nvim_buf_call() is the shortest path from Lua to nlua_pcall().
208          vim.api.nvim_buf_call(0, function() called = true end)
209          return called
210        ]]):format(override))
211      )
212      -- Error reports the broken situation.
213      matches(
214        'boom\nNo traceback: debug.traceback is not a function',
215        pcall_err(exec_lua, [[vim.api.nvim_buf_call(0, function() error('boom') end)]])
216      )
217      -- vim.on_key() callbacks run on every keystroke, they should not break either.
218      exec_lua([[
219        _G.keys = 0
220        vim.on_key(function() _G.keys = _G.keys + 1 end)
221      ]])
222      feed('jjj')
223      eq(3, exec_lua('return _G.keys'))
224    end
225
226    -- We accept non-broken `debug.traceback` overrides (e.g. tui_spec.lua does this).
227    matches(
228      'boom %(custom traceback%)',
229      pcall_err(
230        exec_lua,
231        [[
232          debug.traceback = function(msg) return msg .. ' (custom traceback)' end
233          vim.api.nvim_buf_call(0, function() error('boom') end)
234        ]]
235      )
236    )
237  end)
238
239  it('debug() works', function()
240    command([[lua
241      function Test(a)
242        print(a)
243        debug.debug()
244        print(a * 100)
245      end
246    ]])
247    feed(':lua Test()\n')
248    screen:expect {
249      grid = [[
250                                                           |
251      {1:~                                                    }|*10
252      {3:                                                     }|
253      nil                                                  |
254      lua_debug> ^                                          |
255    ]],
256    }
257    feed('print("TEST")\n')
258    screen:expect([[
259                                                           |
260      {1:~                                                    }|*8
261      {3:                                                     }|
262      nil                                                  |
263      lua_debug> print("TEST")                             |
264      TEST                                                 |
265      lua_debug> ^                                          |
266    ]])
267    feed('<C-c>')
268    screen:expect([[
269                                                           |
270      {1:~                                                    }|*2
271      {3:                                                     }|
272      nil                                                  |
273      lua_debug> print("TEST")                             |
274      TEST                                                 |
275                                                           |
276      {9:E5108: Lua: [string ":lua"]:5: attempt to perform ari}|
277      {9:thmetic on local 'a' (a nil value)}                   |
278      {9:stack traceback:}                                     |
279      {9:        [string ":lua"]:5: in function 'Test'}        |
280      {9:        [string ":lua"]:1: in main chunk}             |
281      Interrupt: {6:Press ENTER or type command to continue}^   |
282    ]])
283    feed('<C-l>:lua Test()\n')
284    screen:expect([[
285                                                           |
286      {1:~                                                    }|*10
287      {3:                                                     }|
288      nil                                                  |
289      lua_debug> ^                                          |
290    ]])
291    feed('\n')
292    screen:expect([[
293                                                           |
294      {1:~                                                    }|*4
295      {3:                                                     }|
296      nil                                                  |
297      lua_debug>                                           |
298      {9:E5108: Lua: [string ":lua"]:5: attempt to perform ari}|
299      {9:thmetic on local 'a' (a nil value)}                   |
300      {9:stack traceback:}                                     |
301      {9:        [string ":lua"]:5: in function 'Test'}        |
302      {9:        [string ":lua"]:1: in main chunk}             |
303      {6:Press ENTER or type command to continue}^              |
304    ]])
305  end)
306
307  it("debug() can be safely exited with 'cont'", function()
308    feed('<cr>')
309    feed(':lua debug.debug() print("x")<cr>')
310    screen:expect {
311      grid = [[
312                                                           |
313      {1:~                                                    }|*12
314      lua_debug> ^                                          |
315    ]],
316    }
317
318    feed('conttt<cr>') -- misspelled cont; invalid syntax
319    screen:expect([[
320                                                           |
321      {1:~                                                    }|*8
322      {3:                                                     }|
323      lua_debug> conttt                                    |
324      {9:E5115: Loading Lua debug string: (debug command):1: '}|
325      {9:=' expected near '<eof>'}                             |
326      lua_debug> ^                                          |
327    ]])
328
329    feed('cont<cr>') -- exactly "cont", exit now
330    screen:expect([[
331                                                           |
332      {1:~                                                    }|*6
333      {3:                                                     }|
334      lua_debug> conttt                                    |
335      {9:E5115: Loading Lua debug string: (debug command):1: '}|
336      {9:=' expected near '<eof>'}                             |
337      lua_debug> cont                                      |
338      x                                                    |
339      {6:Press ENTER or type command to continue}^              |
340    ]])
341
342    feed('<cr>')
343    screen:expect {
344      grid = [[
345      ^                                                     |
346      {1:~                                                    }|*12
347                                                           |
348    ]],
349    }
350  end)
351end)
352
353describe('os.getenv', function()
354  it('returns nothing for undefined env var', function()
355    eq(NIL, fn.luaeval('os.getenv("XTEST_1")'))
356  end)
357  it('returns env var set by the parent process', function()
358    local value = 'foo'
359    clear({ env = { ['XTEST_1'] = value } })
360    eq(value, fn.luaeval('os.getenv("XTEST_1")'))
361  end)
362  it('returns env var set by let', function()
363    local value = 'foo'
364    command('let $XTEST_1 = "' .. value .. '"')
365    eq(value, fn.luaeval('os.getenv("XTEST_1")'))
366  end)
367end)
368
369-- "bit" module is always available, regardless if nvim is built with
370-- luajit or PUC lua 5.1.
371describe('bit module', function()
372  it('works', function()
373    eq(9, exec_lua [[ return require'bit'.band(11,13) ]])
374  end)
375end)