robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
13.7 KiB423 linesraw
1local t = require('test.testutil')
2local n = require('test.functional.testnvim')()
3local Screen = require('test.functional.ui.screen')
4local describe, it, before_each, after_each = t.describe, t.it, t.before_each, t.after_each
5local uv = vim.uv
6
7local assert_log = t.assert_log
8local assert_nolog = t.assert_nolog
9local clear = n.clear
10local command = n.command
11local eq = t.eq
12local neq = t.neq
13local ok = t.ok
14local feed = n.feed
15local fn = n.fn
16local nvim_prog = n.nvim_prog
17local request = n.request
18local retry = t.retry
19local rmdir = n.rmdir
20local matches = t.matches
21local api = n.api
22local mkdir = t.mkdir
23local sleep = vim.uv.sleep
24local read_file = t.read_file
25local trim = vim.trim
26local currentdir = n.fn.getcwd
27local assert_alive = n.assert_alive
28local check_close = n.check_close
29local expect_exit = n.expect_exit
30local write_file = t.write_file
31local feed_command = n.feed_command
32local skip = t.skip
33local is_os = t.is_os
34local set_session = n.set_session
35
36describe('fileio', function()
37  before_each(function() end)
38  after_each(function()
39    check_close()
40    os.remove('Xtest_startup_shada')
41    os.remove('Xtest_startup_file1')
42    os.remove('Xtest_startup_file1~')
43    os.remove('Xtest_startup_file2')
44    os.remove('Xtest_startup_file2~')
45    os.remove('Xtest_тест.md')
46    os.remove('Xtest-u8-int-max')
47    os.remove('Xtest-overwrite-forced')
48    rmdir('Xtest_startup_swapdir')
49    rmdir('Xtest_backupdir')
50    rmdir('Xtest_backupdir with spaces')
51    rmdir('Xtest_rename_dir')
52    rmdir('Xtest_rename_dest')
53  end)
54
55  local args = { '--clean', '--cmd', 'set nofsync directory=Xtest_startup_swapdir' }
56  --- Starts a new nvim session and returns an attached screen.
57  local function startup()
58    local argv = vim.iter({ args, '--embed' }):flatten():totable()
59    local screen_nvim = n.new_session(false, { args = argv, merge = false })
60    set_session(screen_nvim)
61    local screen = Screen.new(70, 10)
62    screen:set_default_attr_ids({
63      [1] = { foreground = Screen.colors.NvimDarkGrey4 },
64      [2] = { background = Screen.colors.NvimDarkGrey1, foreground = Screen.colors.NvimLightGrey3 },
65      [3] = { foreground = Screen.colors.NvimLightCyan },
66    })
67    return screen
68  end
69
70  it("fsync() with 'nofsync' #8304", function()
71    clear({ args = { '--cmd', 'set nofsync directory=Xtest_startup_swapdir' } })
72
73    -- These cases ALWAYS force fsync (regardless of 'fsync' option):
74
75    -- 1. Idle (CursorHold) with modified buffers (+ 'swapfile').
76    command('write Xtest_startup_file1')
77    feed('Afoo<esc>h')
78    command('write')
79    eq(0, request('nvim__stats').fsync)
80    command('set swapfile')
81    command('set updatetime=1')
82    feed('Azub<esc>h') -- File is 'modified'.
83    sleep(3) -- Allow 'updatetime' to expire.
84    retry(3, nil, function()
85      eq(1, request('nvim__stats').fsync)
86    end)
87    command('set updatetime=100000 updatecount=100000')
88
89    -- 2. Explicit :preserve command.
90    command('preserve')
91    -- TODO: should be exactly 2; where is the extra fsync() is coming from? #26404
92    ok(request('nvim__stats').fsync == 2 or request('nvim__stats').fsync == 3)
93
94    -- 3. Enable 'fsync' option, write file.
95    command('set fsync')
96    feed('Abaz<esc>h')
97    command('write')
98    -- TODO: should be exactly 4; where is the extra fsync() is coming from? #26404
99    ok(request('nvim__stats').fsync == 4 or request('nvim__stats').fsync == 5)
100    eq('foozubbaz', trim(read_file('Xtest_startup_file1')))
101
102    -- 4. Exit caused by deadly signal (+ 'swapfile').
103    local j =
104      fn.jobstart(vim.iter({ nvim_prog, args, '--embed' }):flatten():totable(), { rpc = true })
105    fn.rpcrequest(
106      j,
107      'nvim_exec2',
108      [[
109      set nofsync directory=Xtest_startup_swapdir
110      edit Xtest_startup_file2
111      write
112      put ='fsyncd text'
113    ]],
114      {}
115    )
116    eq('Xtest_startup_swapdir', fn.rpcrequest(j, 'nvim_eval', '&directory'))
117    fn.jobstop(j) -- Send deadly signal.
118
119    local screen = startup()
120    feed(':recover Xtest_startup_file2<cr>')
121    screen:expect({ any = [[Using swap file "Xtest_startup_swapdir[/\]Xtest_startup_file2%.swp"]] })
122    feed('<cr>')
123    screen:expect({ any = 'fsyncd text' })
124
125    -- 5. SIGPWR signal.
126    -- oldtest: Test_signal_PWR()
127  end)
128
129  it('backup #9709', function()
130    clear({
131      args = {
132        '-i',
133        'Xtest_startup_shada',
134        '--cmd',
135        'set directory=Xtest_startup_swapdir',
136      },
137    })
138
139    command('write Xtest_startup_file1')
140    feed('ifoo<esc>')
141    command('set backup')
142    command('set backupcopy=yes')
143    command('write')
144    feed('Abar<esc>')
145    command('write')
146
147    local foobar_contents = trim(read_file('Xtest_startup_file1'))
148    local bar_contents = trim(read_file('Xtest_startup_file1~'))
149
150    eq('foobar', foobar_contents)
151    eq('foo', bar_contents)
152  end)
153
154  it('backup with full path #11214', function()
155    clear()
156    mkdir('Xtest_backupdir')
157    command('set backup')
158    command('set backupdir=Xtest_backupdir//')
159    command('write Xtest_startup_file1')
160    feed('ifoo<esc>')
161    command('write')
162    feed('Abar<esc>')
163    command('write')
164
165    -- Backup filename = fullpath, separators replaced with "%".
166    local backup_file_name = string.gsub(
167      currentdir() .. '/Xtest_startup_file1',
168      is_os('win') and '[:/\\]' or '/',
169      '%%'
170    ) .. '~'
171    local foo_contents = trim(read_file('Xtest_backupdir/' .. backup_file_name))
172    local foobar_contents = trim(read_file('Xtest_startup_file1'))
173
174    eq('foobar', foobar_contents)
175    eq('foo', foo_contents)
176  end)
177
178  it('backup with full path with spaces', function()
179    clear()
180    mkdir('Xtest_backupdir with spaces')
181    command('set backup')
182    command('set backupdir=Xtest_backupdir\\ with\\ spaces//')
183    command('write Xtest_startup_file1')
184    feed('ifoo<esc>')
185    command('write')
186    feed('Abar<esc>')
187    command('write')
188
189    -- Backup filename = fullpath, separators replaced with "%".
190    local backup_file_name = string.gsub(
191      currentdir() .. '/Xtest_startup_file1',
192      is_os('win') and '[:/\\]' or '/',
193      '%%'
194    ) .. '~'
195    local foo_contents = trim(read_file('Xtest_backupdir with spaces/' .. backup_file_name))
196    local foobar_contents = trim(read_file('Xtest_startup_file1'))
197
198    eq('foobar', foobar_contents)
199    eq('foo', foo_contents)
200  end)
201
202  it('backup symlinked files #11349', function()
203    clear()
204
205    local initial_content = 'foo'
206    local link_file_name = 'Xtest_startup_file2'
207    local backup_file_name = link_file_name .. '~'
208
209    write_file('Xtest_startup_file1', initial_content, false)
210    uv.fs_symlink('Xtest_startup_file1', link_file_name)
211    command('set backup')
212    command('set backupcopy=yes')
213    command('edit ' .. link_file_name)
214    feed('Abar<esc>')
215    command('write')
216
217    local backup_raw = read_file(backup_file_name)
218    neq(nil, backup_raw, 'Expected backup file ' .. backup_file_name .. 'to exist but did not')
219    eq(initial_content, trim(backup_raw), 'Expected backup to contain original contents')
220  end)
221
222  it('backup symlinked files in first available backupdir #11349', function()
223    clear()
224
225    local initial_content = 'foo'
226    local backup_dir = 'Xtest_backupdir'
227    local sep = n.get_pathsep()
228    local link_file_name = 'Xtest_startup_file2'
229    local backup_file_name = backup_dir .. sep .. link_file_name .. '~'
230
231    write_file('Xtest_startup_file1', initial_content, false)
232    uv.fs_symlink('Xtest_startup_file1', link_file_name)
233    mkdir(backup_dir)
234    command('set backup')
235    command('set backupcopy=yes')
236    command('set backupdir=.__this_does_not_exist__,' .. backup_dir)
237    command('edit ' .. link_file_name)
238    feed('Abar<esc>')
239    command('write')
240
241    local backup_raw = read_file(backup_file_name)
242    neq(nil, backup_raw, 'Expected backup file ' .. backup_file_name .. ' to exist but did not')
243    eq(initial_content, trim(backup_raw), 'Expected backup to contain original contents')
244  end)
245
246  it('readfile() on multibyte filename #10586', function()
247    clear()
248    local text = {
249      'line1',
250      '  ...line2...  ',
251      '',
252      'line3!',
253      'тест yay тест.',
254      '',
255    }
256    local fname = 'Xtest_тест.md'
257    fn.writefile(text, fname, 's')
258    table.insert(text, '')
259    eq(text, fn.readfile(fname, 'b'))
260  end)
261  it("read invalid u8 over INT_MAX doesn't segfault", function()
262    clear()
263    command('call writefile(0zFFFFFFFF, "Xtest-u8-int-max")')
264    -- This should not segfault
265    command('edit ++enc=utf32 Xtest-u8-int-max')
266    assert_alive()
267  end)
268
269  it('rename() replaces an existing file with a directory', function()
270    clear()
271    mkdir('Xtest_rename_dir')
272    write_file('Xtest_rename_dir/file', 'dir_content')
273    write_file('Xtest_rename_dest', 'old_content')
274
275    eq(0, fn.rename('Xtest_rename_dir', 'Xtest_rename_dest'))
276    eq(nil, uv.fs_stat('Xtest_rename_dir'))
277    eq('directory', uv.fs_stat('Xtest_rename_dest').type)
278    eq('dir_content', read_file('Xtest_rename_dest/file'))
279  end)
280
281  it(':w! does not show "file has been changed" warning', function()
282    clear()
283    write_file('Xtest-overwrite-forced', 'foobar')
284    command('set nofixendofline')
285    local screen = Screen.new(40, 4)
286    command('set shortmess-=F')
287
288    command('e Xtest-overwrite-forced')
289    screen:expect([[
290      ^foobar                                  |
291      {1:~                                       }|*2
292      "Xtest-overwrite-forced" [noeol] 1L, 6B |
293    ]])
294
295    -- Get current unix time.
296    local cur_unix_time = os.time(os.date('!*t'))
297    local future_time = cur_unix_time + 999999
298    -- Set the file's access/update time to be
299    -- greater than the time at which it was created.
300    uv.fs_utime('Xtest-overwrite-forced', future_time, future_time)
301    -- use async feed_command because nvim basically hangs on the prompt
302    feed_command('w')
303    screen:expect([[
304      {9:WARNING: The file has been changed since}|
305      {9: reading it!!!}                          |
306      {6:Do you really want to write to it (y/n)?}|
307      ^                                        |
308    ]])
309
310    feed('n')
311    feed('<cr>')
312    screen:expect([[
313      ^foobar                                  |
314      {1:~                                       }|*2
315                                              |
316    ]])
317    -- Use a screen test because the warning does not set v:errmsg.
318    command('w!')
319    screen:expect([[
320      ^foobar                                  |
321      {1:~                                       }|*2
322      <erwrite-forced" [noeol] 1L, 6B written |
323    ]])
324  end)
325end)
326
327describe('tmpdir', function()
328  local tmproot_pat = [=[.*[/\\]nvim%.[^/\\]+]=]
329  local testlog = 'Xtest_tmpdir_log'
330  local os_tmpdir ---@type string
331
332  before_each(function()
333    -- Fake /tmp dir so that we can mess it up.
334    os_tmpdir = assert(vim.uv.fs_mkdtemp(vim.fs.dirname(t.tmpname(false)) .. '/nvim_XXXXXXXXXX'))
335  end)
336
337  after_each(function()
338    check_close()
339    os.remove(testlog)
340  end)
341
342  local function get_tmproot()
343    -- Tempfiles typically look like: "…/nvim.<user>/xxx/0".
344    --  - "…/nvim.<user>/xxx/" is the per-process tmpdir, not shared with other Nvims.
345    --  - "…/nvim.<user>/" is the tmpdir root, shared by all Nvims (normally).
346    local tmproot = (fn.tempname()):match(tmproot_pat)
347    ok(tmproot:len() > 4, 'tmproot like "nvim.foo"', tmproot)
348    return tmproot
349  end
350
351  it('failure modes', function()
352    clear({ env = { NVIM_LOG_FILE = testlog, TMPDIR = os_tmpdir } })
353    assert_nolog('tempdir is not a directory', testlog)
354    assert_nolog('tempdir has invalid permissions', testlog)
355
356    local tmproot = get_tmproot()
357
358    -- Test how Nvim handles invalid tmpdir root (by hostile users or accidents).
359    --
360    -- "…/nvim.<user>/" is not a directory:
361    expect_exit(command, ':qall!')
362    rmdir(tmproot)
363    write_file(tmproot, '') -- Not a directory, vim_mktempdir() should skip it.
364    clear({ env = { NVIM_LOG_FILE = testlog, TMPDIR = os_tmpdir } })
365    matches(tmproot_pat, fn.stdpath('run')) -- Tickle vim_mktempdir().
366    -- Assert that broken tmpdir root was handled.
367    assert_log('tempdir root not a directory', testlog, 100)
368
369    -- "…/nvim.<user>/" has wrong permissions:
370    skip(is_os('win'), 'TODO(justinmk): need setfperm/getfperm on Windows. #8244')
371    os.remove(testlog)
372    os.remove(tmproot)
373    mkdir(tmproot)
374    fn.setfperm(tmproot, 'rwxr--r--') -- Invalid permissions, vim_mktempdir() should skip it.
375    clear({ env = { NVIM_LOG_FILE = testlog, TMPDIR = os_tmpdir } })
376    matches(tmproot_pat, fn.stdpath('run')) -- Tickle vim_mktempdir().
377    -- Assert that broken tmpdir root was handled.
378    assert_log('tempdir root has invalid permissions', testlog, 100)
379  end)
380
381  it('too long', function()
382    local bigname = ('%s/%s'):format(os_tmpdir, ('x'):rep(666))
383    mkdir(bigname)
384    clear({ env = { NVIM_LOG_FILE = testlog, TMPDIR = bigname } })
385    matches(tmproot_pat, fn.stdpath('run')) -- Tickle vim_mktempdir().
386    local len = (fn.tempname()):len()
387    ok(len > 4 and len < 256, '4 < len < 256', tostring(len))
388  end)
389
390  it('disappeared #1432', function()
391    clear({ env = { NVIM_LOG_FILE = testlog, TMPDIR = os_tmpdir } })
392    assert_nolog('tempdir disappeared', testlog)
393
394    local function rm_tmpdir()
395      local tmpname1 = fn.tempname()
396      local tmpdir1 = fn.fnamemodify(tmpname1, ':h')
397      eq(fn.stdpath('run'), tmpdir1)
398
399      rmdir(tmpdir1)
400      retry(nil, 1000, function()
401        eq(0, fn.isdirectory(tmpdir1))
402      end)
403      local tmpname2 = fn.tempname()
404      local tmpdir2 = fn.fnamemodify(tmpname2, ':h')
405      neq(tmpdir1, tmpdir2)
406    end
407
408    -- Your antivirus hates you...
409    rm_tmpdir()
410    assert_log('tempdir disappeared', testlog, 100)
411    fn.tempname()
412    fn.tempname()
413    fn.tempname()
414    eq('', api.nvim_get_vvar('errmsg'))
415    rm_tmpdir()
416    fn.tempname()
417    fn.tempname()
418    fn.tempname()
419    eq('E5431: tempdir disappeared (2 times)', api.nvim_get_vvar('errmsg'))
420    rm_tmpdir()
421    eq('E5431: tempdir disappeared (3 times)', api.nvim_get_vvar('errmsg'))
422  end)
423end)