robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1--- Result statuses emitted for test, hook, and synthetic records. 2--- @alias test.harness.ResultStatus 3---| 'success' 4---| 'pending' 5---| 'failure' 6---| 'error' 7 8--- Hook phases supported by the test framework. 9--- @alias test.harness.HookKind 10---| 'setup' 11---| 'teardown' 12---| 'before_each' 13---| 'after_each' 14 15--- Execution scopes that can run under harness error handling. 16--- @alias test.harness.ExecutionScope 17---| 'test' 18---| 'setup' 19---| 'teardown' 20---| 'before_each' 21---| 'after_each' 22---| 'suite_end' 23 24--- Source location recorded for defined suites, tests, and hooks. 25--- @class test.harness.Trace 26--- @field short_src string 27--- @field currentline integer 28 29--- Structured error payload used internally by the harness. 30--- @class test.harness.ErrorPayload 31--- @field __harness_pending? boolean 32--- @field message string 33--- @field trace? test.harness.Trace 34--- @field traceback? string 35 36--- @alias test.harness.Element 37--- | test.harness.Suite 38--- | test.harness.Test 39 40--- Base node shared by suite and test definitions. 41--- @class test.harness.ElementBase 42--- @field name string 43--- @field parent? test.harness.Suite 44--- @field trace? test.harness.Trace 45--- @field duration? number 46--- @field full_name? string 47 48--- Registered callback together with the location where it was registered. 49--- @class test.harness.RegisteredCallback 50--- @field fn fun() 51--- @field trace? test.harness.Trace 52 53--- Hook callbacks grouped by phase. 54--- @class test.harness.HookSet 55--- @field setup test.harness.RegisteredCallback[] 56--- @field teardown test.harness.RegisteredCallback[] 57--- @field before_each test.harness.RegisteredCallback[] 58--- @field after_each test.harness.RegisteredCallback[] 59 60--- Suite node containing hooks and nested children. 61--- @class test.harness.Suite : test.harness.ElementBase 62--- @field kind 'suite' 63--- @field is_file boolean 64--- @field children test.harness.Element[] 65--- @field selected_count integer 66--- @field hooks test.harness.HookSet 67 68--- Test node containing an optional runnable body. 69--- @class test.harness.Test : test.harness.ElementBase 70--- @field kind 'test' 71--- @field fn? fun() 72--- @field parent test.harness.Suite 73--- @field pending_message? string 74--- @field retries? integer 75--- @field selected? boolean 76 77--- Test context: state passed to the `it` callback (the test body). 78--- @class test.harness.Context 79--- @field retry integer Attempt index: 0 on the first run, 1 on the first retry. 80 81--- Normalized result returned from running a test or hook. 82--- @class test.harness.Result 83--- @field status test.harness.ResultStatus 84--- @field message? string 85--- @field traceback? string 86--- @field trace? test.harness.Trace 87 88--- Collected test file path plus its display label. 89--- @class test.harness.FileEntry 90--- @field path string 91--- @field display_name string 92 93--- Shallow process baseline restored between test files. 94--- Mutable tables intentionally preserve identity here; deeper isolation 95--- requires separate processes rather than table cloning inside one Lua state. 96--- @class test.harness.RuntimeBaseline 97--- @field cwd string 98--- @field package_path string 99--- @field package_cpath string 100--- @field package_preload table<string, any> 101--- @field globals table<any, any> 102--- @field loaded table<string, any> 103--- @field env table<string, string> 104--- @field arg table<integer, string> 105 106--- Parsed CLI options controlling one harness run. 107--- @class test.harness.Options 108--- @field keep_going boolean 109--- @field verbose boolean 110--- @field repeat_count integer 111--- @field summary_file string 112--- @field helper? string 113--- @field tags string[] 114--- @field filter? string 115--- @field filter_out string[] 116--- @field lpaths string[] 117--- @field cpaths string[] 118--- @field paths string[] 119 120--- Stored suite-end callback together with its registration site. 121--- @class test.harness.SuiteEndRegistration : test.harness.RegisteredCallback 122--- @field key string 123 124--- Active execution context for one running hook or test. 125--- @class test.harness.Execution 126--- @field scope test.harness.ExecutionScope 127--- @field finalizers test.harness.RegisteredCallback[] 128 129--- Mutable harness state shared across definition and execution. 130--- @class test.harness.State 131--- @field suite_end_callbacks test.harness.SuiteEndRegistration[] 132--- @field current_define_suite? test.harness.Suite 133--- @field current_execution? test.harness.Execution 134 135local uv =vim . uv 136 137--- Public test harness module surface. 138--- @class test.harness 139--- @field is_ci fun(name?: 'github'): boolean 140--- @field is_defining fun(): boolean 141--- @field on_suite_end fun(callback: fun()): fun() 142--- @field read_nvim_log fun(logfile?: string, ci_rename?: boolean): string? 143local M ={} 144 145--- @type test.harness.State 146local state ={ 147suite_end_callbacks ={} , 148current_define_suite =nil , 149current_execution =nil , 150} 151 152--- Return the current wall-clock time in seconds. 153--- @return number 154local function now_seconds () 155local sec , usec =assert ( uv . gettimeofday ()) 156return sec + usec * 1e-6 157end 158 159--- Check whether the harness is running in CI, optionally for one provider. 160--- @param name? 'github' 161--- @return boolean 162function M . is_ci ( name ) 163local any_provider =( name == nil ) 164assert ( any_provider or name == 'github' ) 165local github_actions =(( any_provider or name == 'github' ) and nil ~= os . getenv ( 'GITHUB_ACTIONS' )) 166return github_actions 167end 168 169--- Read the last `keep` lines from a file. 170--- @param path string 171--- @param keep integer 172--- @return string[]? 173local function read_tail_lines ( path , keep ) 174local file =io . open ( path , 'r' ) 175if not file then 176return nil 177end 178 179local lines ={} 180for line in file : lines () do 181lines [ # lines + 1 ] =line 182if # lines > keep then 183table . remove ( lines , 1 ) 184end 185end 186file : close () 187return lines 188end 189 190-- TODO(lewis6991): move out of harness 191--- Read and optionally rename the current Nvim log for failure output. 192--- @param logfile? string 193--- @param ci_rename? boolean 194--- @return string? 195function M . read_nvim_log ( logfile , ci_rename ) 196logfile =logfile or os . getenv ( 'NVIM_LOG_FILE' ) or 'nvim.log' 197if not uv . fs_stat ( logfile ) then 198return 199end 200 201local ci =M . is_ci () 202local keep =ci and 100 or 10 203local lines =read_tail_lines ( logfile , keep ) or {} 204local separator =( '-' ): rep ( 78 ) 205local parts ={ 206separator , 207'\n' , 208string . format ( '$NVIM_LOG_FILE: %s\n' , logfile ), 209# lines > 0 and string . format ( '(last %d lines)\n' , keep ) or '(empty)\n' , 210} 211for _ , line in ipairs ( lines ) do 212parts [ # parts + 1 ] =line 213parts [ # parts + 1 ] ='\n' 214end 215if ci and ci_rename then 216os . rename ( logfile , logfile .. '.displayed' ) 217end 218parts [ # parts + 1 ] =separator 219parts [ # parts + 1 ] ='\n' 220return table . concat ( parts ) 221end 222 223--- Normalize a path relative to the current working directory. 224--- @param path string 225--- @return string 226local function normalize_path ( path ) 227return vim . fs . normalize ( vim . fs . abspath ( path )) 228end 229 230--- Render a path relative to the current working directory when possible. 231--- @param path string 232--- @return string 233local function display_path ( path ) 234path =normalize_path ( path ) 235local relative =vim . fs . relpath ( '.' , path ) 236if relative then 237return relative 238end 239return path 240end 241 242--- Restore a table to a previously captured shallow snapshot. 243--- @generic K, V 244--- @param current table<K, V> 245--- @param snapshot table<K, V> 246--- @param unset? fun(key: K) 247--- @param set? fun(key: K, value: V) 248local function restore_snapshot ( current , snapshot , unset , set ) 249unset =unset or function ( k ) 250rawset ( current , k , nil ) 251end 252set =set or function ( k , v ) 253rawset ( current , k , v ) 254end 255for k in pairs ( current ) do 256if rawget ( snapshot , k ) == nil then 257unset ( k ) 258end 259end 260for k , v in pairs ( snapshot ) do 261set ( k , v ) 262end 263end 264 265--- Restore the process state to a captured baseline. 266--- @param baseline test.harness.RuntimeBaseline 267local function restore_runtime_baseline ( baseline ) 268if uv . cwd () ~= baseline . cwd then 269uv . chdir ( baseline . cwd ) 270end 271 272package . path =baseline . package_path 273package . cpath =baseline . package_cpath 274restore_snapshot ( package . preload , baseline . package_preload ) 275restore_snapshot ( package . loaded , baseline . loaded ) 276restore_snapshot ( _G , baseline . globals ) 277restore_snapshot ( uv . os_environ (), baseline . env , uv . os_unsetenv , uv . os_setenv ) 278_G . arg =vim . _copy ( baseline . arg ) 279state . current_define_suite =nil 280state . current_execution =nil 281end 282 283--- Restore the baseline and run GC cleanup. 284--- @param baseline test.harness.RuntimeBaseline 285local function cleanup_runtime_baseline ( baseline ) 286restore_runtime_baseline ( baseline ) 287-- One full cycle may only run __gc/finalizers for dead userdata/cdata. 288-- Those finalizers can release the last references to more uv/mpack objects, 289-- which do not become collectible until the next cycle. Collect twice before 290-- switching files or ending the harness so leak checks see only live state. 291collectgarbage ( 'collect' ) 292collectgarbage ( 'collect' ) 293end 294 295local harness_source =debug . getinfo ( 1 , 'S' ). source 296local test_assert =require ( 'test.assert' ) 297local assert_source =debug . getinfo ( test_assert . eq , 'S' ). source 298 299--- @param info? debug.Info 300--- @return test.harness.Trace 301local function trace_from_info ( info ) 302return { 303short_src =info and vim . fs . normalize ( info . short_src or '' ) or '' , 304currentline =info and info . currentline or 0 , 305} 306end 307 308--- Capture the source location of a caller frame. 309--- Walk upward until we find a user Lua frame so Lua 5.1 tail-call elision 310--- does not collapse `it()`/hook registrations into `(tail call) @ -1`. 311--- @param level? integer 312--- @return test.harness.Trace 313local function caller_trace ( level ) 314local frame =level or 3 315local fallback 316 317while true do 318local info =debug . getinfo ( frame , 'Sln' ) 319if not info then 320return trace_from_info ( fallback ) 321end 322 323fallback =fallback or info 324if 325info . what ~= 'C' 326and info . source ~= harness_source 327and info . short_src ~= '(tail call)' 328and info . currentline > 0 329then 330return trace_from_info ( info ) 331end 332 333frame =frame + 1 334end 335end 336 337--- Register a suite-end callback, deduplicated by callsite. 338--- @param callback fun() 339--- @return fun() 340function M . on_suite_end ( callback ) 341assert ( type ( callback ) == 'function' , 'on_suite_end() expects a function' ) 342local trace =caller_trace ( 3 ) 343local caller_info =debug . getinfo ( 2 , 'S' ) 344local key_source =caller_info and caller_info . source 345if type ( key_source ) == 'string' and vim . startswith ( key_source , '@' ) then 346key_source =vim . fs . normalize ( key_source : sub ( 2 )) 347else 348key_source =trace . short_src 349end 350local key =( '%s:%d' ): format ( key_source , trace . currentline ) 351for _ , registration in ipairs ( state . suite_end_callbacks ) do 352if registration . key == key then 353return registration . fn 354end 355end 356table . insert ( state . suite_end_callbacks , { 357fn =callback , 358trace =trace , 359key =key , 360} ) 361return callback 362end 363 364--- Create a suite node for the definition tree. 365--- @param name string? 366--- @param parent? test.harness.Suite 367--- @param trace? test.harness.Trace 368--- @param is_file? boolean 369--- @return test.harness.Suite 370local function create_suite ( name , parent , trace , is_file ) 371return { 372kind ='suite' , 373name =name or '' , 374parent =parent , 375trace =trace , 376is_file =is_file or false , 377hooks ={ 378setup ={} , 379teardown ={} , 380before_each ={} , 381after_each ={} , 382} , 383children ={} , 384selected_count =0 , 385} 386end 387 388--- Return the suite currently receiving test definitions. 389--- @return test.harness.Suite 390local function current_suite () 391assert ( state . current_define_suite , 'test definition is not active' ) 392return state . current_define_suite 393end 394 395--- Whether a test file/suite is currently being defined (vs. executing, or neither: e.g. when this 396--- module is loaded from a preload/helper). Lets callers register hooks at a valid stage. 397--- @return boolean 398function M . is_defining () 399return state . current_define_suite ~= nil 400end 401 402--- Add a test node to the current suite. 403--- @param name string 404--- @param fn? fun() 405--- @param pending_message? string 406--- @return test.harness.Test 407local function register_test ( name , fn , pending_message , opts ) 408assert ( type ( name ) == 'string' and name ~= '' , 'test name must be a non-empty string' ) 409if fn ~= nil then 410assert ( type ( fn ) == 'function' , 'test body must be a function' ) 411end 412local retries =opts and opts . retries or 0 413assert ( type ( retries ) == 'number' and retries >= 0 , 'retries must be a non-negative number' ) 414 415local suite =current_suite () 416local test ={ 417kind ='test' , 418name =name , 419fn =fn , 420parent =suite , 421trace =caller_trace ( 3 ), 422pending_message =pending_message , 423retries =retries , 424} 425table . insert ( suite . children , test ) 426return test 427end 428 429--- Build a hook registrar exposed in the test framework. 430--- @param kind test.harness.HookKind 431--- @return fun(fn: fun()) 432local function chunk_hook ( kind ) 433return function ( fn ) 434assert ( type ( fn ) == 'function' , ( '%s expects a function' ): format ( kind )) 435table . insert ( current_suite (). hooks [ kind ], { 436fn =fn , 437trace =caller_trace ( 3 ), 438} ) 439end 440end 441 442-- Busted-style test API. 443-- Specs import it explicitly (`local describe, it = require('test.testutil').describe, …`). 444M . setup =chunk_hook ( 'setup' ) 445M . teardown =chunk_hook ( 'teardown' ) 446M . before_each =chunk_hook ( 'before_each' ) 447M . after_each =chunk_hook ( 'after_each' ) 448 449--- Define a nested suite. 450--- @param name string 451--- @param fn fun() 452--- @return test.harness.Suite 453function M . describe ( name , fn ) 454assert ( type ( name ) == 'string' , 'describe() expects a string' ) 455assert ( type ( fn ) == 'function' , 'describe() expects a function body' ) 456 457local parent =current_suite () 458local suite =create_suite ( name , parent , caller_trace ( 3 ), false ) 459table . insert ( parent . children , suite ) 460 461local previous_define_suite =state . current_define_suite 462state . current_define_suite =suite 463local ok , err =xpcall ( fn , debug . traceback ) 464state . current_define_suite =previous_define_suite 465 466if not ok then 467error ( err , 0 ) 468end 469 470return suite 471end 472 473--- Define a test. 474--- 475--- @param name string Test description. 476--- @param opts? table|fun() Options: 477--- - `retries`: (default: 0) Retry the test, including setup/teardown 478--- (`before_each`/`after_each`/`finally`), up to this many times. 479--- Only the last attempt is reported. 480--- @param fn? fun(ctx: test.harness.Context) Test body. 481--- - `ctx.retry` is the index of the `retries` attempt, or 0 if this is not a retry. 482--- @return test.harness.Test 483function M . it ( name , opts , fn ) 484if type ( opts ) == 'function' then 485opts , fn =nil , opts 486end 487assert ( opts == nil or type ( opts ) == 'table' , 'it() arg 2 must be an opts table or a function' ) 488return register_test ( name , fn , nil , opts ) 489end 490 491--- Mark the current test as pending or define a pending test. 492--- When called while a test or hook is running, this aborts the current 493--- execution and reports the current test as pending with `name` as the 494--- pending message. 495--- When called during file definition, this registers a new pending test in 496--- the current suite. In that form, `block` may be a string used as the 497--- pending message. 498--- @param name? string 499--- @param block? fun()|string 500--- @return boolean 501function M . pending ( name , block ) 502if state . current_execution then 503error ( { 504__harness_pending =true , 505message =name or 'pending' , 506} , 0 ) 507end 508local pending_message =type ( block ) == 'string' and block or nil 509register_test ( name or 'pending' , nil , pending_message ) 510return false 511end 512 513--- Register a finalizer to run after the current test body. 514--- @param fn fun() 515function M . finally ( fn ) 516assert ( type ( fn ) == 'function' , 'finally() expects a function' ) 517assert ( 518state . current_execution and state . current_execution . scope == 'test' , 519'finally() must be called while a test body is running' 520) 521table . insert ( state . current_execution . finalizers , { 522fn =fn , 523trace =caller_trace ( 3 ), 524} ) 525end 526 527--- Convert an arbitrary error value into printable text. 528--- @param err any 529--- @return string 530function M . format_error_value ( err ) 531if type ( err ) == 'string' then 532return err 533end 534 535local ok , inspected =pcall ( vim . inspect , err ) 536if ok then 537return inspected 538end 539 540return tostring ( err ) 541end 542 543--- Parse one traceback line into a source location. 544--- @param text? string 545--- @return test.harness.Trace? 546local function parse_trace_line ( text ) 547if type ( text ) ~= 'string' then 548return 549end 550 551local src , line =text : match ( '^(.+):(%d+):' ) 552if not src or not line then 553return 554end 555 556return { 557short_src =vim . fs . normalize ( src ), 558currentline =tonumber ( line ) or 0 , 559} 560end 561 562--- @param source string 563--- @param candidate string 564--- @return boolean 565local function source_matches ( source , candidate ) 566if source == candidate then 567return true 568end 569 570local tail =source : match ( '^%.%.%.(.+)$' ) 571return tail ~= nil and vim . endswith ( candidate , tail ) 572end 573 574--- @param left? test.harness.Trace 575--- @param right? test.harness.Trace 576--- @return boolean 577local function same_trace_source ( left , right ) 578if left == nil or right == nil then 579return false 580end 581return source_matches ( left . short_src , right . short_src ) 582or source_matches ( right . short_src , left . short_src ) 583end 584 585--- Extract a source location from an error message or traceback. 586--- @param message? string 587--- @param traceback? string 588--- @return test.harness.Trace? 589local function parse_error_trace ( message , traceback ) 590if type ( message ) == 'string' then 591local first_line =message : match ( '^[^\n]+' ) 592local trace =parse_trace_line ( first_line ) 593if trace then 594return trace 595end 596 597local load_path =first_line 598and first_line : match ( "^error loading module .+ from file '([^']+)':$" ) 599if load_path == nil and first_line then 600load_path =first_line : match ( '^error loading module .+ from file "([^"]+)":$' ) 601end 602if load_path then 603local detail_line =message : match ( '\n([^\n]+)' ) 604trace =parse_trace_line ( detail_line and detail_line : gsub ( '^%s+' , '' )) 605local load_trace ={ 606short_src =vim . fs . normalize ( load_path ), 607currentline =0 , 608} 609if trace and same_trace_source ( trace , load_trace ) then 610return trace 611end 612end 613end 614 615if type ( traceback ) == 'string' then 616for line in traceback : gmatch ( '[^\n]+' ) do 617local trace =parse_trace_line ( line : gsub ( '^%s+' , '' )) 618if trace then 619return trace 620end 621end 622end 623end 624 625--- Capture only user-visible Lua frames for test and hook failures. 626--- Once execution returns to the harness, the rest of the stack is framework 627--- noise and should not be printed in verbose failure output. 628--- @return string? 629function M . build_error_traceback ( framework_source ) 630local lines ={} 631 632for level =3 , math . huge do 633local info =debug . getinfo ( level , 'Sln' ) 634if not info then 635break 636end 637 638if info . source == framework_source then 639break 640end 641 642if ( info . what == 'Lua' or info . what == 'main' ) and info . source ~= assert_source then 643local trace =trace_from_info ( info ) 644if trace . currentline > 0 and trace . short_src ~= '' then 645local location =( '%s:%d' ): format ( trace . short_src , trace . currentline ) 646if info . what == 'main' then 647lines [ # lines + 1 ] =( '\t%s: in main chunk' ): format ( location ) 648elseif info . name and info . name ~= '' then 649lines [ # lines + 1 ] =( "\t%s: in function '%s'" ): format ( location , info . name ) 650elseif ( info . linedefined or 0 ) > 0 then 651lines [ # lines + 1 ] =( '\t%s: in function <%s:%d>' ): format ( 652location , 653trace . short_src , 654info . linedefined 655) 656else 657lines [ # lines + 1 ] =( '\t%s: in function ?' ): format ( location ) 658end 659end 660end 661end 662 663if # lines == 0 then 664return 665end 666 667return 'stack traceback:\n' .. table . concat ( lines , '\n' ) 668end 669 670--- Normalize thrown values into harness error payloads. 671--- @param err any 672--- @return test.harness.ErrorPayload 673local function exception_handler ( err ) 674if type ( err ) == 'table' and err . __harness_pending then 675--- @cast err test.harness.ErrorPayload 676return err 677end 678 679local message =M . format_error_value ( err ) 680local raw_traceback =debug . traceback ( '' , 2 ) 681return { 682message =message , 683trace =parse_error_trace ( message , raw_traceback ), 684traceback =M . build_error_traceback ( harness_source ) or raw_traceback , 685} 686end 687 688--- Convert a handled error payload into a test result. 689--- @param err test.harness.ErrorPayload 690--- @param fallback_status? test.harness.ResultStatus 691--- @return test.harness.Result 692local function decode_error ( err , fallback_status ) 693return { 694status =err . __harness_pending and 'pending' or fallback_status or 'failure' , 695message =err . message , 696traceback =err . traceback , 697trace =err . trace or parse_error_trace ( err . message , err . traceback ), 698} 699end 700 701--- Run a callable under harness error handling and finalizer cleanup. 702--- @param scope test.harness.ExecutionScope 703--- @param callable test.harness.RegisteredCallback 704--- @param fallback_status? test.harness.ResultStatus 705--- @return test.harness.Result, test.harness.Trace? 706local function run_callable ( scope , callable , fallback_status , ctx ) 707local previous_execution =state . current_execution 708--- @type test.harness.Execution 709local execution ={ 710scope =scope , 711finalizers ={} , 712} 713state . current_execution =execution 714 715-- Note: xpcall variadic args not supported by Lua 5.1. 716local ok , err =xpcall ( function () 717return callable . fn ( ctx ) 718end , exception_handler ) 719local finalizer_err 720local finalizer_trace 721for i =# execution . finalizers , 1 , - 1 do 722local finalizer =execution . finalizers [ i ] 723local finalizer_ok , ferr =xpcall ( finalizer . fn , exception_handler ) 724if not finalizer_ok and not finalizer_err then 725finalizer_err =ferr 726finalizer_trace =finalizer . trace 727end 728end 729 730state . current_execution =previous_execution 731 732local result =ok and { status ='success' } or decode_error ( err , fallback_status ) 733local report_trace =not ok and callable . trace or nil 734if not finalizer_err then 735return result , report_trace 736end 737 738local finalizer_result =decode_error ( finalizer_err , 'error' ) 739if result . status == 'success' then 740finalizer_result . status ='error' 741return finalizer_result , finalizer_trace 742end 743 744if result . status == 'pending' then 745return { 746status ='error' , 747message =( 'finally: %s' ): format ( finalizer_result . message ), 748traceback =finalizer_result . traceback , 749trace =finalizer_result . trace , 750} , 751finalizer_trace 752end 753 754result . message =result . message .. '\n\nfinally: ' .. finalizer_result . message 755if not result . traceback then 756result . traceback =finalizer_result . traceback 757end 758if not result . trace then 759result . trace =finalizer_result . trace 760end 761return result , report_trace 762end 763 764--- Prefer the parsed trace only when it points at the same source file as the 765--- owning test or callback. Otherwise, fall back to the definition site. 766--- @param trace? test.harness.Trace 767--- @param fallback? test.harness.Trace 768--- @return test.harness.Trace? 769local function summary_trace ( trace , fallback ) 770if same_trace_source ( trace , fallback ) then 771return trace 772end 773return fallback or trace 774end 775 776--- Build the suite and test name parts used for reporting. 777--- @param element test.harness.Element? 778--- @return string[] 779local function full_name_parts ( element ) 780local parts ={} 781local node =element 782while node do 783if node . kind == 'test' and node . name ~= '' then 784table . insert ( parts , 1 , node . name ) 785elseif node . kind == 'suite' and not node . is_file and node . name ~= '' then 786table . insert ( parts , 1 , node . name ) 787end 788node =node . parent 789end 790return parts 791end 792 793--- Return the full hierarchical name for a suite or test. 794--- @param element test.harness.Element 795--- @return string 796function M . get_full_name ( element ) 797return table . concat ( full_name_parts ( element ), ' ' ) 798end 799 800--- Check whether a test matches the current selection options. 801--- @param test test.harness.Test 802--- @param opts test.harness.Options 803--- @return boolean 804local function test_selected ( test , opts ) 805test . full_name =M . get_full_name ( test ) 806 807if # opts . tags > 0 then 808local tagged =false 809for tag in test . full_name : gmatch ( '#([%w_%-]+)' ) do 810if vim . list_contains ( opts . tags , tag ) then 811tagged =true 812break 813end 814end 815 816if not tagged then 817return false 818end 819end 820 821if opts . filter and not test . full_name : match ( opts . filter ) then 822return false 823end 824 825for _ , filter_out in ipairs ( opts . filter_out ) do 826if test . full_name : match ( filter_out ) then 827return false 828end 829end 830 831return true 832end 833 834--- Mark selected tests in a suite subtree and count them. 835--- @param node test.harness.Suite 836--- @param opts test.harness.Options 837--- @return integer 838local function mark_selected ( node , opts ) 839local selected_count =0 840for _ , child in ipairs ( node . children ) do 841if child . kind == 'suite' then 842selected_count =selected_count + mark_selected ( child , opts ) 843else 844--- @cast child test.harness.Test 845child . selected =test_selected ( child , opts ) 846if child . selected then 847selected_count =selected_count + 1 848end 849end 850end 851 852node . selected_count =selected_count 853return selected_count 854end 855 856--- Collect inherited `before_each` hooks from outermost to innermost. 857--- @param suite test.harness.Suite 858--- @return test.harness.RegisteredCallback[] 859local function gather_before_each ( suite ) 860local hooks ={} 861if suite . parent then 862vim . list_extend ( hooks , gather_before_each ( suite . parent )) 863end 864for _ , hook in ipairs ( suite . hooks . before_each ) do 865hooks [ # hooks + 1 ] =hook 866end 867return hooks 868end 869 870--- Collect inherited `after_each` hooks from innermost to outermost. 871--- @param suite test.harness.Suite 872--- @return test.harness.RegisteredCallback[] 873local function gather_after_each ( suite ) 874local hooks ={} 875for _ , hook in ipairs ( suite . hooks . after_each ) do 876hooks [ # hooks + 1 ] =hook 877end 878if suite . parent then 879vim . list_extend ( hooks , gather_after_each ( suite . parent )) 880end 881return hooks 882end 883 884--- Finalized result record passed to the reporter and stored in summaries. 885--- @class test.harness.Record 886--- @field name string 887--- @field status test.harness.ResultStatus 888--- @field trace? test.harness.Trace 889--- @field duration number 890--- @field message? string 891--- @field traceback? string 892 893--- Execution summary accumulated by the harness for one suite iteration. 894--- @class test.harness.RunSummary 895--- @field file_count integer 896--- @field result_count integer 897--- @field test_count integer 898--- @field success_count integer 899--- @field skipped_count integer 900--- @field failure_count integer 901--- @field error_count integer 902--- @field pendings test.harness.Record[] 903--- @field failures test.harness.Record[] 904--- @field errors test.harness.Record[] 905 906--- Per-file summary accumulated by the harness while one file runs. 907--- @class test.harness.FileRunSummary 908--- @field test_count integer 909 910--- Build the reporter record for a completed result. 911--- @param name string 912--- @param result test.harness.Result 913--- @param trace? test.harness.Trace 914--- @param duration number 915--- @return test.harness.Record 916local function build_record ( name , result , trace , duration ) 917return { 918name =name , 919status =result . status , 920trace =trace , 921duration =duration , 922message =result . message , 923traceback =result . traceback , 924} 925end 926 927--- Record a completed test or synthetic result into the harness summary. 928--- @param summary test.harness.RunSummary 929--- @param file_summary? test.harness.FileRunSummary 930--- @param record test.harness.Record 931--- @param count_as_test? boolean 932local function record_result ( summary , file_summary , record , count_as_test ) 933summary . result_count =summary . result_count + 1 934if count_as_test ~= false then 935summary . test_count =summary . test_count + 1 936if file_summary then 937file_summary . test_count =file_summary . test_count + 1 938end 939end 940 941if record . status == 'success' then 942summary . success_count =summary . success_count + 1 943elseif record . status == 'pending' then 944summary . skipped_count =summary . skipped_count + 1 945table . insert ( summary . pendings , record ) 946elseif record . status == 'failure' then 947summary . failure_count =summary . failure_count + 1 948table . insert ( summary . failures , record ) 949else -- error 950summary . error_count =summary . error_count + 1 951table . insert ( summary . errors , record ) 952end 953end 954 955--- Report a synthetic result as a test-shaped record. 956--- @param reporter test.base_reporter 957--- @param summary test.harness.RunSummary 958--- @param file_summary? test.harness.FileRunSummary 959--- @param parent test.harness.Suite 960--- @param phase string 961--- @param result test.harness.Result 962--- @param trace? test.harness.Trace 963--- @return test.harness.ResultStatus 964local function run_synthetic_result ( reporter , summary , file_summary , parent , phase , result , trace ) 965local name =M . get_full_name ( parent ) 966if name == '' then 967name =parent . name ~= '' and parent . name or 'suite' 968end 969name =( '%s [%s]' ): format ( name , phase ) 970local record_trace =trace or result . trace or parent . trace 971local record =build_record ( name , result , record_trace , 0 ) 972reporter : test_start ( record . name ) 973record_result ( summary , file_summary , record , false ) 974reporter : test_end ( record ) 975return record . status 976end 977 978--- Run registered suite-end callbacks and report failures. 979--- @param reporter test.base_reporter 980--- @param summary test.harness.RunSummary 981--- @return boolean 982local function run_suite_end_callbacks ( reporter , summary ) 983local suite_end_callbacks =vim . _copy ( state . suite_end_callbacks ) 984local callback_failed =false 985 986for index , callback in ipairs ( suite_end_callbacks ) do 987local result , report_trace =run_callable ( 'suite_end' , callback , 'error' ) 988if result . status ~= 'success' then 989callback_failed =true 990result . status ='error' 991local name =( '[suite_end %d]' ): format ( index ) 992local record_trace =summary_trace ( result . trace , report_trace or callback . trace ) 993local record =build_record ( name , result , record_trace , 0 ) 994reporter : test_start ( record . name ) 995record_result ( summary , nil , record , false ) 996reporter : test_end ( record ) 997end 998end 999 1000return callback_failed 1001end 1002 1003--- Run a single test with its surrounding before and after hooks. 1004--- @param test test.harness.Test 1005--- @param reporter test.base_reporter 1006--- @param summary test.harness.RunSummary 1007--- @param file_summary test.harness.FileRunSummary 1008--- @return test.harness.ResultStatus 1009local function run_test ( test , reporter , summary , file_summary ) 1010local name =test . full_name or M . get_full_name ( test ) 1011 1012local start_time =now_seconds () 1013--- @type test.harness.Result 1014local result 1015local report_trace =test . trace 1016if test . fn == nil then 1017reporter : test_start ( name ) 1018result ={ 1019status ='pending' , 1020message =test . pending_message , 1021} 1022else 1023local attempt =0 1024repeat 1025attempt =attempt + 1 1026--- @type test.harness.Context 1027local ctx ={ retry =attempt - 1 } 1028result ={ status ='success' } 1029 1030for _ , hook in ipairs ( gather_before_each ( test . parent )) do 1031result , report_trace =run_callable ( 'before_each' , hook , 'failure' ) 1032if result . status ~= 'success' then 1033break 1034end 1035end 1036 1037if attempt == 1 then 1038reporter : test_start ( name ) 1039end 1040 1041if result . status == 'success' then 1042result , report_trace = 1043run_callable ( 'test' , { fn =test . fn , trace =test . trace } , 'failure' , ctx ) 1044end 1045 1046for _ , hook in ipairs ( gather_after_each ( test . parent )) do 1047local hook_result , hook_trace =run_callable ( 'after_each' , hook , 'failure' ) 1048if result . status == 'success' then 1049result =hook_result 1050report_trace =hook_trace 1051elseif hook_result . status ~= 'success' then 1052local hook_report_trace =hook_trace or hook . trace 1053result . message =( result . message or '' ) 1054.. ( result . message and result . message ~= '' and '\n\n' or '' ) 1055.. 'after_each: ' 1056.. hook_result . message 1057if not result . traceback then 1058result . traceback =hook_result . traceback 1059end 1060if not result . trace then 1061result . trace =hook_result . trace 1062end 1063if result . status == 'pending' then 1064result . status ='error' 1065report_trace =hook_report_trace 1066elseif not report_trace then 1067report_trace =hook_report_trace 1068end 1069end 1070end 1071-- check for interrupts 1072vim . wait ( 0 ) 1073until result . status == 'success' or attempt > test . retries 1074end 1075 1076test . duration =now_seconds () - start_time 1077local record =build_record ( 1078name , 1079result , 1080summary_trace ( result . trace , report_trace or test . trace ), 1081test . duration 1082) 1083record_result ( summary , file_summary , record ) 1084reporter : test_end ( record ) 1085return record . status 1086end 1087 1088--- Run a suite subtree until completion or a stop condition. 1089--- @param suite test.harness.Suite 1090--- @param reporter test.base_reporter 1091--- @param summary test.harness.RunSummary 1092--- @param file_summary test.harness.FileRunSummary 1093--- @param opts test.harness.Options 1094--- @return boolean 1095local function run_suite ( suite , reporter , summary , file_summary , opts ) 1096if suite . selected_count == 0 then 1097return false 1098end 1099 1100local stop_requested =false 1101local run_children =true 1102 1103-- Run setup() hooks 1104for _ , hook in ipairs ( suite . hooks . setup ) do 1105local result =run_callable ( 'setup' , hook , 'error' ) 1106if result . status ~= 'success' then 1107run_synthetic_result ( reporter , summary , file_summary , suite , 'setup' , result , hook . trace ) 1108run_children =false 1109if result . status ~= 'pending' and not opts . keep_going then 1110stop_requested =true 1111end 1112break 1113end 1114end 1115 1116if run_children and not stop_requested then 1117for _ , child in ipairs ( suite . children ) do 1118if child . kind == 'suite' then 1119stop_requested =run_suite ( child , reporter , summary , file_summary , opts ) or stop_requested 1120elseif child . selected then 1121local status =run_test ( child , reporter , summary , file_summary ) 1122if status ~= 'success' and status ~= 'pending' and not opts . keep_going then 1123stop_requested =true 1124end 1125end 1126 1127if stop_requested then 1128break 1129end 1130end 1131end 1132 1133-- Run teardown() hooks 1134for _ , hook in ipairs ( suite . hooks . teardown ) do 1135local result =run_callable ( 'teardown' , hook , 'error' ) 1136if result . status ~= 'success' then 1137run_synthetic_result ( reporter , summary , file_summary , suite , 'teardown' , result , hook . trace ) 1138if result . status ~= 'pending' and not opts . keep_going then 1139stop_requested =true 1140end 1141end 1142end 1143 1144return stop_requested 1145end 1146 1147--- Collect test files from a file or directory path. 1148--- @param path string 1149--- @param files test.harness.FileEntry[] 1150--- @param seen_files table<string, boolean> 1151--- @return boolean?, string? 1152local function collect_test_files ( path , files , seen_files ) 1153--- @param file string 1154local function add_test_file ( file ) 1155local abs_file =normalize_path ( file ) 1156if seen_files [ abs_file ] then 1157return 1158end 1159 1160seen_files [ abs_file ] =true 1161files [ # files + 1 ] ={ 1162path =abs_file , 1163display_name =display_path ( abs_file ), 1164} 1165end 1166 1167local abs =normalize_path ( path ) 1168local stat =uv . fs_stat ( abs ) 1169if not stat then 1170return nil , ( 'test path not found: %s' ): format ( path ) 1171end 1172 1173if stat . type == 'file' then 1174add_test_file ( abs ) 1175return true 1176end 1177 1178if stat . type ~= 'directory' then 1179return nil , ( 'unsupported test path: %s' ): format ( path ) 1180end 1181 1182for _ , file in 1183ipairs ( vim . fs . find ( function ( name ) 1184return name : match ( '_spec%.lua$' ) ~= nil 1185end , { 1186path =abs , 1187type ='file' , 1188limit =math . huge , 1189} )) 1190do 1191add_test_file ( file ) 1192end 1193 1194return true 1195end 1196 1197--- Parse harness CLI arguments into execution options. 1198--- @param argv string[] 1199--- @return test.harness.Options?, string? 1200local function parse_args ( argv ) 1201--- @type test.harness.Options 1202local opts ={ 1203keep_going =true , 1204verbose =false , 1205repeat_count =1 , 1206summary_file ='-' , 1207tags ={} , 1208filter_out ={} , 1209lpaths ={} , 1210cpaths ={} , 1211paths ={} , 1212} 1213 1214--- @type table<string, boolean> 1215local seen_tags ={} 1216 1217--- @param flag string 1218--- @return nil, string 1219local function missing_value ( flag ) 1220return nil , 'missing value for ' .. flag 1221end 1222 1223--- Parse and validate the `--repeat` argument. 1224--- @param value? string 1225--- @return integer?, string? 1226local function parse_repeat_count ( value ) 1227if type ( value ) ~= 'string' or value == '' then 1228return missing_value ( '--repeat' ) 1229end 1230 1231local count =tonumber ( value ) 1232if count == nil or count < 1 or count ~= math . floor ( count ) then 1233return nil , ( 'invalid value for --repeat: %s' ): format ( value ) 1234end 1235--- @cast count integer 1236 1237return count 1238end 1239 1240--- @type table<string, fun()> 1241local switch_options ={ 1242[ '-v' ] =function () 1243opts . verbose =true 1244end , 1245[ '--verbose' ] =function () 1246opts . verbose =true 1247end , 1248[ '--no-keep-going' ] =function () 1249opts . keep_going =false 1250end , 1251} 1252 1253--- @param flag string 1254--- @param value string 1255--- @return string?, string? 1256local function require_nonempty ( flag , value ) 1257if value == '' then 1258return missing_value ( flag ) 1259end 1260return value 1261end 1262 1263--- @param setter fun(value: any) 1264--- @return fun(value: any): boolean?, string? 1265local function set_value ( setter ) 1266return function ( value ) 1267setter ( value ) 1268return true 1269end 1270end 1271 1272--- @param parse fun(value: string): any?, string? 1273--- @param setter fun(value: any) 1274--- @return fun(value: string): boolean?, string? 1275local function set_parsed_value ( parse , setter ) 1276return function ( value ) 1277local parsed , err =parse ( value ) 1278if parsed == nil then 1279return nil , err 1280end 1281setter ( parsed ) 1282return true 1283end 1284end 1285 1286--- @param flag string 1287--- @param setter fun(value: string) 1288--- @return fun(value: string): boolean?, string? 1289local function set_nonempty_value ( flag , setter ) 1290return set_parsed_value ( function ( value ) 1291return require_nonempty ( flag , value ) 1292end , setter ) 1293end 1294 1295--- Validate that a filter option contains a valid Lua pattern. 1296--- @param flag string 1297--- @param value string 1298--- @return string?, string? 1299local function validate_pattern ( flag , value ) 1300local ok , err =pcall ( string . match , '' , value ) 1301if not ok then 1302local message =tostring ( err ) 1303local detail =message : match ( 'malformed pattern.*' ) or message 1304return nil , ( 'invalid value for %s: %s' ): format ( flag , detail ) 1305end 1306return value 1307end 1308 1309--- @param flag string 1310--- @param setter fun(value: string) 1311--- @return fun(value: string): boolean?, string? 1312local function set_pattern_value ( flag , setter ) 1313return set_parsed_value ( function ( value ) 1314return validate_pattern ( flag , value ) 1315end , setter ) 1316end 1317 1318--- @param values string[] 1319--- @return fun(value: string): boolean?, string? 1320local function append_value ( values ) 1321return set_value ( function ( value ) 1322table . insert ( values , value ) 1323end ) 1324end 1325 1326--- @type table<string, fun(value: string): boolean?, string?> 1327local value_options ={ 1328[ '--repeat' ] =set_parsed_value ( parse_repeat_count , function ( count ) 1329opts . repeat_count =count 1330end ), 1331[ '--helper' ] =set_nonempty_value ( '--helper' , function ( value ) 1332opts . helper =value 1333end ), 1334[ '--summary-file' ] =set_nonempty_value ( '--summary-file' , function ( value ) 1335opts . summary_file =value 1336end ), 1337[ '--tags' ] =function ( value ) 1338for token in value : gmatch ( '[^,%s]+' ) do 1339local tag =token : gsub ( '^#' , '' ) 1340if tag ~= '' and not seen_tags [ tag ] then 1341seen_tags [ tag ] =true 1342table . insert ( opts . tags , tag ) 1343end 1344end 1345return true 1346end , 1347[ '--filter' ] =set_pattern_value ( '--filter' , function ( pattern ) 1348opts . filter =pattern 1349end ), 1350[ '--filter-out' ] =set_pattern_value ( '--filter-out' , function ( pattern ) 1351table . insert ( opts . filter_out , pattern ) 1352end ), 1353[ '--lpath' ] =append_value ( opts . lpaths ), 1354[ '--cpath' ] =append_value ( opts . cpaths ), 1355[ '--default-path' ] =set_nonempty_value ( '--default-path' , function ( path ) 1356opts . default_path =path 1357end ), 1358} 1359 1360local i =1 1361 1362--- @param arg string 1363--- @return string, string? 1364local function split_option ( arg ) 1365local eq =arg : find ( '=' , 1 , true ) 1366if not eq then 1367return arg , nil 1368end 1369return arg : sub ( 1 , eq - 1 ), arg : sub ( eq + 1 ) 1370end 1371 1372--- Consume the next argv item as the value for `flag`. 1373--- @param flag string 1374--- @return string?, string? 1375local function take_value ( flag ) 1376i =i + 1 1377local value =argv [ i ] 1378if type ( value ) ~= 'string' then 1379return missing_value ( flag ) 1380end 1381return value 1382end 1383 1384--- Parse one named option and apply it to `opts`. 1385--- @param arg string 1386--- @return boolean, string? 1387local function apply_named_option ( arg ) 1388local switch_handler =switch_options [ arg ] 1389if switch_handler then 1390switch_handler () 1391return true 1392end 1393 1394local flag , value =split_option ( arg ) 1395local handler =value_options [ flag ] 1396if handler then 1397if value == nil then 1398local err 1399value , err =take_value ( flag ) 1400if not value then 1401return false , err 1402end 1403end 1404local ok , handler_err =handler ( value ) 1405if not ok then 1406return false , handler_err 1407end 1408return true 1409end 1410 1411return false 1412end 1413 1414while i <= # argv do 1415local arg =assert ( argv [ i ]) 1416local handled , err =apply_named_option ( arg ) 1417if handled then 1418elseif err then 1419return nil , err 1420elseif vim . startswith ( arg , '-' ) then 1421return nil , 'unknown test harness option: ' .. arg 1422else 1423opts . paths [ # opts . paths + 1 ] =arg 1424end 1425i =i + 1 1426end 1427 1428if # opts . paths == 0 then 1429if opts . default_path then 1430opts . paths [ 1 ] =opts . default_path 1431else 1432return nil , 'no test paths provided' 1433end 1434end 1435 1436return opts 1437end 1438 1439--- Load a Lua chunk. 1440--- 1441--- Note: Tests run in the real global environment and import the "framework" explicitly 1442--- (`testutil.it()`, …), so we no longer inject it into the spec environment via `setfenv`. 1443--- @param path string 1444--- @return function?, string? 1445local function load_chunk ( path ) 1446return loadfile ( path ) 1447end 1448 1449--- Load a helper file before the test baseline is captured. 1450--- Helper files are preload-only: they may require modules, set defaults, 1451--- and register suite-end callbacks, but they do not define tests or hooks. 1452--- @param path string 1453--- @return boolean?, string? 1454local function load_helper ( path ) 1455local helper_path =normalize_path ( path ) 1456local chunk , err =load_chunk ( helper_path ) 1457if not chunk then 1458return nil , err 1459end 1460local ok , load_err =xpcall ( chunk , debug . traceback ) 1461if not ok then 1462return nil , load_err 1463end 1464 1465return true 1466end 1467 1468--- Evaluate a test file into a per-file root suite. 1469--- @param file test.harness.FileEntry 1470--- @param root_suite test.harness.Suite 1471--- @return test.harness.Suite, test.harness.Result? 1472local function evaluate_test_file ( file , root_suite ) 1473local file_suite =create_suite ( file . display_name , root_suite , { 1474short_src =file . display_name , 1475currentline =1 , 1476} , true ) 1477table . insert ( root_suite . children , file_suite ) 1478 1479state . current_define_suite =file_suite 1480local chunk , load_err =load_chunk ( file . path ) 1481if not chunk then 1482state . current_define_suite =nil 1483return file_suite , 1484{ 1485status ='error' , 1486message =load_err , 1487trace =parse_error_trace ( load_err , nil ), 1488} 1489end 1490 1491local ok , runtime_err =xpcall ( chunk , exception_handler ) 1492state . current_define_suite =nil 1493if not ok then 1494local load_error =decode_error ( runtime_err , 'error' ) 1495load_error . status ='error' 1496return file_suite , load_error 1497end 1498 1499return file_suite 1500end 1501 1502--- Run a single file in the current prepared runtime state. 1503--- @param file test.harness.FileEntry 1504--- @param reporter test.base_reporter 1505--- @param summary test.harness.RunSummary 1506--- @param opts test.harness.Options 1507--- @return boolean, boolean 1508local function run_test_file ( file , reporter , summary , opts ) 1509local root_suite =create_suite ( '' ) 1510local saved_suite_end_callbacks =vim . _copy ( state . suite_end_callbacks ) 1511 1512local file_suite , load_error =evaluate_test_file ( file , root_suite ) 1513 1514local selected_count =mark_selected ( root_suite , opts ) 1515 1516if load_error then 1517state . suite_end_callbacks =saved_suite_end_callbacks 1518elseif selected_count == 0 then 1519state . suite_end_callbacks =saved_suite_end_callbacks 1520return false , false 1521end 1522 1523--- @type test.reporter.FileElement 1524local file_element ={ name =file . display_name , duration =0 } 1525 1526--- @type test.harness.FileRunSummary 1527local file_summary ={ test_count =0 } 1528 1529reporter : file_start ( file_element ) 1530 1531local start =now_seconds () 1532local stop_requested =false 1533if load_error then 1534local status =run_synthetic_result ( 1535reporter , 1536summary , 1537file_summary , 1538file_suite , 1539'load' , 1540load_error , 1541load_error . trace 1542) 1543if status ~= 'success' and status ~= 'pending' and not opts . keep_going then 1544stop_requested =true 1545end 1546else 1547stop_requested =run_suite ( root_suite , reporter , summary , file_summary , opts ) 1548end 1549 1550file_element . duration =now_seconds () - start 1551summary . file_count =summary . file_count + 1 1552 1553reporter : file_end ( file_element , file_summary . test_count ) 1554 1555return true , stop_requested 1556end 1557 1558--- Aggregate outcome from running one suite iteration. 1559--- @class test.harness.IterationResult 1560--- @field ran_any boolean 1561--- @field stop_requested boolean 1562--- @field summary test.harness.RunSummary 1563 1564--- Run one full suite iteration across the selected files. 1565--- @param Reporter test.base_reporter 1566--- @param opts test.harness.Options 1567--- @param files test.harness.FileEntry[] 1568--- @param pre_helper_baseline test.harness.RuntimeBaseline 1569--- @param repeat_index integer 1570--- @return test.harness.IterationResult?, string? 1571local function run_iteration ( Reporter , opts , files , pre_helper_baseline , repeat_index ) 1572local reporter =Reporter . new ( { 1573paths =opts . paths , 1574verbose =opts . verbose , 1575summary_file =opts . summary_file , 1576} ) 1577--- @type test.harness.RunSummary 1578local summary ={ 1579file_count =0 , 1580result_count =0 , 1581test_count =0 , 1582success_count =0 , 1583skipped_count =0 , 1584failure_count =0 , 1585error_count =0 , 1586pendings ={} , 1587failures ={} , 1588errors ={} , 1589} 1590restore_runtime_baseline ( pre_helper_baseline ) 1591state . suite_end_callbacks ={} 1592if opts . helper then 1593local ok , err =load_helper ( opts . helper ) 1594if not ok then 1595return nil , err 1596end 1597end 1598--- @type test.harness.RuntimeBaseline 1599local file_baseline ={ 1600cwd =assert ( uv . cwd ()), 1601package_path =package . path , 1602package_cpath =package . cpath , 1603package_preload =vim . _copy ( package . preload ), 1604globals =vim . _copy ( _G ), 1605loaded =vim . _copy ( package . loaded ), 1606env =vim . _copy ( uv . os_environ ()), 1607arg =vim . _copy ( _G . arg or {} ), 1608} 1609reporter : suite_start ( repeat_index , opts . repeat_count ) 1610 1611local start_time =now_seconds () 1612local ran_any =false 1613local stop_requested =false 1614 1615for _ , file in ipairs ( files ) do 1616restore_runtime_baseline ( file_baseline ) 1617local ran_file , stop =run_test_file ( file , reporter , summary , opts ) 1618cleanup_runtime_baseline ( file_baseline ) 1619ran_any =ran_any or ran_file 1620if stop then 1621stop_requested =true 1622break 1623end 1624end 1625 1626local duration =now_seconds () - start_time 1627 1628run_suite_end_callbacks ( reporter , summary ) 1629cleanup_runtime_baseline ( file_baseline ) 1630 1631state . suite_end_callbacks ={} 1632 1633local failure_output 1634if summary . failure_count > 0 or summary . error_count > 0 then 1635failure_output =M . read_nvim_log ( nil , true ) 1636end 1637 1638reporter : suite_end ( duration , summary , failure_output ) 1639 1640return { 1641ran_any =ran_any , 1642stop_requested =stop_requested , 1643summary =summary , 1644} 1645end 1646 1647--- Run the test harness CLI entrypoint. 1648--- @param argv string[] 1649--- @return integer 1650function M . main ( argv ) 1651if os . getenv ( 'BUSTED_ARGS' ) ~= nil then 1652io . stderr : write ( '$BUSTED_ARGS is no longer supported; use $TEST_ARGS instead.\n' ) 1653return 1 1654end 1655 1656local opts , err =parse_args ( argv ) 1657if not opts then 1658io . stderr : write ( err .. '\n' ) 1659return 1 1660end 1661 1662if # opts . lpaths > 0 then 1663package . path =table . concat ( opts . lpaths , ';' ) .. ';' .. package . path 1664end 1665 1666if # opts . cpaths > 0 then 1667package . cpath =table . concat ( opts . cpaths , ';' ) .. ';' .. package . cpath 1668end 1669 1670--- @type test.harness.RuntimeBaseline 1671local pre_helper_baseline ={ 1672cwd =assert ( uv . cwd ()), 1673package_path =package . path , 1674package_cpath =package . cpath , 1675package_preload =vim . _copy ( package . preload ), 1676globals =vim . _copy ( _G ), 1677loaded =vim . _copy ( package . loaded ), 1678env =vim . _copy ( uv . os_environ ()), 1679arg =vim . _copy ( _G . arg or {} ), 1680} 1681local files ={} --- @type test.harness.FileEntry[] 1682local seen_files ={} --- @type table<string, boolean> 1683for _ , path in ipairs ( opts . paths ) do 1684local ok , collect_err =collect_test_files ( path , files , seen_files ) 1685if not ok then 1686io . stderr : write ( collect_err .. '\n' ) 1687return 1 1688end 1689end 1690 1691table . sort ( files , function ( a , b ) 1692return a . display_name < b . display_name 1693end ) 1694 1695if # files == 0 then 1696io . stderr : write ( 'No test files found.\n' ) 1697return 1 1698end 1699 1700local ReporterModule =require ( 'reporter' ) 1701local exit_code =0 1702local ran_any =false 1703for repeat_index =1 , opts . repeat_count do 1704local result , run_err = 1705run_iteration ( ReporterModule , opts , files , pre_helper_baseline , repeat_index ) 1706if not result then 1707io . stderr : write ( run_err .. '\n' ) 1708return 1 1709end 1710 1711ran_any =ran_any or result . ran_any 1712 1713if not result . ran_any and result . summary . result_count == 0 then 1714io . stderr : write ( 'No tests matched the current selection.\n' ) 1715exit_code =1 1716break 1717end 1718 1719if result . summary . failure_count > 0 or result . summary . error_count > 0 then 1720exit_code =1 1721end 1722 1723if result . stop_requested then 1724break 1725end 1726end 1727 1728if not ran_any then 1729exit_code =1 1730end 1731 1732return exit_code 1733end 1734 1735return M