robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
dab5fab948
master
1local uv =vim . uv 2local t =require ( 'test.testutil' ) 3---@type test.harness 4local harness =require ( 'test.harness' ) 5 6local Session =require ( 'test.client.session' ) 7local uv_stream =require ( 'test.client.uv_stream' ) 8local SocketStream =uv_stream . SocketStream 9local ProcStream =uv_stream . ProcStream 10 11local check_cores =t . check_cores 12local check_logs =t . check_logs 13local dedent =t . dedent 14local eq =t . eq 15local is_os =t . is_os 16local ok =t . ok 17local sleep =uv . sleep 18 19--- Functions executing in the current nvim session/process being tested. 20local M ={} 21 22M . runtime_set ='set runtimepath^=' .. t . paths . test_build_dir .. '/lib/nvim' 23 24M . nvim_prog =( os . getenv ( 'NVIM_PRG' ) or t . paths . test_build_dir .. '/bin/nvim' ) 25-- Default settings for the test session. 26M . nvim_set =( 27'set shortmess+=IS background=light noswapfile noautoindent startofline' 28.. ' laststatus=1 undodir=. directory=. viewdir=. backupdir=.' 29.. " belloff= wildoptions-=pum joinspaces noshowcmd noruler nomore redrawdebug=invalid shada=!,'100,<50,s10,h" 30.. [[ statusline=%<%f\ %{%nvim_eval_statusline('%h%w%m%r',\ {'maxwidth':\ 30}).width\ >\ 0\ ?\ '%h%w%m%r\ '\ :\ ''%}%=%{%\ &showcmdloc\ ==\ 'statusline'\ ?\ '%-10.S\ '\ :\ ''\ %}%{%\ exists('b:keymap_name')\ ?\ '<'..b:keymap_name..'>\ '\ :\ ''\ %}%{%\ &ruler\ ?\ &rulerformat\ :\ ''\ %}]] 31.. ' rulerformat=%18(%l,%c%V%=%P%)' 32) 33M . nvim_argv ={ 34M . nvim_prog , 35'-u' , 36'NONE' , 37'-i' , 38'NONE' , 39-- XXX: find treesitter parsers. 40'--cmd' , 41M . runtime_set , 42'--cmd' , 43M . nvim_set , 44-- Remove default user commands and mappings. 45'--cmd' , 46'comclear | mapclear | mapclear!' , 47-- Make screentest work after changing to the new default color scheme 48-- Source 'vim' color scheme without side effects 49-- TODO: rewrite tests 50'--cmd' , 51'lua dofile("runtime/colors/vim.lua")' , 52'--cmd' , 53'unlet g:colors_name' , 54'--embed' , 55} 56if os . getenv ( 'OSV_PORT' ) then 57table . insert ( M . nvim_argv , '--cmd' ) 58table . insert ( 59M . nvim_argv , 60string . format ( 61"lua require('osv').launch({ port = %s, blocking = true })" , 62os . getenv ( 'OSV_PORT' ) 63) 64) 65end 66 67-- Directory containing nvim. 68M . nvim_dir =M . nvim_prog : gsub ( '[/\\][^/\\]+$' , '' ) 69if M . nvim_dir == M . nvim_prog then 70M . nvim_dir ='.' 71end 72 73local prepend_argv --- @type string[]? 74 75if os . getenv ( 'VALGRIND' ) then 76local log_file =os . getenv ( 'VALGRIND_LOG' ) or 'valgrind-%p.log' 77prepend_argv ={ 78'valgrind' , 79'-q' , 80'--tool=memcheck' , 81'--leak-check=yes' , 82'--track-origins=yes' , 83'--show-possibly-lost=no' , 84'--suppressions=src/.valgrind.supp' , 85'--log-file=' .. log_file , 86} 87if os . getenv ( 'GDB' ) then 88table . insert ( prepend_argv , '--vgdb=yes' ) 89table . insert ( prepend_argv , '--vgdb-error=0' ) 90end 91elseif os . getenv ( 'GDB' ) then 92local gdbserver_port =os . getenv ( 'GDBSERVER_PORT' ) or '7777' 93prepend_argv ={ 'gdbserver' , 'localhost:' .. gdbserver_port } 94end 95 96if prepend_argv then 97local new_nvim_argv ={} --- @type string[] 98local len =# prepend_argv 99for i =1 , len do 100new_nvim_argv [ i ] =prepend_argv [ i ] 101end 102for i =1 , # M . nvim_argv do 103new_nvim_argv [ i + len ] =M . nvim_argv [ i ] 104end 105M . nvim_argv =new_nvim_argv 106M . prepend_argv =prepend_argv 107end 108 109local session --- @type test.Session? 110local sessions ={} --- @type table<test.Session, true> 111local sigpipe_handler --- @type uv.uv_signal_t? 112local loop_running --- @type boolean? 113local last_error --- @type string? 114local method_error --- @type string? 115 116if not is_os ( 'win' ) then 117sigpipe_handler =assert ( uv . new_signal ()) 118uv . signal_start ( sigpipe_handler , 'sigpipe' , function () 119( 'warning: got SIGPIPE signal. Likely related to a crash in nvim' ) 120end ) 121end 122 123function M . get_session () 124return session 125end 126 127function M . set_session ( s ) 128session =s 129end 130 131--- @param method string 132--- @param ... any 133--- @return any 134function M . request ( method , ... ) 135assert ( session , 'no Nvim session' ) 136assert ( not session . eof_err , 'RPC request after Nvim EOF' ) 137local status , rv =session : request ( method , ... ) 138if not status then 139if loop_running then 140--- @type string 141last_error =rv [ 2 ] 142session : stop () 143else 144error ( rv [ 2 ]) 145end 146end 147return rv 148end 149 150--- @param method string 151--- @param ... any 152--- @return any 153function M . request_lua ( method , ... ) 154return M . exec_lua ( [[return vim.api[...](select(2, ...))]] , method , ... ) 155end 156 157--- @param timeout? integer 158--- @return string? 159function M . next_msg ( timeout ) 160assert ( session ) 161return session : next_message ( timeout or 10000 ) 162end 163 164function M . expect_twostreams ( msgs1 , msgs2 ) 165local pos1 , pos2 =1 , 1 166while pos1 <= # msgs1 or pos2 <= # msgs2 do 167local msg =M . next_msg () 168if pos1 <= # msgs1 and pcall ( eq , msgs1 [ pos1 ], msg ) then 169pos1 =pos1 + 1 170elseif pos2 <= # msgs2 then 171eq ( msgs2 [ pos2 ], msg ) 172pos2 =pos2 + 1 173else 174-- already failed, but show the right error message 175eq ( msgs1 [ pos1 ], msg ) 176end 177end 178end 179 180-- Expects a sequence of next_msg() results. If multiple sequences are 181-- passed they are tried until one succeeds, in order of shortest to longest. 182-- 183-- Can be called with positional args (list of sequences only): 184-- expect_msg_seq(seq1, seq2, ...) 185-- or keyword args: 186-- expect_msg_seq{ignore={...}, seqs={seq1, seq2, ...}} 187-- 188-- ignore: List of ignored event names. 189-- seqs: List of one or more potential event sequences. 190function M . expect_msg_seq ( ... ) 191if select ( '#' , ... ) < 1 then 192error ( 'need at least 1 argument' ) 193end 194local arg1 =select ( 1 , ... ) 195if ( arg1 [ 'seqs' ] and select ( '#' , ... ) > 1 ) or type ( arg1 ) ~= 'table' then 196error ( 'invalid args' ) 197end 198local ignore =arg1 [ 'ignore' ] and arg1 [ 'ignore' ] or {} 199--- @type string[] 200local seqs =arg1 [ 'seqs' ] and arg1 [ 'seqs' ] or { ... } 201if type ( ignore ) ~= 'table' then 202error ( "'ignore' arg must be a list of strings" ) 203end 204table . sort ( seqs , function ( a , b ) -- Sort ascending, by (shallow) length. 205return # a < # b 206end ) 207 208local actual_seq ={} 209local nr_ignored =0 210local final_error ='' 211local function cat_err ( err1 , err2 ) 212if err1 == nil then 213return err2 214end 215return string . format ( '%s\n%s\n%s' , err1 , string . rep ( '=' , 78 ), err2 ) 216end 217local msg_timeout =M . load_adjust ( 10000 ) -- Big timeout for ASAN/valgrind. 218for anum =1 , # seqs do 219local expected_seq =seqs [ anum ] 220-- Collect enough messages to compare the next expected sequence. 221while # actual_seq < # expected_seq do 222local msg =M . next_msg ( msg_timeout ) 223local msg_type =msg and msg [ 2 ] or nil 224if msg == nil then 225error ( 226cat_err ( 227final_error , 228string . format ( 229'got %d messages (ignored %d), expected %d' , 230# actual_seq , 231nr_ignored , 232# expected_seq 233) 234) 235) 236elseif vim . tbl_contains ( ignore , msg_type ) then 237nr_ignored =nr_ignored + 1 238else 239table . insert ( actual_seq , msg ) 240end 241end 242local status , result =pcall ( eq , expected_seq , actual_seq ) 243if status then 244return result 245end 246local message =result 247if type ( result ) == 'table' then 248-- 'eq' returns several things 249--- @type string 250message =result . message 251end 252final_error =cat_err ( final_error , message ) 253end 254error ( final_error ) 255end 256 257local function call_and_stop_on_error ( lsession , ... ) 258local status , result =Session . safe_pcall ( ... ) -- luacheck: ignore 259if not status then 260lsession : stop () 261last_error =result 262return '' 263end 264return result 265end 266 267function M . set_method_error ( err ) 268method_error =err 269end 270 271--- Runs the event loop of the given session. 272--- 273--- @param lsession test.Session 274--- @param request_cb function? 275--- @param notification_cb function? 276--- @param setup_cb function? 277--- @param timeout integer 278--- @return [integer, string] 279function M . run_session ( lsession , request_cb , notification_cb , setup_cb , timeout ) 280local on_request --- @type function? 281local on_notification --- @type function? 282local on_setup --- @type function? 283 284if request_cb then 285function on_request ( method , args ) 286method_error =nil 287local result =call_and_stop_on_error ( lsession , request_cb , method , args ) 288if method_error ~= nil then 289return method_error , true 290end 291return result 292end 293end 294 295if notification_cb then 296function on_notification ( method , args ) 297call_and_stop_on_error ( lsession , notification_cb , method , args ) 298end 299end 300 301if setup_cb then 302function on_setup () 303call_and_stop_on_error ( lsession , setup_cb ) 304end 305end 306 307loop_running =true 308lsession : run ( on_request , on_notification , on_setup , timeout ) 309loop_running =false 310if last_error then 311local err =last_error 312last_error =nil 313error ( err ) 314end 315 316return lsession . eof_err 317end 318 319--- Runs the event loop of the current global session. 320function M . run ( request_cb , notification_cb , setup_cb , timeout ) 321assert ( session ) 322return M . run_session ( session , request_cb , notification_cb , setup_cb , timeout ) 323end 324 325function M . stop () 326if loop_running then 327assert ( session ): stop () 328end 329end 330 331-- Use for commands which expect nvim to quit. 332-- The first argument can also be a timeout. 333function M . expect_exit ( fn_or_timeout , ... ) 334if type ( fn_or_timeout ) == 'function' then 335t . matches ( vim . pesc ( Session . eof_err_msg ), t . pcall_err ( fn_or_timeout , ... )) 336else 337t . matches ( 338vim . pesc ( Session . eof_err_msg ), 339t . pcall_err ( function ( timeout , fn , ... ) 340fn ( ... ) 341assert ( session ) 342while session : next_message ( timeout ) do 343end 344if session . eof_err then 345error ( session . eof_err [ 2 ]) 346end 347end , fn_or_timeout , ... ) 348) 349end 350M . check_close () 351end 352 353--- Executes a Vimscript function via Lua. 354--- Fails on Vimscript error, but does not update v:errmsg. 355--- @param name string 356--- @param ... any 357--- @return any 358function M . call_lua ( name , ... ) 359return M . exec_lua ( [[return vim.call(...)]] , name , ... ) 360end 361 362--- Sends user input to Nvim. 363--- Does not fail on Vimscript error, but v:errmsg will be updated. 364--- @param input string 365local function nvim_feed ( input ) 366while # input > 0 do 367local written =M . request ( 'nvim_input' , input ) 368if written == nil then 369M . assert_alive () 370error ( 'crash? (nvim_input returned nil)' ) 371end 372input =input : sub ( written + 1 ) 373end 374end 375 376--- @param ... string 377function M . feed ( ... ) 378for _ , v in ipairs ( { ... } ) do 379nvim_feed ( v ) 380end 381end 382 383---@param ... string[]? 384---@return string[] 385function M . merge_args ( ... ) 386local i =1 387local argv ={} --- @type string[] 388for anum =1 , select ( '#' , ... ) do 389--- @type string[]? 390local args =select ( anum , ... ) 391if args then 392for _ , arg in ipairs ( args ) do 393argv [ i ] =arg 394i =i + 1 395end 396end 397end 398return argv 399end 400 401--- Removes Nvim startup args from `args` matching items in `args_rm`. 402--- 403--- - Special case: "-u", "-i", "--cmd" are treated specially: their "values" are also removed. 404--- - Special case: "runtimepath" will remove only { '--cmd', 'set runtimepath^=…', } 405--- 406--- Example: 407--- args={'--headless', '-u', 'NONE'} 408--- args_rm={'--cmd', '-u'} 409--- Result: 410--- {'--headless'} 411--- 412--- All matching cases are removed. 413--- 414--- Example: 415--- args={'--cmd', 'foo', '-N', '--cmd', 'bar'} 416--- args_rm={'--cmd', '-u'} 417--- Result: 418--- {'-N'} 419--- @param args string[] 420--- @param args_rm string[] 421--- @return string[] 422local function remove_args ( args , args_rm ) 423local new_args ={} --- @type string[] 424local skip_following ={ '-u' , '-i' , '-c' , '--cmd' , '-s' , '--listen' } 425if not args_rm or # args_rm == 0 then 426return { unpack ( args ) } 427end 428for _ , v in ipairs ( args_rm ) do 429assert ( type ( v ) == 'string' ) 430end 431local last ='' 432for _ , arg in ipairs ( args ) do 433if vim . tbl_contains ( skip_following , last ) then 434last ='' 435elseif vim . tbl_contains ( args_rm , arg ) then 436last =arg 437elseif arg == M . runtime_set and vim . tbl_contains ( args_rm , 'runtimepath' ) then 438table . remove ( new_args ) -- Remove the preceding "--cmd". 439last ='' 440else 441table . insert ( new_args , arg ) 442end 443end 444return new_args 445end 446 447function M . check_close ( noblock ) 448if not session then 449return 450end 451 452local s =session 453s : close ( nil , noblock ) 454sessions [ s ] =nil 455session =nil 456end 457 458local function close_extra_sessions ( test_id , noblock ) 459for s in pairs ( sessions ) do 460if s ~= session and ( test_id == nil or ( s . data and s . data . test_id == test_id )) then 461if not s . closed then 462s : close ( nil , noblock ) 463end 464sessions [ s ] =nil 465end 466end 467end 468 469-- Creates a new Session connected by domain socket (named pipe) or TCP. 470function M . connect ( file_or_address ) 471local addr , port =string . match ( file_or_address , '(.*):(%d+)' ) 472local stream =( addr and port ) and SocketStream . connect ( addr , port ) 473or SocketStream . open ( file_or_address ) 474local s =Session . new ( stream ) 475s . data ={ test_id =_G . _nvim_test_id } 476sessions [ s ] =true 477return s 478end 479 480--- Starts a new, global Nvim session and clears the current one. 481--- 482--- Note: 483--- - Use `new_session()` to start a session without replacing the current one. 484--- - Use `spawn_wait()` to start Nvim without connecting a RPC session. 485--- 486--- Parameters are interpreted as startup args, OR a map with these keys: 487--- - args: List: Args appended to the default `nvim_argv` set. 488--- - args_rm: List: Args removed from the default set. All cases are 489--- removed, e.g. args_rm={'--cmd'} removes all cases of "--cmd" 490--- (and its value) from the default set. 491--- - env: Map: Defines the environment of the new session. 492--- 493--- Example: 494--- ``` 495--- clear('-e') 496--- clear{args={'-e'}, args_rm={'-i'}, env={TERM=term}} 497--- ``` 498--- 499--- @param ... string Nvim CLI args 500--- @return test.Session 501--- @overload fun(opts: test.session.Opts): test.Session 502function M . clear ( ... ) 503M . set_session ( M . new_session ( false , ... )) 504return M . get_session () 505end 506 507local n_processes =0 508 509--- Starts a new Nvim process with the given args and returns a msgpack-RPC session. 510--- 511--- Does not replace the current global session, unlike `clear()`. 512--- 513--- @param keep boolean (default: false) Don't close the current global session. 514--- @param ... string Nvim CLI args 515--- @return test.Session 516--- @overload fun(keep: boolean, opts: test.session.Opts): test.Session 517function M . new_session ( keep , ... ) 518local test_id =_G . _nvim_test_id 519if not keep and session ~= nil then 520local s =session 521-- Don't block for the previous session's exit if it's from a different test. 522s : close ( nil , s . data and s . data . test_id ~= test_id ) 523sessions [ s ] =nil 524session =nil 525end 526 527local argv , env , io_extra =M . _new_argv ( ... ) 528 529local proc =ProcStream . spawn ( argv , env , io_extra , function ( closed ) 530n_processes =n_processes - 1 531local delta =0 532if closed then 533uv . update_time () -- Update cached value of uv.now() (libuv: uv_now()). 534delta =uv . now () - closed 535end 536if delta > 500 then 537( 538( '\nNvim session %s took %d milliseconds to exit\n' ): format ( test_id , delta ) 539.. 'This indicates a likely problem with the test even if it passed!' 540) 541io . stdout : flush () 542end 543end , true ) 544n_processes =n_processes + 1 545 546local new_session =Session . new ( proc ) 547sessions [ new_session ] =true 548-- Make it possible to check whether two sessions are from the same test. 549new_session . data ={ test_id =test_id } 550return new_session 551end 552 553harness . on_suite_end ( function () 554M . check_close ( true ) 555-- Some tests create extra sessions without replacing the global one. 556-- Close any that individual tests did not clean up before the runner exits. 557close_extra_sessions ( nil , true ) 558 559local timed_out =false 560local timer =assert ( vim . uv . new_timer ()) 561timer : start ( 10000 , 0 , function () 562timed_out =true 563end ) 564while n_processes > 0 and not timed_out do 565uv . run ( 'once' ) 566end 567timer : close () 568if sigpipe_handler and not sigpipe_handler : is_closing () then 569sigpipe_handler : close () 570end 571-- Drain close callbacks queued by explicit Session/ProcStream cleanup before 572-- Nvim checks the runner loop for active handles. 573for _ =1 , 10 do 574uv . run ( 'nowait' ) 575end 576if timed_out then 577(( 'warning: %d dangling Nvim processes' ): format ( n_processes )) 578io . stdout : flush () 579end 580end ) 581 582--- Starts a (non-RPC, `--headless --listen "Tx"`) Nvim process, waits for exit, and returns result. 583--- 584--- @param ... string Nvim CLI args, or `test.session.Opts` table. 585--- @return test.ProcStream 586--- @overload fun(opts: test.session.Opts): test.ProcStream 587function M . spawn_wait ( ... ) 588local opts =type ( ... ) == 'string' and { args ={ ... } } or ... 589opts . args_rm =opts . args_rm and opts . args_rm or {} 590table . insert ( opts . args_rm , '--embed' ) 591local argv , env , io_extra =M . _new_argv ( opts ) 592local proc =ProcStream . spawn ( argv , env , io_extra ) 593proc . collect_text =true 594proc : read_start () 595proc : wait () 596proc : close () 597return proc 598end 599 600--- @class test.session.Opts 601--- Nvim CLI args 602--- @field args? string[] 603--- Remove these args from the default `nvim_argv` args set. Ignored if `merge=false`. 604--- @field args_rm? string[] 605--- (default: true) Merge `args` with the default set. Else use only the provided `args`. 606--- @field merge? boolean 607--- Environment variables 608--- @field env? table<string,string> 609--- Used for stdin_fd, see `:help ui-option` 610--- @field io_extra? uv.uv_pipe_t 611 612--- @private 613--- 614--- Builds an argument list for use in `new_session()`, `clear()`, and `spawn_wait()`. 615--- 616--- @param ... string Nvim CLI args, or `test.session.Opts` table. 617--- @return string[] 618--- @return string[]? 619--- @return uv.uv_pipe_t? 620--- @overload fun(opts: test.session.Opts): string[], string[]?, uv.uv_pipe_t? 621function M . _new_argv ( ... ) 622--- @type test.session.Opts|string 623local opts =select ( 1 , ... ) 624local merge =type ( opts ) ~= 'table' and true or opts . merge ~= false 625 626local args =merge and { unpack ( M . nvim_argv ) } or { M . nvim_prog } 627if merge then 628table . insert ( args , '--headless' ) 629if _G . _nvim_test_id then 630-- Set the server name to the test-id for logging. #8519 631table . insert ( args , '--listen' ) 632table . insert ( args , _G . _nvim_test_id ) 633end 634end 635 636local new_args --- @type string[] 637local io_extra --- @type uv.uv_pipe_t? 638local env --- @type string[]? List of "key=value" env vars. 639 640if type ( opts ) ~= 'table' then 641new_args ={ ... } 642else 643args =merge and remove_args ( args , opts . args_rm ) or args 644if opts . env then 645local env_opt ={} --- @type table<string,string> 646for k , v in pairs ( opts . env ) do 647assert ( type ( k ) == 'string' ) 648assert ( type ( v ) == 'string' ) 649env_opt [ k ] =v 650end 651-- Set these from the environment unless the caller defined them. 652for _ , k in ipairs ( { 653'ASAN_OPTIONS' , 654'GCOV_ERROR_FILE' , 655'HOME' , 656'LD_LIBRARY_PATH' , 657'MSAN_OPTIONS' , 658'NVIM_TEST' , 659'NVIM_LOG_FILE' , 660'NVIM_RPLUGIN_MANIFEST' , 661'PATH' , 662'TMPDIR' , 663'TSAN_OPTIONS' , 664'VIMRUNTIME' , 665'XDG_DATA_DIRS' , 666} ) do 667if not env_opt [ k ] then 668env_opt [ k ] =os . getenv ( k ) 669end 670end 671env ={} 672for k , v in pairs ( env_opt ) do 673env [ # env + 1 ] =k .. '=' .. v 674end 675end 676new_args =opts . args or {} 677io_extra =opts . io_extra 678end 679for _ , arg in ipairs ( new_args ) do 680table . insert ( args , arg ) 681end 682return args , env , io_extra 683end 684 685--- Dedents string arguments and inserts the resulting text into the current buffer. 686--- @param ... string 687function M . insert ( ... ) 688nvim_feed ( 'i' ) 689for _ , v in ipairs ( { ... } ) do 690local escaped =v : gsub ( '<' , '<lt>' ) 691nvim_feed ( dedent ( escaped )) 692end 693nvim_feed ( '<ESC>' ) 694end 695 696--- @deprecated Use `command()` or `feed()` instead. 697--- 698--- Executes an ex-command by user input. Because nvim_input() is used, Vimscript 699--- errors will not manifest as client (lua) errors. Use command() for that. 700--- @param ... string 701function M . feed_command ( ... ) 702for _ , v in ipairs ( { ... } ) do 703if v : sub ( 1 , 1 ) ~= '/' then 704-- not a search command, prefix with colon 705nvim_feed ( ':' ) 706end 707nvim_feed ( v : gsub ( '<' , '<lt>' )) 708nvim_feed ( '<CR>' ) 709end 710end 711 712-- @deprecated use nvim_exec2() 713function M . source ( code ) 714M . exec ( dedent ( code )) 715end 716 717function M . has_powershell () 718return M . eval ( 'executable("pwsh")' ) == 1 719end 720 721--- Sets Nvim shell to powershell. 722--- 723--- @param fake boolean? Use a fake if powershell is not found on the system. 724--- @returns true if powershell was found on the system, else false. 725function M . set_shell_powershell ( fake ) 726local found =M . has_powershell () 727if not fake then 728assert ( found ) 729end 730local shell =found and 'pwsh' or M . testprg ( 'pwsh-test' ) 731local cmd ='Remove-Item -Force ' 732.. table . concat ( 733is_os ( 'win' ) and { 'alias:cat' , 'alias:echo' , 'alias:sleep' , 'alias:sort' , 'alias:tee' } 734or { 'alias:echo' } , 735',' 736) 737.. ';' 738M . exec ( [[ 739let &shell = ']] .. shell .. [[' 740set shellquote= shellxquote= 741let &shellcmdflag = '-NoLogo -NoProfile -ExecutionPolicy RemoteSigned -Command ' 742let &shellcmdflag .= '[Console]::InputEncoding=[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new();' 743let &shellcmdflag .= '$PSDefaultParameterValues[''Out-File:Encoding'']=''utf8'';' 744let &shellcmdflag .= ']] .. cmd .. [[' 745let &shellredir = '2>&1 | %%{ "$_" } | Out-File %s; exit $LastExitCode' 746let &shellpipe = '> %s 2>&1' 747]] ) 748return found 749end 750 751---@param func function 752---@return table<string,function> 753function M . create_callindex ( func ) 754return setmetatable ( {} , { 755--- @param tbl table<any,function> 756--- @param arg1 string 757--- @return function 758__index =function ( tbl , arg1 ) 759local ret =function ( ... ) 760return func ( arg1 , ... ) 761end 762tbl [ arg1 ] =ret 763return ret 764end , 765} ) 766end 767 768--- @param method string 769--- @param ... any 770function M . nvim_async ( method , ... ) 771assert ( session , 'no Nvim session' ) 772assert ( not session . eof_err , 'sending notification after EOF from Nvim' ) 773session : notify ( method , ... ) 774end 775 776--- Executes a Vimscript function via RPC. 777--- Fails on Vimscript error, but does not update v:errmsg. 778--- @param name string 779--- @param ... any 780--- @return any 781function M . call ( name , ... ) 782return M . request ( 'nvim_call_function' , name , { ... } ) 783end 784 785M . async_meths =M . create_callindex ( M . nvim_async ) 786 787M . rpc ={ 788fn =M . create_callindex ( M . call ), 789api =M . create_callindex ( M . request ), 790} 791 792M . lua ={ 793fn =M . create_callindex ( M . call_lua ), 794api =M . create_callindex ( M . request_lua ), 795} 796 797M . describe_lua_and_rpc =function ( describe ) 798return function ( what , tests ) 799local function d ( flavour ) 800describe ( string . format ( '%s (%s)' , what , flavour ), function ( ... ) 801return tests ( M [ flavour ]. api , ... ) 802end ) 803end 804 805d ( 'rpc' ) 806d ( 'lua' ) 807end 808end 809 810--- add for typing. The for loop after will overwrite this 811M . api =vim . api 812M . fn =vim . fn 813 814for name , fns in pairs ( M . rpc ) do 815--- @diagnostic disable-next-line:no-unknown 816M [ name ] =fns 817end 818 819-- Executes an ex-command. Vimscript errors manifest as client (lua) errors, but 820-- v:errmsg will not be updated. 821M . command =M . api . nvim_command 822 823-- Evaluates a Vimscript expression. 824-- Fails on Vimscript error, but does not update v:errmsg. 825M . eval =M . api . nvim_eval 826 827function M . poke_eventloop () 828-- Execute 'nvim_eval' (a deferred function) to 829-- force at least one main_loop iteration 830M . api . nvim_eval ( '1' ) 831end 832 833function M . buf_lines ( bufnr ) 834return M . exec_lua ( 'return vim.api.nvim_buf_get_lines((...), 0, -1, false)' , bufnr ) 835end 836 837---@see buf_lines() 838function M . curbuf_contents () 839M . poke_eventloop () -- Before inspecting the buffer, do whatever. 840return table . concat ( M . api . nvim_buf_get_lines ( 0 , 0 , - 1 , true ), '\n' ) 841end 842 843function M . expect ( contents ) 844return eq ( dedent ( contents ), M . curbuf_contents ()) 845end 846 847function M . expect_any ( contents ) 848contents =dedent ( contents ) 849return ok ( nil ~= string . find ( M . curbuf_contents (), contents , 1 , true )) 850end 851 852-- Checks that the Nvim session did not terminate. 853function M . assert_alive () 854assert ( 2 == M . eval ( '1+1' ), 'crash? request failed' ) 855end 856 857-- Asserts that buffer is loaded and visible in the current tabpage. 858function M . assert_visible ( bufnr , visible ) 859assert ( type ( visible ) == 'boolean' ) 860eq ( visible , M . api . nvim_buf_is_loaded ( bufnr )) 861if visible then 862assert ( 863- 1 ~= M . fn . bufwinnr ( bufnr ), 864'expected buffer to be visible in current tabpage: ' .. tostring ( bufnr ) 865) 866else 867assert ( 868- 1 == M . fn . bufwinnr ( bufnr ), 869'expected buffer NOT visible in current tabpage: ' .. tostring ( bufnr ) 870) 871end 872end 873 874local start_dir =assert ( uv . cwd ()) 875 876function M . rmdir ( path ) 877local ret , _ =pcall ( vim . fs . rm , path , { recursive =true , force =true } ) 878local did_cd =false 879if not ret and is_os ( 'win' ) then 880-- Maybe "Permission denied"; try again after changing the nvim 881-- process to the top-level directory. 882ret , _ =pcall ( function () 883M . fn . chdir ( start_dir ) 884vim . fs . rm ( path , { recursive =true , force =true } ) 885end ) 886did_cd =true 887end 888-- During teardown, the nvim process may not exit quickly enough, then rmdir() 889-- will fail (on Windows). 890if not ret then -- Try again. 891sleep ( 1000 ) 892vim . fs . rm ( path , { recursive =true , force =true } ) 893end 894if did_cd then 895-- Try to restore CWD in case rmdir() is used within a test. Needs pcall: #38278 896pcall ( M . command , 'cd -' ) 897end 898end 899 900function M . exec ( code ) 901M . api . nvim_exec2 ( code , {} ) 902end 903 904--- @param code string 905--- @return string 906function M . exec_capture ( code ) 907return M . api . nvim_exec2 ( code , { output =true } ). output 908end 909 910--- Execute Lua code in the wrapped Nvim session. 911--- 912--- When `code` is passed as a function, it is converted into Lua byte code. 913--- 914--- Direct upvalues are copied over, however upvalues contained 915--- within nested functions are not. Upvalues are also copied back when `code` 916--- finishes executing. See `:help lua-upvalue`. 917--- 918--- Only types which can be serialized can be transferred over, e.g: 919--- `table`, `number`, `boolean`, `string`. 920--- 921--- `code` runs with a different environment and thus will have a different global 922--- environment. See `:help lua-environments`. 923--- 924--- Example: 925--- ```lua 926--- local upvalue1 = 'upvalue1' 927--- exec_lua(function(a, b, c) 928--- print(upvalue1, a, b, c) 929--- (function() 930--- print(upvalue2) 931--- end)() 932--- end, 'a', 'b', 'c' 933--- ``` 934--- Prints: 935--- ``` 936--- upvalue1 a b c 937--- nil 938--- ``` 939--- 940--- Not supported: 941--- ```lua 942--- local a = vim.uv.new_timer() 943--- exec_lua(function() 944--- print(a) -- Error: a is of type 'userdata' which cannot be serialized. 945--- end) 946--- ``` 947--- @param code string|function 948--- @param ... any 949--- @return any 950function M . exec_lua ( code , ... ) 951if type ( code ) == 'string' then 952return M . api . nvim_exec_lua ( code , { ... } ) 953end 954 955assert ( session , 'no Nvim session' ) 956return require ( 'test.functional.testnvim.exec_lua' )( session , 2 , code , ... ) 957end 958 959--- Runs `cmd` via `vim.system()` in the Nvim-under-test and returns its result. 960--- 961--- Asserts the child process is gone afterward, polling to absorb the brief lag between the 962--- exit-handler and nvim_get_proc() reporting it (seen on Windows). 963--- 964--- @param cmd string[] 965--- @param opts? vim.SystemOpts 966--- @param async? boolean Wait via the on_exit callback instead of a blocking `obj:wait()`. 967--- @return vim.SystemCompleted 968local function system ( cmd , opts , async ) 969return M . exec_lua ( function () 970local res --- @type vim.SystemCompleted? 971local obj 972if async then 973local done =false 974obj =vim . system ( cmd , opts , function ( o ) 975done =true 976res =o 977end ) 978assert ( 979vim . wait ( 10000 , function () 980return done 981end ), 982'process did not exit' 983) 984else 985obj =vim . system ( cmd , opts ) 986if opts and opts . timeout then 987-- Minor delay before calling wait() so the timeout uv timer can have a headstart over the 988-- internal call to vim.wait() in wait(). 989vim . wait ( 10 ) 990end 991res =obj : wait () 992end 993 994-- Assert that the process terminated. 995-- XXX: Poll bc nvim_get_proc() can briefly lag the exit callback (on Windows): `uv_close` 996-- completes on a later tick, thus the PID is still briefly resolvable. 997assert ( 998vim . wait ( 1000 , function () 999return not vim . api . nvim_get_proc ( obj . pid ) 1000end ), 1001'process still exists' 1002) 1003 1004return res 1005end ) 1006end 1007 1008--- Runs `cmd` via `vim.system()` in the Nvim-under-test and waits (synchronously) for it to exit. 1009function M . system_sync ( cmd , opts ) 1010return system ( cmd , opts , false ) 1011end 1012 1013--- Like `system_sync()` but waits via the `vim.system()` on_exit callback. 1014function M . system_async ( cmd , opts ) 1015return system ( cmd , opts , true ) 1016end 1017 1018--- Benchmarks `fn` in the Nvim-under-test: runs it `opts.n` times, timing each run in-session, then reports. 1019--- 1020--- Note: see `testutil.bench()` to run in the test-runner process. 1021--- 1022--- @param body string Lua source executed each iteration; the iteration index is available as `i`. 1023--- @param opts { n: integer, label?: string, unit?: 'ms'|'us', warmup?: integer } 1024--- @return table stats See `testutil.bench_report()`. 1025function M . bench ( body , opts ) 1026local samples =M . exec_lua ( 1027[[ 1028local body, n, warmup = ... 1029local fn = assert(loadstring('local i = ...\n' .. body)) 1030for i = 1, warmup do 1031fn(i) 1032end 1033local samples = {} 1034for i = 1, n do 1035local t0 = vim.uv.hrtime() 1036fn(i) 1037samples[i] = vim.uv.hrtime() - t0 1038end 1039return samples 1040]] , 1041body , 1042opts . n , 1043opts . warmup or 100 1044) 1045return t . bench_report ( samples , opts ) 1046end 1047 1048function M . get_pathsep () 1049return is_os ( 'win' ) and '\\' or '/' 1050end 1051 1052--- Gets the filesystem root dir, namely "/" or "C:/". 1053function M . pathroot () 1054local pathsep =package . config : sub ( 1 , 1 ) 1055return is_os ( 'win' ) and ( M . nvim_dir : sub ( 1 , 2 ) .. pathsep ) or '/' 1056end 1057 1058--- Gets the full `…/build/bin/{name}` path of a test program produced by 1059--- `test/functional/fixtures/CMakeLists.txt`. 1060--- 1061--- @param name (string) Name of the test program. 1062function M . testprg ( name ) 1063local ext =is_os ( 'win' ) and '.exe' or '' 1064return ( '%s/%s%s' ): format ( M . nvim_dir , name , ext ) 1065end 1066 1067--- Returns a valid, platform-independent Nvim listen address. 1068--- Useful for communicating with child instances. 1069--- 1070--- @return string 1071function M . new_pipename () 1072-- HACK: Start a server temporarily, get the name, then stop it. 1073-- 1074-- XXX: If a (still-alive) Nvim process is using an old "--listen nvim.<PID>.<counter>" pipename, 1075-- and the OS reuses the PID, then serverstart() may generate a duplicate name (bc of PID reuse). 1076-- Retry serverstart() to force an incremented <counter>. 1077local ok =false 1078local pipename ---@type string 1079for _ =1 , 100 do 1080ok , pipename =pcall ( M . eval , 'serverstart()' ) 1081if ok then 1082break 1083end 1084sleep ( 20 ) -- Avoid hot loop; give stale process time to exit. 1085end 1086assert ( ok , pipename ) 1087M . fn . serverstop ( pipename ) 1088-- Remove the pipe so that trying to connect to it without a server listening 1089-- will be an error instead of a hang. 1090os . remove ( pipename ) 1091return pipename 1092end 1093 1094--- @param provider string 1095--- @return string|boolean? 1096function M . missing_provider ( provider ) 1097if provider == 'ruby' or provider == 'perl' then 1098--- @type string? 1099local e =M . exec_lua ( "return {require('vim.provider." .. provider .. "').detect()}" )[ 2 ] 1100return e ~= '' and e or false 1101elseif provider == 'node' then 1102--- @type string? 1103local e =M . fn [ 'provider#node#Detect' ]()[ 2 ] 1104return e ~= '' and e or false 1105elseif provider == 'python' then 1106return M . exec_lua ( [[return {require('vim.provider.python').detect_by_module('neovim')}]] )[ 2 ] 1107end 1108assert ( false , 'Unknown provider: ' .. provider ) 1109end 1110 1111local load_factor =1 1112if t . is_ci () then 1113-- Compute load factor only once (but outside of any tests). 1114M . clear () 1115M . request ( 'nvim_command' , 'source test/old/testdir/load.vim' ) 1116load_factor =M . request ( 'nvim_eval' , 'g:test_load_factor' ) 1117end 1118 1119--- @param num number 1120--- @return number 1121function M . load_adjust ( num ) 1122return math . ceil ( num * load_factor ) 1123end 1124 1125--- @param ctx table<string,any> 1126--- @return table 1127function M . parse_context ( ctx ) 1128local parsed ={} --- @type table<string,any> 1129for _ , item in ipairs ( { 'regs' , 'jumps' , 'bufs' , 'gvars' } ) do 1130--- @param v any 1131parsed [ item ] =vim . tbl_filter ( function ( v ) 1132return type ( v ) == 'table' 1133end , M . call ( 'msgpackparse' , ctx [ item ])) 1134end 1135parsed [ 'bufs' ] =parsed [ 'bufs' ][ 1 ] 1136--- @param v any 1137return vim . tbl_map ( function ( v ) 1138if # v == 0 then 1139return nil 1140end 1141return v 1142end , parsed ) 1143end 1144 1145function M . add_builddir_to_rtp () 1146-- Add runtime from build dir for doc/tags (used with :help). 1147M . command ( string . format ( [[set rtp+=%s/runtime]] , t . paths . test_build_dir )) 1148end 1149 1150--- Create folder with non existing parents 1151--- 1152--- TODO(justinmk): lift this and `t.mkdir()` into vim.fs. 1153--- 1154--- @param path string 1155--- @return boolean? 1156function M . mkdir_p ( path ) 1157return os . execute ( 1158( is_os ( 'win' ) and 'mkdir ' .. string . gsub ( path , '/' , '\\' ) or 'mkdir -p ' .. path ) 1159) 1160end 1161 1162local testid =( function () 1163local id =0 1164return function () 1165id =id + 1 1166return id 1167end 1168end )() 1169 1170return function () 1171if harness . is_defining () then 1172harness . before_each ( function () 1173local id =( 'T%d' ): format ( testid ()) 1174_G . _nvim_test_id =id 1175end ) 1176 1177harness . after_each ( function () 1178close_extra_sessions ( _G . _nvim_test_id , true ) 1179if not vim . endswith ( _G . _nvim_test_id , 'x' ) then 1180-- Use a different test ID for skipped tests as well as Nvim instances spawned 1181-- between this after_each() and the next before_each() (e.g. in setup()). 1182_G . _nvim_test_id =_G . _nvim_test_id .. 'x' 1183end 1184check_logs () 1185check_cores ( 'build/bin/nvim' ) 1186if session then 1187local msg =session : next_message ( 0 ) 1188if msg then 1189if msg [ 1 ] == 'notification' and msg [ 2 ] == 'nvim_error_event' then 1190error ( msg [ 3 ][ 2 ]) 1191end 1192end 1193end 1194end ) 1195end 1196 1197return M 1198end