summaryrefslogtreecommitdiff
path: root/uvim/src/testdir/test_plugin_netrw.mnv
blob: 2850fa841e4ad3c921a34645cb96883dc4ed1c12 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
const s:testdir = expand("<script>:h")
const s:runtimedir = simplify(s:testdir . '/../../runtime')
const s:netrw_path = s:runtimedir . '/pack/dist/opt/netrw/autoload/netrw.mnv'
const s:netrw_test_path = s:testdir . '/samples/netrw.mnv'
const s:testScript =<< trim END

" Testing functions: {{{1
function! TestNetrwCaptureRemotePath(dirname)
  call s:RemotePathAnalysis(a:dirname)
  return {"method": s:method, "user": s:user, "machine": s:machine, "port": s:port, "path": s:path, "fname": s:fname}
endfunction

" Test directory creation via s:NetrwMakeDir()
" Precondition: inputsave() and inputrestore() must be disabled in s:NetrwMakeDir

function s:test_inputsave()
    if exists("s:inputguards_disabled") && s:inputguards_disabled
        return
    endif
    call inputsave()
endfunction

function s:test_inputrestore()
    if exists("s:inputguards_disabled") && s:inputguards_disabled
        return
    endif
    call inputrestore()
endfunction

function s:test_input(prompt, text = v:none, completion = v:none)

    if exists("s:inputdefaults_disabled") && s:inputdefaults_disabled || a:text == v:none
        return input(a:prompt)
    elseif a:completion == v:none
        return input(a:prompt, a:text)
    endif

    return input(a:prompt, a:text, a:completion)
endfunction

function Test_NetrwMakeDir(parentdir = $HOME, dirname = "NetrwMakeDir", symlink = 0) abort
    if a:symlink
        " Plainly delegate, this device is necessary because feedkeys() can't
        " access script functions directly.
        call s:NetrwMakeDir('')
        " wipe out the test buffer
        bw
        " reenable the guards
        let s:inputguards_disabled = 0
    else
        " Use feedkeys() to simulate user input (directory name)
        new
        let b:netrw_curdir = a:parentdir
        let s:inputguards_disabled = 1
        call feedkeys($"\<Cmd>call Test_NetrwMakeDir('{a:parentdir}', '{a:dirname}', 1)\<CR>{a:dirname}\<CR>", "x")
    endif
endfunction

" Test file copy operations via s:NetrwMarkFileCopy()
function Test_NetrwMarkFileCopy(source_dir, target_dir, marked_files) abort
    " set up
    new
    let b:netrw_curdir= a:source_dir
    let s:netrwmftgt = a:target_dir
    let s:netrwmarkfilelist_{bufnr("%")} = a:marked_files
    let s:netrwmftgt_islocal = 1
    " delegate
    call s:NetrwMarkFileCopy(1)
    " wipe out the test buffer
    bw
endfunction

" Corner case: copy into the same dir triggers a user prompt
function Test_NetrwMarkFileCopy_SameDir(dir = $HOME, symlink = 0) abort
    const filename = "filename.txt"
    const file = netrw#fs#PathJoin(a:dir, filename)

    const newfilename = "newfilename.txt"
    const newfile = netrw#fs#PathJoin(a:dir, newfilename)

    if a:symlink
        " Plainly delegate, this device is necessary because feedkeys() can't
        " access script functions directly.
        " set up
        new
        let b:netrw_curdir = a:dir
        let s:netrwmftgt = a:dir
        let s:netrwmarkfilelist_{bufnr("%")} = [filename]
        let s:netrwmftgt_islocal = 1

        " delegate
        call s:NetrwMarkFileCopy(1)

        " validate
        call assert_equalfile(file, newfile, "File copy in same dir failed")

        " tear down
        call delete(file)
        call delete(newfile)
        " wipe out the test buffer
        bw
        " reenable the guards
        let s:inputguards_disabled = 0
        let s:inputdefaults_disabled = 0
    else
        " Use feedkeys() to simulate user input (directory name)
        let s:inputguards_disabled = 1
        let s:inputdefaults_disabled = 1

        call writefile([$"NetrwMarkFileCopy test file"], file)

        call feedkeys($"\<Cmd>call Test_NetrwMarkFileCopy_SameDir('{a:dir}', 1)\<CR>{newfilename}\<CR>", "x")
    endif
endfunction

" Test file copy operations via s:NetrwMarkFileMove()
function Test_NetrwMarkFileMove(source_dir, target_dir, marked_files) abort
    " set up
    new
    let b:netrw_curdir= a:source_dir
    let s:netrwmftgt = a:target_dir
    let s:netrwmarkfilelist_{bufnr("%")} = a:marked_files
    let s:netrwmftgt_islocal = 1
    " delegate
    call s:NetrwMarkFileMove(1)
    " wipe out the test buffer
    bw
endfunction

" Test how netrw fixes paths according with settings
" (g:netrw_keepdir, g:netrw_cygwin, tree style ...)
function Test_NetrwFile(fname) abort
    return s:NetrwFile(a:fname)
endfunction

" Test hostname validation
function Test_NetrwValidateHostname(hostname) abort
    return s:NetrwValidateHostname(a:hostname)
endfunction

" }}}
END

"make copy of netrw script and add function to print local variables"
func s:appendDebugToNetrw(netrw_path, netrw_test_path)

  " load the netrw script
  execute "split" a:netrw_test_path
  execute "read" a:netrw_path

  " replace input guards for convenient testing versions
  %substitute@call inputsave()@call s:test_inputsave()@g
  %substitute@call inputrestore()@call s:test_inputrestore()@g
  %substitute@\<input(@s:test_input(@g

  call cursor(1,1)
  let pos = search("Settings Restoration:")-1
  " insert the test functions before the end guard
  call assert_false(append(pos, s:testScript))

  " save the modified script content
  write
  bwipe!

endfunction

func SetUp()

  " prepare modified netrw script
  call s:appendDebugToNetrw(s:netrw_path, s:netrw_test_path)

  " source the modified script
  exe "source" s:netrw_test_path

  " Rig the package. The modified script guard prevents loading it again.
  let &runtimepath=s:runtimedir
  let &packpath=s:runtimedir
  packadd netrw

  " use proper path
  if has('win32')
    let $HOME = substitute($HOME, '/', '\\', 'g')
  endif

endfunction

func TearDown()
  " cleanup
  call delete(s:netrw_test_path)
endfunction

func SetShell(shell)
    " select different shells
    if a:shell == "default"
        set shell& shellcmdflag& shellxquote& shellpipe& shellredir&
    elseif a:shell == "powershell" " help dos-powershell
        " powershell desktop is windows only
        if !has("win32")
            throw 'Skipped: powershell desktop is missing'
        endif
        set shell=powershell shellcmdflag=-NoProfile\ -Command shellxquote=\"
        set shellpipe=2>&1\ \|\ Out-File\ -Encoding\ default shellredir=2>&1\ \|\ Out-File\ -Encoding\ default
    elseif a:shell == "pwsh" " help dos-powershell
        " powershell core works crossplatform
        if !executable("pwsh")
            throw 'Skipped: powershell core is missing'
        endif
        set shell=pwsh shellcmdflag=-NoProfile\ -c shellpipe=>%s\ 2>&1 shellredir=>%s\ 2>&1
        if has("win32")
            set shellxquote=\"
        else
            set shellxquote=
        endif
    else
        call assert_report("Trying to select an unknown shell")
    endif
endfunc

func s:combine
  \( usernames
  \, methods
  \, hosts
  \, ports
  \, dirs
  \, files)
  for username in a:usernames
    for method in a:methods
      for host in a:hosts
        for port in a:ports
          for dir in a:dirs
            for file in a:files
               " --- Build a full remote path ---

              let port_str = empty(port) ? "" : ':' . port
              let remote = printf('%s://%s@%s%s/%s%s', method, username, host, port_str, dir, file)

              let result = TestNetrwCaptureRemotePath(remote)

              call assert_equal(result.method, method)
              call assert_equal(result.user, username)
              call assert_equal(result.machine, host)
              call assert_equal(result.port, port)
              call assert_equal(result.path, dir . file)
            endfor
          endfor
        endfor
      endfor
    endfor
  endfor
endfunction


func Test_netrw_parse_remote_simple()
  let result = TestNetrwCaptureRemotePath('scp://user@localhost:2222/test.txt')
  call assert_equal(result.method, 'scp')
  call assert_equal(result.user, 'user')
  call assert_equal(result.machine, 'localhost')
  call assert_equal(result.port, '2222')
  call assert_equal(result.path, 'test.txt')
endfunction

"testing different combinations"
func Test_netrw_parse_regular_usernames()

  " --- sample data for combinations ---"
  let usernames = ["root", "toor", "user01", "skillIssue"]
  let methods = ["scp", "ssh", "ftp", "sftp"]
  let hosts = ["localhost", "server.com", "fit-workspaces.ksi.fit.cvut.cz", "192.168.1.42"]
  let ports = ["", "22","420", "443", "2222", "1234"]
  let dirs = ["", "somefolder/", "path/to/the/bottom/of/the/world/please/send/help/"]
  let files = ["test.txt", "tttt.mnv", "Makefile"]

  call s:combine(usernames, methods, hosts, ports, dirs, files)

endfunc

"Host myserver
"    HostName 192.168.1.42
"    User alice
func Test_netrw_parse_ssh_config_entries()
  let result = TestNetrwCaptureRemotePath('scp://myserver//etc/nginx/nginx.conf')
  call assert_equal(result.method, 'scp')
  call assert_equal(result.user, '')
  call assert_equal(result.machine, 'myserver')
  call assert_equal(result.port, '')
  call assert_equal(result.path, '/etc/nginx/nginx.conf')
endfunction

"username containing special-chars"
func Test_netrw_parse_special_char_user()
  let result = TestNetrwCaptureRemotePath('scp://user-01@localhost:2222/test.txt')
  call assert_equal(result.method, 'scp')
  call assert_equal(result.user, 'user-01')
  call assert_equal(result.machine, 'localhost')
  call assert_equal(result.port, '2222')
  call assert_equal(result.path, 'test.txt')
endfunction

func Test_netrw_empty_buffer_fastpath_wipe()
  " SetUp() may have opened some buffers
  let previous = bufnr('$')
  let g:netrw_fastbrowse=0
  call setline(1, 'foobar')
  let  bufnr = bufnr('%')
  tabnew
  Explore
  call search('README.txt', 'W')
  exe ":norm \<cr>"
  call assert_equal(previous + 2, bufnr('$'))
  call assert_true(bufexists(bufnr))
  bw

  unlet! netrw_fastbrowse
endfunction

" Test UNC paths on windows
func Test_netrw_check_UNC_paths()
  CheckMSWindows

  let test_paths = [
  \ '\\Server2\Share\Test\Foo.txt',
  \ '//Server2/Share/Test/Foo.txt',
  \ '\\Server2\Share\Test\',
  \ '//Server2/Share/Test/',
  \ '\\wsl.localhost\Ubuntu\home\user\_mnvrc',
  \ '//wsl.localhost/Ubuntu/home/user/_mnvrc',
  \ '\\wsl.localhost\Ubuntu\home\user',
  \ '//wsl.localhost/Ubuntu/home/user']

  " The paths must be interpreted as absolute ones
  for path in test_paths
    call assert_equal(
    \   path,
    \   Test_NetrwFile(path),
    \   $"UNC path: {path} misinterpreted")
  endfor

endfunction

" ---------------------------------
" Testing file management functions
" ---------------------------------

" Browser directory creation
func s:netrw_mkdir()

  " create a testdir in the fake $HOME
  call Test_NetrwMakeDir($HOME, "NetrwMakeDir")

  " Check the test directory was created
  let test_dir = netrw#fs#PathJoin($HOME, "NetrwMakeDir")
  call WaitForAssert({-> assert_true(
  \     isdirectory(test_dir),
  \     "Unable to create a dir via s:NetrwMakeDir()")
  \ })

  " remove the test directory
  call delete(test_dir, 'd')
endfunc

func Test_netrw_mkdir_default()
  call SetShell('default')
  call s:netrw_mkdir()
endfunc

func Test_netrw_mkdir_powershell()
  call SetShell('powershell')
  call s:netrw_mkdir()
endfunc

func Test_netrw_mkdir_pwsh()
  call SetShell('pwsh')
  call s:netrw_mkdir()
endfunc

func s:netrw_filecopy(count = 1)
  " setup
  let marked_files = []
  let source_dir = netrw#fs#PathJoin($HOME, "src")
  let target_dir = netrw#fs#PathJoin($HOME, "target")

  call mkdir(source_dir, "R")
  call mkdir(target_dir, "R")

  for i in range(a:count)
    call add(marked_files, $"testfile{i}.txt")
    call writefile(
    \   [$"NetrwMarkFileCopy test file {i}"],
    \   netrw#fs#PathJoin(source_dir, marked_files[-1]))
  endfor

  " delegate
  call Test_NetrwMarkFileCopy(source_dir, target_dir, marked_files)

  " verify
  for file in marked_files
    call assert_equalfile(
    \   netrw#fs#PathJoin(source_dir, file),
    \   netrw#fs#PathJoin(target_dir, file),
    \   "File copy failed for " . file)
  endfor
endfunc

" Browser file copy
func s:test_netrw_filecopy()

  " if shellslash is available, check both settings
  if exists('+shellslash')
    set shellslash&
    call s:netrw_filecopy(1)
    call s:netrw_filecopy(10)
    set shellslash!
  endif

  call s:netrw_filecopy(1)
  call s:netrw_filecopy(10)

endfunc

func Test_netrw_filecopy_default()
  call SetShell('default')
  call s:test_netrw_filecopy()
endfunc

func Test_netrw_filecopy_powershell()
  call SetShell('powershell')
  call s:test_netrw_filecopy()
endfunc

func Test_netrw_filecopy_pwsh()
  call SetShell('pwsh')
  call s:test_netrw_filecopy()
endfunc

" Browser recursive directory copy
func s:netrw_dircopy(count = 1)

  " setup
  let marked_dirname = "test_dir"
  let marked_dir = netrw#fs#PathJoin($HOME, marked_dirname)
  let target_dir = netrw#fs#PathJoin($HOME, "target")

  call mkdir(marked_dir, "R")
  call mkdir(target_dir, "R")

  let dir_content = []
  for i in range(a:count)
    call add(dir_content, $"testfile{i}.txt")
    call writefile(
    \   [$"NetrwMarkFileCopy test dir content {i}"],
    \   netrw#fs#PathJoin(marked_dir, dir_content[-1]))
  endfor

  " delegate
  call Test_NetrwMarkFileCopy($HOME, target_dir, [marked_dirname])

  " verify
  for file in dir_content
    call assert_equalfile(
    \   netrw#fs#PathJoin(marked_dir, file),
    \   netrw#fs#PathJoin(target_dir, marked_dirname, file),
    \   "File copy failed for " . file)
  endfor

endfunc

func s:test_netrw_dircopy()

  " if shellslash is available, check both settings
  if exists('+shellslash')
    set shellslash&
    call s:netrw_dircopy(10)
    set shellslash!
  endif

  call s:netrw_dircopy(10)

endfunc

func Test_netrw_dircopy_default()
  call SetShell('default')
  call s:test_netrw_dircopy()
endfunc

func Test_netrw_dircopy_powershell()
  call SetShell('powershell')
  call s:test_netrw_dircopy()
endfunc

func Test_netrw_dircopy_pwsh()
  call SetShell('pwsh')
  call s:test_netrw_dircopy()
endfunc

" Copy file into the same directory with a different name
func Test_netrw_dircopy_rename_default()
  call SetShell('default')
  call Test_NetrwMarkFileCopy_SameDir()
endfunc

func Test_netrw_dircopy_rename_powershell()
  call SetShell('powershell')
  call Test_NetrwMarkFileCopy_SameDir()
endfunc

func Test_netrw_dircopy_rename_pwsh()
  call SetShell('pwsh')
  call Test_NetrwMarkFileCopy_SameDir()
endfunc

" Browser file move
func s:netrw_filemove(count = 1)
  " setup
  let marked_files = []
  let source_dir = netrw#fs#PathJoin($HOME, "src")
  let target_dir = netrw#fs#PathJoin($HOME, "target")

  call mkdir(source_dir, "R")
  call mkdir(target_dir, "R")

  for i in range(a:count)
    call add(marked_files, $"testfile{i}.txt")
    call writefile(
    \   [$"NetrwMarkFileMove test file {i}"],
    \   netrw#fs#PathJoin(source_dir, marked_files[-1]))
  endfor

  " delegate
  call Test_NetrwMarkFileMove(source_dir, target_dir, marked_files)

  " verify
  for i in range(a:count)
    call assert_equal(
    \   [$"NetrwMarkFileMove test file {i}"],
    \   readfile(netrw#fs#PathJoin(target_dir, $"testfile{i}.txt")),
    \   $"File move failed for testfile{i}.txt")
  endfor
endfunc

func s:test_netrw_filemove()

  " if shellslash is available, check both settings
  if exists('+shellslash')
    set shellslash&
    call s:netrw_filemove(10)
    set shellslash!
  endif

  call s:netrw_filemove(10)

endfunc

func Test_netrw_filemove_default()
  call SetShell('default')
  call s:test_netrw_filemove()
endfunc

func Test_netrw_filemove_powershell()
  call SetShell('powershell')
  call s:test_netrw_filemove()
endfunc

func Test_netrw_filemove_pwsh()
  call SetShell('pwsh')
  call s:test_netrw_filemove()
endfunc

func Test_netrw_reject_evil_hostname()
  let msg = execute(':e scp://x;touch RCE;x/dir/')
  let msg = split(msg, "\n")[-1]
  call assert_match('Rejecting invalid hostname', msg)
endfunc

func Test_netrw_hostname()
  let valid_hostnames = [
  \   'localhost',
  \   '127.0.0.1',
  \   '::1',
  \   '0:0:0:0:0:0:0:1',
  \   'user@localhost',
  \   'usuario@127.0.0.1',
  \   'utilisateur@::1',
  \   'benutzer@0:0:0:0:0:0:0:1',
  \   'localhost:22',
  \   '127.0.0.1:80',
  \   '[::1]:443',
  \   '[0:0:0:0:0:0:0:1]:5432',
  \   'user@localhost:22',
  \   'usuario@127.0.0.1:80',
  \   'utilisateur@[::1]:443',
  \   'benutzer@[0:0:0:0:0:0:0:1]:5432']

  for hostname in valid_hostnames
    call assert_true(Test_NetrwValidateHostname(hostname), $"Valid hostname {hostname} was rejected")
  endfor
endfunc

func Test_netrw_FileUrlEdit_pipe_injection()
  CheckExecutable id
  let fname = 'Xtestfile'
  let url = 'file:///tmp/file.md%7C!id>'..fname
  sil call netrw#FileUrlEdit(url)
  call assert_false(filereadable(fname), 'Command injection via pipe in file URL')
endfunc

" mnv:ts=8 sts=2 sw=2 et