NovaSharp ships with a comprehensive test suite that blends historical Lua fixtures with .NET focused regression checks.
- Lua compatibility (TestMore): Lua TAP fixtures exercise language semantics, standard library coverage, and coroutine behaviour. See
docs/testing/tap-suite-index.mdfor the canonical mapping between the historical suite numbers and the new category-based folder layout (e.g.,TestMore/StandardLibrary/307-bit.t). TAP suites that need stdin input must route throughplatform.stdin_helper.run(...), which feeds the chunk viaTapStdinHelperso the tests work on every platform without invokingio.popen. The helper searches the active working directory (set byTapRunnerTUnit), the suite directory, andAppContext.BaseDirectory, so create temporary stdin files in the same directory as the suite or inside the process working directory when a test needs to read incremental fixtures. - End-to-end suites: C# driven TUnit scenarios cover userdata interop, debugger contracts, serialization, hardwire generation, and coroutine pipelines.
- Units: Focused checks for low-level structures (stacks, instruction decoding, binary dump/load).
DOTNET_ROLL_FORWARD=Major dotnet test \
--project src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit.csproj \
-c Release --report-trx --report-trx-filename NovaSharpInterpreterTUnit.trx- Produces a standards-based TRX file under
TestResults/(or the supplied--results-directory) so failures can be inspected with the test explorer of your choice. - Mirrors the test execution and TRX output that power CI. Use
scripts/coverage/coverage.ps1orscripts/coverage/coverage.shwhen you need branch/line coverage.
- The .NET 10 SDK selects Microsoft.Testing.Platform through
global.json. Use--projectwhen selecting a test project from the repository root and pass runner options directly todotnet test. - The interpreter TUnit suite completes quickly on a many-core workstation; expect a slower first run when a clean build is required because the Microsoft.Testing.Platform entry point is re-generated.
- IDEs that honor the SDK test runner configuration use the Microsoft.Testing.Platform setting in
global.json.
- Interpreter and debugger suites now live entirely on TUnit. Use TUnit’s async assertions and data sources for every new test, and only introduce NUnit fixtures if a third-party dependency requires it; document that exception in this guide and the change record.
- Shared Lua fixtures, TAP corpuses, and helper infrastructure remain under
src/tests/WallstopStudios.NovaSharp.Interpreter.Tests. Link the files you need into the TUnit project instead of reviving the deleted NUnit host. - The runtime/TAP blueprint in
docs/testing/tunit-migration-blueprint.mdis preserved for historical context. If you need to compare timing against the retired NUnit host, usepwsh ./scripts/tests/compare-test-runtimes.ps1 -Name <scenario> -BaselineArguments @(...) -TUnitArguments @(...)so the JSON artefact captures the delta.
Use the helpers in scripts/build when you need the canonical build + interpreter-test pipeline in a single command (matching the CI lane).
pwsh ./scripts/build/build.ps1bash ./scripts/build/build.sh- Both scripts restore local tools (unless
-SkipToolRestore/--skip-tool-restoreis supplied), buildsrc/NovaSharp.slnin Release by default, and execute the interpreter tests with the TUnit command above, writing logs toartifacts/test-results. - Pass
-SkipTests/--skip-testsfor build-only runs, or override-Configuration/--configurationto target Debug builds.
- Detector overrides (Unity/Mono/AOT flags, assembly enumeration hooks) must go through the shared scope helpers in
src/tests/TestInfrastructure/Scopes. Runpython scripts/lint/check-platform-testhooks.py(or./scripts/ci/check-platform-testhooks.sh) before sending a PR to ensure no new files referencePlatformAutoDetector.TestHooksdirectly. CI runs the same guard in the lint job, so treating it as a local pre-flight check prevents avoidable failures. - Console capture is now centralized in
ConsoleTestUtilities(WithConsoleRedirectionAsync/WithConsoleCaptureAsync), which wrapsConsoleCaptureCoordinator.RunAsyncand the redirection scopes. Runpython scripts/lint/check-console-capture-semaphore.py(or./scripts/ci/check-console-capture-semaphore.sh) and fix any violations by switching to the helper instead of referencingConsoleCaptureCoordinator.Semaphoreor instantiatingConsoleCaptureScope/ConsoleRedirectionScopedirectly. - Cleanup helpers (
TempFileScope,SemaphoreSlimScope,DeferredActionScope, etc.) replaced the last manualtry/finallyblocks undersrc/tests. Runpython scripts/lint/check-test-finally.py(or./scripts/ci/check-test-finally.sh) to ensure new tests do not reintroduce rawfinallyblocks; the script fails on the first match so the offending file is easy to spot. - Tests must never call
Path.GetTempPath()orPath.GetTempFileName()directly anymore—useTempFileScope/TempDirectoryScopeso cleanup stays centralized.python scripts/lint/check-temp-path-usage.py(or./scripts/ci/check-temp-path-usage.sh) enforces this by failing whenever a test references either API outside the shared scope helper. dotnet_diagnostic.CA2007is enforced as an error. Every awaited assertion/task must end with.ConfigureAwait(false)(the TUnit assertion extensions already do this—be sure to append the call when writing custom awaits). Avoidawait using/await foreachunless the language demands it; in all other cases, follow the helper pattern so tests remain analyzer-clean.python scripts/lint/check-userdata-scope-usage.py(or./scripts/ci/check-userdata-scope.sh) ensures new tests register userdata throughUserDataRegistrationScope; direct calls toUserData.RegisterType/UserData.UnregisterTypeare confined to the allowlisted isolation/history suites reported by the lint check.
pwsh ./scripts/coverage/coverage.ps1-
Restores local tools, builds the solution in Release, and runs the TUnit test application through the
coverlet.consolewrapper. -
Emits LCOV, Cobertura, and OpenCover artefacts under
artifacts/coverage, with the TRX test logs inartifacts/coverage/test-results. -
Produces HTML + Markdown + JSON summaries in
docs/coverage/latest;SummaryGithub.mdandSummary.jsonare also copied toartifacts/coveragefor automation and PR reporting. -
Pass
-SkipBuildto reuse existing binaries and-Configuration Debugto collect non-Release stats. -
On macOS/Linux without PowerShell, run
bash ./scripts/coverage/coverage.sh(identical flags/behaviour). Both scripts automatically setDOTNET_ROLL_FORWARD=Majorwhen it isn’t already defined so newer .NET runtimes can execute the .NET 8 test host. Set the variable explicitly to use a different roll-forward policy. -
Both coverage helpers honour gating settings: set
COVERAGE_GATING_MODEtomonitor(warn) orenforce(fail), and override the per-metric targets viaCOVERAGE_GATING_TARGET_LINE,COVERAGE_GATING_TARGET_BRANCH, andCOVERAGE_GATING_TARGET_METHOD. CI now exportsCOVERAGE_GATING_MODE=enforcewith 80 % line / 80 % branch / 80 % method thresholds so coverage dips fail fast; set the mode tomonitorlocally if you need a warning-only rehearsal. To mirror the enforced gate (the default in CI), export the same settings before rerunning the script:$env:COVERAGE_GATING_MODE = "enforce" $env:COVERAGE_GATING_TARGET_LINE = "80" $env:COVERAGE_GATING_TARGET_BRANCH = "80" $env:COVERAGE_GATING_TARGET_METHOD = "80" pwsh ./scripts/coverage/coverage.ps1 -SkipBuild
COVERAGE_GATING_MODE=enforce \ COVERAGE_GATING_TARGET_LINE=80 \ COVERAGE_GATING_TARGET_BRANCH=80 \ COVERAGE_GATING_TARGET_METHOD=80 \ bash ./scripts/coverage/coverage.sh --skip-build
.github/workflows/tests.ymlincludes acode-coveragejob that runspwsh ./scripts/coverage/coverage.ps1afterlint. It is independent of the OS unit-test matrix so coverage signal is not skipped by a platform-specific unit-test failure.- The job exports
COVERAGE_GATING_MODE=enforcetogether with 80 % line / 80 % branch / 80 % method targets so coverage dips fail fast. The PowerShell coverage helper enforces the same gate, and the workflow'sEvaluate coverage thresholdstep double-checks all three metrics before publishing artefacts. - Coverage deltas surface automatically on pull requests; the comment is updated in-place on retries to avoid noise. When the gate passes, the Action log includes a "Coverage Gate" summary showing both the current percentages and thresholds.
- The
dotnet-testsjob uses a matrix strategy running onubuntu-latest,windows-latest, andmacos-latestin parallel. - Linux and macOS use
scripts/build/build.sh; Windows usesscripts/build/build.ps1(same parameters). - Test results upload as separate artifacts per platform (
NovaSharp-test-results-<os>). - Coverage collection runs only on Ubuntu after
lintto avoid redundant computation. - Lua comparison runs in a separate
lua-comparisonmatrix afterlintfor Lua 5.1-5.5 on Ubuntu, Windows, and macOS. It fails onmismatch,lua_only,nova_only, or new/changed unclassifiedboth_errorsignatures. - Pull requests receive a sticky aggregate Lua comparison comment generated by
scripts/tests/render-lua-comparison-report.py. The comment summarizes every uploaded matrix artifact, including failed matrix legs, so reviewers can distinguish production regressions from fragile or unnecessary fixture failures without digging through each job.
-
The newly catalogued Lua TAP suites now run inside the TUnit harness.
TestMore/LanguageExtensions/310-debug.tis still skipped because NovaSharp does not expose Lua’s debug library yet, whileTestMore/LanguageExtensions/320-stdin.tnow relies on theplatform.stdin_helperbridge to exercise stdin semantics without shelling out toio.popen. When those suites create files (for examplefile.txtordbg.txt), they write them next to the TAP script soTapStdinHelpercan resolve the relative paths without additional configuration. -
Failures are captured in the generated TRX; the CI pipeline publishes the
artifacts/test-resultsdirectory for inspection. -
Historical baseline (Release via
scripts/coverage/coverage.ps1 -SkipBuild, 2025-12-07 UTC): 96.2 % line / 93.69 % branch / 97.88 % method forNovaSharp.Interpreteracross 3,235 Release tests. -
Fixtures: The current authoritative counts are the observed local/CI test output and Lua comparison
results.jsonsummaries; do not report the suite as green unless the relevant command or PR check was observed passing. -
Key areas covered: Parser/lexer, binary dump/load paths, JSON subsystem, coroutine scheduling, interop binding policies, debugger attach/detach hooks.
-
Gaps: DAP protocol integration tests remain unimplemented.
CRITICAL: Never adjust tests to accommodate production bugs. When a test fails or exposes incorrect behavior:
- Assume production is wrong until proven otherwise
- Fix the production code to produce correct output
- Keep tests unchanged unless they are demonstrably incorrect
- Verify against specification (Lua manual, DAP protocol spec, etc.)
- Document the fix in commit message and PR notes
This applies to all bugs, including:
- Serialization issues (e.g., JSON outputting
{}instead of[]for empty arrays) - Protocol violations (e.g., DAP responses not matching spec)
- Lua semantics diverging from the official interpreter
- API contracts not being honored
If you discover a production bug while writing tests, fix the production code first, then verify the test passes with correct behavior. Never work around bugs with test accommodations.
- NUnit test methods (
[Test],[TestCase], etc.) must use PascalCase without underscores. The solution-wide.editorconfigenforces this as an error, so stray underscore names will fail analyzers and builds. - Author all new failure expectations with
Assert.Throws<TException>(...)/Assert.That(async () => ..., Throws.TypeOf<TException>())rather than[ExpectedException]. The NUnit 3 runner no longer honors the legacy attribute, and the explicit assertion keeps error paths local to the test body. - When a test fixture touches shared static registries (e.g.,
UserData.RegisterType, global caches, or other mutable singletons), decorate the class with[UserDataIsolation]so the registry is sandboxed per test and keep the fixture[Parallelizable(ParallelScope.Self)]. Suites that tweakScript.GlobalOptionsmust route changes through the shared scopes (ScriptGlobalOptionsScope.Override(...),ScriptCustomConvertersScope,ScriptPlatformScope, etc.) so platform/converter/flag overrides are restored automatically. Only drop back to[NonParallelizable]when a given suite still depends on mutable globals you can’t isolate yet. - Multi-word Lua concepts keep their canonical casing when surfaced through C# APIs. In particular, treat “upvalue” as
UpValue/UpValuesso helpers such asGetUpValue,UpValuesType, andSymbolRef.UpValueremain consistent with the runtime surface. Do not collapse these identifiers toUpvalueorUpvalues, and document additional durable casing decisions in the naming guide before introducing new APIs.
- Deepen unit coverage across parser error paths, metatable resolution, and CLI tooling to raise the interpreter namespace above 70 % line coverage.
- Introduce debugger protocol integration tests (attach, breakpoint, variable inspection) and capture golden transcripts for the CLI shell.
- Keep Lua fixtures under version control in
src/tests/WallstopStudios.NovaSharp.Interpreter.Teststo avoid drift and simplify regeneration. - Restore the skipped OS/IO TAP fixtures through conditional execution in trusted environments or provide managed equivalents.
- Restore interactive
debug.debugREPL-loop coverage after fixing the nestedReplInterpreter/ProcessingLoopstate failure; null-input exit and prompt behavior remain covered separately.
Track only selected goals in PLAN.md; keep the complete testing gaps and shipped policies in this document and record completed work in progress/.
-
Formatter gate: Run
dotnet tool restorefollowed bydotnet tool run csharpier format .(ordotnet tool run csharpier check .if you only need verification) before every push. CI executes the same check viascripts/ci/check-csharpier.shduring the lint job, so any mismatch will fail PRs immediately. Ifdotnet formator another tool disagrees with CSharpier output, treat that as a tooling bug—update.editorconfig/workflow settings instead of reformatting away from CSharpier style. -
Solution baseline (2025-12-07):
Directory.Build.propsnow sets<TreatWarningsAsErrors>true>, sodotnet build src/NovaSharp.sln -c Release -nologofails on any compiler or analyzer warning. Run that command before every push and note it in your PR (the template now calls out analyzer commands explicitly). If a warning is unavoidable, add a targeted suppression with rationale in the closest authoritative analyzer documentation and change record. -
src/debuggers/NovaSharp.VsCodeDebugger/NovaSharp.VsCodeDebugger.csprojnow builds with<TreatWarningsAsErrors>true>. Any new warning in the VS Code debugger project fails the build locally and in CI, so always run:dotnet build src/debuggers/NovaSharp.VsCodeDebugger/NovaSharp.VsCodeDebugger.csproj -c Release -nologo
before pushing debugger changes. Keep the analyzer configuration warning-free; document unavoidable suppressions in the closest authoritative analyzer documentation and change record.
-
src/tooling/NovaSharp.Hardwire/NovaSharp.Hardwire.csprojnow also treats warnings as errors. Rundotnet build src/tooling/NovaSharp.Hardwire/NovaSharp.Hardwire.csproj -c Release -nologobefore committing tooling changes, and keep analyzer suppressions documented. -
src/debuggers/WallstopStudios.NovaSharp.RemoteDebugger/WallstopStudios.NovaSharp.RemoteDebugger.csprojnow builds with<TreatWarningsAsErrors>true>(2025‑11‑24). Before pushing debugger/network changes, rundotnet build src/debuggers/WallstopStudios.NovaSharp.RemoteDebugger/WallstopStudios.NovaSharp.RemoteDebugger.csproj -c Release -nologo(or the full solution build) to keep the analyzer set clean. Remote-debugger tests now live insrc/tests/WallstopStudios.NovaSharp.RemoteDebugger.Tests.TUnit; add coverage there when touching RemoteDebugger code. -
Record every analyzer command you run when filling out
.github/pull_request_template.md. Reviewers expect to see the solution build plus any scoped project builds/tests for the areas you touched. -
Because the solution-wide warning gate is now on, suppressions must remain surgical. Any new
[SuppressMessage]or ruleset tweak requires a nearby or analyzer-policy record of the rule, justification, and follow-up owner before merging.
Both debugger stacks now rely on analyzers to catch regressions; any new warning fails the Release build, so keep the following guardrails in mind whenever you touch debugger code.
- Disposal & ownership (CA1063/CA2213/CA2000):
NovaSharpVsCodeDebugServer,ProtocolServer,DebugSession,RemoteDebuggerService,HttpServer,Utf8TcpServer, and every socket/listener/HttpClientwrapper must implement the full dispose pattern and wrap transient streams/sockets/readers inusingstatements. Tests should assert deterministic disposal by creating helpers such as the blocking channel/queue fixtures already in the suite. - Argument validation & targeted catches (CA1031/CA1062): Guard every public/protected entry point (commands, protocol handlers, HTTP endpoints) against
nullor invalid arguments and only catch specific exception types (IO/security/format) so analyzers keepProgram,RunCommand,HardwireCommand, and debugger transports free of blanketcatch (Exception)blocks. - Culture/compare invariance (CA1305/CA1310/CA1865/CA1866): Always format/parse using
CultureInfo.InvariantCultureand specifyStringComparison.Ordinal(or the char overloads) for protocol routing, manifest parsing, and CLI messaging. Remote debugger HTTP payload builders should also stay culture-invariant when emitting JSON or diagnostics. - Collections & API surfaces (CA1002/CA1012/CA1716/CA1822/CA1854/CA1859): Expose protocol lists as
IEnumerable<T>, keep debugger constructorsprotectedto enforce abstract entry points, rename identifiers that collide with reserved keywords, and favorstatichelpers when no instance state is touched. Access dictionaries viaTryGetValueto avoid double lookups, and store concrete list/dictionary instances instead of their interfaces when state mutation is required. - Binary payload & immutability rules (CA1008/CA1056/CA1815/CA1819): Remote debugger URIs must use
System.Uri, byte payloads should flow throughReadOnlyMemory<byte>/ReadOnlySpan<byte>, and value types such asRemoteDebuggerOptionsneed explicit equality members so analyzers see deterministic semantics.
Validation checklist:
dotnet build src/debuggers/WallstopStudios.NovaSharp.VsCodeDebugger/WallstopStudios.NovaSharp.VsCodeDebugger.csproj -c Release -nologo
dotnet build src/debuggers/WallstopStudios.NovaSharp.RemoteDebugger/WallstopStudios.NovaSharp.RemoteDebugger.csproj -c Release -nologo
$env:DOTNET_ROLL_FORWARD = 'Major'
dotnet test --project src/tests/WallstopStudios.NovaSharp.RemoteDebugger.Tests.TUnit/WallstopStudios.NovaSharp.RemoteDebugger.Tests.TUnit.csproj -c ReleaseDocument new suppressions or analyzer exclusions in the closest authoritative analyzer documentation (with the CA rule, justification, and follow-up owner) before merging.