Files
Library/include/Void/TestingMock/Session.hpp
T

532 lines
14 KiB
C++

#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <atomic>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <format>
#include <functional>
#include <limits>
#include <memory>
#include <mutex>
#include <optional>
#include <stdexcept>
#include <string>
#include <string_view>
#include <thread>
#include <utility>
#include <vector>
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<std::int32_t>(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<Step> m_steps;
std::size_t m_cursor{0};
};
struct Verification {
std::vector<std::string> unmet{};
std::vector<std::string> excess{};
std::vector<std::string> unmatched{};
std::vector<std::string> prohibited{};
std::vector<std::string> matcher_errors{};
std::vector<std::string> threading_errors{};
std::vector<std::string> 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<std::string>& 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<void>
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<RegisteredEntry> participants{};
Verification report{};
bool verified{false};
void append_bounded(std::vector<std::string>& 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<Detail::SessionState> 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<Detail::SessionState> 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<Detail::SessionState>())
{
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<void>
freeze(Concurrency mode = Concurrency::SingleThread)
{
std::vector<Detail::SessionParticipant*> 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<Verification> 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<Detail::SessionParticipant*> 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<Detail::SessionState>&
state() const noexcept
{
return m_state;
}
private:
std::shared_ptr<Detail::SessionState> m_state;
};
[[nodiscard]] inline Void::Result::Result<void>
freeze(MockSession& session,
Concurrency mode = Concurrency::SingleThread)
{
return session.freeze(mode);
}
[[nodiscard]] inline Void::Result::Result<Verification>
verify_and_close(MockSession& session)
{
return session.verify_and_close();
}
} // namespace Void::TestingMock