robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1local test_assert =require ( 'test.assert' ) 2---@type test.harness 3local harness =require ( 'test.harness' ) 4local uv =vim . uv 5local Paths =require ( 'test.cmakeconfig.paths' ) 6 7--- Functions executing in the context of the test runner (not the current nvim test session). 8--- @class test.testutil 9local M ={ 10paths =Paths , 11 12-- Test framework: 13after_each =harness . after_each , 14before_each =harness . before_each , 15describe =harness . describe , 16finally =harness . finally , 17it =harness . it , 18pending =harness . pending , 19setup =harness . setup , 20teardown =harness . teardown , 21} 22 23--- @param path string 24--- @return boolean 25function M . isdir ( path ) 26if not path then 27return false 28end 29local stat =uv . fs_stat ( path ) 30if not stat then 31return false 32end 33return stat . type == 'directory' 34end 35 36--- (Only on Windows) Replaces yucky "\\" slashes with delicious "/" slashes in a string, or all 37--- string values in a table (recursively). 38--- 39--- @generic T: string|table 40--- @param obj T 41--- @return T|nil 42function M . fix_slashes ( obj ) 43if not M . is_os ( 'win' ) then 44return obj 45end 46if type ( obj ) == 'string' then 47local ret =string . gsub ( obj , '\\' , '/' ) 48return ret 49elseif type ( obj ) == 'table' then 50--- @cast obj table<any,any> 51local ret ={} --- @type table<any,any> 52for k , v in pairs ( obj ) do 53ret [ k ] =M . fix_slashes ( v ) 54end 55return ret 56end 57assert ( false , 'expected string or table of strings, got ' .. type ( obj )) 58end 59 60--- @param ... string|string[] 61--- @return string[] 62function M . argss_to_cmd ( ... ) 63local cmd ={} --- @type string[] 64for i =1 , select ( '#' , ... ) do 65local arg =select ( i , ... ) 66if type ( arg ) == 'string' then 67cmd [ # cmd + 1 ] =arg 68else 69--- @cast arg string[] 70for _ , subarg in ipairs ( arg ) do 71cmd [ # cmd + 1 ] =subarg 72end 73end 74end 75return cmd 76end 77 78--- Calls fn() until it succeeds, up to `max` times or until `max_ms` 79--- milliseconds have passed. 80--- @param max integer? 81--- @param max_ms integer? 82--- @param fn function 83--- @return any 84function M . retry ( max , max_ms , fn ) 85assert ( max == nil or max > 0 ) 86assert ( max_ms == nil or max_ms > 0 ) 87local tries =1 88local timeout =( max_ms and max_ms or 10000 ) 89local start_time =uv . now () 90while true do 91--- @type boolean, any 92local status , result =pcall ( fn ) 93if status then 94return result 95end 96uv . update_time () -- Update cached value of luv.now() (libuv: uv_now()). 97if ( max and tries >= max ) or ( uv . now () - start_time > timeout ) then 98error ( string . format ( 'retry() attempts: %d\n%s' , tries , tostring ( result )), 2 ) 99end 100tries =tries + 1 101uv . sleep ( 20 ) -- Avoid hot loop... 102end 103end 104 105local check_logs_useless_lines ={ 106[ 'Warning: noted but unhandled ioctl' ] =1 , 107[ 'could cause spurious value errors to appear' ] =2 , 108[ 'See README_MISSING_SYSCALL_OR_IOCTL for guidance' ] =3 , 109} 110 111function M . eq ( expected , actual , context ) 112return test_assert . eq ( expected , actual , context ) 113end 114function M . neq ( expected , actual , context ) 115return test_assert . neq ( expected , actual , context ) 116end 117 118--- Compare paths after resolving symlinks with realpath. 119function M . eq_paths ( expected , actual , context ) 120return M . eq ( uv . fs_realpath ( expected ), uv . fs_realpath ( actual ), context ) 121end 122 123--- Asserts that `cond` is true, or prints a message. 124--- 125--- @param cond (boolean) expression to assert 126--- @param expected (any) description of expected result 127--- @param actual (any) description of actual result 128function M . ok ( cond , expected , actual ) 129assert ( 130( not expected and not actual ) or ( expected and actual ), 131'if "expected" is given, "actual" is also required' 132) 133local msg =expected and ( 'expected %s, got: %s' ): format ( expected , tostring ( actual )) or nil 134return assert ( cond , msg ) 135end 136 137--- @param pat string 138--- @param actual string 139--- @param plain boolean? (default: false) 140--- @return boolean 141function M . matches ( pat , actual , plain ) 142assert ( pat and pat ~= '' , 'pat must be a non-empty string' ) 143assert ( plain == nil or type ( plain ) == 'boolean' , 'plain must be nil or boolean' ) 144if nil ~= string . find ( actual , pat , 1 , plain ) then 145return true 146end 147error (( 'Pattern does not match.\nPattern:\n%s\nActual:\n%s' ): format ( pat , actual )) 148end 149 150--- @param pat string 151--- @param actual string 152--- @param plain boolean? (default: false) 153--- @return boolean 154function M . not_matches ( pat , actual , plain ) 155assert ( pat and pat ~= '' , 'pat must be a non-empty string' ) 156if nil == string . find ( actual , pat , 1 , plain ) then 157return true 158end 159error (( 'Pattern does match.\nPattern:\n%s\nActual:\n%s' ): format ( pat , actual )) 160end 161 162--- Asserts that `pat` matches (or *not* if inverse=true) any text in the tail of `logfile`. 163--- 164--- Matches are not restricted to a single line. 165--- 166--- Retries for 1 second in case of filesystem delay. 167--- 168---@param pat (string) Lua pattern to match text in the log file 169---@param logfile? (string) Full path to log file (default=$NVIM_LOG_FILE) 170---@param nrlines? (number) Search up to this many log lines (default 10) 171---@param inverse? (boolean) Assert that the pattern does NOT match. 172function M . assert_log ( pat , logfile , nrlines , inverse ) 173logfile =logfile or os . getenv ( 'NVIM_LOG_FILE' ) or 'nvim.log' 174assert ( logfile ~= nil , 'no logfile' ) 175nrlines =nrlines or 10 176 177M . retry ( nil , 1000 , function () 178local lines =M . read_file_list ( logfile , - nrlines ) or {} 179local text =table . concat ( lines , '\n' ) 180local ismatch =not not text : match ( pat ) 181if ( ismatch and inverse ) or not ( ismatch or inverse ) then 182local msg =string . format ( 183'Pattern %s %sfound in log (last %d lines): %q:\n%s' , 184vim . inspect ( pat ), 185( inverse and '' or 'not ' ), 186nrlines , 187logfile , 188vim . text . indent ( 4 , text ) 189) 190error ( msg ) 191end 192end ) 193end 194 195--- Asserts that `pat` does NOT match any line in the tail of `logfile`. 196--- 197--- @see assert_log 198--- @param pat (string) Lua pattern to match lines in the log file 199--- @param logfile? (string) Full path to log file (default=$NVIM_LOG_FILE) 200--- @param nrlines? (number) Search up to this many log lines 201function M . assert_nolog ( pat , logfile , nrlines ) 202return M . assert_log ( pat , logfile , nrlines , true ) 203end 204 205--- @param fn fun(...): any 206--- @param ... any 207--- @return boolean, any 208function M . pcall ( fn , ... ) 209assert ( type ( fn ) == 'function' ) 210local status , rv =pcall ( fn , ... ) 211if status then 212return status , rv 213end 214 215-- From: 216-- C:/long/path/foo.lua:186: Expected string, got number 217-- to: 218-- .../foo.lua:0: Expected string, got number 219local errmsg =tostring ( rv ) 220: gsub ( '([%s<])vim[/\\]([^%s:/\\]+):%d+' , '%1\xffvim\xff%2:0' ) 221: gsub ( '[^%s<]-[/\\]([^%s:/\\]+):%d+' , '.../%1:0' ) 222: gsub ( '\xffvim\xff' , 'vim/' ) 223 224-- Scrub numbers in paths/stacktraces: 225-- shared.lua:0: in function 'gsplit' 226-- shared.lua:0: in function <shared.lua:0>' 227errmsg =errmsg : gsub ( '([^%s].lua):%d+' , '%1:0' ) 228-- [string "<nvim>"]:0: 229-- [string ":lua"]:0: 230-- [string ":luado"]:0: 231errmsg =errmsg : gsub ( '(%[string "[^"]+"%]):%d+' , '%1:0' ) 232 233-- Scrub tab chars: 234errmsg =errmsg : gsub ( '\t' , ' ' ) 235-- In Lua 5.1, we sometimes get a "(tail call): ?" on the last line. 236-- We remove this so that the tests are not lua dependent. 237errmsg =errmsg : gsub ( '%s*%(tail call%): %?' , '' ) 238 239return status , errmsg 240end 241 242-- Invokes `fn` and returns the error string (with truncated paths), or raises 243-- an error if `fn` succeeds. 244-- 245-- Replaces line/column numbers with zero: 246-- shared.lua:0: in function 'gsplit' 247-- shared.lua:0: in function <shared.lua:0>' 248-- 249-- Usage: 250-- -- Match exact string. 251-- eq('e', pcall_err(function(a, b) error('e') end, 'arg1', 'arg2')) 252-- -- Match Lua pattern. 253-- matches('e[or]+$', pcall_err(function(a, b) error('some error') end, 'arg1', 'arg2')) 254-- 255--- @param fn function 256--- @return string 257function M . pcall_err_withfile ( fn , ... ) 258assert ( type ( fn ) == 'function' ) 259local status , rv =M . pcall ( fn , ... ) 260if status == true then 261error ( 'expected failure, but got success' ) 262end 263return rv 264end 265 266--- @param fn function 267--- @param ... any 268--- @return string 269function M . pcall_err_withtrace ( fn , ... ) 270local errmsg =M . pcall_err_withfile ( fn , ... ) 271 272return ( 273errmsg 274: gsub ( '^%.%.%./testnvim%.lua:0: ' , '' ) 275: gsub ( '^Lua:- ' , '' ) 276: gsub ( '^%[string "<nvim>"%]:0: ' , '' ) 277) 278end 279 280--- @param fn function 281--- @param ... any 282--- @return string 283function M . pcall_err ( fn , ... ) 284return M . remove_trace ( M . pcall_err_withtrace ( fn , ... )) 285end 286 287--- @param s string 288--- @return string 289function M . remove_trace ( s ) 290return ( s : gsub ( '\n%s*stack traceback:.*' , '' )) 291end 292 293-- initial_path: directory to recurse into 294-- re: include pattern (string) 295-- exc_re: exclude pattern(s) (string or table) 296function M . glob ( initial_path , re , exc_re ) 297exc_re =type ( exc_re ) == 'table' and exc_re or { exc_re } 298local paths_to_check ={ initial_path } --- @type string[] 299local ret ={} --- @type string[] 300local checked_files ={} --- @type table<string,true> 301local function is_excluded ( path ) 302for _ , pat in pairs ( exc_re ) do 303if path : match ( pat ) then 304return true 305end 306end 307return false 308end 309 310if is_excluded ( initial_path ) then 311return ret 312end 313while # paths_to_check > 0 do 314local cur_path =paths_to_check [ # paths_to_check ] 315paths_to_check [ # paths_to_check ] =nil 316for e in vim . fs . dir ( cur_path ) do 317local full_path =cur_path .. '/' .. e 318local checked_path =full_path : sub ( # initial_path + 1 ) 319if ( not is_excluded ( checked_path )) and e : sub ( 1 , 1 ) ~= '.' then 320local stat =uv . fs_stat ( full_path ) 321if stat then 322local check_key =stat . dev .. ':' .. tostring ( stat . ino ) 323if not checked_files [ check_key ] then 324checked_files [ check_key ] =true 325if stat . type == 'directory' then 326paths_to_check [ # paths_to_check + 1 ] =full_path 327elseif not re or checked_path : match ( re ) then 328ret [ # ret + 1 ] =full_path 329end 330end 331end 332end 333end 334end 335return ret 336end 337 338--- Reads sanitizer/valgrind log file lines, filtering out useless warnings. 339--- Waits briefly for the ASAN "SUMMARY" line so we don't read a truncated report 340--- (the crashing process may still be writing when we check). 341local function read_sanitizer_log ( file ) 342local lines ={} --- @type string[] 343local has_summary =false 344-- Poll for up to 2 seconds for the log to be complete. 345for _ =1 , 20 do 346lines ={} 347local warning_line =0 348local fd =assert ( io . open ( file )) 349for line in fd : lines () do 350local cur_warning_line =check_logs_useless_lines [ line ] 351if cur_warning_line == warning_line + 1 then 352warning_line =cur_warning_line 353else 354lines [ # lines + 1 ] =line 355end 356if line : find ( 'SUMMARY' ) then 357has_summary =true 358end 359end 360fd : close () 361if has_summary or # lines == 0 then 362break 363end 364uv . sleep ( 100 ) 365end 366if not has_summary and # lines > 0 then 367lines [ # lines + 1 ] ='(WARNING: sanitizer log may be truncated, no SUMMARY line found)' 368end 369return lines 370end 371 372function M . check_logs () 373local log_dir =os . getenv ( 'LOG_DIR' ) 374local runtime_errors ={} --- @type string[] 375local runtime_errors_detail ={} --- @type string[] 376if log_dir and M . isdir ( log_dir ) then 377for tail in vim . fs . dir ( log_dir ) do 378if tail : sub ( 1 , 30 ) == 'valgrind-' or tail : find ( 'san%.' ) then 379local file =( '%s/%s' ): format ( log_dir , tail ) 380local lines =read_sanitizer_log ( file ) 381if # lines > 0 then 382local start_msg =( '%s File %s %s' ): format (( '=' ): rep ( 20 ), file , ( '=' ): rep ( 20 )) 383local end_msg =select ( 1 , start_msg : gsub ( '.' , '=' )) 384local lines_str =( '= %s' ): format ( table . concat ( lines , '\n= ' )) 385local detail =( '%s\n%s\n%s' ): format ( start_msg , lines_str , end_msg ) 386--- @type boolean?, file*? 387local status , f 388if os . getenv ( 'SYMBOLIZER' ) then 389status , f =pcall ( M . repeated_read_cmd , os . getenv ( 'SYMBOLIZER' ), '-l' , file ) 390end 391local out =io . stdout 392out : write ( start_msg .. '\n' ) 393if status then 394assert ( f ) 395for line in f : lines () do 396out : write (( '= %s\n' ): format ( line )) 397end 398f : close () 399else 400out : write ( lines_str .. '\n' ) 401end 402out : write ( end_msg .. '\n' ) 403table . insert ( runtime_errors , file ) 404table . insert ( runtime_errors_detail , detail ) 405end 406os . remove ( file ) 407end 408end 409end 410test_assert ( 4110 == # runtime_errors , 412string . format ( 413'Found runtime errors in logfile(s):\n%s' , 414table . concat ( runtime_errors_detail , '\n' ) 415) 416) 417end 418 419local sysname =uv . os_uname (). sysname : lower () 420 421--- @param s 'win'|'mac'|'linux'|'freebsd'|'openbsd'|'bsd' 422--- @return boolean 423function M . is_os ( s ) 424if 425not ( s == 'win' or s == 'mac' or s == 'linux' or s == 'freebsd' or s == 'openbsd' or s == 'bsd' ) 426then 427error ( 'unknown platform: ' .. tostring ( s )) 428end 429return not not ( 430( s == 'win' and ( sysname : find ( 'windows' ) or sysname : find ( 'mingw' ))) 431or ( s == 'mac' and sysname == 'darwin' ) 432or ( s == 'linux' and sysname == 'linux' ) 433or ( s == 'freebsd' and sysname == 'freebsd' ) 434or ( s == 'openbsd' and sysname == 'openbsd' ) 435or ( s == 'bsd' and sysname : find ( 'bsd' )) 436) 437end 438 439local architecture =uv . os_uname (). machine 440 441--- @param s 'x86_64'|'arm64'|'s390x' 442--- @return boolean 443function M . is_arch ( s ) 444if not ( s == 'x86_64' or s == 'arm64' or s == 's390x' ) then 445error ( 'unknown architecture: ' .. tostring ( s )) 446end 447return s == architecture 448end 449 450function M . is_asan () 451return M . paths . is_asan 452end 453 454function M . is_zig_build () 455return M . paths . is_zig_build 456end 457 458local tmpname_id =0 459local tmpdir =os . getenv ( 'TMPDIR' ) or os . getenv ( 'TEMP' ) 460local tmpdir_is_local =not not ( tmpdir and tmpdir : find ( 'Xtest' )) 461 462local function get_tmpname () 463if tmpdir_is_local then 464-- Cannot control os.tmpname() dir, so hack our own tmpname() impl. 465tmpname_id =tmpname_id + 1 466-- "…/Xtest_tmpdir/T42.7" 467return ( '%s/%s.%d' ): format ( tmpdir , ( _G . _nvim_test_id or 'nvim-test' ), tmpname_id ) 468end 469 470local fname =os . tmpname () 471 472if M . is_os ( 'win' ) and fname : sub ( 1 , 2 ) == '\\s' then 473-- In Windows tmpname() returns a filename starting with 474-- special sequence \s, prepend $TEMP path 475return tmpdir .. fname 476elseif M . is_os ( 'mac' ) and fname : match ( '^/tmp' ) then 477-- In OS X /tmp links to /private/tmp 478return '/private' .. fname 479end 480return fname 481end 482 483--- Generates a unique filepath for use by tests, in a test-specific "…/Xtest_tmpdir/T42.7" 484--- directory (which is cleaned up by the test runner). 485--- 486--- @param create? boolean (default true) Create the file. 487--- @return string 488function M . tmpname ( create ) 489local fname =get_tmpname () 490os . remove ( fname ) 491if create ~= false then 492assert ( io . open ( fname , 'w' )): close () 493end 494return fname 495end 496 497local function deps_prefix () 498local env =os . getenv ( 'DEPS_PREFIX' ) 499return ( env and env ~= '' ) and env or '.deps/usr' 500end 501 502local tests_skipped =0 503 504function M . check_cores ( app , force ) -- luacheck: ignore 505-- Temporary workaround: skip core check as it interferes with CI. 506if true then 507return 508end 509app =app or 'build/bin/nvim' -- luacheck: ignore 510--- @type string, string?, string[] 511local initial_path , re , exc_re 512local gdb_db_cmd = 513'gdb -n -batch -ex "thread apply all bt full" "$_NVIM_TEST_APP" -c "$_NVIM_TEST_CORE"' 514local lldb_db_cmd ='lldb -Q -o "bt all" -f "$_NVIM_TEST_APP" -c "$_NVIM_TEST_CORE"' 515local random_skip =false 516-- Workspace-local $TMPDIR, scrubbed and pattern-escaped. 517-- "./Xtest-tmpdir/" => "Xtest%-tmpdir" 518local local_tmpdir =nil 519if tmpdir_is_local and tmpdir then 520local_tmpdir = 521vim . pesc ( vim . fs . relpath ( assert ( vim . uv . cwd ()), tmpdir ): gsub ( '^[ ./]+' , '' ): gsub ( '%/+$' , '' )) 522end 523 524local db_cmd --- @type string 525local test_glob_dir =os . getenv ( 'NVIM_TEST_CORE_GLOB_DIRECTORY' ) 526if test_glob_dir and test_glob_dir ~= '' then 527initial_path =test_glob_dir 528re =os . getenv ( 'NVIM_TEST_CORE_GLOB_RE' ) 529exc_re ={ os . getenv ( 'NVIM_TEST_CORE_EXC_RE' ), local_tmpdir } 530db_cmd =os . getenv ( 'NVIM_TEST_CORE_DB_CMD' ) or gdb_db_cmd 531random_skip =os . getenv ( 'NVIM_TEST_CORE_RANDOM_SKIP' ) ~= '' 532elseif M . is_os ( 'mac' ) then 533initial_path ='/cores' 534re =nil 535exc_re ={ local_tmpdir } 536db_cmd =lldb_db_cmd 537else 538initial_path ='.' 539if M . is_os ( 'freebsd' ) then 540re ='/nvim.core$' 541else 542re ='/core[^/]*$' 543end 544exc_re ={ '^/%.deps$' , '^/%' .. deps_prefix () .. '$' , local_tmpdir , '^/%node_modules$' } 545db_cmd =gdb_db_cmd 546random_skip =true 547end 548-- Finding cores takes too much time on linux 549if not force and random_skip and math . random () < 0.9 then 550tests_skipped =tests_skipped + 1 551return 552end 553local cores =M . glob ( initial_path , re , exc_re ) 554local found_cores =0 555local out =io . stdout 556for _ , core in ipairs ( cores ) do 557local len =80 - # core - # 'Core file ' - 2 558local esigns =( '=' ): rep ( len / 2 ) 559out : write (( '\n%s Core file %s %s\n' ): format ( esigns , core , esigns )) 560out : flush () 561os . execute ( db_cmd : gsub ( '%$_NVIM_TEST_APP' , app ): gsub ( '%$_NVIM_TEST_CORE' , core ) .. ' 2>&1' ) 562out : write ( '\n' ) 563found_cores =found_cores + 1 564os . remove ( core ) 565end 566if found_cores ~= 0 then 567out : write (( '\nTests covered by this check: %u\n' ): format ( tests_skipped + 1 )) 568end 569tests_skipped =0 570if found_cores > 0 then 571error ( 'crash detected (see above)' ) 572end 573end 574 575--- @return string? 576function M . repeated_read_cmd ( ... ) 577local cmd =M . argss_to_cmd ( ... ) 578local data ={} 579local got_code =nil 580local stdout =assert ( vim . uv . new_pipe ( false )) 581local handle =assert ( 582vim . uv . spawn ( 583cmd [ 1 ], 584{ args =vim . list_slice ( cmd , 2 ), stdio ={ nil , stdout , 2 } , hide =true } , 585function ( code , _signal ) 586got_code =code 587end 588) 589) 590stdout : read_start ( function ( err , chunk ) 591if err or chunk == nil then 592stdout : read_stop () 593stdout : close () 594else 595table . insert ( data , chunk ) 596end 597end ) 598 599while not stdout : is_closing () or got_code == nil do 600vim . uv . run ( 'once' ) 601end 602 603if got_code ~= 0 then 604error ( 'command ' .. vim . inspect ( cmd ) .. 'unexpectedly exited with status ' .. got_code ) 605end 606handle : close () 607return table . concat ( data ) 608end 609 610--- Projects the named fields of `t` (a nil field stays absent). 611--- @param t table<string,any> 612--- @param ... string Field names. 613--- @return table<string,any> 614function M . pick ( t , ... ) 615local r ={} --- @type table<string,any> 616for _ , f in ipairs ( { ... } ) do 617r [ f ] =t [ f ] 618end 619return r 620end 621 622--- @generic T 623--- @param orig T 624--- @return T 625function M . shallowcopy ( orig ) 626if type ( orig ) ~= 'table' then 627return orig 628end 629--- @cast orig table<any,any> 630local copy ={} --- @type table<any,any> 631for orig_key , orig_value in pairs ( orig ) do 632copy [ orig_key ] =orig_value 633end 634return copy 635end 636 637--- @param d1 table<any,any> 638--- @param d2 table<any,any> 639--- @return table<any,any> 640function M . mergedicts_copy ( d1 , d2 ) 641local ret =M . shallowcopy ( d1 ) 642for k , v in pairs ( d2 ) do 643if d2 [ k ] == vim . NIL then 644ret [ k ] =nil 645elseif type ( d1 [ k ]) == 'table' and type ( v ) == 'table' then 646ret [ k ] =M . mergedicts_copy ( d1 [ k ], v ) 647else 648ret [ k ] =v 649end 650end 651return ret 652end 653 654--- dictdiff: find a diff so that mergedicts_copy(d1, diff) is equal to d2 655--- 656--- Note: does not do copies of d2 values used. 657--- @param d1 table<any,any> 658--- @param d2 table<any,any> 659function M . dictdiff ( d1 , d2 ) 660local ret ={} --- @type table<any,any> 661local hasdiff =false 662for k , v in pairs ( d1 ) do 663if d2 [ k ] == nil then 664hasdiff =true 665ret [ k ] =vim . NIL 666elseif type ( v ) == type ( d2 [ k ]) then 667if type ( v ) == 'table' then 668local subdiff =M . dictdiff ( v , d2 [ k ]) 669if subdiff ~= nil then 670hasdiff =true 671ret [ k ] =subdiff 672end 673elseif v ~= d2 [ k ] then 674ret [ k ] =d2 [ k ] 675hasdiff =true 676end 677else 678ret [ k ] =d2 [ k ] 679hasdiff =true 680end 681end 682local shallowcopy =M . shallowcopy 683for k , v in pairs ( d2 ) do 684if d1 [ k ] == nil then 685ret [ k ] =shallowcopy ( v ) 686hasdiff =true 687end 688end 689if hasdiff then 690return ret 691else 692return nil 693end 694end 695 696-- Concat list-like tables. 697function M . concat_tables ( ... ) 698local ret ={} --- @type table<any,any> 699for i =1 , select ( '#' , ... ) do 700--- @type table<any,any> 701local tbl =select ( i , ... ) 702if tbl then 703for _ , v in ipairs ( tbl ) do 704ret [ # ret + 1 ] =v 705end 706end 707end 708return ret 709end 710 711--- Get all permutations of an array. 712--- 713--- @param arr any[] 714--- @return any[][] 715function M . permutations ( arr ) 716local res ={} --- @type any[][] 717--- @param a any[] 718--- @param n integer 719local function gen ( a , n ) 720if n == 0 then 721res [ # res + 1 ] =M . shallowcopy ( a ) 722return 723end 724for i =1 , n do 725a [ n ], a [ i ] =a [ i ], a [ n ] 726gen ( a , n - 1 ) 727a [ n ], a [ i ] =a [ i ], a [ n ] 728end 729end 730gen ( M . shallowcopy ( arr ), # arr ) 731return res 732end 733 734--- @param str string 735--- @param leave_indent? integer 736--- @return string 737function M . dedent ( str , leave_indent ) 738-- Last blank line often has non-matching indent, so remove it. 739str =str : gsub ( '\n[ ]+$' , '\n' ) 740return ( vim . text . indent ( leave_indent or 0 , str )) 741end 742 743function M . intchar2lua ( ch ) 744ch =tonumber ( ch ) 745return ( 20 <= ch and ch < 127 ) and ( '%c' ): format ( ch ) or ch 746end 747 748--- @param str string 749--- @return string 750function M . hexdump ( str ) 751local len =string . len ( str ) 752local dump ='' 753local hex ='' 754local asc ='' 755 756for i =1 , len do 757if 1 == i % 8 then 758dump =dump .. hex .. asc .. '\n' 759hex =string . format ( '%04x: ' , i - 1 ) 760asc ='' 761end 762 763local ord =string . byte ( str , i ) 764hex =hex .. string . format ( '%02x ' , ord ) 765if ord >= 32 and ord <= 126 then 766asc =asc .. string . char ( ord ) 767else 768asc =asc .. '.' 769end 770end 771 772return dump .. hex .. string . rep ( ' ' , 8 - len % 8 ) .. asc 773end 774 775--- Reads text lines from `filename` into a table. 776--- @param filename string path to file 777--- @param start? integer start line (1-indexed), negative means "lines before end" (tail) 778--- @return string[]? 779function M . read_file_list ( filename , start ) 780local lnum =( start ~= nil and type ( start ) == 'number' ) and start or 1 781local tail =( lnum < 0 ) 782local maxlines =tail and math . abs ( lnum ) or nil 783local file =io . open ( filename , 'r' ) 784if not file then 785return nil 786end 787 788-- There is no need to read more than the last 2MB of the log file, so seek 789-- to that. 790local file_size =file : seek ( 'end' ) 791local offset =file_size - 2000000 792if offset < 0 then 793offset =0 794end 795file : seek ( 'set' , offset ) 796 797local lines ={} 798local i =1 799local line =file : read ( '*l' ) 800while line ~= nil do 801if i >= lnum then 802table . insert ( lines , line ) 803if maxlines and # lines > maxlines then 804table . remove ( lines , 1 ) 805end 806end 807i =i + 1 808line =file : read ( '*l' ) 809end 810file : close () 811return lines 812end 813 814--- Reads the entire contents of `filename` into a string. 815--- @param filename string 816--- @return string? 817function M . read_file ( filename ) 818local file =io . open ( filename , 'r' ) 819if not file then 820return nil 821end 822local ret =file : read ( '*a' ) 823file : close () 824return ret 825end 826 827-- Dedent the given text and write it to the file name. 828function M . write_file ( name , text , no_dedent , append ) 829local file =assert ( io . open ( name , ( append and 'a' or 'w' ))) 830if type ( text ) == 'table' then 831-- Byte blob 832--- @type string[] 833local bytes =text 834text ='' 835for _ , char in ipairs ( bytes ) do 836text =( '%s%c' ): format ( text , char ) 837end 838elseif not no_dedent then 839text =M . dedent ( text ) 840end 841file : write ( text ) 842file : flush () 843file : close () 844end 845 846--- @param name? 'github' 847--- @return boolean 848function M . is_ci ( name ) 849return harness . is_ci ( name ) 850end 851 852-- Gets the (tail) contents of `logfile`. 853-- Also moves the file to "${NVIM_LOG_FILE}.displayed" on CI environments. 854function M . read_nvim_log ( logfile , ci_rename ) 855logfile =logfile or os . getenv ( 'NVIM_LOG_FILE' ) or 'nvim.log' 856local log =harness . read_nvim_log ( logfile , ci_rename ) 857assert ( log , ( 'logfile not found: %q' ): format ( logfile )) 858return log 859end 860 861--- @param path string 862--- @return boolean? 863function M . mkdir ( path ) 864-- 493 is 0755 in decimal 865return ( uv . fs_mkdir ( path , 493 )) 866end 867 868--- @param expected any[] 869--- @param received any[] 870--- @param kind string 871--- @return any 872function M . expect_events ( expected , received , kind ) 873if not pcall ( M . eq , expected , received ) then 874local msg ='unexpected ' .. kind .. ' received.\n\n' 875 876msg =msg .. 'received events:\n' 877for _ , e in ipairs ( received ) do 878msg =msg .. ' ' .. vim . inspect ( e ) .. ';\n' 879end 880msg =msg .. '\nexpected events:\n' 881for _ , e in ipairs ( expected ) do 882msg =msg .. ' ' .. vim . inspect ( e ) .. ';\n' 883end 884error ( msg , 2 ) 885end 886return received 887end 888 889--- @param cond boolean 890--- @param reason? string 891--- @return boolean 892function M . skip ( cond , reason ) 893if cond then 894M . pending ( reason or 'FIXME' ) 895return true 896end 897return false 898end 899 900-- Calls pending() and returns `true` if the system is too slow to 901-- run fragile or expensive tests. Else returns `false`. 902function M . skip_fragile ( pending_fn , cond ) 903if pending_fn == nil or type ( pending_fn ) ~= type ( function () end ) then 904error ( 'invalid pending_fn' ) 905end 906if cond then 907pending_fn ( 'skipped (test is fragile on this system)' , function () end ) 908return true 909elseif os . getenv ( 'TEST_SKIP_FRAGILE' ) then 910pending_fn ( 'skipped (TEST_SKIP_FRAGILE)' , function () end ) 911return true 912end 913return false 914end 915 916function M . translations_enabled () 917return M . paths . translations_enabled 918end 919 920--- Sorts timing `samples` and prints + returns min/q25/median/q75/max/mean. 921--- 922--- Shared reporter for `test/benchmark/`. Pair it with `M.bench()` (in-process) or `n.bench()` 923--- (Nvim-under-test), or call it directly with samples you collected yourself. 924--- 925--- @param samples number[] Per-iteration durations, in nanoseconds. Sorted in place. 926--- @param opts? { label?: string, unit?: 'ms'|'us' } 927--- @return { n: integer, min: number, q25: number, median: number, q75: number, max: number, mean: number } 928function M . bench_report ( samples , opts ) 929opts =opts or {} 930local n =# samples 931assert ( n > 0 , 'bench_report: no samples' ) 932local unit =opts . unit or 'ms' 933local scale =unit == 'us' and 1e3 or 1e6 934 935table . sort ( samples ) 936local sum =0 937for _ , v in ipairs ( samples ) do 938sum =sum + v 939end 940--- @param p number percentile in [0,1] 941local function pct ( p ) 942return samples [ math . max ( 1 , math . min ( n , 1 + math . floor ( n * p )))] / scale 943end 944local stats ={ 945n =n , 946min =samples [ 1 ] / scale , 947q25 =pct ( 0.25 ), 948median =pct ( 0.5 ), 949q75 =pct ( 0.75 ), 950max =samples [ n ] / scale , 951mean =( sum / n ) / scale , 952} 953 954( 955( '\n%smin %.4f q25 %.4f median %.4f q75 %.4f max %.4f mean %.4f (%s, n=%d)' ): format ( 956opts . label and ( opts . label .. '\n ' ) or '' , 957stats . min , 958stats . q25 , 959stats . median , 960stats . q75 , 961stats . max , 962stats . mean , 963unit , 964n 965) 966) 967return stats 968end 969 970--- Benchmarks `fn` in the test-runner process: runs it `opts.n` times, timing each run, then reports. 971--- 972--- Note: see `testnvim.bench()` to run in the Nvim-under-test. 973--- 974--- @param fn fun() 975--- @param opts { n: integer, label?: string, unit?: 'ms'|'us', warmup?: integer } 976--- @return table stats See `M.bench_report()`. 977function M . bench ( fn , opts ) 978for _ =1 , ( opts . warmup or 0 ) do 979fn () 980end 981local samples ={} --- @type number[] 982for i =1 , opts . n do 983local t0 =uv . hrtime () 984fn () 985samples [ i ] =uv . hrtime () - t0 986end 987return M . bench_report ( samples , opts ) 988end 989 990return M