150 lines
11 KiB
Markdown
150 lines
11 KiB
Markdown
# TestingMock — deterministic expectations and owned actions
|
||
|
||
Status: plan; implementation tasks PLANNED. Baseline `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`.
|
||
R-002/R-014/R-016 and [C-02–C-05](../ARCHITECTURE.md) govern future work.
|
||
|
||
## Existing capabilities and concrete gaps
|
||
|
||
`Void::TestingMock` provides [MockFunction](../../../include/Void/TestingMock/MockFunction.hpp),
|
||
[Expectation](../../../include/Void/TestingMock/Expectation.hpp),
|
||
[matchers](../../../include/Void/TestingMock/Matcher.hpp), and
|
||
[Mock/MockBase](../../../include/Void/TestingMock/Mock.hpp). Expectations match arguments,
|
||
record calls and run actions; `times`, `once`, `returns` and `invokes` are existing names.
|
||
Actions use `std::move_only_function`; the [move-only action test](../../../tests/standalone/TestingMock/MoveOnlyAction.cpp)
|
||
specifically demonstrates a unique_ptr-capturing lambda, not arbitrary move-only arguments
|
||
or move-only returned values. Matching/execution currently passes arguments through several
|
||
by-value layers, and `returns` returns its stored value as an lvalue.
|
||
|
||
`MockFunction::operator()` holds its mutex while matching and executing user actions.
|
||
Expectation registration and verify/clear do not use that same synchronization. MockBase
|
||
stores non-owning function pointers; registration has no lifetime token. `verify()` clears
|
||
expectations, while destructors call it automatically. Preserve existing convenient usage
|
||
but do not infer concurrent reconfiguration or reentrant action safety from the mutex.
|
||
|
||
[Reflect.hpp](../../../include/Void/TestingMock/Reflect.hpp) lists virtual methods and checks
|
||
handwritten mocks; its source explicitly distinguishes introspection from unsupported
|
||
override-code injection. Reflection availability is toolchain-probed, not a promise that
|
||
complete automatic mock generation already exists. [module.cmake](../../../src/TestingMock/module.cmake)
|
||
depends on Testing and Functional. Evidence includes
|
||
[VerifyAll](../../../tests/standalone/TestingMock/VerifyAll.cpp),
|
||
[FailureMessages](../../../tests/standalone/TestingMock/FailureMessages.cpp), and
|
||
[Reflect tests](../../../tests/standalone/TestingMock/Reflect.cpp).
|
||
|
||
## Selected native design and NEW contract
|
||
|
||
Retain a native header-oriented mock library integrated with [Testing](Testing.md); no new
|
||
external mocking engine. Separate configuration from invocation. A NEW session freezes
|
||
expectations before concurrent calls, retains action/registration state, and closes after
|
||
the test's task scope has joined. Existing `expect(...).invokes(...).times(...)` remains a
|
||
builder adapter. Mutating a frozen session returns InvalidState rather than racing.
|
||
|
||
Illustrative NEW shapes in the existing namespace:
|
||
|
||
```cpp
|
||
enum class Concurrency { SingleThread, ConcurrentActions };
|
||
struct MockLimits { std::size_t expectations = 1024; std::size_t events = 4096; };
|
||
class MockSession; // owns registrations, diagnostics and verification state
|
||
class Sequence; // explicit order group, never global registration order
|
||
struct Verification; // structured missing/excess/unmatched/action failures
|
||
Result<void> freeze(MockSession&, Concurrency);
|
||
Verification verify_and_close(MockSession&);
|
||
// NEW builder operations: at_least(n), at_most(n), in_sequence(seq),
|
||
// returns_once(move_only_value), invokes_once(move_only_action).
|
||
```
|
||
|
||
`SingleThread` is the NEW default and permits same-thread reentrant calls after releasing
|
||
internal locks; concurrent entry from another thread returns a deterministic framework
|
||
failure. `ConcurrentActions` explicitly requires custom matchers/actions to support concurrent
|
||
invocation. The library does not secretly serialize arbitrary user code under a mutex and
|
||
cannot make a captured mutable object thread-safe by retaining it.
|
||
|
||
Invocation dataflow: snapshot immutable candidate matchers under a short session lock,
|
||
evaluate pure matchers outside it, then reacquire to reserve a matching unsaturated
|
||
expectation and sequence position. If another call consumed it, retry the remaining immutable
|
||
candidates against the same borrowed arguments. Reservation is the call's linearization
|
||
point. Release the lock, run the reserved action, then record terminal outcome. Keep the
|
||
expectation/action storage alive through that outcome; verification waits for owned calls.
|
||
Registration order breaks ties among otherwise eligible expectations. A custom matcher
|
||
must be side-effect-free because it may be reevaluated; exceptions become MatcherFailure.
|
||
|
||
Once-actions transfer their move-only callable/value to the reserved invocation. Repeated
|
||
actions stay in a retained immutable registration holder and use the explicitly selected
|
||
concurrency policy; do not copy a move-only callable. Matchers inspect arguments through
|
||
const references; forward each argument to the action exactly once after selection. Provide
|
||
compile-time diagnostics for impossible reference lifetimes and missing return actions.
|
||
For reference-return mocks the user must supply a lifetime-safe referent. A mismatched
|
||
non-default-constructible return cannot fall back to `R{}`: record failure then throw a
|
||
Testing-owned invocation-abort exception, caught at the test boundary. No exception crosses
|
||
a plugin C boundary; C-facing mocks use status/result actions.
|
||
|
||
Explicit order groups model call dependencies. `never()` is an explicit prohibition checked
|
||
before ordinary candidate selection; it is not a saturated zero-count expectation silently
|
||
skipped by the matcher loop. Negative counts are invalid; min≤max is checked at freeze.
|
||
Verification is idempotent and reports each unmet condition once, retaining a bounded
|
||
summary for subsequent calls rather than destroying evidence prematurely.
|
||
|
||
## Ownership, diagnostics and resource limits
|
||
|
||
A registration token replaces MockBase's untracked raw-pointer lifetime for dynamic mocks.
|
||
Removing a registration stops admission and joins its admitted calls before releasing action
|
||
state. Destructors never throw; they perform best-effort verification through a retained
|
||
Testing context. Explicit `verify_and_close` is preferred so failures cannot arrive after
|
||
the result has frozen. Closing from inside an action returns WouldDeadlock or schedules
|
||
deferred close; it cannot synchronously wait for itself.
|
||
|
||
NEW defaults: 1,024 expectations per session, 64 matchers per expectation, 4,096 retained
|
||
invocation events, 4 MiB diagnostic memory and 4 KiB rendering per argument. Event overflow
|
||
keeps total counters and first/last bounded samples, marks truncation, and does not drop
|
||
the fact that an unexpected call happened. Bound matcher-description depth at 32. Test
|
||
configuration may lower these; zero means zero capacity, never unlimited. User action
|
||
allocations remain outside the framework's memory bound and are subject to process-test
|
||
limits. Use Time's injected clock for timestamps and Testing's event sequence for ordering.
|
||
|
||
FailureCapture from Testing records expected mock failures in an isolated child assertion
|
||
sink. Replace framework tests that temporarily alter the live test result with this API.
|
||
Diagnostics report actual arguments, candidate matcher descriptions, declaration location,
|
||
reserved call index and order-group position. Redaction is available for fixtures containing
|
||
sensitive-looking fields; captured arbitrary object bytes are never a default diagnostic.
|
||
|
||
Async actions compose with Async tasks owned by the test scope. A NEW scripted action can
|
||
yield a response, error, partial transfer, cancellation or delayed completion through the
|
||
deterministic executor. It cannot retain borrowed arguments after return unless it copies
|
||
them into an admitted owned buffer. The mock does not invent a second scheduler or wall-clock
|
||
sleep mechanism. Scripted transport/file mocks are reusable test ports, not production APIs.
|
||
|
||
## Ordered backlog
|
||
|
||
| ID | Phase / dependencies | Scope and acceptance | Recommended role |
|
||
| --- | --- | --- | --- |
|
||
| M-TESTINGMOCK-01 | P0; current tests, Testing failure capture | Characterize once/count/unmatched/destructor semantics with isolated expected failures and compile fixtures; preserve current examples. | sol_implementer |
|
||
| M-TESTINGMOCK-02 | P1; M-TESTINGMOCK-01, Testing context ownership | Session freeze/close, registration tokens and action-outside-lock reservation; reentrant actions complete, destroyed dynamic registrations cannot dangle. | astra_implementer |
|
||
| M-TESTINGMOCK-03 | P2; M-TESTINGMOCK-02 | Perfect forwarding, once/repeated actions, explicit prohibition/ranges/sequence groups; move-only args/returns and count races have defined results. | astra_implementer |
|
||
| M-TESTINGMOCK-04 | P2; M-TESTINGMOCK-03 | Bounded structured diagnostics, matcher combinators, property models and regression tests of the mock framework itself; injected wrong behavior is detected. | sol_implementer |
|
||
| M-TESTINGMOCK-05 | P3; M-TESTINGMOCK-04, Testing deterministic run, Async/Time contracts | Scripted async/file/transport faults and cancellation; no post-close callback and every script is replayable by seed. | astra_implementer |
|
||
| M-TESTINGMOCK-06 | P3; M-TESTINGMOCK-03, compiler probes | Reflection signature checks for overload/cv/ref/noexcept/inheritance cases; unsupported code generation remains explicitly unavailable. | sol_implementer |
|
||
|
||
P4 distributed tests reuse scripted ports; consensus assertions stay with Coordination and
|
||
Replication. Cross-module ownership is tracked in [dependencies](../DEPENDENCIES.md).
|
||
|
||
## Acceptance and migration
|
||
|
||
CURRENT TEMPLATE for verified names:
|
||
`<existing-build>/tests/VoidTests --filter '^(invokes_accepts_unique_ptr_capturing_lambda|verify_all_.*|failure_message_.*)$'`.
|
||
See [validation](../VALIDATION.md) for build prerequisites and actual baseline outcomes.
|
||
PROPOSED after M-TESTINGMOCK-02–05: deterministic two-call reservation races, action reentry,
|
||
action throwing, verification while calls are admitted, unmatched move-only return,
|
||
dynamic unregister, expired test context, never/range violations, scripted cancellation,
|
||
seed replay and diagnostics saturation. Compile-negative fixtures verify lifetime/signature
|
||
diagnostics separately from runtime tests. Use sanitizers where supported.
|
||
|
||
[Performance](../PERFORMANCE.md) measures matching cost versus expectation count, contention,
|
||
diagnostic allocation and reflection build cost, with p50/p95/p99 and peak RSS/CPU. Avoid
|
||
optimizations that skip mismatch evidence. [Migration](../MIGRATION.md) adds explicit sessions
|
||
first; legacy destructor verification stays documented until the major transition. Repeated
|
||
stateful actions must opt into concurrency; existing serial tests should need only optional
|
||
explicit close. Keep handwritten mocks usable when reflection lacks a capability.
|
||
|
||
Coverage: graph checks and direct reads covered cited files, including MockFunction's flagged
|
||
template parse range. New thread-safety, property/fuzz and async behavior is planned, not
|
||
verified by the existing move-only action test or this documentation change.
|