robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
3b00ddb601
master
1" This script is sourced while editing the .vim file with the tests. 2" When the script is successful the .res file will be created. 3" Errors are appended to the test.log file. 4" 5" To execute only specific test functions, add a second argument. It will be 6" matched against the names of the Test_ function. E.g.: 7" ../vim -u NONE -S runtest.vim test_channel.vim open_delay 8" The output can be found in the "messages" file. 9" 10" If the environment variable $TEST_FILTER is set then only test functions 11" matching this pattern are executed. E.g. for sh/bash: 12" export TEST_FILTER=Test_channel 13" For csh: 14" setenv TEST_FILTER Test_channel 15" 16" If the environment variable $TEST_SKIP_PAT is set then test functions 17" matching this pattern will be skipped. It's the opposite of $TEST_FILTER. 18" 19" While working on a test you can make $TEST_NO_RETRY non-empty to not retry: 20" export TEST_NO_RETRY=yes 21" 22" To ignore failure for tests that are known to fail in a certain environment, 23" set $TEST_MAY_FAIL to a comma separated list of function names. E.g. for 24" sh/bash: 25" export TEST_MAY_FAIL=Test_channel_one,Test_channel_other 26" The failure report will then not be included in the test.log file and 27" "make test" will not fail. 28" 29" The test script may contain anything, only functions that start with 30" "Test_" are special. These will be invoked and should contain assert 31" functions. See test_assert.vim for an example. 32" 33" It is possible to source other files that contain "Test_" functions. This 34" can speed up testing, since Vim does not need to restart. But be careful 35" that the tests do not interfere with each other. 36" 37" If an error cannot be detected properly with an assert function add the 38" error to the v:errors list: 39" call add(v:errors, 'test foo failed: Cannot find xyz') 40" 41" If preparation for each Test_ function is needed, define a SetUp function. 42" It will be called before each Test_ function. 43" 44" If cleanup after each Test_ function is needed, define a TearDown function. 45" It will be called after each Test_ function. 46" 47" When debugging a test it can be useful to add messages to v:errors: 48" call add(v:errors, "this happened") 49 50 51" Without the +eval feature we can't run these tests, bail out. 52silent ! while 0 53qa ! 54silent ! endwhile 55 56" In the GUI we can always change the screen size. 57if has ( 'gui_running' ) 58if has ( 'gui_gtk' ) 59" to keep screendump size unchanged 60set guifont = Monospace\ 10 61endif 62set columns = 80 lines = 25 63endif 64 65" Check that the screen size is at least 24 x 80 characters. 66if & lines < 24 || & columns < 80 67let error = 'Screen size too small! Tests require at least 24 lines with 80 characters, got ' .. & lines .. ' lines with ' .. & columns .. ' characters' 68echoerr error 69split test.log 70$ put =error 71write 72split messages 73call append ( line ( '$' ), '' ) 74call append ( line ( '$' ), 'From ' . expand ( '%' ) . ':' ) 75call append ( line ( '$' ), error ) 76write 77qa ! 78endif 79 80if has ( 'reltime' ) 81let s: run_start_time = reltime () 82 83if ! filereadable ( 'starttime' ) 84" first test, store the overall test starting time 85let s: test_start_time = localtime () 86call writefile ([ string ( s: test_start_time )], 'starttime' ) 87else 88" second or later test, read the overall test starting time 89let s: test_start_time = readfile ( 'starttime' )[ 0 ] ->str2nr () 90endif 91endif 92 93" Always use forward slashes. 94set shellslash 95 96" Common with all tests on all systems. 97source setup.vim 98 99" Needed for RunningWithValgrind(). 100source shared.vim 101 102" Needed for the various Check commands 103source check.vim 104 105" For consistency run all tests with 'nocompatible' set. 106" This also enables use of line continuation. 107set nocp viminfo += nviminfo 108 109" Use utf-8 by default, instead of whatever the system default happens to be. 110" Individual tests can overrule this at the top of the file and use 111" g:orig_encoding if needed. 112let g: orig_encoding = & encoding 113set encoding = utf-8 114 115" REDIR_TEST_TO_NULL has a very permissive SwapExists autocommand which is for 116" the test_name.vim file itself. Replace it here with a more restrictive one, 117" so we still catch mistakes. 118if has ( "win32" ) 119" replace any '/' directory separators by '\\' 120let s: test_script_fname = substitute ( expand ( '%' ), '/' , '\\' , 'g' ) 121else 122let s: test_script_fname = expand ( '%' ) 123endif 124au ! SwapExists * call HandleSwapExists () 125func HandleSwapExists () 126if exists ( 'g:ignoreSwapExists' ) 127if type ( g: ignoreSwapExists ) == v: t_string 128let v: swapchoice = g: ignoreSwapExists 129endif 130return 131endif 132" Ignore finding a swap file for the test script (the user might be 133" editing it and do ":make test_name") and the output file. 134" Report finding another swap file and chose 'q' to avoid getting stuck. 135if expand ( '<afile>' ) == 'messages' || expand ( '<afile>' ) =~ s: test_script_fname 136let v: swapchoice = 'e' 137else 138call assert_report ( 'Unexpected swap file: ' .. v: swapname ) 139let v: swapchoice = 'q' 140endif 141endfunc 142 143" Avoid stopping at the "hit enter" prompt 144set nomore 145 146" Output all messages in English. 147lang mess C 148 149" Nvim: append runtime from build dir, which contains the generated doc/tags. 150let & runtimepath ..= ',' .. expand ( $ BUILD_DIR ) .. '/runtime/' 151" Nvim: append libdir from build dir, which contains the bundled TS parsers. 152let & runtimepath ..= ',' .. expand ( $ BUILD_DIR ) .. '/lib/nvim/' 153" Nvim: load the ":helptags" module + parser now, because tests reset 'runtimepath'. 154lua pcall ( vim . treesitter . language . add , 'vimdoc' ) 155 156let s: t_bold = & t_md 157let s: t_normal = & t_me 158if has ( 'win32' ) 159" avoid prompt that is long or contains a line break 160let $ PROMPT = '$P$G' 161endif 162 163if has ( 'mac' ) 164" In macOS, when starting a shell in a terminal, a bash deprecation warning 165" message is displayed. This breaks the terminal test. Disable the warning 166" message. 167let $ BASH_SILENCE_DEPRECATION_WARNING = 1 168endif 169 170 171" Prepare for calling test_garbagecollect_now(). 172" Also avoids some delays in Insert mode completion. 173let v: testing = 1 174 175let s: has_ffi = luaeval ( 'pcall(require, "ffi")' ) 176if s: has_ffi 177lua << trim EOF 178require ( 'ffi' ). cdef ( [[ 179int starting ; 180bool test_disable_char_avail ; 181]] ) 182EOF 183endif 184 185" This can emulate test_override('starting') and test_override('char_avail') 186" if LuaJIT FFI is enabled. 187" Other flags are not supported. 188func Ntest_override ( name , val ) 189if a: name !=# 'starting' && a: name != 'char_avail' && a: name !=# 'ALL' 190throw 'Unexpected use of Ntest_override()' 191endif 192if ! s: has_ffi 193throw 'Skipped: missing LuaJIT FFI' 194endif 195 196if a: name ==# 'starting' || a: name ==# 'ALL' 197if a: val 198if ! exists ( 's:save_starting' ) 199let s: save_starting = luaeval ( 'require("ffi").C.starting' ) 200endif 201lua require ( "ffi" ). C . starting =0 202elseif exists ( 's:save_starting' ) 203exe 'lua require("ffi").C.starting =' s: save_starting 204unlet s: save_starting 205endif 206endif 207 208if a: name ==# 'char_avail' || a: name ==# 'ALL' 209exe 'lua require("ffi").C.test_disable_char_avail =' a: val 210endif 211endfunc 212 213" roughly equivalent to test_setmouse() in Vim 214func Ntest_setmouse ( row , col ) 215call nvim_input_mouse ( 'move' , '' , '' , 0 , a: row - 1 , a: col - 1 ) 216if state ( 'm' ) == '' 217call getchar ( 0 ) 218endif 219endfunc 220 221" roughly equivalent to term_wait() in Vim 222func Nterm_wait ( buf , time = 10 ) 223execute $ 'sleep {a:time}m' 224endfunc 225 226" Support function: get the alloc ID by name. 227func GetAllocId ( name ) 228exe 'split ' . s: srcdir . '/alloc.h' 229let top = search ( 'typedef enum' ) 230if top == 0 231call add ( v: errors , 'typedef not found in alloc.h' ) 232endif 233let lnum = search ( 'aid_' . a: name . ',' ) 234if lnum == 0 235call add ( v: errors , 'Alloc ID ' . a: name . ' not defined' ) 236endif 237close 238return lnum - top - 1 239endfunc 240 241" Get the list of swap files in the current directory. 242func s: GetSwapFileList () 243let save_dir = & directory 244let & directory = '.' 245let files = swapfilelist () 246let & directory = save_dir 247 248" remove a match with runtest.vim 249let idx = indexof ( files , 'v:val =~ "runtest.vim."' ) 250if idx >= 0 251call remove ( files , idx ) 252endif 253 254return files 255endfunc 256 257" A previous (failed) test run may have left swap files behind. Delete them 258" before running tests again, they might interfere. 259for name in s: GetSwapFileList () 260call delete ( name ) 261endfor 262unlet ! name 263 264 265" Invoked when a test takes too much time. 266func TestTimeout ( id ) 267split test.log 268call append ( line ( '$' ), '' ) 269 270let text = 'Test timed out: ' .. g: testfunc 271if g: timeout_start > 0 272let text ..= strftime ( ' after %s seconds' , localtime () - g: timeout_start ) 273endif 274call append ( line ( '$' ), text ) 275write 276call add ( v: errors , text ) 277 278cquit ! 42 279endfunc 280let g: timeout_start = 0 281 282func RunTheTest ( test ) 283let prefix = '' 284if has ( 'reltime' ) 285let prefix = strftime ( '%M:%S' , localtime () - s: test_start_time ) .. ' ' 286let g: func_start = reltime () 287endif 288echo prefix .. 'Executing ' .. a: test 289 290if has ( 'timers' ) 291" No test should take longer than 45 seconds. If it takes longer we 292" assume we are stuck and need to break out. 293let test_timeout_timer = 294 \timer_start ( RunningWithValgrind () ? 90000 : 45000 , 'TestTimeout' ) 295let g: timeout_start = localtime () 296endif 297 298" Avoid stopping at the "hit enter" prompt 299set nomore 300 301" Avoid a three second wait when a message is about to be overwritten by the 302" mode message. 303set noshowmode 304 305" Some tests wipe out buffers. To be consistent, always wipe out all 306" buffers. 307 %bwipe ! 308 309" The test may change the current directory. Save and restore the 310" directory after executing the test. 311let save_cwd = getcwd () 312 313" Align Nvim defaults to Vim. 314source setup.vim 315 316if exists ( "*SetUp" ) 317try 318call SetUp () 319catch 320call add ( v: errors , 'Caught exception in SetUp() before ' . a: test . ': ' . v: exception . ' @ ' . v: throwpoint ) 321endtry 322endif 323 324let skipped = v: false 325 326au VimLeavePre * call EarlyExit ( g: testfunc ) 327if a: test =~ 'Test_nocatch_' 328" Function handles errors itself. This avoids skipping commands after the 329" error. 330let g: skipped_reason = '' 331exe 'call ' . a: test 332if g: skipped_reason != '' 333call add ( s: messages , ' Skipped' ) 334call add ( s: skipped , 'SKIPPED ' . a: test . ': ' . g: skipped_reason ) 335let skipped = v: true 336endif 337elseif ! s: has_ffi && execute ( 'func ' .. a: test [: -3 ]) ->match ( "\n[ 0-9]*call Ntest_override(" ) >= 0 338call add ( s: messages , ' Skipped' ) 339call add ( s: skipped , 'SKIPPED ' . a: test . ': missing LuaJIT FFI' .) 340let skipped = v: true 341else 342try 343exe 'call ' . a: test 344catch /^\cskipped/ 345call add ( s: messages , ' Skipped' ) 346call add ( s: skipped , 'SKIPPED ' . a: test . ': ' . substitute ( v: exception , '^\S*\s\+' , '' , '' )) 347let skipped = v: true 348catch 349call add ( v: errors , 'Caught exception in ' . a: test . ': ' . v: exception . ' @ ' . v: throwpoint ) 350endtry 351endif 352au ! VimLeavePre 353 354if a: test =~ '_terminal_' 355" Terminal tests sometimes hang, give extra information 356echoconsole 'After executing ' .. a:test 357endif 358 359" In case 'insertmode' was set and something went wrong, make sure it is 360" reset to avoid trouble with anything else. 361set noinsertmode 362 363if exists ( "*TearDown" ) 364try 365call TearDown () 366catch 367call add ( v: errors , 'Caught exception in TearDown() after ' . a: test . ': ' . v: exception . ' @ ' . v: throwpoint ) 368endtry 369endif 370 371if has ( 'timers' ) 372call timer_stop ( test_timeout_timer ) 373let g: timeout_start = 0 374endif 375 376" Clear any autocommands and put back the catch-all for SwapExists. 377au ! 378au SwapExists * call HandleSwapExists () 379 380" Close any stray popup windows 381if has ( 'popupwin' ) 382call popup_clear () 383endif 384 385" Close any extra tab pages and windows and make the current one not modified. 386while tabpagenr ( '$' ) > 1 387let winid = win_getid () 388quit ! 389if winid == win_getid () 390echoerr 'Could not quit window' 391break 392endif 393endwhile 394 395while 1 396let wincount = winnr ( '$' ) 397if wincount == 1 398break 399endif 400bwipe ! 401if wincount == winnr ( '$' ) 402" Did not manage to close a window. 403only ! 404break 405endif 406endwhile 407 408exe 'cd ' . save_cwd 409 410if a: test =~ '_terminal_' 411" Terminal tests sometimes hang, give extra information 412echoconsole 'Finished ' . a:test 413endif 414 415let message = 'Executed ' . a: test 416if has ( 'reltime' ) 417let message ..= repeat ( ' ' , 50 - len ( message )) 418let time = reltime ( g: func_start ) 419if reltimefloat ( time ) > 0.1 420let message = s: t_bold .. message 421endif 422let message ..= ' in ' .. reltimestr ( time ) .. ' seconds' 423if reltimefloat ( time ) > 0.1 424let message ..= s: t_normal 425endif 426endif 427call add ( s: messages , message ) 428let s: done += 1 429 430" close any split windows 431while winnr ( '$' ) > 1 432noswapfile bwipe! 433endwhile 434 435" May be editing some buffer, wipe it out. Then we may end up in another 436" buffer, continue until we end up in an empty no-name buffer without a swap 437" file. 438while bufname () != '' || execute ( 'swapname' ) !~ 'No swap file' 439let bn = bufnr () 440 441noswapfile bwipe! 442 443if bn == bufnr () 444" avoid getting stuck in the same buffer 445break 446endif 447endwhile 448 449if ! skipped 450" Check if the test has left any swap files behind. Delete them before 451" running tests again, they might interfere. 452let swapfiles = s: GetSwapFileList () 453if len ( swapfiles ) > 0 454call add ( s: messages , "Found swap files: " .. string ( swapfiles )) 455for name in swapfiles 456call delete ( name ) 457endfor 458endif 459endif 460endfunc 461 462function Delete_Xtest_Files () 463for file in glob ( 'X*' , v: false , v: true ) 464if file ==? 'XfakeHOME' 465" Clean up files created by setup.vim 466call delete ( 'XfakeHOME' , 'rf' ) 467continue 468endif 469" call add(v:errors, file .. " exists when it shouldn't, trying to delete it!") 470call delete ( file ) 471if ! empty ( glob ( file , v: false , v: true )) 472" call add(v:errors, file .. " still exists after trying to delete it!") 473if has ( 'unix' ) 474call system ( 'rm -rf ' .. file ) 475endif 476endif 477endfor 478endfunc 479 480func AfterTheTest ( func_name ) 481if len ( v: errors ) > 0 482if match ( s: may_fail_list , '^' .. a: func_name ) >= 0 483let s: fail_expected += 1 484call add ( s: errors_expected , 'Found errors in ' . g: testfunc . ':' ) 485call extend ( s: errors_expected , v: errors ) 486else 487let s: fail += 1 488call add ( s: errors , 'Found errors in ' . g: testfunc . ':' ) 489call extend ( s: errors , v: errors ) 490endif 491let v: errors = [] 492endif 493endfunc 494 495func EarlyExit ( test ) 496" It's OK for the test we use to test the quit detection. 497if a: test != 'Test_zz_quit_detected()' 498call add ( v: errors , v: errmsg ) 499call add ( v: errors , 'Test caused Vim to exit: ' . a: test ) 500endif 501 502call FinishTesting () 503endfunc 504 505" This function can be called by a test if it wants to abort testing. 506func FinishTesting () 507call AfterTheTest ( '' ) 508call Delete_Xtest_Files () 509 510" Don't write viminfo on exit. 511set viminfo = 512 513if s: fail == 0 && s: fail_expected == 0 514" Success, create the .res file so that make knows it's done. 515exe 'split ' . fnamemodify ( g: testname , ':r' ) . '.res' 516write 517endif 518 519if len ( s: errors ) > 0 520" Append errors to test.log 521split test.log 522call append ( line ( '$' ), '' ) 523call append ( line ( '$' ), 'From ' . g: testname . ':' ) 524call append ( line ( '$' ), s: errors ) 525write 526endif 527 528if s: done == 0 529if s: filtered > 0 530if $ TEST_FILTER != '' 531let message = "NO tests match $TEST_FILTER: '" .. $ TEST_FILTER .. "'" 532else 533let message = "ALL tests match $TEST_SKIP_PAT: '" .. $ TEST_SKIP_PAT .. "'" 534endif 535else 536let message = 'NO tests executed' 537endif 538else 539if s: filtered > 0 540call add ( s: messages , "Filtered " .. s: filtered .. " tests with $TEST_FILTER and $TEST_SKIP_PAT" ) 541endif 542let message = 'Executed ' . s: done . ( s: done > 1 ? ' tests' : ' test' ) 543endif 544if s: done > 0 && has ( 'reltime' ) 545let message = s: t_bold .. message .. repeat ( ' ' , 40 - len ( message )) 546let message ..= ' in ' .. reltimestr ( reltime ( s: run_start_time )) .. ' seconds' 547let message ..= s: t_normal 548endif 549echo message 550call add ( s: messages , message ) 551if s: fail > 0 552let message = s: fail . ' FAILED:' 553echo message 554call add ( s: messages , message ) 555call extend ( s: messages , s: errors ) 556endif 557if s: fail_expected > 0 558let message = s: fail_expected . ' FAILED (matching $TEST_MAY_FAIL):' 559echo message 560call add ( s: messages , message ) 561call extend ( s: messages , s: errors_expected ) 562endif 563 564" Add SKIPPED messages 565call extend ( s: messages , s: skipped ) 566 567" Append messages to the file "messages" 568split messages 569call append ( line ( '$' ), '' ) 570call append ( line ( '$' ), 'From ' . g: testname . ':' ) 571call append ( line ( '$' ), s: messages ) 572write 573 574qall ! 575endfunc 576 577" Source the test script. First grab the file name, in case the script 578" navigates away. g:testname can be used by the tests. 579let g: testname = expand ( '%' ) 580let s: done = 0 581let s: fail = 0 582let s: fail_expected = 0 583let s: errors = [] 584let s: errors_expected = [] 585let s: messages = [] 586let s: skipped = [] 587if expand ( '%' ) =~ 'test_vimscript.vim' 588" this test has intentional errors, don't use try/catch. 589source % 590else 591try 592source % 593catch /^\cskipped/ 594call add ( s: messages , ' Skipped' ) 595call add ( s: skipped , 'SKIPPED ' . expand ( '%' ) . ': ' . substitute ( v: exception , '^\S*\s\+' , '' , '' )) 596catch 597let s: fail += 1 598call add ( s: errors , 'Caught exception: ' . v: exception . ' @ ' . v: throwpoint ) 599endtry 600endif 601 602" Delete the .res file, it may change behavior for completion 603call delete ( fnamemodify ( g: testname , ':r' ) .. '.res' ) 604 605" Locate Test_ functions and execute them. 606redir @q 607silent function /^Test_ 608redir END 609let s: tests = split ( substitute ( @q, 'function \(\k*()\)' , '\1' , 'g' )) 610 611" If there is an extra argument filter the function names against it. 612if argc () > 1 613let s: tests = filter ( s: tests , 'v:val =~ argv(1)' ) 614endif 615 616" If the environment variable $TEST_FILTER is set then filter the function 617" names against it. 618let s: filtered = 0 619if $ TEST_FILTER != '' 620let s: filtered = len ( s: tests ) 621let s: tests = filter ( s: tests , 'v:val =~ $TEST_FILTER' ) 622let s: filtered -= len ( s: tests ) 623endif 624 625let s: may_fail_list = [] 626if $ TEST_MAY_FAIL != '' 627" Split the list at commas and add () to make it match g:testfunc. 628let s: may_fail_list = split ( $ TEST_MAY_FAIL , ',' ) ->map ({ i , v ->v .. '()' }) 629endif 630 631" Execute the tests in alphabetical order. 632for g: testfunc in sort ( s: tests ) 633if $ TEST_SKIP_PAT != '' && g: testfunc =~ $ TEST_SKIP_PAT 634call add ( s: messages , g: testfunc .. ' matches $TEST_SKIP_PAT' ) 635let s: filtered += 1 636continue 637endif 638 639" Silence, please! 640set belloff = all 641let prev_error = '' 642let total_errors = [] 643let g: run_nr = 1 644 645" A test can set g:test_is_flaky to retry running the test. 646let g: test_is_flaky = 0 647 648let g: check_screendump_called = v: false 649 650" A test can set g:max_run_nr to change the max retry count. 651let g: max_run_nr = 5 652if has ( 'mac' ) 653let g: max_run_nr = 10 654endif 655 656" By default, give up if the same error occurs. A test can set 657" g:giveup_same_error to 0 to not give up on the same error and keep trying. 658let g: giveup_same_error = 1 659 660let starttime = strftime ( "%H:%M:%S" ) 661call RunTheTest ( g: testfunc ) 662 663" Repeat a flaky test. Give up when: 664" - $TEST_NO_RETRY is not empty 665" - it fails again with the same message 666" - it fails five times (with a different message) 667if len ( v: errors ) > 0 668 \&& $ TEST_NO_RETRY == '' 669 \&& g: test_is_flaky 670while 1 671call add ( s: messages , 'Found errors in ' .. g: testfunc .. ':' ) 672call extend ( s: messages , v: errors ) 673 674let endtime = strftime ( "%H:%M:%S" ) 675if has ( 'reltime' ) 676let suffix = $ ' in{reltimestr(reltime(g: func_start ) )} seconds' 677else 678let suffix = '' 679endif 680call add ( total_errors , $ 'Run {g: run_nr } , {starttime} - {endtime}{suffix}:') 681call extend ( total_errors , v: errors ) 682 683if g: run_nr >= g: max_run_nr || g: giveup_same_error && prev_error == v: errors [ 0 ] 684call add ( total_errors , 'Flaky test failed too often, giving up' ) 685let v: errors = total_errors 686break 687endif 688 689call add ( s: messages , 'Flaky test failed, running it again' ) 690 691" Flakiness is often caused by the system being very busy. Sleep a 692" couple of seconds to have a higher chance of succeeding the second 693" time. 694let delay = g: run_nr * 2 695exe 'sleep' delay 696 697let prev_error = v: errors [ 0 ] 698let v: errors = [] 699let g: run_nr += 1 700 701let starttime = strftime ( "%H:%M:%S" ) 702call RunTheTest ( g: testfunc ) 703 704if len ( v: errors ) == 0 705" Test passed on rerun. 706break 707endif 708endwhile 709endif 710 711call AfterTheTest ( g: testfunc ) 712endfor 713 714call FinishTesting () 715 716" vim: shiftwidth=2 sts=2 expandtab