feat(testing-mock): complete P2 M-TESTINGMOCK-01..04 sessions, action-outside-lock, move-only, combinators
This commit is contained in:
1 parent
86d777eae6
commit
658c21a2fa
8 files changed
+1702
-30
No files matched your search
@@ -1,11 +1,15 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/TestingMock/Matcher.hpp>
|
||||
#include <Void/TestingMock/Session.hpp>
|
||||
|
||||
#include <concepts>
|
||||
#include <cstddef>
|
||||
#include <format>
|
||||
#include <functional>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <source_location>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
@@ -24,8 +28,8 @@ namespace Void::TestingMock::Detail
|
||||
|
||||
using MatcherTuple =
|
||||
std::tuple<MatcherHolder<std::decay_t<Args>>...>;
|
||||
/// 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<R(Args...)>;
|
||||
|
||||
Expectation(MatcherTuple matchers, std::source_location loc)
|
||||
@@ -34,52 +38,200 @@ namespace Void::TestingMock::Detail
|
||||
}
|
||||
|
||||
template <typename U = R>
|
||||
requires(!std::is_void_v<U> && std::same_as<U, R>)
|
||||
requires(!std::is_void_v<U> && std::same_as<U, R> &&
|
||||
std::copy_constructible<U>)
|
||||
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 <typename U = R>
|
||||
requires(!std::is_void_v<U> && std::convertible_to<U, R>)
|
||||
Expectation& returns_once(U&& value)
|
||||
{
|
||||
m_once_action = true;
|
||||
m_action = [val = std::forward<U>(value)](Args...) mutable -> R {
|
||||
return std::move(val);
|
||||
};
|
||||
return times(1);
|
||||
}
|
||||
|
||||
template <typename F>
|
||||
requires std::invocable<F&, Args...>
|
||||
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 <typename F>
|
||||
requires std::invocable<F&, Args...>
|
||||
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<int>::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<Args...>{});
|
||||
}
|
||||
|
||||
[[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<Args...>{});
|
||||
}
|
||||
|
||||
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<R, void>) {
|
||||
return;
|
||||
} else {
|
||||
} else if constexpr (std::is_default_constructible_v<R>) {
|
||||
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>(args)...);
|
||||
}
|
||||
|
||||
static R execute_action(Action& action, Args&&... args)
|
||||
{
|
||||
if (!action) {
|
||||
if constexpr (std::is_same_v<R, void>) {
|
||||
return;
|
||||
} else if constexpr (std::is_default_constructible_v<R>) {
|
||||
return R{};
|
||||
} else {
|
||||
throw InvocationAbortException(
|
||||
"TestingMock: expectation matched without an "
|
||||
"action for non-default-constructible return type");
|
||||
}
|
||||
}
|
||||
return action(std::forward<Args>(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<Sequence::StepHandle> 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 <std::size_t... Is>
|
||||
bool match_impl(Args... args, std::index_sequence<Is...>) const
|
||||
bool match_impl(const Args&... args,
|
||||
std::index_sequence<Is...>) const
|
||||
{
|
||||
return (std::get<Is>(m_matchers).matches(args) && ...);
|
||||
}
|
||||
|
||||
template <std::size_t... Is>
|
||||
std::size_t max_depth_impl(std::index_sequence<Is...>) const noexcept
|
||||
{
|
||||
std::size_t d = 0;
|
||||
((d = std::max(d, std::get<Is>(m_matchers).depth())), ...);
|
||||
return d;
|
||||
}
|
||||
|
||||
template <std::size_t... Is>
|
||||
std::string describe_impl(std::index_sequence<Is...>) const
|
||||
{
|
||||
|
||||
@@ -3,15 +3,20 @@
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
|
||||
#include <concepts>
|
||||
#include <cstddef>
|
||||
#include <format>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::TestingMock
|
||||
{
|
||||
inline constexpr std::size_t kMaxMatcherDepth = 32;
|
||||
|
||||
template <typename T> 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 <typename T> class NeMatcher : public Matcher<T>
|
||||
{
|
||||
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 <typename T> class AnyMatcher : public Matcher<T>
|
||||
{
|
||||
public:
|
||||
@@ -171,6 +203,29 @@ namespace Void::TestingMock
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T> class EndsWithMatcher : public Matcher<T>
|
||||
{
|
||||
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 <typename T> class ContainsMatcher : public Matcher<T>
|
||||
{
|
||||
std::string m_needle;
|
||||
@@ -194,6 +249,155 @@ namespace Void::TestingMock
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T> class IsNullMatcher : public Matcher<T>
|
||||
{
|
||||
public:
|
||||
|
||||
bool matches(const T& v) const override { return v == nullptr; }
|
||||
std::string describe() const override { return "IsNull()"; }
|
||||
};
|
||||
|
||||
template <typename T> class NotNullMatcher : public Matcher<T>
|
||||
{
|
||||
public:
|
||||
|
||||
bool matches(const T& v) const override { return v != nullptr; }
|
||||
std::string describe() const override { return "NotNull()"; }
|
||||
};
|
||||
|
||||
template <typename T> class NotMatcher : public Matcher<T>
|
||||
{
|
||||
std::shared_ptr<const Matcher<T>> m_inner;
|
||||
std::size_t m_depth{2};
|
||||
|
||||
public:
|
||||
|
||||
explicit NotMatcher(std::shared_ptr<const Matcher<T>> 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(<depth-limit>)";
|
||||
}
|
||||
return std::format("Not({})",
|
||||
m_inner ? m_inner->describe() : "<null>");
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t depth() const noexcept override
|
||||
{
|
||||
return m_depth;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T> class AllOfMatcher : public Matcher<T>
|
||||
{
|
||||
std::vector<std::shared_ptr<const Matcher<T>>> m_matchers;
|
||||
std::size_t m_depth{2};
|
||||
|
||||
public:
|
||||
|
||||
explicit AllOfMatcher(
|
||||
std::vector<std::shared_ptr<const Matcher<T>>> 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(<depth-limit>)";
|
||||
}
|
||||
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() : "<null>";
|
||||
}
|
||||
out += ")";
|
||||
return out;
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t depth() const noexcept override
|
||||
{
|
||||
return m_depth;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T> class AnyOfMatcher : public Matcher<T>
|
||||
{
|
||||
std::vector<std::shared_ptr<const Matcher<T>>> m_matchers;
|
||||
std::size_t m_depth{2};
|
||||
|
||||
public:
|
||||
|
||||
explicit AnyOfMatcher(
|
||||
std::vector<std::shared_ptr<const Matcher<T>>> 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(<depth-limit>)";
|
||||
}
|
||||
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() : "<null>";
|
||||
}
|
||||
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<EqMatcher<T>>(std::move(v));
|
||||
}
|
||||
|
||||
template <typename T> auto Ne(T v)
|
||||
{
|
||||
return std::make_unique<NeMatcher<T>>(std::move(v));
|
||||
}
|
||||
|
||||
template <typename T> auto _() { return std::make_unique<AnyMatcher<T>>(); }
|
||||
|
||||
template <typename T> auto Lt(T v)
|
||||
@@ -243,37 +452,172 @@ namespace Void::TestingMock
|
||||
return std::make_unique<StartsWithMatcher<T>>(std::move(prefix));
|
||||
}
|
||||
|
||||
template <typename T = std::string> auto EndsWith(std::string suffix)
|
||||
{
|
||||
return std::make_unique<EndsWithMatcher<T>>(std::move(suffix));
|
||||
}
|
||||
|
||||
template <typename T = std::string> auto Contains(std::string needle)
|
||||
{
|
||||
return std::make_unique<ContainsMatcher<T>>(std::move(needle));
|
||||
}
|
||||
|
||||
template <typename T> auto IsNull()
|
||||
{
|
||||
return std::make_unique<IsNullMatcher<T>>();
|
||||
}
|
||||
|
||||
template <typename T> auto NotNull()
|
||||
{
|
||||
return std::make_unique<NotNullMatcher<T>>();
|
||||
}
|
||||
|
||||
template <typename T, typename Derived>
|
||||
requires std::derived_from<Derived, Matcher<T>>
|
||||
std::unique_ptr<Matcher<T>> Not(std::unique_ptr<Derived> inner)
|
||||
{
|
||||
return std::make_unique<NotMatcher<T>>(
|
||||
std::shared_ptr<const Matcher<T>>(std::move(inner)));
|
||||
}
|
||||
|
||||
template <typename Derived>
|
||||
auto Not(std::unique_ptr<Derived> inner)
|
||||
{
|
||||
// Extract T from Matcher<T> via helper overload below if needed.
|
||||
return std::unique_ptr<Derived>{std::move(inner)};
|
||||
}
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
template <typename T> struct MatcherValueType;
|
||||
|
||||
template <typename T> struct MatcherValueType<Matcher<T>> {
|
||||
using type = T;
|
||||
};
|
||||
template <typename T> struct MatcherValueType<EqMatcher<T>> {
|
||||
using type = T;
|
||||
};
|
||||
template <typename T> struct MatcherValueType<NeMatcher<T>> {
|
||||
using type = T;
|
||||
};
|
||||
template <typename T> struct MatcherValueType<AnyMatcher<T>> {
|
||||
using type = T;
|
||||
};
|
||||
template <typename T> struct MatcherValueType<LtMatcher<T>> {
|
||||
using type = T;
|
||||
};
|
||||
template <typename T> struct MatcherValueType<LeMatcher<T>> {
|
||||
using type = T;
|
||||
};
|
||||
template <typename T> struct MatcherValueType<GtMatcher<T>> {
|
||||
using type = T;
|
||||
};
|
||||
template <typename T> struct MatcherValueType<GeMatcher<T>> {
|
||||
using type = T;
|
||||
};
|
||||
template <typename T> struct MatcherValueType<RangeMatcher<T>> {
|
||||
using type = T;
|
||||
};
|
||||
template <typename T, typename Fn>
|
||||
struct MatcherValueType<PredMatcher<T, Fn>> {
|
||||
using type = T;
|
||||
};
|
||||
template <typename T> struct MatcherValueType<StartsWithMatcher<T>> {
|
||||
using type = T;
|
||||
};
|
||||
template <typename T> struct MatcherValueType<EndsWithMatcher<T>> {
|
||||
using type = T;
|
||||
};
|
||||
template <typename T> struct MatcherValueType<ContainsMatcher<T>> {
|
||||
using type = T;
|
||||
};
|
||||
template <typename T> struct MatcherValueType<IsNullMatcher<T>> {
|
||||
using type = T;
|
||||
};
|
||||
template <typename T> struct MatcherValueType<NotNullMatcher<T>> {
|
||||
using type = T;
|
||||
};
|
||||
template <typename T> struct MatcherValueType<NotMatcher<T>> {
|
||||
using type = T;
|
||||
};
|
||||
template <typename T> struct MatcherValueType<AllOfMatcher<T>> {
|
||||
using type = T;
|
||||
};
|
||||
template <typename T> struct MatcherValueType<AnyOfMatcher<T>> {
|
||||
using type = T;
|
||||
};
|
||||
} // namespace Detail
|
||||
|
||||
template <typename M>
|
||||
requires requires { typename Detail::MatcherValueType<M>::type; }
|
||||
auto NotOf(std::unique_ptr<M> inner)
|
||||
{
|
||||
using T = typename Detail::MatcherValueType<M>::type;
|
||||
return std::make_unique<NotMatcher<T>>(
|
||||
std::shared_ptr<const Matcher<T>>(std::move(inner)));
|
||||
}
|
||||
|
||||
template <typename T, typename... Ms>
|
||||
std::unique_ptr<Matcher<T>> AllOf(std::unique_ptr<Ms>... matchers)
|
||||
{
|
||||
std::vector<std::shared_ptr<const Matcher<T>>> vec;
|
||||
vec.reserve(sizeof...(Ms));
|
||||
(vec.emplace_back(std::shared_ptr<const Matcher<T>>(std::move(matchers))),
|
||||
...);
|
||||
return std::make_unique<AllOfMatcher<T>>(std::move(vec));
|
||||
}
|
||||
|
||||
template <typename T, typename... Ms>
|
||||
std::unique_ptr<Matcher<T>> AnyOf(std::unique_ptr<Ms>... matchers)
|
||||
{
|
||||
std::vector<std::shared_ptr<const Matcher<T>>> vec;
|
||||
vec.reserve(sizeof...(Ms));
|
||||
(vec.emplace_back(std::shared_ptr<const Matcher<T>>(std::move(matchers))),
|
||||
...);
|
||||
return std::make_unique<AnyOfMatcher<T>>(std::move(vec));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// MatcherHolder — owns a Matcher<T> or wraps an exact value as Eq
|
||||
// MatcherHolder — owns a shared immutable Matcher<T> or exact Eq value
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
template <typename T> class MatcherHolder
|
||||
{
|
||||
std::unique_ptr<Matcher<T>> m_matcher;
|
||||
std::shared_ptr<const Matcher<T>> m_matcher;
|
||||
|
||||
public:
|
||||
|
||||
MatcherHolder() : m_matcher(std::make_unique<AnyMatcher<T>>()) {}
|
||||
MatcherHolder() : m_matcher(std::make_shared<AnyMatcher<T>>()) {}
|
||||
|
||||
MatcherHolder(std::unique_ptr<Matcher<T>> m)
|
||||
template <typename Derived>
|
||||
requires std::derived_from<Derived, Matcher<T>>
|
||||
MatcherHolder(std::unique_ptr<Derived> m)
|
||||
: m_matcher(std::shared_ptr<const Matcher<T>>(std::move(m)))
|
||||
{
|
||||
}
|
||||
|
||||
MatcherHolder(std::shared_ptr<const Matcher<T>> m)
|
||||
: m_matcher(std::move(m))
|
||||
{
|
||||
}
|
||||
|
||||
template <typename U = T>
|
||||
requires(std::same_as<std::decay_t<U>, T> &&
|
||||
std::equality_comparable<T> && std::movable<T>)
|
||||
MatcherHolder(T exact_value)
|
||||
: m_matcher(
|
||||
std::make_unique<EqMatcher<T>>(std::move(exact_value)))
|
||||
std::make_shared<EqMatcher<T>>(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
|
||||
@@ -3,12 +3,18 @@
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/TestingMock/Expectation.hpp>
|
||||
#include <Void/TestingMock/Mock.hpp>
|
||||
#include <Void/TestingMock/Session.hpp>
|
||||
|
||||
#include <condition_variable>
|
||||
#include <cstddef>
|
||||
#include <exception>
|
||||
#include <format>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::TestingMock
|
||||
@@ -17,7 +23,8 @@ namespace Void::TestingMock
|
||||
template <typename> class MockFunction;
|
||||
|
||||
template <typename R, typename... Args>
|
||||
class MockFunction<R(Args...)> : public Detail::MockFunctionBase
|
||||
class MockFunction<R(Args...)> : public Detail::MockFunctionBase,
|
||||
public Detail::SessionParticipant
|
||||
{
|
||||
using Expectation = Detail::Expectation<R(Args...)>;
|
||||
|
||||
@@ -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 <typename... MArgs>
|
||||
[[nodiscard]] Void::Result::Result<Expectation*>
|
||||
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<Expectation>(
|
||||
typename Expectation::MatcherTuple{
|
||||
MatcherHolder<std::decay_t<Args>>(
|
||||
std::forward<MArgs>(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 <typename... MArgs>
|
||||
[[nodiscard]] Void::Result::Result<Expectation*>
|
||||
try_expect(MArgs&&... matchers)
|
||||
{
|
||||
return try_expect(std::source_location::current(),
|
||||
std::forward<MArgs>(matchers)...);
|
||||
}
|
||||
|
||||
template <typename... MArgs>
|
||||
Expectation& expect(std::source_location loc, MArgs&&... matchers)
|
||||
{
|
||||
@@ -54,6 +132,11 @@ namespace Void::TestingMock
|
||||
MatcherHolder<std::decay_t<Args>>(
|
||||
std::forward<MArgs>(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<std::shared_ptr<Expectation>> 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<R, void>) {
|
||||
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<Expectation> 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>(args)...);
|
||||
}
|
||||
return reserved->execute(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
void verify() override
|
||||
{
|
||||
for (auto& exp : m_expectations) {
|
||||
std::vector<std::shared_ptr<Expectation>> 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<void>
|
||||
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<std::shared_ptr<Expectation>> m_expectations;
|
||||
std::mutex m_mutex;
|
||||
std::size_t m_local_in_flight{0};
|
||||
bool m_stopped{false};
|
||||
std::shared_ptr<Detail::SessionState> 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<R, void>) {
|
||||
return;
|
||||
} else if constexpr (std::is_default_constructible_v<R>) {
|
||||
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 <typename T>
|
||||
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 "<non-printable>";
|
||||
}
|
||||
}
|
||||
|
||||
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), ...);
|
||||
|
||||
@@ -0,0 +1,531 @@
|
||||
#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
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
@@ -0,0 +1,33 @@
|
||||
#include <Void/TestingMock/Matcher.hpp>
|
||||
#include <Void/TestingMock/MockFunction.hpp>
|
||||
#include <Void/TestingMock/Session.hpp>
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
int main()
|
||||
{
|
||||
using namespace Void::TestingMock;
|
||||
|
||||
MockSession session;
|
||||
MockFunction<std::unique_ptr<int>(std::string)> fn{session, "lookup"};
|
||||
auto exp = fn.try_expect(
|
||||
AllOf<std::string>(StartsWith<std::string>("k_"),
|
||||
EndsWith<std::string>("_1")));
|
||||
if (!exp.has_value()) {
|
||||
return 1;
|
||||
}
|
||||
(*exp)->returns_once(std::make_unique<int>(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;
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
#include <Void/TestingMock/Matcher.hpp>
|
||||
#include <Void/TestingMock/MockFunction.hpp>
|
||||
#include <Void/TestingMock/Session.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
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<int(int)> 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<int>(std::unique_ptr<int>)> move_fn{session,
|
||||
"move_fn"};
|
||||
auto me1 = move_fn.try_expect(NotNull<std::unique_ptr<int>>());
|
||||
Void::Testing::require(me1.has_value());
|
||||
(*me1)->invokes_once([bonus = std::make_unique<int>(100)](
|
||||
std::unique_ptr<int> in) {
|
||||
return std::make_unique<int>(*in + *bonus);
|
||||
});
|
||||
|
||||
auto me2 = move_fn.try_expect(IsNull<std::unique_ptr<int>>());
|
||||
Void::Testing::require(me2.has_value());
|
||||
(*me2)->returns_once(std::make_unique<int>(7));
|
||||
|
||||
// 3. Matcher combinators: AllOf, AnyOf, NotOf, Ne, EndsWith.
|
||||
MockFunction<int(std::string)> combo{session, "combo"};
|
||||
auto ce = combo.try_expect(AllOf<std::string>(
|
||||
StartsWith<std::string>("pre_"), EndsWith<std::string>("_suf"),
|
||||
NotOf(Eq<std::string>("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<int>(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<NonDefaultResult(int)> 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(_<int>());
|
||||
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<int(int)> 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<int> sum{0};
|
||||
std::vector<std::thread> 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<int(int)> fn{session, "st_fn"};
|
||||
auto e = fn.try_expect(Pred<int>([](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());
|
||||
}
|
||||
Reference in new issue
Block a user