Files
Library/docs/roadmap/modules/Testing.md

171 lines
12 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Testing — trustworthy framework and deterministic verification
Status: plan; all feature tasks PLANNED. Baseline `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`.
R-002/R-003/R-012/R-016 and [C-01–C-05](../ARCHITECTURE.md) apply. Testing owns reusable
harness primitives; each feature owns its behavioral oracle and fixtures.
## Existing framework and evidence
The namespace is `Void::Testing`. [Config.hpp](../../../include/Void/Testing/Config.hpp)
defines test/assertion results, skip/crash states, filters, reporters, shuffle/seed/repeat
and parallel options. [Runner](../../../src/Testing/Runner.cpp) implements regex filters,
exact suite/tag filters, sequential and optional Async-thread-pool execution, console/JUnit
output and exit handling. [Suite.hpp](../../../include/Void/Testing/Suite.hpp) registers
annotated methods using reflection where supported. [tests/CMakeLists.txt](../../../tests/CMakeLists.txt)
collects generated standalone shims into `VoidTests`. [module.cmake](../../../src/Testing/module.cmake)
declares LogState and optional diagnostics/execution/configuration/text integrations.
[Math.cpp](../../../tests/standalone/Testing/Math.cpp) intentionally includes DisabledTest
examples named `broken_feature` and `unquoted_skip`; these exercise skip behavior and are
not missing product implementations. [ContainerFixture](../../../tests/standalone/Testing/ContainerFixture.cpp)
and [StructRepr](../../../tests/standalone/Testing/StructRepr.cpp) provide further framework
examples. The baseline result is 1,245 passed, two environmental process-fixture failures
and three skips out of 1,250; see [validation](../VALIDATION.md). This task ran no tests.
Source-backed improvement targets: malformed regex currently yields an empty selection;
JUnit reporter creation holds a static output stream; sequential signal handling invokes
rich diagnostics and jumps out of a signal handler; parallel execution omits that crash
recovery. [SignalHandler.cpp](../../../src/Testing/SignalHandler.cpp) has process-global
callback/jump state. These are reasons to specify framework regression tests and process
isolation, not to infer reliable crash containment from ordinary unit-test passes.
## Native harness design and NEW API
Keep the existing native framework and C++26 reflection/scanner paths. No wholesale
replacement by a third-party testing framework. Optional compiler fuzz/sanitizer adapters
are development tooling, absent from consumer dependencies. Runtime is never required
merely to register or execute a synchronous test. [Time](Time.md) owns fake-clock semantics
and [Async](Async.md) owns executor semantics; Testing supplies controlled adapters and
schedule exploration around those contracts, not competing production types.
NEW illustrative shapes in `Void::Testing`:
```cpp
struct ReplayToken { std::uint64_t seed; std::uint32_t generator_version; };
struct PropertyOptions {
unsigned cases = 256;
unsigned max_size = 64;
unsigned max_shrinks = 1000;
};
template<class Generator, class Predicate>
PropertyResult check_property(Generator, Predicate, PropertyOptions, ReplayToken);
class DeterministicRun; // ready-queue control, injected clock, event trace
class FailureCapture; // bounded child assertion sink, explicit result inspection
struct ProcessTestOptions; // timeout/output/resource budget, expected exit policy
```
These types and `PropertyResult` are NEW. Failures retain the original case, minimized
case, seed, generator/codec version, shrink path and schedule decisions. Select
`std::mt19937_64` with a recorded 64-bit seed and case ordinal. M-TESTING-03 freezes
bounded-uniform rejection mapping over its integer outputs, with cross-toolchain golden
sequences; standard distribution implementation details must not silently change replay.
User-supplied generators own their values and deterministic
shrinkers produce a strictly decreasing complexity measure or exhaust the shrink budget.
Example workflow: generate a vector, apply a container operation, compare to a simple
reference, then replay the stored minimal case in a normal regression test.
The deterministic executor runs one ready action at a time in recorded admission order,
advances the injected clock only under test control, and records alternative runnable
choices. A bounded exploration mode enumerates selected interleavings. It must not claim
to simulate OS threads, cache coherence, or arbitrary data races. Dedicated stress/TSan
work remains necessary. Stop/completion races are assertions on exactly one terminal
result and released ownership, not on wall-clock sleep timing.
## Framework correctness and failure handling
Registration becomes a frozen catalog before running tests. Duplicate stable test IDs,
invalid regex/options, missing requested suites and unreadable report paths are explicit
configuration failures. A NEW default fails an explicitly requested empty selection;
`--allow-empty` is an explicit override. Listing is side-effect-free with respect to test
bodies. Shuffle/repeat reports seed and iteration; discovery order is stable by test ID.
Every run owns its reporter streams and context. An assertion emitted outside an active
test is a framework error, not silently assigned to the next test. Async test adapters
retain a context handle until their task scope joins; thread-local convenience access does
not permit borrowed `TestResult*` pointers to escape. Freeze a result only after callbacks
and mock verifiers finish. Reporter callbacks see immutable result snapshots outside registry
locks; reporter failure makes the overall run fail and preserves an emergency summary.
One fixture lifecycle controller handles construction, setup, body, teardown and destruction.
After setup is entered, teardown is attempted exactly once even if setup/body fails; destroy
always runs for a constructed fixture. Report primary and cleanup errors separately. A
require/fatal assertion aborts only that test's controlled scope, while ordinary expect
records and continues. Intentional skip reasons survive console and JUnit output.
Crash/timeout tests run in fresh child processes through [System](System.md), with one
selected test ID and a bounded result channel. Parent waits/reaps and distinguishes ordinary
failure, signal, timeout, infrastructure failure and missing result. It can terminate the
child after its deadline; it cannot safely kill an in-process C++ test thread and continue
using its corrupted objects. Remove promises of rich signal-handler recovery in coordination
with [Stacktrace](Stacktrace.md). Ordinary exception tests remain in-process.
## Resource policies and fuzz/property capabilities
NEW defaults: sequential execution; explicit parallel mode caps workers at four unless
configured otherwise; 100,000 registered tests; 1,000 retained assertions/1 MiB diagnostics
per test; 64 MiB aggregate report buffer. Above the assertion cap, retain first failures
and counters, mark truncation, and continue or abort according to test policy without
unbounded growth. Reporters stream results to avoid retaining all output text.
Property defaults above additionally cap generated input at 1 MiB, corpus at 64 MiB and
one property at five seconds/10,000 scheduled steps. Time checks occur between generator,
case and shrink calls; uncooperative custom callbacks require subprocess isolation for a
hard timeout. A budget exhaustion is Inconclusive,
not Pass. Rejection sampling is limited to ten times the requested successful case count;
an impossible precondition is reported. Shrinking preserves the original failure category
and never consumes production network/filesystem state. Use generated fixtures, not private data.
Process-test defaults: 60-second timeout, 1 MiB captured output per stream, four concurrent
children, 256 pending jobs. Optional Linux resource limits are capability-reported rather
than assumed portable. Output overage truncates with counts; it cannot deadlock a full pipe.
Stop requests close admission, terminate opted-in child jobs, drain pipes, reap children
and join owned harness work. Embedded in-process deadlines remain cooperative.
Fuzz entry points accept byte spans and use feature-owned parsers/models. NEW compiler
adapters expose those same functions to supported fuzz engines; a deterministic corpus
replay runner works without them. Corpus metadata records format, fixture license/source,
seed and maximum memory/time. Minimized failures become normal regression fixtures.
Mutation/crash-injection campaigns verify the oracle: intentionally broken length checks,
lost writes or duplicate completions must be detected by the harness.
## Ordered tasks
| ID | Phase / dependencies | Scope and acceptance | Recommended role |
| --- | --- | --- | --- |
| M-TESTING-01 | P0; existing runner/registration | Framework self-tests for filter/seed/skip/fixture/reporter/exit behavior, with subprocess expected-failure fixtures; skip demonstrations remain intentional. | astra_implementer |
| M-TESTING-02 | P1; M-TESTING-01, Async context ownership, System child process | Per-run contexts/reporters and crash isolation; cleanup runs once, child crash is contained, invalid selection cannot produce false success. | astra_implementer |
| M-TESTING-03 | P1; M-TESTING-02, Time fake clock, Async test executor | Deterministic schedule driver, versioned generator/shrinker and replay token; cross-build seed replay and schedule minimization are reproducible. | astra_implementer |
| M-TESTING-04 | P2; M-TESTING-03, Binary/Data bounded fixtures | Property combinators, model traces and failure capture; known faulty algorithms are caught and shrink to replayable cases. | sol_implementer |
| M-TESTING-05 | P2; M-TESTING-02/04, supported compiler probes | Corpus runner, optional fuzz adapters, subprocess resource controls and sanitizer matrix; unsupported tooling is reported and corpus replay still works. | sol_implementer |
| M-TESTING-06 | P3; M-TESTING-03/05, shared validation/performance schemas | Fault-file/transport ports and benchmark evidence adapters used by Storage/IO/Net; injected faults occur at named boundaries and totals reconcile. | astra_implementer |
| M-TESTING-07 | P4; M-TESTING-06, Coordination/Replication models | Distributed schedule/history harness; partition/restart/duplicate scenarios reproduce and reject deliberately invalid histories. | astra_implementer |
## Validation and migration
CURRENT test-runner syntax is source-verified. TEMPLATE:
`<existing-build>/tests/VoidTests --filter '^(addition|db_query|broken_feature|unquoted_skip)$'`.
`--filter` matches test names and suite-qualified names using regex search. No run is claimed
here. PROPOSED after M-TESTING-01: a separate framework-verification child fixture set with
known exit codes, exact counts and parsed JUnit output, driven by a parent checker independent
of the framework assertions being checked. A green self-hosted suite alone is insufficient.
Required regressions include malformed regex, empty explicit selection, report-open failure,
two runs to different output files, duplicate registration, require during setup/teardown,
late async assertion, deterministic repeat/shuffle, intentional skips, signal/timeout,
pipe saturation and a deliberately failing property. Verify expected failures without
editing a live result to Passed. Run isolated module consumers and supported reflection
configurations under [build/distribution](../BUILD-AND-DISTRIBUTION.md).
Apply [performance](../PERFORMANCE.md) to assertion overhead, reflection/registration build
cost, worker scheduling and bounded report memory; preserve p50/p95/p99, throughput,
allocations and RSS/CPU evidence without turning benchmark variance into test failure.
[Validation](../VALIDATION.md) owns sanitizer/toolchain gates and baseline failure reporting.
[Migration](../MIGRATION.md) keeps Test/Suite/expect/require adapters while introducing
explicit contexts, replay and isolation. NEW strict option validation is a documented
major behavior change. Rollback may keep old output formats via adapters, but must not
restore silent passing of invalid selections. [TestingMock](TestingMock.md) integrates
through FailureCapture and joined contexts, with no reverse dependency from Testing to mocks.
Graph coverage was checked for all cited source; partial Registrar syntax was read directly.
No new framework, fuzz, crash or benchmark checks ran during documentation authoring.