robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
49.4 KiB1735 linesraw
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 = {
147  suite_end_callbacks = {},
148  current_define_suite = nil,
149  current_execution = nil,
150}
151
152--- Return the current wall-clock time in seconds.
153--- @return number
154local function now_seconds()
155  local sec, usec = assert(uv.gettimeofday())
156  return 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)
163  local any_provider = (name == nil)
164  assert(any_provider or name == 'github')
165  local github_actions = ((any_provider or name == 'github') and nil ~= os.getenv('GITHUB_ACTIONS'))
166  return 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)
174  local file = io.open(path, 'r')
175  if not file then
176    return nil
177  end
178
179  local lines = {}
180  for line in file:lines() do
181    lines[#lines + 1] = line
182    if #lines > keep then
183      table.remove(lines, 1)
184    end
185  end
186  file:close()
187  return 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)
196  logfile = logfile or os.getenv('NVIM_LOG_FILE') or 'nvim.log'
197  if not uv.fs_stat(logfile) then
198    return
199  end
200
201  local ci = M.is_ci()
202  local keep = ci and 100 or 10
203  local lines = read_tail_lines(logfile, keep) or {}
204  local separator = ('-'):rep(78)
205  local parts = {
206    separator,
207    '\n',
208    string.format('$NVIM_LOG_FILE: %s\n', logfile),
209    #lines > 0 and string.format('(last %d lines)\n', keep) or '(empty)\n',
210  }
211  for _, line in ipairs(lines) do
212    parts[#parts + 1] = line
213    parts[#parts + 1] = '\n'
214  end
215  if ci and ci_rename then
216    os.rename(logfile, logfile .. '.displayed')
217  end
218  parts[#parts + 1] = separator
219  parts[#parts + 1] = '\n'
220  return 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)
227  return 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)
234  path = normalize_path(path)
235  local relative = vim.fs.relpath('.', path)
236  if relative then
237    return relative
238  end
239  return 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)
249  unset = unset or function(k)
250    rawset(current, k, nil)
251  end
252  set = set or function(k, v)
253    rawset(current, k, v)
254  end
255  for k in pairs(current) do
256    if rawget(snapshot, k) == nil then
257      unset(k)
258    end
259  end
260  for k, v in pairs(snapshot) do
261    set(k, v)
262  end
263end
264
265--- Restore the process state to a captured baseline.
266--- @param baseline test.harness.RuntimeBaseline
267local function restore_runtime_baseline(baseline)
268  if uv.cwd() ~= baseline.cwd then
269    uv.chdir(baseline.cwd)
270  end
271
272  package.path = baseline.package_path
273  package.cpath = baseline.package_cpath
274  restore_snapshot(package.preload, baseline.package_preload)
275  restore_snapshot(package.loaded, baseline.loaded)
276  restore_snapshot(_G, baseline.globals)
277  restore_snapshot(uv.os_environ(), baseline.env, uv.os_unsetenv, uv.os_setenv)
278  _G.arg = vim._copy(baseline.arg)
279  state.current_define_suite = nil
280  state.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)
286  restore_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.
291  collectgarbage('collect')
292  collectgarbage('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)
302  return {
303    short_src = info and vim.fs.normalize(info.short_src or '') or '',
304    currentline = 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)
314  local frame = level or 3
315  local fallback
316
317  while true do
318    local info = debug.getinfo(frame, 'Sln')
319    if not info then
320      return trace_from_info(fallback)
321    end
322
323    fallback = fallback or info
324    if
325      info.what ~= 'C'
326      and info.source ~= harness_source
327      and info.short_src ~= '(tail call)'
328      and info.currentline > 0
329    then
330      return trace_from_info(info)
331    end
332
333    frame = frame + 1
334  end
335end
336
337--- Register a suite-end callback, deduplicated by callsite.
338--- @param callback fun()
339--- @return fun()
340function M.on_suite_end(callback)
341  assert(type(callback) == 'function', 'on_suite_end() expects a function')
342  local trace = caller_trace(3)
343  local caller_info = debug.getinfo(2, 'S')
344  local key_source = caller_info and caller_info.source
345  if type(key_source) == 'string' and vim.startswith(key_source, '@') then
346    key_source = vim.fs.normalize(key_source:sub(2))
347  else
348    key_source = trace.short_src
349  end
350  local key = ('%s:%d'):format(key_source, trace.currentline)
351  for _, registration in ipairs(state.suite_end_callbacks) do
352    if registration.key == key then
353      return registration.fn
354    end
355  end
356  table.insert(state.suite_end_callbacks, {
357    fn = callback,
358    trace = trace,
359    key = key,
360  })
361  return 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)
371  return {
372    kind = 'suite',
373    name = name or '',
374    parent = parent,
375    trace = trace,
376    is_file = is_file or false,
377    hooks = {
378      setup = {},
379      teardown = {},
380      before_each = {},
381      after_each = {},
382    },
383    children = {},
384    selected_count = 0,
385  }
386end
387
388--- Return the suite currently receiving test definitions.
389--- @return test.harness.Suite
390local function current_suite()
391  assert(state.current_define_suite, 'test definition is not active')
392  return 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()
399  return 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)
408  assert(type(name) == 'string' and name ~= '', 'test name must be a non-empty string')
409  if fn ~= nil then
410    assert(type(fn) == 'function', 'test body must be a function')
411  end
412  local retries = opts and opts.retries or 0
413  assert(type(retries) == 'number' and retries >= 0, 'retries must be a non-negative number')
414
415  local suite = current_suite()
416  local test = {
417    kind = 'test',
418    name = name,
419    fn = fn,
420    parent = suite,
421    trace = caller_trace(3),
422    pending_message = pending_message,
423    retries = retries,
424  }
425  table.insert(suite.children, test)
426  return 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)
433  return function(fn)
434    assert(type(fn) == 'function', ('%s expects a function'):format(kind))
435    table.insert(current_suite().hooks[kind], {
436      fn = fn,
437      trace = caller_trace(3),
438    })
439  end
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)
454  assert(type(name) == 'string', 'describe() expects a string')
455  assert(type(fn) == 'function', 'describe() expects a function body')
456
457  local parent = current_suite()
458  local suite = create_suite(name, parent, caller_trace(3), false)
459  table.insert(parent.children, suite)
460
461  local previous_define_suite = state.current_define_suite
462  state.current_define_suite = suite
463  local ok, err = xpcall(fn, debug.traceback)
464  state.current_define_suite = previous_define_suite
465
466  if not ok then
467    error(err, 0)
468  end
469
470  return 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)
484  if type(opts) == 'function' then
485    opts, fn = nil, opts
486  end
487  assert(opts == nil or type(opts) == 'table', 'it() arg 2 must be an opts table or a function')
488  return 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)
502  if state.current_execution then
503    error({
504      __harness_pending = true,
505      message = name or 'pending',
506    }, 0)
507  end
508  local pending_message = type(block) == 'string' and block or nil
509  register_test(name or 'pending', nil, pending_message)
510  return false
511end
512
513--- Register a finalizer to run after the current test body.
514--- @param fn fun()
515function M.finally(fn)
516  assert(type(fn) == 'function', 'finally() expects a function')
517  assert(
518    state.current_execution and state.current_execution.scope == 'test',
519    'finally() must be called while a test body is running'
520  )
521  table.insert(state.current_execution.finalizers, {
522    fn = fn,
523    trace = 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)
531  if type(err) == 'string' then
532    return err
533  end
534
535  local ok, inspected = pcall(vim.inspect, err)
536  if ok then
537    return inspected
538  end
539
540  return 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)
547  if type(text) ~= 'string' then
548    return
549  end
550
551  local src, line = text:match('^(.+):(%d+):')
552  if not src or not line then
553    return
554  end
555
556  return {
557    short_src = vim.fs.normalize(src),
558    currentline = tonumber(line) or 0,
559  }
560end
561
562--- @param source string
563--- @param candidate string
564--- @return boolean
565local function source_matches(source, candidate)
566  if source == candidate then
567    return true
568  end
569
570  local tail = source:match('^%.%.%.(.+)$')
571  return 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)
578  if left == nil or right == nil then
579    return false
580  end
581  return source_matches(left.short_src, right.short_src)
582    or 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)
590  if type(message) == 'string' then
591    local first_line = message:match('^[^\n]+')
592    local trace = parse_trace_line(first_line)
593    if trace then
594      return trace
595    end
596
597    local load_path = first_line
598      and first_line:match("^error loading module .+ from file '([^']+)':$")
599    if load_path == nil and first_line then
600      load_path = first_line:match('^error loading module .+ from file "([^"]+)":$')
601    end
602    if load_path then
603      local detail_line = message:match('\n([^\n]+)')
604      trace = parse_trace_line(detail_line and detail_line:gsub('^%s+', ''))
605      local load_trace = {
606        short_src = vim.fs.normalize(load_path),
607        currentline = 0,
608      }
609      if trace and same_trace_source(trace, load_trace) then
610        return trace
611      end
612    end
613  end
614
615  if type(traceback) == 'string' then
616    for line in traceback:gmatch('[^\n]+') do
617      local trace = parse_trace_line(line:gsub('^%s+', ''))
618      if trace then
619        return trace
620      end
621    end
622  end
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)
630  local lines = {}
631
632  for level = 3, math.huge do
633    local info = debug.getinfo(level, 'Sln')
634    if not info then
635      break
636    end
637
638    if info.source == framework_source then
639      break
640    end
641
642    if (info.what == 'Lua' or info.what == 'main') and info.source ~= assert_source then
643      local trace = trace_from_info(info)
644      if trace.currentline > 0 and trace.short_src ~= '' then
645        local location = ('%s:%d'):format(trace.short_src, trace.currentline)
646        if info.what == 'main' then
647          lines[#lines + 1] = ('\t%s: in main chunk'):format(location)
648        elseif info.name and info.name ~= '' then
649          lines[#lines + 1] = ("\t%s: in function '%s'"):format(location, info.name)
650        elseif (info.linedefined or 0) > 0 then
651          lines[#lines + 1] = ('\t%s: in function <%s:%d>'):format(
652            location,
653            trace.short_src,
654            info.linedefined
655          )
656        else
657          lines[#lines + 1] = ('\t%s: in function ?'):format(location)
658        end
659      end
660    end
661  end
662
663  if #lines == 0 then
664    return
665  end
666
667  return '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)
674  if type(err) == 'table' and err.__harness_pending then
675    --- @cast err test.harness.ErrorPayload
676    return err
677  end
678
679  local message = M.format_error_value(err)
680  local raw_traceback = debug.traceback('', 2)
681  return {
682    message = message,
683    trace = parse_error_trace(message, raw_traceback),
684    traceback = 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)
693  return {
694    status = err.__harness_pending and 'pending' or fallback_status or 'failure',
695    message = err.message,
696    traceback = err.traceback,
697    trace = 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)
707  local previous_execution = state.current_execution
708  --- @type test.harness.Execution
709  local execution = {
710    scope = scope,
711    finalizers = {},
712  }
713  state.current_execution = execution
714
715  -- Note: xpcall variadic args not supported by Lua 5.1.
716  local ok, err = xpcall(function()
717    return callable.fn(ctx)
718  end, exception_handler)
719  local finalizer_err
720  local finalizer_trace
721  for i = #execution.finalizers, 1, -1 do
722    local finalizer = execution.finalizers[i]
723    local finalizer_ok, ferr = xpcall(finalizer.fn, exception_handler)
724    if not finalizer_ok and not finalizer_err then
725      finalizer_err = ferr
726      finalizer_trace = finalizer.trace
727    end
728  end
729
730  state.current_execution = previous_execution
731
732  local result = ok and { status = 'success' } or decode_error(err, fallback_status)
733  local report_trace = not ok and callable.trace or nil
734  if not finalizer_err then
735    return result, report_trace
736  end
737
738  local finalizer_result = decode_error(finalizer_err, 'error')
739  if result.status == 'success' then
740    finalizer_result.status = 'error'
741    return finalizer_result, finalizer_trace
742  end
743
744  if result.status == 'pending' then
745    return {
746      status = 'error',
747      message = ('finally: %s'):format(finalizer_result.message),
748      traceback = finalizer_result.traceback,
749      trace = finalizer_result.trace,
750    },
751      finalizer_trace
752  end
753
754  result.message = result.message .. '\n\nfinally: ' .. finalizer_result.message
755  if not result.traceback then
756    result.traceback = finalizer_result.traceback
757  end
758  if not result.trace then
759    result.trace = finalizer_result.trace
760  end
761  return 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)
770  if same_trace_source(trace, fallback) then
771    return trace
772  end
773  return 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)
780  local parts = {}
781  local node = element
782  while node do
783    if node.kind == 'test' and node.name ~= '' then
784      table.insert(parts, 1, node.name)
785    elseif node.kind == 'suite' and not node.is_file and node.name ~= '' then
786      table.insert(parts, 1, node.name)
787    end
788    node = node.parent
789  end
790  return 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)
797  return 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)
805  test.full_name = M.get_full_name(test)
806
807  if #opts.tags > 0 then
808    local tagged = false
809    for tag in test.full_name:gmatch('#([%w_%-]+)') do
810      if vim.list_contains(opts.tags, tag) then
811        tagged = true
812        break
813      end
814    end
815
816    if not tagged then
817      return false
818    end
819  end
820
821  if opts.filter and not test.full_name:match(opts.filter) then
822    return false
823  end
824
825  for _, filter_out in ipairs(opts.filter_out) do
826    if test.full_name:match(filter_out) then
827      return false
828    end
829  end
830
831  return 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)
839  local selected_count = 0
840  for _, child in ipairs(node.children) do
841    if child.kind == 'suite' then
842      selected_count = selected_count + mark_selected(child, opts)
843    else
844      --- @cast child test.harness.Test
845      child.selected = test_selected(child, opts)
846      if child.selected then
847        selected_count = selected_count + 1
848      end
849    end
850  end
851
852  node.selected_count = selected_count
853  return 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)
860  local hooks = {}
861  if suite.parent then
862    vim.list_extend(hooks, gather_before_each(suite.parent))
863  end
864  for _, hook in ipairs(suite.hooks.before_each) do
865    hooks[#hooks + 1] = hook
866  end
867  return 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)
874  local hooks = {}
875  for _, hook in ipairs(suite.hooks.after_each) do
876    hooks[#hooks + 1] = hook
877  end
878  if suite.parent then
879    vim.list_extend(hooks, gather_after_each(suite.parent))
880  end
881  return 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)
917  return {
918    name = name,
919    status = result.status,
920    trace = trace,
921    duration = duration,
922    message = result.message,
923    traceback = 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)
933  summary.result_count = summary.result_count + 1
934  if count_as_test ~= false then
935    summary.test_count = summary.test_count + 1
936    if file_summary then
937      file_summary.test_count = file_summary.test_count + 1
938    end
939  end
940
941  if record.status == 'success' then
942    summary.success_count = summary.success_count + 1
943  elseif record.status == 'pending' then
944    summary.skipped_count = summary.skipped_count + 1
945    table.insert(summary.pendings, record)
946  elseif record.status == 'failure' then
947    summary.failure_count = summary.failure_count + 1
948    table.insert(summary.failures, record)
949  else -- error
950    summary.error_count = summary.error_count + 1
951    table.insert(summary.errors, record)
952  end
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)
965  local name = M.get_full_name(parent)
966  if name == '' then
967    name = parent.name ~= '' and parent.name or 'suite'
968  end
969  name = ('%s [%s]'):format(name, phase)
970  local record_trace = trace or result.trace or parent.trace
971  local record = build_record(name, result, record_trace, 0)
972  reporter:test_start(record.name)
973  record_result(summary, file_summary, record, false)
974  reporter:test_end(record)
975  return 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)
983  local suite_end_callbacks = vim._copy(state.suite_end_callbacks)
984  local callback_failed = false
985
986  for index, callback in ipairs(suite_end_callbacks) do
987    local result, report_trace = run_callable('suite_end', callback, 'error')
988    if result.status ~= 'success' then
989      callback_failed = true
990      result.status = 'error'
991      local name = ('[suite_end %d]'):format(index)
992      local record_trace = summary_trace(result.trace, report_trace or callback.trace)
993      local record = build_record(name, result, record_trace, 0)
994      reporter:test_start(record.name)
995      record_result(summary, nil, record, false)
996      reporter:test_end(record)
997    end
998  end
999
1000  return 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)
1010  local name = test.full_name or M.get_full_name(test)
1011
1012  local start_time = now_seconds()
1013  --- @type test.harness.Result
1014  local result
1015  local report_trace = test.trace
1016  if test.fn == nil then
1017    reporter:test_start(name)
1018    result = {
1019      status = 'pending',
1020      message = test.pending_message,
1021    }
1022  else
1023    local attempt = 0
1024    repeat
1025      attempt = attempt + 1
1026      --- @type test.harness.Context
1027      local ctx = { retry = attempt - 1 }
1028      result = { status = 'success' }
1029
1030      for _, hook in ipairs(gather_before_each(test.parent)) do
1031        result, report_trace = run_callable('before_each', hook, 'failure')
1032        if result.status ~= 'success' then
1033          break
1034        end
1035      end
1036
1037      if attempt == 1 then
1038        reporter:test_start(name)
1039      end
1040
1041      if result.status == 'success' then
1042        result, report_trace =
1043          run_callable('test', { fn = test.fn, trace = test.trace }, 'failure', ctx)
1044      end
1045
1046      for _, hook in ipairs(gather_after_each(test.parent)) do
1047        local hook_result, hook_trace = run_callable('after_each', hook, 'failure')
1048        if result.status == 'success' then
1049          result = hook_result
1050          report_trace = hook_trace
1051        elseif hook_result.status ~= 'success' then
1052          local hook_report_trace = hook_trace or hook.trace
1053          result.message = (result.message or '')
1054            .. (result.message and result.message ~= '' and '\n\n' or '')
1055            .. 'after_each: '
1056            .. hook_result.message
1057          if not result.traceback then
1058            result.traceback = hook_result.traceback
1059          end
1060          if not result.trace then
1061            result.trace = hook_result.trace
1062          end
1063          if result.status == 'pending' then
1064            result.status = 'error'
1065            report_trace = hook_report_trace
1066          elseif not report_trace then
1067            report_trace = hook_report_trace
1068          end
1069        end
1070      end
1071      -- check for interrupts
1072      vim.wait(0)
1073    until result.status == 'success' or attempt > test.retries
1074  end
1075
1076  test.duration = now_seconds() - start_time
1077  local record = build_record(
1078    name,
1079    result,
1080    summary_trace(result.trace, report_trace or test.trace),
1081    test.duration
1082  )
1083  record_result(summary, file_summary, record)
1084  reporter:test_end(record)
1085  return 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)
1096  if suite.selected_count == 0 then
1097    return false
1098  end
1099
1100  local stop_requested = false
1101  local run_children = true
1102
1103  -- Run setup() hooks
1104  for _, hook in ipairs(suite.hooks.setup) do
1105    local result = run_callable('setup', hook, 'error')
1106    if result.status ~= 'success' then
1107      run_synthetic_result(reporter, summary, file_summary, suite, 'setup', result, hook.trace)
1108      run_children = false
1109      if result.status ~= 'pending' and not opts.keep_going then
1110        stop_requested = true
1111      end
1112      break
1113    end
1114  end
1115
1116  if run_children and not stop_requested then
1117    for _, child in ipairs(suite.children) do
1118      if child.kind == 'suite' then
1119        stop_requested = run_suite(child, reporter, summary, file_summary, opts) or stop_requested
1120      elseif child.selected then
1121        local status = run_test(child, reporter, summary, file_summary)
1122        if status ~= 'success' and status ~= 'pending' and not opts.keep_going then
1123          stop_requested = true
1124        end
1125      end
1126
1127      if stop_requested then
1128        break
1129      end
1130    end
1131  end
1132
1133  -- Run teardown() hooks
1134  for _, hook in ipairs(suite.hooks.teardown) do
1135    local result = run_callable('teardown', hook, 'error')
1136    if result.status ~= 'success' then
1137      run_synthetic_result(reporter, summary, file_summary, suite, 'teardown', result, hook.trace)
1138      if result.status ~= 'pending' and not opts.keep_going then
1139        stop_requested = true
1140      end
1141    end
1142  end
1143
1144  return 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
1154  local function add_test_file(file)
1155    local abs_file = normalize_path(file)
1156    if seen_files[abs_file] then
1157      return
1158    end
1159
1160    seen_files[abs_file] = true
1161    files[#files + 1] = {
1162      path = abs_file,
1163      display_name = display_path(abs_file),
1164    }
1165  end
1166
1167  local abs = normalize_path(path)
1168  local stat = uv.fs_stat(abs)
1169  if not stat then
1170    return nil, ('test path not found: %s'):format(path)
1171  end
1172
1173  if stat.type == 'file' then
1174    add_test_file(abs)
1175    return true
1176  end
1177
1178  if stat.type ~= 'directory' then
1179    return nil, ('unsupported test path: %s'):format(path)
1180  end
1181
1182  for _, file in
1183    ipairs(vim.fs.find(function(name)
1184      return name:match('_spec%.lua$') ~= nil
1185    end, {
1186      path = abs,
1187      type = 'file',
1188      limit = math.huge,
1189    }))
1190  do
1191    add_test_file(file)
1192  end
1193
1194  return 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
1202  local opts = {
1203    keep_going = true,
1204    verbose = false,
1205    repeat_count = 1,
1206    summary_file = '-',
1207    tags = {},
1208    filter_out = {},
1209    lpaths = {},
1210    cpaths = {},
1211    paths = {},
1212  }
1213
1214  --- @type table<string, boolean>
1215  local seen_tags = {}
1216
1217  --- @param flag string
1218  --- @return nil, string
1219  local function missing_value(flag)
1220    return nil, 'missing value for ' .. flag
1221  end
1222
1223  --- Parse and validate the `--repeat` argument.
1224  --- @param value? string
1225  --- @return integer?, string?
1226  local function parse_repeat_count(value)
1227    if type(value) ~= 'string' or value == '' then
1228      return missing_value('--repeat')
1229    end
1230
1231    local count = tonumber(value)
1232    if count == nil or count < 1 or count ~= math.floor(count) then
1233      return nil, ('invalid value for --repeat: %s'):format(value)
1234    end
1235    --- @cast count integer
1236
1237    return count
1238  end
1239
1240  --- @type table<string, fun()>
1241  local switch_options = {
1242    ['-v'] = function()
1243      opts.verbose = true
1244    end,
1245    ['--verbose'] = function()
1246      opts.verbose = true
1247    end,
1248    ['--no-keep-going'] = function()
1249      opts.keep_going = false
1250    end,
1251  }
1252
1253  --- @param flag string
1254  --- @param value string
1255  --- @return string?, string?
1256  local function require_nonempty(flag, value)
1257    if value == '' then
1258      return missing_value(flag)
1259    end
1260    return value
1261  end
1262
1263  --- @param setter fun(value: any)
1264  --- @return fun(value: any): boolean?, string?
1265  local function set_value(setter)
1266    return function(value)
1267      setter(value)
1268      return true
1269    end
1270  end
1271
1272  --- @param parse fun(value: string): any?, string?
1273  --- @param setter fun(value: any)
1274  --- @return fun(value: string): boolean?, string?
1275  local function set_parsed_value(parse, setter)
1276    return function(value)
1277      local parsed, err = parse(value)
1278      if parsed == nil then
1279        return nil, err
1280      end
1281      setter(parsed)
1282      return true
1283    end
1284  end
1285
1286  --- @param flag string
1287  --- @param setter fun(value: string)
1288  --- @return fun(value: string): boolean?, string?
1289  local function set_nonempty_value(flag, setter)
1290    return set_parsed_value(function(value)
1291      return require_nonempty(flag, value)
1292    end, setter)
1293  end
1294
1295  --- Validate that a filter option contains a valid Lua pattern.
1296  --- @param flag string
1297  --- @param value string
1298  --- @return string?, string?
1299  local function validate_pattern(flag, value)
1300    local ok, err = pcall(string.match, '', value)
1301    if not ok then
1302      local message = tostring(err)
1303      local detail = message:match('malformed pattern.*') or message
1304      return nil, ('invalid value for %s: %s'):format(flag, detail)
1305    end
1306    return value
1307  end
1308
1309  --- @param flag string
1310  --- @param setter fun(value: string)
1311  --- @return fun(value: string): boolean?, string?
1312  local function set_pattern_value(flag, setter)
1313    return set_parsed_value(function(value)
1314      return validate_pattern(flag, value)
1315    end, setter)
1316  end
1317
1318  --- @param values string[]
1319  --- @return fun(value: string): boolean?, string?
1320  local function append_value(values)
1321    return set_value(function(value)
1322      table.insert(values, value)
1323    end)
1324  end
1325
1326  --- @type table<string, fun(value: string): boolean?, string?>
1327  local value_options = {
1328    ['--repeat'] = set_parsed_value(parse_repeat_count, function(count)
1329      opts.repeat_count = count
1330    end),
1331    ['--helper'] = set_nonempty_value('--helper', function(value)
1332      opts.helper = value
1333    end),
1334    ['--summary-file'] = set_nonempty_value('--summary-file', function(value)
1335      opts.summary_file = value
1336    end),
1337    ['--tags'] = function(value)
1338      for token in value:gmatch('[^,%s]+') do
1339        local tag = token:gsub('^#', '')
1340        if tag ~= '' and not seen_tags[tag] then
1341          seen_tags[tag] = true
1342          table.insert(opts.tags, tag)
1343        end
1344      end
1345      return true
1346    end,
1347    ['--filter'] = set_pattern_value('--filter', function(pattern)
1348      opts.filter = pattern
1349    end),
1350    ['--filter-out'] = set_pattern_value('--filter-out', function(pattern)
1351      table.insert(opts.filter_out, pattern)
1352    end),
1353    ['--lpath'] = append_value(opts.lpaths),
1354    ['--cpath'] = append_value(opts.cpaths),
1355    ['--default-path'] = set_nonempty_value('--default-path', function(path)
1356      opts.default_path = path
1357    end),
1358  }
1359
1360  local i = 1
1361
1362  --- @param arg string
1363  --- @return string, string?
1364  local function split_option(arg)
1365    local eq = arg:find('=', 1, true)
1366    if not eq then
1367      return arg, nil
1368    end
1369    return arg:sub(1, eq - 1), arg:sub(eq + 1)
1370  end
1371
1372  --- Consume the next argv item as the value for `flag`.
1373  --- @param flag string
1374  --- @return string?, string?
1375  local function take_value(flag)
1376    i = i + 1
1377    local value = argv[i]
1378    if type(value) ~= 'string' then
1379      return missing_value(flag)
1380    end
1381    return value
1382  end
1383
1384  --- Parse one named option and apply it to `opts`.
1385  --- @param arg string
1386  --- @return boolean, string?
1387  local function apply_named_option(arg)
1388    local switch_handler = switch_options[arg]
1389    if switch_handler then
1390      switch_handler()
1391      return true
1392    end
1393
1394    local flag, value = split_option(arg)
1395    local handler = value_options[flag]
1396    if handler then
1397      if value == nil then
1398        local err
1399        value, err = take_value(flag)
1400        if not value then
1401          return false, err
1402        end
1403      end
1404      local ok, handler_err = handler(value)
1405      if not ok then
1406        return false, handler_err
1407      end
1408      return true
1409    end
1410
1411    return false
1412  end
1413
1414  while i <= #argv do
1415    local arg = assert(argv[i])
1416    local handled, err = apply_named_option(arg)
1417    if handled then
1418    elseif err then
1419      return nil, err
1420    elseif vim.startswith(arg, '-') then
1421      return nil, 'unknown test harness option: ' .. arg
1422    else
1423      opts.paths[#opts.paths + 1] = arg
1424    end
1425    i = i + 1
1426  end
1427
1428  if #opts.paths == 0 then
1429    if opts.default_path then
1430      opts.paths[1] = opts.default_path
1431    else
1432      return nil, 'no test paths provided'
1433    end
1434  end
1435
1436  return 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)
1446  return 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)
1455  local helper_path = normalize_path(path)
1456  local chunk, err = load_chunk(helper_path)
1457  if not chunk then
1458    return nil, err
1459  end
1460  local ok, load_err = xpcall(chunk, debug.traceback)
1461  if not ok then
1462    return nil, load_err
1463  end
1464
1465  return 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)
1473  local file_suite = create_suite(file.display_name, root_suite, {
1474    short_src = file.display_name,
1475    currentline = 1,
1476  }, true)
1477  table.insert(root_suite.children, file_suite)
1478
1479  state.current_define_suite = file_suite
1480  local chunk, load_err = load_chunk(file.path)
1481  if not chunk then
1482    state.current_define_suite = nil
1483    return file_suite,
1484      {
1485        status = 'error',
1486        message = load_err,
1487        trace = parse_error_trace(load_err, nil),
1488      }
1489  end
1490
1491  local ok, runtime_err = xpcall(chunk, exception_handler)
1492  state.current_define_suite = nil
1493  if not ok then
1494    local load_error = decode_error(runtime_err, 'error')
1495    load_error.status = 'error'
1496    return file_suite, load_error
1497  end
1498
1499  return 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)
1509  local root_suite = create_suite('')
1510  local saved_suite_end_callbacks = vim._copy(state.suite_end_callbacks)
1511
1512  local file_suite, load_error = evaluate_test_file(file, root_suite)
1513
1514  local selected_count = mark_selected(root_suite, opts)
1515
1516  if load_error then
1517    state.suite_end_callbacks = saved_suite_end_callbacks
1518  elseif selected_count == 0 then
1519    state.suite_end_callbacks = saved_suite_end_callbacks
1520    return false, false
1521  end
1522
1523  --- @type test.reporter.FileElement
1524  local file_element = { name = file.display_name, duration = 0 }
1525
1526  --- @type test.harness.FileRunSummary
1527  local file_summary = { test_count = 0 }
1528
1529  reporter:file_start(file_element)
1530
1531  local start = now_seconds()
1532  local stop_requested = false
1533  if load_error then
1534    local status = run_synthetic_result(
1535      reporter,
1536      summary,
1537      file_summary,
1538      file_suite,
1539      'load',
1540      load_error,
1541      load_error.trace
1542    )
1543    if status ~= 'success' and status ~= 'pending' and not opts.keep_going then
1544      stop_requested = true
1545    end
1546  else
1547    stop_requested = run_suite(root_suite, reporter, summary, file_summary, opts)
1548  end
1549
1550  file_element.duration = now_seconds() - start
1551  summary.file_count = summary.file_count + 1
1552
1553  reporter:file_end(file_element, file_summary.test_count)
1554
1555  return 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)
1572  local reporter = Reporter.new({
1573    paths = opts.paths,
1574    verbose = opts.verbose,
1575    summary_file = opts.summary_file,
1576  })
1577  --- @type test.harness.RunSummary
1578  local summary = {
1579    file_count = 0,
1580    result_count = 0,
1581    test_count = 0,
1582    success_count = 0,
1583    skipped_count = 0,
1584    failure_count = 0,
1585    error_count = 0,
1586    pendings = {},
1587    failures = {},
1588    errors = {},
1589  }
1590  restore_runtime_baseline(pre_helper_baseline)
1591  state.suite_end_callbacks = {}
1592  if opts.helper then
1593    local ok, err = load_helper(opts.helper)
1594    if not ok then
1595      return nil, err
1596    end
1597  end
1598  --- @type test.harness.RuntimeBaseline
1599  local file_baseline = {
1600    cwd = assert(uv.cwd()),
1601    package_path = package.path,
1602    package_cpath = package.cpath,
1603    package_preload = vim._copy(package.preload),
1604    globals = vim._copy(_G),
1605    loaded = vim._copy(package.loaded),
1606    env = vim._copy(uv.os_environ()),
1607    arg = vim._copy(_G.arg or {}),
1608  }
1609  reporter:suite_start(repeat_index, opts.repeat_count)
1610
1611  local start_time = now_seconds()
1612  local ran_any = false
1613  local stop_requested = false
1614
1615  for _, file in ipairs(files) do
1616    restore_runtime_baseline(file_baseline)
1617    local ran_file, stop = run_test_file(file, reporter, summary, opts)
1618    cleanup_runtime_baseline(file_baseline)
1619    ran_any = ran_any or ran_file
1620    if stop then
1621      stop_requested = true
1622      break
1623    end
1624  end
1625
1626  local duration = now_seconds() - start_time
1627
1628  run_suite_end_callbacks(reporter, summary)
1629  cleanup_runtime_baseline(file_baseline)
1630
1631  state.suite_end_callbacks = {}
1632
1633  local failure_output
1634  if summary.failure_count > 0 or summary.error_count > 0 then
1635    failure_output = M.read_nvim_log(nil, true)
1636  end
1637
1638  reporter:suite_end(duration, summary, failure_output)
1639
1640  return {
1641    ran_any = ran_any,
1642    stop_requested = stop_requested,
1643    summary = summary,
1644  }
1645end
1646
1647--- Run the test harness CLI entrypoint.
1648--- @param argv string[]
1649--- @return integer
1650function M.main(argv)
1651  if os.getenv('BUSTED_ARGS') ~= nil then
1652    io.stderr:write('$BUSTED_ARGS is no longer supported; use $TEST_ARGS instead.\n')
1653    return 1
1654  end
1655
1656  local opts, err = parse_args(argv)
1657  if not opts then
1658    io.stderr:write(err .. '\n')
1659    return 1
1660  end
1661
1662  if #opts.lpaths > 0 then
1663    package.path = table.concat(opts.lpaths, ';') .. ';' .. package.path
1664  end
1665
1666  if #opts.cpaths > 0 then
1667    package.cpath = table.concat(opts.cpaths, ';') .. ';' .. package.cpath
1668  end
1669
1670  --- @type test.harness.RuntimeBaseline
1671  local pre_helper_baseline = {
1672    cwd = assert(uv.cwd()),
1673    package_path = package.path,
1674    package_cpath = package.cpath,
1675    package_preload = vim._copy(package.preload),
1676    globals = vim._copy(_G),
1677    loaded = vim._copy(package.loaded),
1678    env = vim._copy(uv.os_environ()),
1679    arg = vim._copy(_G.arg or {}),
1680  }
1681  local files = {} --- @type test.harness.FileEntry[]
1682  local seen_files = {} --- @type table<string, boolean>
1683  for _, path in ipairs(opts.paths) do
1684    local ok, collect_err = collect_test_files(path, files, seen_files)
1685    if not ok then
1686      io.stderr:write(collect_err .. '\n')
1687      return 1
1688    end
1689  end
1690
1691  table.sort(files, function(a, b)
1692    return a.display_name < b.display_name
1693  end)
1694
1695  if #files == 0 then
1696    io.stderr:write('No test files found.\n')
1697    return 1
1698  end
1699
1700  local ReporterModule = require('reporter')
1701  local exit_code = 0
1702  local ran_any = false
1703  for repeat_index = 1, opts.repeat_count do
1704    local result, run_err =
1705      run_iteration(ReporterModule, opts, files, pre_helper_baseline, repeat_index)
1706    if not result then
1707      io.stderr:write(run_err .. '\n')
1708      return 1
1709    end
1710
1711    ran_any = ran_any or result.ran_any
1712
1713    if not result.ran_any and result.summary.result_count == 0 then
1714      io.stderr:write('No tests matched the current selection.\n')
1715      exit_code = 1
1716      break
1717    end
1718
1719    if result.summary.failure_count > 0 or result.summary.error_count > 0 then
1720      exit_code = 1
1721    end
1722
1723    if result.stop_requested then
1724      break
1725    end
1726  end
1727
1728  if not ran_any then
1729    exit_code = 1
1730  end
1731
1732  return exit_code
1733end
1734
1735return M