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

345 lines
8.5 KiB
C++

#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>
#include <tuple>
#include <type_traits>
#include <utility>
namespace Void::TestingMock::Detail
{
template <typename> class Expectation;
template <typename R, typename... Args> class Expectation<R(Args...)>
{
public:
using MatcherTuple =
std::tuple<MatcherHolder<std::decay_t<Args>>...>;
/// 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)
: m_matchers(std::move(matchers)), m_location(loc)
{
}
template <typename 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); }
/// 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...>{});
}
[[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 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(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; }
[[nodiscard]] bool is_saturated() const noexcept
{
return m_call_count >= m_max_calls;
}
void verify(std::string_view func_name)
{
if (m_call_count < m_min_calls) {
Void::Testing::fail(std::format(
"unsatisfied expectation on {}: {} — {}/{} calls",
func_name, describe_matchers(), m_call_count,
m_min_calls));
}
}
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
{
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
{
return m_location;
}
/// Render the matcher tuple as e.g. "(Eq(7), _, Gt(3))".
[[nodiscard]] std::string describe_matchers() const
{
return describe_impl(std::index_sequence_for<Args...>{});
}
private:
MatcherTuple m_matchers;
Action m_action;
std::source_location m_location;
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(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
{
if constexpr (sizeof...(Is) == 0) {
return "()";
} else {
std::string out{"("};
bool first = true;
auto append = [&](const auto& m) {
if (!first) {
out += ", ";
}
out += m.describe();
first = false;
};
(append(std::get<Is>(m_matchers)), ...);
out += ")";
return out;
}
}
};
} // namespace Void::TestingMock::Detail