#pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace Void::TestingMock { template class MockFunction; template class MockFunction : public Detail::MockFunctionBase, public Detail::SessionParticipant { using Expectation = Detail::Expectation; public: /// Standalone constructor — no auto-registration. The /// destructor will still call verify() so isolated tests work /// without a Mock wrapper. explicit MockFunction(std::string name = "unnamed_mock") : m_name(std::move(name)) { } /// Owner-aware constructor — registers with `owner` so /// `owner.verify_all()` drives this mock's verify(). MockFunction(MockBase& owner, std::string name = "unnamed_mock") : m_name(std::move(name)) { owner.register_function(this); } /// 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) { auto exp = std::make_shared( typename Expectation::MatcherTuple{ 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; } template Expectation& expect(MArgs&&... matchers) { return expect(std::source_location::current(), std::forward(matchers)...); } R operator()(Args... 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); } } // 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 { 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); } } // -------- 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::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_locked(const Args&... args) const { std::string msg = std::format("no expectation matched call to {}({})", m_name, render_args(args...)); if (m_expectations.empty()) { msg += "\n (no expectations registered)"; return msg; } for (std::size_t i = 0; i < m_expectations.size(); ++i) { const auto& exp = *m_expectations[i]; msg += std::format("\n expectation {}: {} — {}/{} calls", i + 1, exp.describe_matchers(), exp.call_count(), exp.max_calls()); } 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; bool first = true; auto append = [&](const auto& a) { if (!first) { out += ", "; } out += render_one_arg(a); first = false; }; (append(args), ...); return out; } }; } // namespace Void::TestingMock