Skip to content

Testing Tua

Use tua test to check and compile your project, run its unit tests with Busted, and report failures against Tua source. Tests use normal Busted functions and Lua assertions; Tua adds the build and source-map integration, not a new test syntax.

Pure functions, data transformations, and classes are easiest to test. Code that calls LOVE needs test doubles or a separate game/runtime test; Busted runs under a Lua interpreter and does not create a LOVE window or graphics context.

Install The Backend

Install Lua/LuaJIT, LuaRocks, and Busted for the interpreter you plan to use:

luarocks install busted
busted --version

Busted and its dependencies are external tools, not bundled into Tua or the VSIX. Tua does not download them when tests run. Ensure the terminal or VS Code process can find busted on PATH, or select the executable explicitly:

tua test --busted /path/to/busted

TUA_BUSTED also selects the executable; --busted takes precedence. A bare name is resolved on PATH; a relative executable path such as ./tools/busted is resolved from the project root. To choose another installed Lua runtime:

tua test --lua luajit

Busted and any Lua modules or native dependencies must be installed for that interpreter. This integration is exercised with Busted 2.3.0.

Write A Typed Spec

Create a module under the configured source root (normally src/):

src/mathlib.tua
local function double(value: number): number
  return value * 2
end

return { double = double }

For a dedicated test directory, configure a project-relative root:

[test]
source = "tests"

In VS Code, right-click inside a function in a saved .tua file and choose Tua: Create Unit Test for Function. Tua creates a matching *_spec file under [test].source, preserving the source file's subdirectory, opens it, and adds a pending Busted example with a commented module import ready to extend. If no test source is configured, the project source directory is used. Existing specs are opened instead of overwritten.

The generated placeholder does not load the module. It should report one pending test until you arrange dependencies, enable the import, and replace pending(...) with assertions. Module imports can execute code immediately: a LOVE asset loader at module scope needs LOVE even when the test body is pending. Set up LOVE or dependency test doubles before require, and restore changed globals/module-cache entries after the test. To exercise real graphics, use a test running inside LOVE; tua test does not provide a LOVE runtime.

Then create a spec ending in _spec.tua:

tests/math_spec.tua
local mathlib = require("mathlib")

describe("mathlib #unit", function()
  it("doubles a number", function()
    local result: number = mathlib.double(3)
    assert.equals(6, result)
  end)
end)

Run from the project folder containing tua.toml:

tua test

Busted prints its test summary. Assertion failures, runtime errors, compiler errors, and an unavailable backend make the command fail with a nonzero exit status. No discovered spec files is also an error. Tua never runs stale output when the current test build has errors.

Configured test sources receive built-in Busted and LuaAssert types in checking and editor features, including DSL functions, hooks, common assertions, and spy, stub, mock, and match helpers. This works for both .tua and .lua specs. With [test] source configured, files under that root receive the types; otherwise, _spec files under the source root receive them. The declarations improve diagnostics, completion, hover, and signature help; they do not install Busted or add runtime functions. Plugin-specific APIs and custom matchers may need project declarations. Use ordinary Tua types in the functions and classes under test.

diagnostics.globals remains useful for Busted names in other files, but it only permits names and does not provide Busted-specific signatures.

Select Tests

With [test] source = "tests", Tua discovers specs recursively under that project-relative directory. Without it, discovery uses the normal source root. Both *_spec.tua and *_spec.lua work; a custom Tua extension follows extension in tua.toml. Declaration-only libraries and build/state directories are excluded from test discovery.

An optional file or directory is relative to the test discovery root:

tua test math_spec.tua
tua test .
tua test --filter doubles
tua test --tags unit

--filter uses Busted's Lua-pattern name filter; --tags passes the requested tags to Busted. Filtering happens after discovery, and Busted may report zero executed tests when a filter matches nothing. The project is still compiled together with the entire test root when selecting one spec, so errors in another Tua source can block that run.

Use Busted's standard hooks, assertions, spies, and mocks inside specs. See the upstream reference for their APIs. The command currently exposes executable, interpreter, name-filter, and tag selection rather than forwarding every Busted CLI option.

Discover Tests And Export Results

tua test --list
tua test --report test-results.json

--list returns versioned JSON with absolute file paths, source-root-relative selectors, parse errors, statically discovered cases and nested suites. It does not compile, run Busted, execute specs or create test output. Literal, unshadowed describe/context and it/pending registrations include full names and one-based source positions. Escaped literal names use Lua string decoding. Dynamic names and aliased registration functions remain runnable at file level; discovery does not claim they are absent.

--report PATH preserves terminal output and writes JSON containing completion and success flags, captured output, and passed/failed/errored/skipped cases. Locations in native Tua and ordinary Lua specs refer to source files. User print output cannot corrupt the JSON. A run that fails before Busted completes leaves completed: false instead of stale results from a previous run. The destination's parent directory must exist. Check both the command exit status and the report; --list cannot be combined with result or coverage output.

Measure Line Coverage

Install LuaCov for the same interpreter as Busted, then run:

luarocks install luacov
tua test --coverage coverage.json --report test-results.json

The coverage file contains version, completed, and files. Each file has an absolute source path, covered and total line counts, and lines containing one-based line numbers and hits. Native Tua locations use compiler source maps; ordinary Lua retains its original lines. Unloaded project modules appear as uncovered. Comments and blank lines do not enter the denominator. Both production modules and test sources are included, while generated helpers and external dependencies are excluded.

LuaCov classifies executable Lua lines. When several generated lines map to one Tua line, Tua keeps the largest hit count; it is not a statement or branch count. This does not measure branch or function coverage. Coverage reflects only the selected tests. A build/backend/reporting error leaves completed: false; a completed run with failing assertions can still produce coverage. Check the command exit status too. The destination parent must exist, and coverage and test results must use different paths. Project .luacov configuration is not loaded; each run uses isolated statistics and removes them after reporting.

Run In VS Code Or CI

Open a saved Tua or Lua file in a trusted project. Tua automatically discovers configured tests using tua test --list, without running test code or requiring you to open the Testing view first. The editor gutter (left of the line numbers) shows VS Code's native play buttons beside literal it/pending cases and describe/context suites. Click a case's button to run that case; click a suite's button to run its descendants, including dynamically registered descendants. If gutter buttons are hidden, enable VS Code's Testing: Gutter Enabled setting.

The Testing view also supports project, file, suite and case runs. Use Tua: Refresh Unit Tests to refresh manually. Dynamic registrations remain runnable through their spec file; executed cases also appear in the results. Literal names use Lua's string escape decoding, so filters match Busted's runtime names. Busted filters by full name: tests or suites sharing a full name in one file run together. Suite runs use a space-delimited full-name prefix, so math does not select a neighboring mathematics suite.

The Run with Busted profile supports continuous run: opt in through the Testing view to rerun the selected tests after saved source/config/asset changes. Runs are serialized and refreshes coalesced. Generated output and .tua/ changes do not retrigger tests. Stop cancels the owned CLI/backend process group; abrupt cancellation can leave an ignored temporary .tua/test-* directory.

Test Explorer requires a trusted workspace and an installed Busted backend. tua.test.bustedPath and tua.test.luaPath select optional executables; empty values use the CLI defaults. It uses saved files, not unsaved editor buffers. Results show mapped failure locations and captured terminal output. No tests run just because a file was edited or the tree refreshed.

Choose Coverage with LuaCov in the Testing view to run selected tests with coverage. VS Code shows per-file totals and source-line decorations, including uncovered lines. Install LuaCov for the same interpreter as Busted. Independent selected runs combine their line hits; coverage represents the selected tests, not necessarily the entire suite. The coverage profile runs on demand.

Tua: Run Unit Tests remains available as a visible-terminal workflow.

For CI, install the intended Lua interpreter and Busted, then run:

tua check
tua fmt --check
tua test

check validates the project, fmt --check verifies formatting, and test executes assertions. One does not replace the others. A complete example is available in examples/unit-testing.

Output And Runtime Boundaries

Each run builds fresh Lua and source maps into a unique directory under .tua/. It does not overwrite the normal out directory. It uses the normal build pipeline, including configured asset pipelines and bundled helper runtimes. Test output is removed after the backend finishes or a handled error occurs. An abruptly terminated process can leave a temporary directory behind.

Busted's working directory is the temporary build root, with that root on its Lua module search path. Source-tree assets are copied there. Relative file I/O therefore addresses the built project, not the original repository root. The project-root .busted file is not automatically loaded from that directory.

The terminal report is collected until Busted exits. Tua maps its plain-text failure headers and verbose Lua traceback locations through compiler source maps, even if normal builds set emit_maps = false. Plain Lua specs retain Lua locations.

Normal tua build, watch builds and tua package omit the configured test directory, including its helpers and assets. They also omit *_spec.tua and *_spec.lua under the production source root by default. Set [test] exclude_specs = false only when those filenames are intentional production modules; the dedicated test directory remains test-only. Previously generated, compiler-owned spec output is removed on the next build.

check, lint, fmt and editor analysis include the dedicated test root. During tua test, production modules keep their normal paths and dedicated test files are emitted under __tua_tests__/; both roots are on Busted's module search path, with production modules taking precedence. Keep __tua_tests__ out of your production source tree. Tests can import production modules and test helpers; production code should not import test-only modules. Test assets are available under __tua_tests__/ relative to the temporary build directory.

A CLI watch loop is not implemented; use Test Explorer continuous runs. For runtime/gameplay checks, see Debugging.

Large output and cancellation

tua test retains up to 8 MiB from each of the backend's stdout and stderr streams. It continues draining larger logs and reports truncation; the backend's exit status and separate JSON result/coverage files remain authoritative. Test Explorer likewise truncates oversized terminal logs while reading test outcomes from the separate report. Discovery JSON must fit its output limit; an oversized discovery response is reported as an error rather than parsed as an incomplete inventory.

Test Explorer cancellation first requests process termination. On Unix, a child that ignores that request is forcibly stopped after a one-second grace period so the next queued test run can proceed. Windows uses process-tree termination.

Native LÖVE Scenarios And Video

For graphics and input checks, the repository includes the opt-in development script scripts/love_replay.py (Python 3.11+, a Tua compiler and native LÖVE). It builds the project, copies its output into a disposable directory, and runs scripted input against the real game callbacks. Ordinary builds do not include the runner. Run this from a Tua repository checkout:

python3 scripts/love_replay.py --project examples/pause-input \
  --tua target/release/tua --love /path/to/love \
  --scenario-module scenario --frames 60 --fps 30 \
  --output /tmp/pause-replay --video

The output directory must be new. --capture saves PNG frames; --video also encodes replay.mp4 using an installed ffmpeg. Audio is not recorded. Without either option, the scenario still renders and verifies behavior. Projects need a main.lua entry point in their configured build output inside the project.

Use --scenario-module for a typed module in a dedicated test/example project, or --scenario /path/to/check.lua for an external authored Lua scenario. The module returns these hooks:

return {
  setup = function(context)
    -- Runs after love.load.
  end,
  beforeFrame = function(context)
    if context.frame == 2 then context.key("space", true) end
    if context.frame == 3 then context.key("space", false) end
  end,
  afterFrame = function(context)
    -- Assert game-specific observable state after love.update.
  end,
  verify = function(context)
    assert(context.frame == 60)
    -- Add outcome assertions: completion alone does not validate gameplay.
  end,
}

verify is required; the other hooks are optional. Context contains frame, time, dt, and seed; key(name, down) controls polling and key callbacks, and pointer(x, y, down) controls the mouse and button 1. Physical keyboard, mouse, touch and controller callback events are ignored; joystick polling, external I/O and custom event loops are outside this runner's contract. Closing the window aborts the run. Games must use the normal LÖVE update/draw loop.

Each run has a unique save identity, including while conf.lua executes; project calls to change that identity are redirected. Test saves are cleaned up afterward. This isolation covers love.filesystem, not arbitrary io writes or network access: run trusted projects and scenarios. Game shutdown callbacks are not called; put test teardown in verify where needed.

runtime.log, build.log and provenance.json record failures as well as success. Provenance includes compiler identity/hash, project revision and dirty state, scenario hash, LÖVE/Lua versions, JIT status, seed and fixed timestep. A nonzero exit, timeout, missing verification or incomplete capture fails the run.

Fixed timestep and seeded Lua/LÖVE random sources improve repeatability; they do not make asynchronous work or all physics/GPU behavior deterministic. These are functional recordings, not CPU, rendered-FPS or latency benchmarks. GC policy remains project-controlled and is reported as unknown. The pause/input example checks paused gameplay, advancing UI, held input, command priority and practice mode gating using existing Tua features.