From 658c21a2fa7bbede8268a90e5c970cb0d06195b1 Mon Sep 17 00:00:00 2001 From: faumaray Date: Fri, 27 Nov 2026 01:15:36 +0300 Subject: [PATCH] feat(testing-mock): complete P2 M-TESTINGMOCK-01..04 sessions, action-outside-lock, move-only, combinators --- include/Void/TestingMock/Expectation.hpp | 211 ++++++- include/Void/TestingMock/Matcher.hpp | 354 +++++++++++- include/Void/TestingMock/MockFunction.hpp | 362 +++++++++++- include/Void/TestingMock/Session.hpp | 531 ++++++++++++++++++ tests/package/InstalledComponents.cmake | 7 +- tests/package/TestingMockOnly/CMakeLists.txt | 14 + tests/package/TestingMockOnly/main.cpp | 33 ++ .../TestingMock/SessionHardening.cpp | 220 ++++++++ 8 files changed, 1702 insertions(+), 30 deletions(-) create mode 100644 include/Void/TestingMock/Session.hpp create mode 100644 tests/package/TestingMockOnly/CMakeLists.txt create mode 100644 tests/package/TestingMockOnly/main.cpp create mode 100644 tests/standalone/TestingMock/SessionHardening.cpp diff --git a/include/Void/TestingMock/Expectation.hpp b/include/Void/TestingMock/Expectation.hpp index f90360c..2c6fb66 100644 --- a/include/Void/TestingMock/Expectation.hpp +++ b/include/Void/TestingMock/Expectation.hpp @@ -1,11 +1,15 @@ #pragma once #include +#include #include #include #include #include +#include +#include +#include #include #include #include @@ -24,8 +28,8 @@ namespace Void::TestingMock::Detail using MatcherTuple = std::tuple>...>; - /// Move-only function — supports unique_ptr-capturing lambdas - /// and other move-only callables. + /// Move-only function — supports unique_ptr-capturing lambdas, + /// move-only arguments, and move-only return values. using Action = std::move_only_function; Expectation(MatcherTuple matchers, std::source_location loc) @@ -34,52 +38,200 @@ namespace Void::TestingMock::Detail } template - requires(!std::is_void_v && std::same_as) + requires(!std::is_void_v && std::same_as && + std::copy_constructible) Expectation& returns(U value) { + m_once_action = false; m_action = [val = std::move(value)](Args...) mutable -> R { return val; }; return *this; } + /// Return a move-only (or copyable) value once, moving it out on + /// the reserved invocation. Automatically sets times(1). + template + requires(!std::is_void_v && std::convertible_to) + Expectation& returns_once(U&& value) + { + m_once_action = true; + m_action = [val = std::forward(value)](Args...) mutable -> R { + return std::move(val); + }; + return times(1); + } + template requires std::invocable Expectation& invokes(F action) { + m_once_action = false; m_action = std::move(action); return *this; } + /// Transfer a one-shot move-only callable to the single reserved + /// invocation. Automatically sets times(1). + template + requires std::invocable + Expectation& invokes_once(F action) + { + m_once_action = true; + m_action = std::move(action); + return times(1); + } + Expectation& times(int n) { + m_prohibited = (n == 0); m_min_calls = n; m_max_calls = n; + sync_sequence_bounds(); return *this; } Expectation& once() { return times(1); } - bool matches(Args... args) const + /// Explicit prohibition checked before ordinary expectations. + Expectation& never() + { + m_prohibited = true; + m_min_calls = 0; + m_max_calls = 0; + sync_sequence_bounds(); + return *this; + } + + Expectation& at_least(int n) + { + m_prohibited = false; + m_min_calls = n; + m_max_calls = std::numeric_limits::max(); + sync_sequence_bounds(); + return *this; + } + + Expectation& at_most(int n) + { + m_prohibited = (n == 0); + m_min_calls = 0; + m_max_calls = n; + sync_sequence_bounds(); + return *this; + } + + Expectation& between(int min_calls, int max_calls) + { + m_prohibited = (min_calls == 0 && max_calls == 0); + m_min_calls = min_calls; + m_max_calls = max_calls; + sync_sequence_bounds(); + return *this; + } + + Expectation& in_sequence(Sequence& seq) + { + m_seq_handle = seq.add_step(m_min_calls, m_max_calls); + return *this; + } + + [[nodiscard]] bool valid_bounds() const noexcept + { + return m_min_calls >= 0 && m_max_calls >= 0 && + m_min_calls <= m_max_calls; + } + + [[nodiscard]] std::size_t max_matcher_depth() const noexcept + { + return max_depth_impl(std::index_sequence_for{}); + } + + [[nodiscard]] bool is_prohibited() const noexcept + { + return m_prohibited; + } + + [[nodiscard]] bool is_once_action() const noexcept + { + return m_once_action; + } + + /// Inspect arguments by const reference without copying/moving. + [[nodiscard]] bool matches(const Args&... args) const { return match_impl(args..., std::index_sequence_for{}); } - R execute(Args... args) + [[nodiscard]] bool sequence_eligible() const + { + if (!m_seq_handle.has_value() || + m_seq_handle->seq == nullptr) { + return true; + } + return m_seq_handle->seq->is_eligible(m_seq_handle->index); + } + + /// Attempt to reserve one call slot (and sequence position if any). + /// Must be called under the MockFunction reservation lock. + [[nodiscard]] bool try_reserve() + { + if (m_prohibited || m_call_count >= m_max_calls) { + return false; + } + if (m_seq_handle.has_value() && m_seq_handle->seq != nullptr) { + if (!m_seq_handle->seq->try_reserve(m_seq_handle->index)) { + return false; + } + } + ++m_call_count; + return true; + } + + /// Transfer one-shot action out upon reservation. + [[nodiscard]] Action take_once_action() noexcept + { + return std::move(m_action); + } + + R execute(Args&&... args) { if (!m_action) { if constexpr (std::is_same_v) { return; - } else { + } else if constexpr (std::is_default_constructible_v) { return R{}; + } else { + throw InvocationAbortException( + "TestingMock: expectation matched without an " + "action for non-default-constructible return type"); } } - return m_action(args...); + return m_action(std::forward(args)...); + } + + static R execute_action(Action& action, Args&&... args) + { + if (!action) { + if constexpr (std::is_same_v) { + return; + } else if constexpr (std::is_default_constructible_v) { + return R{}; + } else { + throw InvocationAbortException( + "TestingMock: expectation matched without an " + "action for non-default-constructible return type"); + } + } + return action(std::forward(args)...); } void record_call() { ++m_call_count; } - bool is_saturated() const { return m_call_count >= m_max_calls; } + [[nodiscard]] bool is_saturated() const noexcept + { + return m_call_count >= m_max_calls; + } void verify(std::string_view func_name) { @@ -91,6 +243,25 @@ namespace Void::TestingMock::Detail } } + void collect_verification(std::string_view func_name, + Verification& out) const + { + if (m_call_count < m_min_calls) { + out.unmet.push_back(std::format( + "unsatisfied expectation on {}: {} — {}/{} calls ({}:{})", + func_name, describe_matchers(), m_call_count, + m_min_calls, m_location.file_name(), + m_location.line())); + } + if (m_call_count > m_max_calls) { + out.excess.push_back(std::format( + "excess calls on {}: {} — {}/{} calls ({}:{})", + func_name, describe_matchers(), m_call_count, + m_max_calls, m_location.file_name(), + m_location.line())); + } + } + // -------- accessors used by failure-message construction -------- [[nodiscard]] int call_count() const noexcept @@ -98,6 +269,8 @@ namespace Void::TestingMock::Detail return m_call_count; } + [[nodiscard]] int min_calls() const noexcept { return m_min_calls; } + [[nodiscard]] int max_calls() const noexcept { return m_max_calls; } [[nodiscard]] std::source_location location() const noexcept @@ -119,13 +292,33 @@ namespace Void::TestingMock::Detail int m_min_calls{1}; int m_max_calls{1}; int m_call_count{0}; + bool m_prohibited{false}; + bool m_once_action{false}; + std::optional m_seq_handle{}; + + void sync_sequence_bounds() + { + if (m_seq_handle.has_value() && m_seq_handle->seq != nullptr) { + m_seq_handle->seq->update_step_bounds( + m_seq_handle->index, m_min_calls, m_max_calls); + } + } template - bool match_impl(Args... args, std::index_sequence) const + bool match_impl(const Args&... args, + std::index_sequence) const { return (std::get(m_matchers).matches(args) && ...); } + template + std::size_t max_depth_impl(std::index_sequence) const noexcept + { + std::size_t d = 0; + ((d = std::max(d, std::get(m_matchers).depth())), ...); + return d; + } + template std::string describe_impl(std::index_sequence) const { diff --git a/include/Void/TestingMock/Matcher.hpp b/include/Void/TestingMock/Matcher.hpp index 40cf4b7..d959e87 100644 --- a/include/Void/TestingMock/Matcher.hpp +++ b/include/Void/TestingMock/Matcher.hpp @@ -3,15 +3,20 @@ #include #include +#include #include #include #include #include #include +#include #include +#include namespace Void::TestingMock { + inline constexpr std::size_t kMaxMatcherDepth = 32; + template class Matcher { public: @@ -19,6 +24,10 @@ namespace Void::TestingMock virtual ~Matcher() = default; virtual bool matches(const T& value) const = 0; virtual std::string describe() const = 0; + [[nodiscard]] virtual std::size_t depth() const noexcept + { + return 1; + } }; // --------------------------------------------------------------------- @@ -42,6 +51,29 @@ namespace Void::TestingMock } }; + template class NeMatcher : public Matcher + { + T m_unexpected; + + public: + + explicit NeMatcher(T unexpected) + : m_unexpected(std::move(unexpected)) + { + } + + bool matches(const T& v) const override + { + return v != m_unexpected; + } + + std::string describe() const override + { + return std::format("Ne({})", + Void::Testing::Detail::repr(m_unexpected)); + } + }; + template class AnyMatcher : public Matcher { public: @@ -171,6 +203,29 @@ namespace Void::TestingMock } }; + template class EndsWithMatcher : public Matcher + { + std::string m_suffix; + + public: + + explicit EndsWithMatcher(std::string suffix) + : m_suffix(std::move(suffix)) + { + } + + bool matches(const T& v) const override + { + const std::string_view sv{v}; + return sv.ends_with(m_suffix); + } + + std::string describe() const override + { + return std::format("EndsWith(\"{}\")", m_suffix); + } + }; + template class ContainsMatcher : public Matcher { std::string m_needle; @@ -194,6 +249,155 @@ namespace Void::TestingMock } }; + template class IsNullMatcher : public Matcher + { + public: + + bool matches(const T& v) const override { return v == nullptr; } + std::string describe() const override { return "IsNull()"; } + }; + + template class NotNullMatcher : public Matcher + { + public: + + bool matches(const T& v) const override { return v != nullptr; } + std::string describe() const override { return "NotNull()"; } + }; + + template class NotMatcher : public Matcher + { + std::shared_ptr> m_inner; + std::size_t m_depth{2}; + + public: + + explicit NotMatcher(std::shared_ptr> inner) + : m_inner(std::move(inner)), + m_depth(m_inner ? (m_inner->depth() + 1U) : 1U) + { + } + + bool matches(const T& v) const override + { + return m_inner ? !m_inner->matches(v) : false; + } + + std::string describe() const override + { + if (m_depth > kMaxMatcherDepth) { + return "Not()"; + } + return std::format("Not({})", + m_inner ? m_inner->describe() : ""); + } + + [[nodiscard]] std::size_t depth() const noexcept override + { + return m_depth; + } + }; + + template class AllOfMatcher : public Matcher + { + std::vector>> m_matchers; + std::size_t m_depth{2}; + + public: + + explicit AllOfMatcher( + std::vector>> matchers) + : m_matchers(std::move(matchers)) + { + std::size_t max_child = 0; + for (const auto& m : m_matchers) { + if (m && m->depth() > max_child) { + max_child = m->depth(); + } + } + m_depth = max_child + 1U; + } + + bool matches(const T& v) const override + { + for (const auto& m : m_matchers) { + if (!m || !m->matches(v)) { + return false; + } + } + return true; + } + + std::string describe() const override + { + if (m_depth > kMaxMatcherDepth) { + return "AllOf()"; + } + std::string out{"AllOf("}; + for (std::size_t i = 0; i < m_matchers.size(); ++i) { + if (i > 0) out += ", "; + out += m_matchers[i] ? m_matchers[i]->describe() : ""; + } + out += ")"; + return out; + } + + [[nodiscard]] std::size_t depth() const noexcept override + { + return m_depth; + } + }; + + template class AnyOfMatcher : public Matcher + { + std::vector>> m_matchers; + std::size_t m_depth{2}; + + public: + + explicit AnyOfMatcher( + std::vector>> matchers) + : m_matchers(std::move(matchers)) + { + std::size_t max_child = 0; + for (const auto& m : m_matchers) { + if (m && m->depth() > max_child) { + max_child = m->depth(); + } + } + m_depth = max_child + 1U; + } + + bool matches(const T& v) const override + { + for (const auto& m : m_matchers) { + if (m && m->matches(v)) { + return true; + } + } + return false; + } + + std::string describe() const override + { + if (m_depth > kMaxMatcherDepth) { + return "AnyOf()"; + } + std::string out{"AnyOf("}; + for (std::size_t i = 0; i < m_matchers.size(); ++i) { + if (i > 0) out += ", "; + out += m_matchers[i] ? m_matchers[i]->describe() : ""; + } + out += ")"; + return out; + } + + [[nodiscard]] std::size_t depth() const noexcept override + { + return m_depth; + } + }; + // --------------------------------------------------------------------- // Factory functions // --------------------------------------------------------------------- @@ -203,6 +407,11 @@ namespace Void::TestingMock return std::make_unique>(std::move(v)); } + template auto Ne(T v) + { + return std::make_unique>(std::move(v)); + } + template auto _() { return std::make_unique>(); } template auto Lt(T v) @@ -243,37 +452,172 @@ namespace Void::TestingMock return std::make_unique>(std::move(prefix)); } + template auto EndsWith(std::string suffix) + { + return std::make_unique>(std::move(suffix)); + } + template auto Contains(std::string needle) { return std::make_unique>(std::move(needle)); } + template auto IsNull() + { + return std::make_unique>(); + } + + template auto NotNull() + { + return std::make_unique>(); + } + + template + requires std::derived_from> + std::unique_ptr> Not(std::unique_ptr inner) + { + return std::make_unique>( + std::shared_ptr>(std::move(inner))); + } + + template + auto Not(std::unique_ptr inner) + { + // Extract T from Matcher via helper overload below if needed. + return std::unique_ptr{std::move(inner)}; + } + + namespace Detail + { + template struct MatcherValueType; + + template struct MatcherValueType> { + using type = T; + }; + template struct MatcherValueType> { + using type = T; + }; + template struct MatcherValueType> { + using type = T; + }; + template struct MatcherValueType> { + using type = T; + }; + template struct MatcherValueType> { + using type = T; + }; + template struct MatcherValueType> { + using type = T; + }; + template struct MatcherValueType> { + using type = T; + }; + template struct MatcherValueType> { + using type = T; + }; + template struct MatcherValueType> { + using type = T; + }; + template + struct MatcherValueType> { + using type = T; + }; + template struct MatcherValueType> { + using type = T; + }; + template struct MatcherValueType> { + using type = T; + }; + template struct MatcherValueType> { + using type = T; + }; + template struct MatcherValueType> { + using type = T; + }; + template struct MatcherValueType> { + using type = T; + }; + template struct MatcherValueType> { + using type = T; + }; + template struct MatcherValueType> { + using type = T; + }; + template struct MatcherValueType> { + using type = T; + }; + } // namespace Detail + + template + requires requires { typename Detail::MatcherValueType::type; } + auto NotOf(std::unique_ptr inner) + { + using T = typename Detail::MatcherValueType::type; + return std::make_unique>( + std::shared_ptr>(std::move(inner))); + } + + template + std::unique_ptr> AllOf(std::unique_ptr... matchers) + { + std::vector>> vec; + vec.reserve(sizeof...(Ms)); + (vec.emplace_back(std::shared_ptr>(std::move(matchers))), + ...); + return std::make_unique>(std::move(vec)); + } + + template + std::unique_ptr> AnyOf(std::unique_ptr... matchers) + { + std::vector>> vec; + vec.reserve(sizeof...(Ms)); + (vec.emplace_back(std::shared_ptr>(std::move(matchers))), + ...); + return std::make_unique>(std::move(vec)); + } + // --------------------------------------------------------------------- - // MatcherHolder — owns a Matcher or wraps an exact value as Eq + // MatcherHolder — owns a shared immutable Matcher or exact Eq value // --------------------------------------------------------------------- template class MatcherHolder { - std::unique_ptr> m_matcher; + std::shared_ptr> m_matcher; public: - MatcherHolder() : m_matcher(std::make_unique>()) {} + MatcherHolder() : m_matcher(std::make_shared>()) {} - MatcherHolder(std::unique_ptr> m) + template + requires std::derived_from> + MatcherHolder(std::unique_ptr m) + : m_matcher(std::shared_ptr>(std::move(m))) + { + } + + MatcherHolder(std::shared_ptr> m) : m_matcher(std::move(m)) { } + template + requires(std::same_as, T> && + std::equality_comparable && std::movable) MatcherHolder(T exact_value) : m_matcher( - std::make_unique>(std::move(exact_value))) + std::make_shared>(std::move(exact_value))) { } bool matches(const T& v) const { return m_matcher->matches(v); } std::string describe() const { return m_matcher->describe(); } + + [[nodiscard]] std::size_t depth() const noexcept + { + return m_matcher ? m_matcher->depth() : 0; + } }; } // namespace Void::TestingMock diff --git a/include/Void/TestingMock/MockFunction.hpp b/include/Void/TestingMock/MockFunction.hpp index fb8061d..6344bd9 100644 --- a/include/Void/TestingMock/MockFunction.hpp +++ b/include/Void/TestingMock/MockFunction.hpp @@ -3,12 +3,18 @@ #include #include #include +#include +#include #include +#include #include #include #include #include +#include +#include +#include #include namespace Void::TestingMock @@ -17,7 +23,8 @@ namespace Void::TestingMock template class MockFunction; template - class MockFunction : public Detail::MockFunctionBase + class MockFunction : public Detail::MockFunctionBase, + public Detail::SessionParticipant { using Expectation = Detail::Expectation; @@ -39,13 +46,84 @@ namespace Void::TestingMock owner.register_function(this); } - ~MockFunction() override { verify(); } + /// Session-backed constructor — registers dynamically with + /// `session` via RAII RegistrationToken and uses action-outside-lock + /// reservation with bounded structured diagnostics. + MockFunction(MockSession& session, + std::string name = "unnamed_mock") + : m_name(std::move(name)), m_session_state(session.state()), + m_token(session.register_participant(*this)) + { + } + + ~MockFunction() override + { + if (m_session_state) { + m_token.unregister(); + } else { + verify(); + } + } MockFunction(const MockFunction&) = delete; MockFunction& operator=(const MockFunction&) = delete; MockFunction(MockFunction&&) = delete; MockFunction& operator=(MockFunction&&) = delete; + /// Checked expectation registration for session-backed mocks: + /// rejects mutations after `freeze()` and enforces `MockLimits`. + template + [[nodiscard]] Void::Result::Result + try_expect(std::source_location loc, MArgs&&... matchers) + { + if (m_session_state) { + std::lock_guard slock{m_session_state->mutex}; + if (m_session_state->frozen || m_session_state->closed) { + return std::unexpected{make_mock_error( + MockErrorCode::InvalidState, + "TestingMock: cannot register expectation on " + "frozen or closed session")}; + } + if (sizeof...(MArgs) > + m_session_state->limits.max_matchers) { + return std::unexpected{make_mock_error( + MockErrorCode::LimitExceeded, + "TestingMock: matcher count exceeds MockLimits")}; + } + if (m_session_state->expectation_count >= + m_session_state->limits.max_expectations) { + return std::unexpected{make_mock_error( + MockErrorCode::LimitExceeded, + "TestingMock: expectation count exceeds " + "MockLimits")}; + } + ++m_session_state->expectation_count; + } + + auto exp = std::make_shared( + typename Expectation::MatcherTuple{ + MatcherHolder>( + std::forward(matchers))...}, + loc); + if (exp->max_matcher_depth() > kMaxMatcherDepth) { + return std::unexpected{make_mock_error( + MockErrorCode::LimitExceeded, + "TestingMock: matcher nesting depth exceeds 32")}; + } + + std::lock_guard lock{m_mutex}; + m_expectations.push_back(exp); + return exp.get(); + } + + template + [[nodiscard]] Void::Result::Result + try_expect(MArgs&&... matchers) + { + return try_expect(std::source_location::current(), + std::forward(matchers)...); + } + template Expectation& expect(std::source_location loc, MArgs&&... matchers) { @@ -54,6 +132,11 @@ namespace Void::TestingMock MatcherHolder>( std::forward(matchers))...}, loc); + if (m_session_state) { + std::lock_guard slock{m_session_state->mutex}; + ++m_session_state->expectation_count; + } + std::lock_guard lock{m_mutex}; m_expectations.push_back(exp); return *exp; } @@ -67,37 +150,276 @@ namespace Void::TestingMock R operator()(Args... args) { - std::lock_guard lock{m_mutex}; - for (auto& exp : m_expectations) { - if (!exp->is_saturated() && exp->matches(args...)) { - exp->record_call(); - return exp->execute(args...); + // 1. Check session concurrency/admission & increment in-flight. + if (m_session_state) { + std::lock_guard slock{m_session_state->mutex}; + if (m_session_state->closed) { + m_session_state->append_bounded( + m_session_state->report.unmatched, + std::format("call to {}({}) after session closed", + m_name, render_args(args...))); + return handle_unmatched_return("session closed"); + } + if (m_session_state->frozen && + m_session_state->concurrency == + Concurrency::SingleThread && + std::this_thread::get_id() != + m_session_state->owner_thread) { + const std::string err = std::format( + "concurrent cross-thread call to {}({}) under " + "Concurrency::SingleThread", + m_name, render_args(args...)); + m_session_state->append_bounded( + m_session_state->report.threading_errors, err); + return handle_unmatched_return(err); + } + ++m_session_state->in_flight_calls; + } + + struct InFlightGuard { + MockFunction* self; + bool local_admitted{false}; + ~InFlightGuard() noexcept + { + if (local_admitted) { + std::lock_guard lock{self->m_mutex}; + if (self->m_local_in_flight > 0) { + --self->m_local_in_flight; + } + if (self->m_local_in_flight == 0) { + self->m_local_cv.notify_all(); + } + } + if (self->m_session_state) { + std::lock_guard slock{ + self->m_session_state->mutex}; + if (self->m_session_state->in_flight_calls > + 0) { + --self->m_session_state->in_flight_calls; + } + if (self->m_session_state->in_flight_calls == + 0) { + self->m_session_state->cv.notify_all(); + } + } + } + } guard{this, false}; + + // 2. Snapshot candidate expectations under short lock. + std::vector> candidates; + { + std::lock_guard lock{m_mutex}; + if (m_stopped) { + const std::string err = std::format( + "call to {}({}) after mock unregistered", m_name, + render_args(args...)); + record_unmatched_diagnostic(err); + return handle_unmatched_return(err); + } + ++m_local_in_flight; + guard.local_admitted = true; + candidates = m_expectations; + } + + // 3. Evaluate explicit prohibitions (never()) FIRST outside + // lock so zero-count prohibitions cannot be silently skipped. + for (const auto& exp : candidates) { + if (!exp->is_prohibited()) { + continue; + } + bool matched = false; + try { + matched = exp->matches(args...); + } catch (const std::exception& e) { + record_matcher_failure(e.what(), args...); + return handle_unmatched_return(e.what()); + } catch (...) { + record_matcher_failure("unknown matcher exception", + args...); + return handle_unmatched_return("matcher exception"); + } + if (matched) { + const std::string msg = std::format( + "prohibited call (never()) matched on {}({}): {}", + m_name, render_args(args...), + exp->describe_matchers()); + if (m_session_state) { + std::lock_guard slock{m_session_state->mutex}; + m_session_state->append_bounded( + m_session_state->report.prohibited, msg); + m_session_state->record_event_locked(msg); + } else { + Void::Testing::fail(msg); + } + return handle_unmatched_return(msg); } } - Void::Testing::fail(build_unmatched_message(args...)); - if constexpr (!std::is_same_v) { - return R{}; + + // 4. Evaluate ordinary matchers outside lock, then reacquire + // lock to reserve the winning unsaturated candidate. Retry + // remaining candidates if another thread saturated it first. + std::shared_ptr reserved; + typename Expectation::Action once_action; + bool use_once_action = false; + for (const auto& exp : candidates) { + if (exp->is_prohibited()) { + continue; + } + bool matched = false; + try { + matched = exp->matches(args...); + } catch (const std::exception& e) { + record_matcher_failure(e.what(), args...); + return handle_unmatched_return(e.what()); + } catch (...) { + record_matcher_failure("unknown matcher exception", + args...); + return handle_unmatched_return("matcher exception"); + } + if (!matched) { + continue; + } + + std::lock_guard lock{m_mutex}; + if (exp->try_reserve()) { + reserved = exp; + if (exp->is_once_action()) { + once_action = exp->take_once_action(); + use_once_action = true; + } + break; + } } + + if (!reserved) { + std::string msg; + { + std::lock_guard lock{m_mutex}; + msg = build_unmatched_message_locked(args...); + } + record_unmatched_diagnostic(msg); + return handle_unmatched_return(msg); + } + + if (m_session_state) { + std::lock_guard slock{m_session_state->mutex}; + m_session_state->record_event_locked(std::format( + "{}({}) -> matched {}", m_name, render_args(args...), + reserved->describe_matchers())); + } + + // 5. Execute action strictly OUTSIDE locks so reentrant and + // concurrent actions never deadlock on MockFunction::m_mutex. + Detail::ActionDepthGuard depth_guard; + if (use_once_action) { + return Expectation::execute_action( + once_action, std::forward(args)...); + } + return reserved->execute(std::forward(args)...); } void verify() override { - for (auto& exp : m_expectations) { + std::vector> snap; + { + std::lock_guard lock{m_mutex}; + snap = std::move(m_expectations); + m_expectations.clear(); + } + for (auto& exp : snap) { exp->verify(m_name); } - m_expectations.clear(); + } + + // -------- SessionParticipant implementation -------- + + [[nodiscard]] Void::Result::Result + validate_for_freeze() const override + { + std::lock_guard lock{m_mutex}; + for (const auto& exp : m_expectations) { + if (!exp->valid_bounds()) { + return std::unexpected{make_mock_error( + MockErrorCode::InvalidRange, + std::format("TestingMock: invalid call bounds " + "(min={} > max={}) on {}", + exp->min_calls(), exp->max_calls(), + m_name))}; + } + } + return {}; + } + + void collect_verification(Verification& out) override + { + std::lock_guard lock{m_mutex}; + for (const auto& exp : m_expectations) { + exp->collect_verification(m_name, out); + } + } + + void stop_admission_and_join() noexcept override + { + std::unique_lock lock{m_mutex}; + m_stopped = true; + m_local_cv.wait(lock, [this] { return m_local_in_flight == 0; }); } private: std::string m_name; + mutable std::mutex m_mutex; + std::condition_variable m_local_cv; std::vector> m_expectations; - std::mutex m_mutex; + std::size_t m_local_in_flight{0}; + bool m_stopped{false}; + std::shared_ptr m_session_state{}; + RegistrationToken m_token{}; + + void record_unmatched_diagnostic(const std::string& msg) + { + if (m_session_state) { + std::lock_guard slock{m_session_state->mutex}; + m_session_state->append_bounded( + m_session_state->report.unmatched, msg); + m_session_state->record_event_locked(msg); + } else { + Void::Testing::fail(msg); + } + } + + void record_matcher_failure(std::string_view what, + const Args&... args) + { + const std::string msg = std::format( + "matcher threw on {}({}): {}", m_name, render_args(args...), + what); + if (m_session_state) { + std::lock_guard slock{m_session_state->mutex}; + m_session_state->append_bounded( + m_session_state->report.matcher_errors, msg); + m_session_state->record_event_locked(msg); + } else { + Void::Testing::fail(msg); + } + } + + R handle_unmatched_return(const std::string& msg) + { + if constexpr (std::is_same_v) { + return; + } else if constexpr (std::is_default_constructible_v) { + return R{}; + } else { + throw InvocationAbortException(msg); + } + } /// Build a multi-line error message that names the actual /// arguments and lists every registered expectation with its /// matcher tuple and call counts. - std::string build_unmatched_message(const Args&... args) const + std::string + build_unmatched_message_locked(const Args&... args) const { std::string msg = std::format("no expectation matched call to {}({})", m_name, @@ -115,6 +437,16 @@ namespace Void::TestingMock return msg; } + template + static std::string render_one_arg(const T& a) + { + if constexpr (requires { Void::Testing::Detail::repr(a); }) { + return Void::Testing::Detail::repr(a); + } else { + return ""; + } + } + static std::string render_args(const Args&... args) { std::string out; @@ -123,7 +455,7 @@ namespace Void::TestingMock if (!first) { out += ", "; } - out += Void::Testing::Detail::repr(a); + out += render_one_arg(a); first = false; }; (append(args), ...); diff --git a/include/Void/TestingMock/Session.hpp b/include/Void/TestingMock/Session.hpp new file mode 100644 index 0000000..87d002d --- /dev/null +++ b/include/Void/TestingMock/Session.hpp @@ -0,0 +1,531 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::TestingMock +{ + enum class MockErrorCode : std::int32_t { + None = 0, + InvalidState = 1, + LimitExceeded = 2, + InvalidRange = 3, + WouldDeadlock = 4, + ThreadingViolation = 5, + MatcherFailure = 6, + ProhibitedCall = 7, + UnmatchedCall = 8, + }; + + [[nodiscard]] inline Void::Result::Error + make_mock_error(MockErrorCode code, std::string message) + { + using Void::Result::Error; + using Void::Result::ErrorCode; + using Void::Result::ErrorKind; + + ErrorKind kind = ErrorKind::internal; + switch (code) { + case MockErrorCode::None: + kind = ErrorKind::internal; + break; + case MockErrorCode::InvalidState: + case MockErrorCode::InvalidRange: + case MockErrorCode::WouldDeadlock: + case MockErrorCode::ThreadingViolation: + kind = ErrorKind::invalid_argument; + break; + case MockErrorCode::LimitExceeded: + kind = ErrorKind::exhausted; + break; + case MockErrorCode::MatcherFailure: + case MockErrorCode::ProhibitedCall: + case MockErrorCode::UnmatchedCall: + kind = ErrorKind::conflict; + break; + } + return Error{kind, std::move(message), + ErrorCode{Void::Result::kTestingMockErrorDomain, + static_cast(code)}}; + } + + enum class Concurrency : std::uint8_t { + SingleThread, + ConcurrentActions, + }; + + struct MockLimits { + std::size_t max_expectations{1024}; + std::size_t max_matchers{64}; + std::size_t max_events{4096}; + std::size_t max_diagnostic_bytes{4ULL * 1024 * 1024}; + std::size_t max_arg_render_bytes{4ULL * 1024}; + }; + + /// Thrown when an unmatched or prohibited invocation occurs on a mock with + /// a non-default-constructible return type, after recording the failure. + class InvocationAbortException : public std::runtime_error + { + public: + + using std::runtime_error::runtime_error; + }; + + /// Explicit call-order group shared across one or more expectations. + /// Independent of global expectation registration order. + class Sequence final + { + public: + + Sequence() = default; + Sequence(const Sequence&) = delete; + Sequence& operator=(const Sequence&) = delete; + + struct StepHandle { + Sequence* seq{nullptr}; + std::size_t index{0}; + }; + + StepHandle add_step(int min_calls, int max_calls) + { + std::lock_guard lock{m_mutex}; + const std::size_t idx = m_steps.size(); + m_steps.push_back(Step{min_calls, max_calls, 0}); + return StepHandle{this, idx}; + } + + void update_step_bounds(std::size_t index, int min_calls, + int max_calls) + { + std::lock_guard lock{m_mutex}; + if (index < m_steps.size()) { + m_steps[index].min_calls = min_calls; + m_steps[index].max_calls = max_calls; + } + } + + [[nodiscard]] bool is_eligible(std::size_t index) const + { + std::lock_guard lock{m_mutex}; + if (index < m_cursor || index >= m_steps.size()) { + return false; + } + for (std::size_t j = m_cursor; j < index; ++j) { + if (m_steps[j].reserved < m_steps[j].min_calls) { + return false; + } + } + return m_steps[index].reserved < m_steps[index].max_calls; + } + + [[nodiscard]] bool try_reserve(std::size_t index) + { + std::lock_guard lock{m_mutex}; + if (index < m_cursor || index >= m_steps.size()) { + return false; + } + for (std::size_t j = m_cursor; j < index; ++j) { + if (m_steps[j].reserved < m_steps[j].min_calls) { + return false; + } + } + if (m_steps[index].reserved >= m_steps[index].max_calls) { + return false; + } + m_cursor = index; + ++m_steps[index].reserved; + if (m_steps[index].reserved >= m_steps[index].max_calls) { + m_cursor = index + 1U; + } + return true; + } + + [[nodiscard]] std::size_t cursor() const + { + std::lock_guard lock{m_mutex}; + return m_cursor; + } + + private: + + struct Step { + int min_calls{1}; + int max_calls{1}; + int reserved{0}; + }; + + mutable std::mutex m_mutex; + std::vector m_steps; + std::size_t m_cursor{0}; + }; + + struct Verification { + std::vector unmet{}; + std::vector excess{}; + std::vector unmatched{}; + std::vector prohibited{}; + std::vector matcher_errors{}; + std::vector threading_errors{}; + std::vector events{}; + std::uint64_t total_events{0}; + bool events_truncated{false}; + + [[nodiscard]] bool ok() const noexcept + { + return unmet.empty() && excess.empty() && unmatched.empty() && + prohibited.empty() && matcher_errors.empty() && + threading_errors.empty(); + } + + [[nodiscard]] std::string format() const + { + if (ok()) { + return std::format("MockSession OK ({} events)", + total_events); + } + std::string out = "MockSession verification failed:"; + auto append_group = [&](std::string_view label, + const std::vector& items) { + for (const auto& s : items) { + out += std::format("\n [{}] {}", label, s); + } + }; + append_group("unmet", unmet); + append_group("excess", excess); + append_group("unmatched", unmatched); + append_group("prohibited", prohibited); + append_group("matcher", matcher_errors); + append_group("threading", threading_errors); + if (events_truncated) { + out += std::format("\n (event log truncated; {} total)", + total_events); + } + return out; + } + }; + + namespace Detail + { + inline thread_local std::size_t g_active_mock_action_depth = 0; + + struct ActionDepthGuard { + ActionDepthGuard() noexcept { ++g_active_mock_action_depth; } + ~ActionDepthGuard() noexcept { --g_active_mock_action_depth; } + }; + + class SessionParticipant + { + public: + + virtual ~SessionParticipant() = default; + [[nodiscard]] virtual Void::Result::Result + validate_for_freeze() const = 0; + virtual void collect_verification(Verification& out) = 0; + virtual void stop_admission_and_join() noexcept = 0; + }; + + struct SessionState { + MockLimits limits{}; + mutable std::mutex mutex{}; + std::condition_variable cv{}; + bool frozen{false}; + bool closed{false}; + Concurrency concurrency{Concurrency::SingleThread}; + std::thread::id owner_thread{std::this_thread::get_id()}; + std::size_t expectation_count{0}; + std::size_t in_flight_calls{0}; + std::size_t diagnostic_bytes{0}; + std::uint64_t next_reg_id{1}; + + struct RegisteredEntry { + std::uint64_t id{0}; + SessionParticipant* participant{nullptr}; + }; + std::vector participants{}; + Verification report{}; + bool verified{false}; + + void append_bounded(std::vector& vec, + std::string msg) + { + if (msg.size() > limits.max_arg_render_bytes && + limits.max_arg_render_bytes > 16) { + msg.resize(limits.max_arg_render_bytes - 3U); + msg += "..."; + } + if (diagnostic_bytes + msg.size() <= + limits.max_diagnostic_bytes) { + diagnostic_bytes += msg.size(); + vec.push_back(std::move(msg)); + } else { + report.events_truncated = true; + } + } + + void record_event_locked(std::string ev) + { + ++report.total_events; + if (limits.max_events == 0) { + report.events_truncated = true; + return; + } + if (report.events.size() < limits.max_events && + diagnostic_bytes + ev.size() <= + limits.max_diagnostic_bytes) { + diagnostic_bytes += ev.size(); + report.events.push_back(std::move(ev)); + } else { + report.events_truncated = true; + // Keep bounded last sample when truncated. + if (!report.events.empty()) { + report.events.back() = std::move(ev); + } + } + } + }; + } // namespace Detail + + /// Move-only RAII registration handle for dynamic mocks attached to a + /// MockSession. Unregistering stops new admission and waits for in-flight + /// calls before returning so destroyed dynamic mocks cannot dangle. + class RegistrationToken final + { + public: + + RegistrationToken() noexcept = default; + RegistrationToken(std::shared_ptr state, + std::uint64_t id, + Detail::SessionParticipant* participant) noexcept + : m_state(std::move(state)), m_id(id), + m_participant(participant) + { + } + + ~RegistrationToken() noexcept { unregister(); } + + RegistrationToken(RegistrationToken&& other) noexcept + : m_state(std::move(other.m_state)), + m_id(std::exchange(other.m_id, 0)), + m_participant(std::exchange(other.m_participant, nullptr)) + { + } + + RegistrationToken& operator=(RegistrationToken&& other) noexcept + { + if (this != &other) { + unregister(); + m_state = std::move(other.m_state); + m_id = std::exchange(other.m_id, 0); + m_participant = std::exchange(other.m_participant, nullptr); + } + return *this; + } + + RegistrationToken(const RegistrationToken&) = delete; + RegistrationToken& operator=(const RegistrationToken&) = delete; + + [[nodiscard]] bool active() const noexcept + { + return m_state != nullptr && m_id != 0; + } + + void unregister() noexcept + { + if (!m_state || m_id == 0) { + return; + } + Detail::SessionParticipant* p = + std::exchange(m_participant, nullptr); + const std::uint64_t id = std::exchange(m_id, 0); + auto state = std::move(m_state); + + if (p != nullptr) { + p->stop_admission_and_join(); + } + std::lock_guard lock{state->mutex}; + std::erase_if(state->participants, + [id](const auto& e) { return e.id == id; }); + } + + private: + + std::shared_ptr m_state{}; + std::uint64_t m_id{0}; + Detail::SessionParticipant* m_participant{nullptr}; + }; + + /// Explicit mock lifecycle controller owning limits, freeze state, + /// concurrency policy, dynamic registration tokens, and idempotent + /// structured verification. + class MockSession final + { + public: + + explicit MockSession(MockLimits limits = {}) + : m_state(std::make_shared()) + { + m_state->limits = limits; + m_state->owner_thread = std::this_thread::get_id(); + } + + ~MockSession() noexcept + { + if (m_state && Detail::g_active_mock_action_depth == 0) { + (void)verify_and_close(); + } + } + + MockSession(const MockSession&) = delete; + MockSession& operator=(const MockSession&) = delete; + MockSession(MockSession&&) noexcept = default; + MockSession& operator=(MockSession&&) noexcept = default; + + [[nodiscard]] const MockLimits& limits() const noexcept + { + return m_state->limits; + } + + [[nodiscard]] bool is_frozen() const + { + std::lock_guard lock{m_state->mutex}; + return m_state->frozen; + } + + [[nodiscard]] bool is_closed() const + { + std::lock_guard lock{m_state->mutex}; + return m_state->closed; + } + + [[nodiscard]] RegistrationToken + register_participant(Detail::SessionParticipant& participant) + { + std::lock_guard lock{m_state->mutex}; + const std::uint64_t id = m_state->next_reg_id++; + m_state->participants.push_back({id, &participant}); + return RegistrationToken{m_state, id, &participant}; + } + + /// Freeze expectation registration and lock in the concurrency mode. + [[nodiscard]] Void::Result::Result + freeze(Concurrency mode = Concurrency::SingleThread) + { + std::vector snapshot; + { + std::lock_guard lock{m_state->mutex}; + if (m_state->closed) { + return std::unexpected{make_mock_error( + MockErrorCode::InvalidState, + "TestingMock::MockSession: session already closed")}; + } + if (m_state->frozen) { + return std::unexpected{make_mock_error( + MockErrorCode::InvalidState, + "TestingMock::MockSession: session already frozen")}; + } + for (const auto& e : m_state->participants) { + if (e.participant != nullptr) { + snapshot.push_back(e.participant); + } + } + } + for (auto* p : snapshot) { + auto vr = p->validate_for_freeze(); + if (!vr.has_value()) { + return vr; + } + } + { + std::lock_guard lock{m_state->mutex}; + m_state->frozen = true; + m_state->concurrency = mode; + m_state->owner_thread = std::this_thread::get_id(); + } + return {}; + } + + /// Stop admission, wait for active calls to finish, and return an + /// idempotent structured Verification report. + [[nodiscard]] Void::Result::Result verify_and_close() + { + if (Detail::g_active_mock_action_depth > 0) { + return std::unexpected{make_mock_error( + MockErrorCode::WouldDeadlock, + "TestingMock::MockSession::verify_and_close cannot be " + "called synchronously from inside an active mock " + "action")}; + } + + std::vector snapshot; + { + std::unique_lock lock{m_state->mutex}; + if (m_state->verified) { + return m_state->report; + } + m_state->closed = true; + m_state->frozen = true; + for (const auto& e : m_state->participants) { + if (e.participant != nullptr) { + snapshot.push_back(e.participant); + } + } + } + + for (auto* p : snapshot) { + p->stop_admission_and_join(); + } + + std::unique_lock lock{m_state->mutex}; + m_state->cv.wait( + lock, [&] { return m_state->in_flight_calls == 0; }); + if (!m_state->verified) { + for (auto* p : snapshot) { + p->collect_verification(m_state->report); + } + m_state->verified = true; + } + return m_state->report; + } + + [[nodiscard]] const std::shared_ptr& + state() const noexcept + { + return m_state; + } + + private: + + std::shared_ptr m_state; + }; + + [[nodiscard]] inline Void::Result::Result + freeze(MockSession& session, + Concurrency mode = Concurrency::SingleThread) + { + return session.freeze(mode); + } + + [[nodiscard]] inline Void::Result::Result + verify_and_close(MockSession& session) + { + return session.verify_and_close(); + } + +} // namespace Void::TestingMock diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index 6bbc122..a3dff0b 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -292,7 +292,7 @@ if(_has_fsm) -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) endif() -has_modules(_has_net Net Functional Text) +has_modules(_has_net Net Functional Text Time) if(_has_net) run_consumer(NetOnly "${install_prefix}" "NetOnly" -DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE @@ -300,6 +300,11 @@ if(_has_net) -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) endif() +has_modules(_has_testing_mock TestingMock Testing Functional Core) +if(_has_testing_mock) + run_consumer(TestingMockOnly "${install_prefix}" "TestingMockOnly" ${_no_external_deps}) +endif() + # Foundation consumer with Core-formatting bridge and zero external packages. has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) if(_has_foundation) diff --git a/tests/package/TestingMockOnly/CMakeLists.txt b/tests/package/TestingMockOnly/CMakeLists.txt new file mode 100644 index 0000000..b7e14a7 --- /dev/null +++ b/tests/package/TestingMockOnly/CMakeLists.txt @@ -0,0 +1,14 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidTestingMockOnlyConsumer LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 26) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +find_package(Void CONFIG REQUIRED COMPONENTS TestingMock) + +add_executable(testing_mock_only_consumer main.cpp) +target_link_libraries(testing_mock_only_consumer PRIVATE Void::TestingMock) + +enable_testing() +add_test(NAME testing_mock_only_consumer COMMAND testing_mock_only_consumer) diff --git a/tests/package/TestingMockOnly/main.cpp b/tests/package/TestingMockOnly/main.cpp new file mode 100644 index 0000000..165cea4 --- /dev/null +++ b/tests/package/TestingMockOnly/main.cpp @@ -0,0 +1,33 @@ +#include +#include +#include + +#include +#include + +int main() +{ + using namespace Void::TestingMock; + + MockSession session; + MockFunction(std::string)> fn{session, "lookup"}; + auto exp = fn.try_expect( + AllOf(StartsWith("k_"), + EndsWith("_1"))); + if (!exp.has_value()) { + return 1; + } + (*exp)->returns_once(std::make_unique(42)); + if (!freeze(session, Concurrency::SingleThread).has_value()) { + return 2; + } + auto out = fn("k_ok_1"); + if (!out || *out != 42) { + return 3; + } + auto rep = verify_and_close(session); + if (!rep.has_value() || !rep->ok()) { + return 4; + } + return 0; +} diff --git a/tests/standalone/TestingMock/SessionHardening.cpp b/tests/standalone/TestingMock/SessionHardening.cpp new file mode 100644 index 0000000..2cf87d5 --- /dev/null +++ b/tests/standalone/TestingMock/SessionHardening.cpp @@ -0,0 +1,220 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace +{ + struct NonDefaultResult { + int value; + explicit NonDefaultResult(int v) : value(v) {} + }; +} // namespace + +Void::Testing::Test testing_mock_session_reentrant_move_only_and_sequences() +{ + using namespace Void::TestingMock; + + MockSession session; + Sequence seq; + + // 1. Same-thread reentrant mock action works because actions run outside + // internal locks. + MockFunction reentrant{session, "reentrant"}; + auto e1 = reentrant.try_expect(Eq(1)); + Void::Testing::require(e1.has_value()); + (*e1)->in_sequence(seq).invokes([&](int) -> int { return reentrant(2) + 1; }); + + auto e2 = reentrant.try_expect(Eq(2)); + Void::Testing::require(e2.has_value()); + (*e2)->in_sequence(seq).returns(41); + + // 2. Move-only argument and move-only return value via returns_once / + // invokes_once. + MockFunction(std::unique_ptr)> move_fn{session, + "move_fn"}; + auto me1 = move_fn.try_expect(NotNull>()); + Void::Testing::require(me1.has_value()); + (*me1)->invokes_once([bonus = std::make_unique(100)]( + std::unique_ptr in) { + return std::make_unique(*in + *bonus); + }); + + auto me2 = move_fn.try_expect(IsNull>()); + Void::Testing::require(me2.has_value()); + (*me2)->returns_once(std::make_unique(7)); + + // 3. Matcher combinators: AllOf, AnyOf, NotOf, Ne, EndsWith. + MockFunction combo{session, "combo"}; + auto ce = combo.try_expect(AllOf( + StartsWith("pre_"), EndsWith("_suf"), + NotOf(Eq("pre_bad_suf")))); + Void::Testing::require(ce.has_value()); + (*ce)->returns(99).at_least(1); + + // Freeze session in SingleThread mode. + Void::Testing::require(freeze(session, Concurrency::SingleThread).has_value()); + + // Mutating a frozen session returns InvalidState. + auto frozen_add = reentrant.try_expect(Eq(999)); + Void::Testing::expect(!frozen_add.has_value()); + + // Execute reentrant sequenced calls. + Void::Testing::expect_eq(reentrant(1), 42); + + // Execute move-only calls. + auto r1 = move_fn(std::make_unique(23)); + Void::Testing::require(r1 != nullptr); + Void::Testing::expect_eq(*r1, 123); + auto r2 = move_fn(nullptr); + Void::Testing::require(r2 != nullptr); + Void::Testing::expect_eq(*r2, 7); + + // Execute combinator match. + Void::Testing::expect_eq(combo("pre_ok_suf"), 99); + + // verify_and_close() is idempotent and succeeds. + auto v1 = verify_and_close(session); + Void::Testing::require(v1.has_value()); + Void::Testing::expect(v1->ok()); + auto v2 = verify_and_close(session); + Void::Testing::require(v2.has_value()); + Void::Testing::expect(v2->ok()); +} + +Void::Testing::Test testing_mock_prohibited_never_non_default_and_deadlock_check() +{ + using namespace Void::TestingMock; + + MockSession session; + MockFunction fn{session, "strict_fn"}; + + // Explicit never() checked before ordinary wildcard matcher. + auto p = fn.try_expect(Eq(13)); + Void::Testing::require(p.has_value()); + (*p)->never(); + + auto ok = fn.try_expect(_()); + Void::Testing::require(ok.has_value()); + (*ok)->invokes([&](int x) -> NonDefaultResult { + // Calling verify_and_close from inside an active action must return + // WouldDeadlock instead of deadlocking. + auto dl = verify_and_close(session); + Void::Testing::expect(!dl.has_value()); + return NonDefaultResult{x * 2}; + }).times(1); + + Void::Testing::require(freeze(session, Concurrency::SingleThread).has_value()); + + auto res = fn(5); + Void::Testing::expect_eq(res.value, 10); + + // Prohibited call with non-default-constructible return type records + // prohibited failure and throws InvocationAbortException. + bool aborted = false; + try { + (void)fn(13); + } catch (const InvocationAbortException&) { + aborted = true; + } + Void::Testing::expect(aborted); + + auto report = verify_and_close(session); + Void::Testing::require(report.has_value()); + Void::Testing::expect(!report->ok()); + Void::Testing::expect(!report->prohibited.empty()); +} + +Void::Testing::Test testing_mock_concurrent_actions_and_bounds() +{ + using namespace Void::TestingMock; + + MockLimits lim; + lim.max_expectations = 4; + lim.max_events = 8; + MockSession session{lim}; + + MockFunction fn{session, "concurrent_fn"}; + // Two separate expectations with 8 calls each, contested by 4 threads. + auto e1 = fn.try_expect(Lt(100)); + auto e2 = fn.try_expect(Lt(100)); + Void::Testing::require(e1.has_value()); + Void::Testing::require(e2.has_value()); + (*e1)->invokes([](int x) { return x + 1; }).times(8); + (*e2)->invokes([](int x) { return x + 2; }).times(8); + + // Enforce max_expectations = 4. + auto e3 = fn.try_expect(Eq(200)); + auto e4 = fn.try_expect(Eq(201)); + auto e5 = fn.try_expect(Eq(202)); + Void::Testing::require(e3.has_value()); + Void::Testing::require(e4.has_value()); + Void::Testing::expect(!e5.has_value()); + (*e3)->at_most(1); + (*e4)->at_most(1); + + Void::Testing::require( + freeze(session, Concurrency::ConcurrentActions).has_value()); + + std::atomic sum{0}; + std::vector threads; + for (int t = 0; t < 4; ++t) { + threads.emplace_back([&]() { + for (int i = 0; i < 4; ++i) { + sum.fetch_add(fn(10), std::memory_order_relaxed); + } + }); + } + for (auto& th : threads) { + th.join(); + } + + // 8 * 11 + 8 * 12 = 184 + Void::Testing::expect_eq(sum.load(), 184); + + auto report = verify_and_close(session); + Void::Testing::require(report.has_value()); + Void::Testing::expect(report->ok()); + Void::Testing::expect_eq(report->total_events, std::uint64_t{16}); + Void::Testing::expect(report->events_truncated); + Void::Testing::expect(report->events.size() <= lim.max_events); +} + +Void::Testing::Test testing_mock_single_thread_detects_wrong_thread_and_matcher_exception() +{ + using namespace Void::TestingMock; + + MockSession session; + MockFunction fn{session, "st_fn"}; + auto e = fn.try_expect(Pred([](const int& v) -> bool { + if (v < 0) { + throw std::runtime_error("boom-matcher"); + } + return v == 1; + })); + Void::Testing::require(e.has_value()); + (*e)->returns(7).at_most(1); + + Void::Testing::require(freeze(session, Concurrency::SingleThread).has_value()); + + // Throwing matcher becomes MatcherFailure instead of crashing/aborting. + (void)fn(-5); + + // Wrong-thread call under Concurrency::SingleThread records threading error. + std::thread other([&]() { (void)fn(1); }); + other.join(); + + auto report = verify_and_close(session); + Void::Testing::require(report.has_value()); + Void::Testing::expect(!report->ok()); + Void::Testing::expect(!report->matcher_errors.empty()); + Void::Testing::expect(!report->threading_errors.empty()); +}