catch3
Progmasoft Catch3: an independently maintained C++17 test framework with a parallel runner, property checks, snapshots and structured results.
Clonegit clone https://git.progmasoft.com/catch3
feat(mock): WillOnce, WillRepeatedly, RetiresOnSaturation and composable actions
- Commit
643b67992a8e7d083e9fa0571e6eec82f7f129fa- Author
- Leitwolf11 ·
- Parents
9f0ba1d32e2d
Changes
docs/progmasoft-mocking.md | 70 ++++- extras/catch_amalgamated.hpp | 508 ++++++++++++++++++++++++++++++++- src/Progmasoft/Catch3/Mock.hpp | 142 ++++++++- src/Progmasoft/Catch3/MockActions.hpp | 369 ++++++++++++++++++++++++ src/Progmasoft/meson.build | 1 + tests/CMakeLists.txt | 1 + tests/Progmasoft/BUILD.bazel | 1 + tests/Progmasoft/Mock.tests.cpp | 6 + tests/Progmasoft/MockActions.tests.cpp | 226 +++++++++++++++ tests/Progmasoft/RunnerFixture.cpp | 19 ++ tests/meson.build | 1 + tools/Amalgamation.cpp | 15 +- 12 files changed, 1343 insertions(+), 16 deletions(-) diff --git a/docs/progmasoft-mocking.md b/docs/progmasoft-mocking.md index 6b77eb07..f99596af 100644 --- a/docs/progmasoft-mocking.md +++ b/docs/progmasoft-mocking.md @@ -83,12 +83,37 @@ The result of `CATCH3_EXPECT_CALL` takes these, in any order: | Member | Meaning | | --- | --- | -| `Times(n)`, `Between(a, b)`, `AtLeast(n)`, `AtMost(n)`, `AnyTimes()`, `Never()` | how many calls it wants; one by default | +| `Times(n)`, `Between(a, b)`, `AtLeast(n)`, `AtMost(n)`, `AnyTimes()`, `Never()` | how many calls it wants; one by default, or as `WillOnce` and `WillRepeatedly` say | | `Returns(value)` | the result of each call; a type that cannot be copied moves out on the first one, and a reference result refers to `value` | -| `Does(function)` | runs `function` with the arguments, and returns what it returns; it keeps its state between calls | +| `Does(action)` | runs `action` with the arguments, and returns what it returns; it keeps its state between calls | | `Throws(exception)` | throws `exception` from each call | +| `WillOnce(action)` | answers the next call with `action`: the first `WillOnce` the first call, and so on | +| `WillRepeatedly(action)` | answers every call after the `WillOnce` ones; the same as `Does` | +| `RetiresOnSaturation()` | once it has all its calls, it takes no more and lets them go on to other expectations | | `InSequence(sequence)` | see below | +An action is a function of the call's arguments, or one of the +[composable actions](#actions). Without `Times` or its siblings, n `WillOnce` +want exactly n calls, and with `WillRepeatedly` at least n; `WillRepeatedly` +alone wants any number. A `Times` given explicitly wins, in whatever order it +is written, and a call past the `WillOnce` actions takes `WillRepeatedly`, then +the default action. + +Calls go to the first expectation, in declaration order, that accepts them +and can take another call, so a saturated expectation already lets calls go on +to the ones after it; declare the particular expectation before the general +one: + +```cpp +CATCH3_EXPECT_CALL(store.GetMock)("ada").WillOnce(Return(41)).RetiresOnSaturation(); +CATCH3_EXPECT_CALL(store.GetMock)(Any).WillRepeatedly(Return(0)); +``` + +What `RetiresOnSaturation` changes is a call that nothing after it takes: from +a saturated expectation that is one too many calls; from a retired one it is an +unexpected call, as if the expectation were not there. (GoogleMock tries the +newest expectation first, which is why retiring matters more there.) + A call goes to the first expectation, in the order they were declared, that accepts its arguments and can take another call. A call none of them accepts fails the test case and returns a value-initialized result. So does a call they @@ -107,7 +132,8 @@ a function nothing was expected of. `CATCH3_ON_CALL(mock)(arguments...)` sets what the mock does for calls whose arguments match, when nothing more particular says. The arguments are written -as for `CATCH3_EXPECT_CALL`, and it takes `Returns`, `Does` or `Throws`: +as for `CATCH3_EXPECT_CALL`, and it takes `Returns`, `Does`, `Throws` or +`WillByDefault(action)`: ```cpp CATCH3_ON_CALL(store.GetMock)(Any).Returns(0); @@ -121,6 +147,44 @@ that match a call, the one declared last wins. A default expects nothing and is never verified, and `Verify()` keeps the defaults while it forgets the expectations. +## Actions + +`<Progmasoft/Catch3/MockActions.hpp>`, which `Mock.hpp` includes, holds actions +in `Progmasoft::Catch3::Actions` that compose. Each takes the arguments of the +call it answers, and each fits `WillOnce`, `WillRepeatedly`, `Does` and +`WillByDefault`: + +| Action | Does | +| --- | --- | +| `Return(value)` | returns `value`, converted to the result; a type that cannot be copied moves out once | +| `ReturnRef(object)` | returns a reference to `object`, which has to outlive the mock | +| `ReturnArg<N>()` | returns a copy of argument `N` | +| `ReturnPointee(pointer)` | returns what `pointer` points to when the call comes | +| `ReturnNew<T>(arguments...)` | returns `new T(arguments...)`, a new object each call | +| `Invoke(function)`, `Invoke(object, &Class::Method)` | calls it with the arguments and returns what it returns | +| `InvokeWithoutArgs(function)` | calls it with no arguments | +| `Throw(exception)` | throws `exception` | +| `SetArgPointee<N>(value)` | sets what argument `N`, a pointer, points to | +| `SetArgReferee<N>(value)` | sets argument `N`, a non-const reference | +| `SaveArg<N>(pointer)`, `SaveArgPointee<N>(pointer)` | stores argument `N`, or what it points to, in `*pointer` | +| `Assign(pointer, value)` | sets `*pointer` to `value` | +| `DoAll(action..., last)` | runs every action in order and returns what `last` returns | +| `IgnoreResult(action)` | runs `action` and drops its result | +| `WithArg<N>(action)`, `WithArgs<N...>(action)`, `WithoutArgs(action)` | runs `action` with only those arguments, in that order, or none | + +```cpp +using namespace Progmasoft::Catch3::Actions; + +CATCH3_EXPECT_CALL(file.ReadMock)(Any, Any) + .WillOnce(DoAll(SetArgReferee<1>(Bytes{ 1, 2 }), Return(true))) + .WillOnce(Throw(IoError("disk gone"))); +``` + +A mock that returns a reference needs an action that returns one, such as +`ReturnRef`; anything else is refused when it compiles. A mock of a void +function drops what its action returns. Steps of `DoAll` before the last see +the arguments as they are; the last may move them. + ## Nice, naggy and strict mocks A call of a function nothing was expected of, one with no expectation at all, diff --git a/extras/catch_amalgamated.hpp b/extras/catch_amalgamated.hpp index d6b28e59..53d35805 100644 --- a/extras/catch_amalgamated.hpp +++ b/extras/catch_amalgamated.hpp @@ -11967,6 +11967,7 @@ namespace Catch { // SPDX-License-Identifier: LGPL-3.0-or-later #include <cstddef> +#include <cstdlib> #include <exception> #include <functional> #include <limits> @@ -12016,6 +12017,12 @@ namespace Progmasoft::Catch3 std::size_t Maximum = 1; std::size_t Calls = 0; bool Retired = false; + // Set by Times and its siblings; until then WillOnce and + // WillRepeatedly decide how many calls are wanted. + bool CallsGiven = false; + // Once it has all the calls it wants, it takes no more and the + // calls go on to the other expectations. + bool RetiresOnSaturation = false; std::vector<std::shared_ptr<MockSequence>> Sequences; MockExpectationState(std::string description, @@ -12368,6 +12375,50 @@ namespace Progmasoft::Catch3 namespace Detail { + template<typename Action, typename = void> + struct NeverReturns: std::false_type + {}; + + template<typename Action> + struct NeverReturns<Action, + std::void_t<typename Action::Catch3NeverReturns>> + : std::true_type + {}; + + /// `work`, an action that takes the arguments of a call, as the + /// function a mock of `Result(Arguments...)` calls: its result is + /// converted, or dropped for a void mock. + template<typename Result, typename... Arguments, typename Work> + [[nodiscard]] std::function<Result(Arguments...)> + AdaptAction(Work &&work) + { + using Held = std::decay_t<Work>; + return [held = Held(std::forward<Work>(work))]( + Arguments... arguments) mutable -> Result { + if constexpr (std::is_void_v<Result>) + { + static_cast<void>( + held(static_cast<Arguments &&>(arguments)...)); + } + else if constexpr (NeverReturns<Held>::value) + { + held(static_cast<Arguments &&>(arguments)...); + // Not reached: the action throws. + std::abort(); + } + else + { + using Produced = decltype(held( + static_cast<Arguments &&>(arguments)...)); + static_assert(!std::is_reference_v<Result> + || std::is_reference_v<Produced>, + "A mock that returns a reference needs an " + "action that returns one: use ReturnRef."); + return held(static_cast<Arguments &&>(arguments)...); + } + }; + } + /// What a call does, set the same way on an expectation and on a /// default action: `Returns`, `Does` or `Throws`. template<typename Derived, typename Result, typename... Arguments> @@ -12418,9 +12469,12 @@ namespace Progmasoft::Catch3 Derived & Does(Work &&work) { + auto adapted + = std::make_shared<std::function<Result(Arguments...)>>( + AdaptAction<Result, Arguments...>( + std::forward<Work>(work))); const auto lock = LockMocks(); - action = std::make_shared<std::function<Result(Arguments...)>>( - std::forward<Work>(work)); + action = std::move(adapted); return static_cast<Derived &>(*this); } @@ -12513,6 +12567,7 @@ namespace Progmasoft::Catch3 const auto lock = Detail::LockMocks(); state->Minimum = minimum; state->Maximum = maximum; + state->CallsGiven = true; return *this; } @@ -12526,6 +12581,48 @@ namespace Progmasoft::Catch3 return *this; } + /// Answers the next call with `action`: the first WillOnce the first + /// call, the second the second, and so on. Without Times and its + /// siblings, n of them want exactly n calls, or at least n with + /// WillRepeatedly. + template<typename Action> + MockExpectation & + WillOnce(Action &&work) + { + auto adapted + = std::make_shared<std::function<Result(Arguments...)>>( + Detail::AdaptAction<Result, Arguments...>( + std::forward<Action>(work))); + const auto lock = Detail::LockMocks(); + once.push_back(std::move(adapted)); + InferCalls(); + return *this; + } + + /// Answers every call after the WillOnce ones with `action`. Without + /// Times and its siblings, it wants any number of calls after them. + template<typename Action> + MockExpectation & + WillRepeatedly(Action &&work) + { + this->Does(std::forward<Action>(work)); + const auto lock = Detail::LockMocks(); + repeated = true; + InferCalls(); + return *this; + } + + /// Once the expectation has all the calls it wants, it is retired: + /// it takes no more, and a call goes on to the other expectations + /// instead of being one too many. + MockExpectation & + RetiresOnSaturation() + { + const auto lock = Detail::LockMocks(); + state->RetiresOnSaturation = true; + return *this; + } + /// What the arguments of a call have to match. using Matchers = std::tuple<Detail::ArgumentMatcher<std::decay_t<Arguments>>...>; @@ -12534,6 +12631,25 @@ namespace Progmasoft::Catch3 template<typename Signature> friend class MockFunction; + void + InferCalls() + { + if (state->CallsGiven) + { + return; + } + state->Minimum = once.size(); + state->Maximum = repeated ? Detail::kUnlimitedCalls : once.size(); + } + + /// Whether a call can no longer reach this expectation at all. + [[nodiscard]] bool + Saturated() const noexcept + { + return state->RetiresOnSaturation + && state->Calls >= state->Maximum; + } + MockExpectation(std::string description, const Catch::SourceLineInfo &line, std::unique_ptr<Matchers> accepted) @@ -12553,6 +12669,9 @@ namespace Progmasoft::Catch3 std::shared_ptr<Detail::MockExpectationState> state; // Empty when any arguments will do. std::unique_ptr<Matchers> matchers; + // The actions of WillOnce, one per call, in order. + std::vector<std::shared_ptr<std::function<Result(Arguments...)>>> once; + bool repeated = false; }; /// What a mock does for calls whose arguments match, when nothing more @@ -12567,6 +12686,14 @@ namespace Progmasoft::Catch3 Arguments...> { public: + /// What the calls this default covers do: the same as Does. + template<typename Action> + MockDefault & + WillByDefault(Action &&work) + { + return this->Does(std::forward<Action>(work)); + } + using Matchers = std::tuple<Detail::ArgumentMatcher<std::decay_t<Arguments>>...>; @@ -12887,7 +13014,7 @@ namespace Progmasoft::Catch3 const Expectation *used = nullptr; for (const auto &expectation : expectations) { - if (!expectation->Accepts(values)) + if (expectation->Saturated() || !expectation->Accepts(values)) { continue; } @@ -12923,10 +13050,12 @@ namespace Progmasoft::Catch3 const std::tuple<const std::decay_t<Arguments> &...> &values) { auto &state = *expectation.state; - ++state.Calls; + const auto index = state.Calls++; Decision decision; decision.line = state.Line; - decision.action = expectation.action != nullptr + decision.action = index < expectation.once.size() + ? expectation.once[index] + : expectation.action != nullptr ? expectation.action : DefaultFor(values); for (const auto &sequence : state.Sequences) @@ -13267,6 +13396,375 @@ namespace Progmasoft::Catch3 /// matchers, `Any` or `Where`, or nothing to accept any. It takes `Returns`, /// `Does` or `Throws`, expects nothing and is never verified. #define CATCH3_ON_CALL(mock) (mock).OnCall() + +// The actions to compose come with the mocks. +// Copyright (c) 2026 Progmasoft. +// SPDX-License-Identifier: LGPL-3.0-or-later + +#include <cstddef> +#include <functional> +#include <memory> +#include <tuple> +#include <type_traits> +#include <utility> + +// Actions to pass to WillOnce, WillRepeatedly, WillByDefault and Does, and to +// compose: each takes the arguments of the call it answers. +// +// using namespace Progmasoft::Catch3::Actions; +// CATCH3_EXPECT_CALL(store.ReadMock)(Any, Any) +// .WillOnce(DoAll(SetArgReferee<1>(42), Return(true))) +// .WillOnce(Return(false)); + +namespace Progmasoft::Catch3::Actions +{ + namespace Detail + { + /// The argument `Index` of a call, as the reference it was passed by. + template<std::size_t Index, typename... Values> + [[nodiscard]] decltype(auto) + Argument(Values &&...values) + { + static_assert(Index < sizeof...(Values), + "The action names an argument the mock does not " + "have."); + return std::get<Index>( + std::forward_as_tuple(std::forward<Values>(values)...)); + } + + template<typename Value> + class ReturnAction final + { + public: + explicit ReturnAction(Value value) + : held(std::make_shared<Value>(std::move(value))) + {} + + template<typename... Values> + Value + operator()(Values &&...) const + { + if constexpr (std::is_copy_constructible_v<Value>) + { + return *held; + } + else + { + // Moved out on the first call; calls can come from + // several threads. + const auto lock = Catch3::Detail::LockMocks(); + return std::move(*held); + } + } + + private: + std::shared_ptr<Value> held; + }; + + template<typename Exception> + class ThrowAction final + { + public: + using Catch3NeverReturns = void; + + explicit ThrowAction(Exception thrown) + : exception(std::move(thrown)) + {} + + template<typename... Values> + [[noreturn]] void + operator()(Values &&...) const + { + Catch::throw_exception(exception); + } + + private: + Exception exception; + }; + + template<typename Last, typename = void> + struct NeverReturnsTag + {}; + + template<typename Last> + struct NeverReturnsTag<Last, std::void_t<typename Last::Catch3NeverReturns>> + { + using Catch3NeverReturns = void; + }; + + template<typename Last, typename... First> + class DoAllAction final: public NeverReturnsTag<Last> + { + public: + DoAllAction(std::tuple<First...> first, Last last) + : steps(std::move(first)) + , final(std::move(last)) + {} + + template<typename... Values> + decltype(auto) + operator()(Values &&...values) + { + // Every step but the last sees the arguments as they are; the + // last one may take them. + std::apply( + [&values...](auto &...step) { + (static_cast<void>(step(values...)), ...); + }, + steps); + return final(std::forward<Values>(values)...); + } + + private: + std::tuple<First...> steps; + Last final; + }; + + template<typename Inner, std::size_t... Indices> + class WithArgsAction final: public NeverReturnsTag<Inner> + { + public: + explicit WithArgsAction(Inner action) + : inner(std::move(action)) + {} + + template<typename... Values> + decltype(auto) + operator()(Values &&...values) + { + return inner(Argument<Indices>(values...)...); + } + + private: + Inner inner; + }; + + /// The DoAll of the actions in `all`: every one but the last is a + /// step, the last one answers. + template<typename All, std::size_t... Indices> + [[nodiscard]] auto + MakeDoAll(All &&all, std::index_sequence<Indices...>) + { + constexpr auto count = std::tuple_size_v<std::decay_t<All>>; + using Last = std::tuple_element_t<count - 1, std::decay_t<All>>; + return DoAllAction< + Last, + std::tuple_element_t<Indices, std::decay_t<All>>...>( + std::make_tuple(std::get<Indices>(std::move(all))...), + std::get<count - 1>(std::move(all))); + } + } // namespace Detail + + /// Returns `value`, converted to the mock's result. A value that cannot be + /// copied is moved out on the first call. For a reference result, use + /// ReturnRef. + template<typename Value> + [[nodiscard]] auto + Return(Value &&value) + { + return Detail::ReturnAction<std::decay_t<Value>>( + std::forward<Value>(value)); + } + + /// Returns a reference to `object`, which has to outlive the mock. + template<typename Object> + [[nodiscard]] auto + ReturnRef(Object &object) + { + return [target = &object](auto &&...) -> Object & { + return *target; + }; + } + + template<typename Object> + void + ReturnRef(const Object &&) = delete; + + /// Returns the argument `Index` of the call, copied. + template<std::size_t Index> + [[nodiscard]] auto + ReturnArg() + { + return [](auto &&...values) { + return std::decay_t<decltype(Detail::Argument<Index>(values...))>( + Detail::Argument<Index>(values...)); + }; + } + + /// Returns what `pointer` points to at the time of the call. + template<typename Object> + [[nodiscard]] auto + ReturnPointee(const Object *pointer) + { + return [pointer](auto &&...) { + return *pointer; + }; + } + + /// Returns `new Object(arguments...)`, a new object for every call. + template<typename Object, typename... Parameters> + [[nodiscard]] auto + ReturnNew(Parameters &&...parameters) + { + return [held = std::make_tuple(std::forward<Parameters>(parameters)...)]( + auto &&...) { + return std::apply( + [](const auto &...values) { + return new Object(values...); + }, + held); + }; + } + + /// Calls `function` with the arguments of the call and returns what it + /// returns. + template<typename Function> + [[nodiscard]] auto + Invoke(Function function) + { + return [function = std::move(function)](auto &&...values) mutable + -> decltype(auto) { + return std::invoke(function, + std::forward<decltype(values)>(values)...); + }; + } + + /// Calls the member `method` of `object` with the arguments of the call. + template<typename Object, typename Method> + [[nodiscard]] auto + Invoke(Object *object, Method method) + { + return [object, method](auto &&...values) -> decltype(auto) { + return std::invoke(method, + object, + std::forward<decltype(values)>(values)...); + }; + } + + /// Calls `function` with no arguments and returns what it returns. + template<typename Function> + [[nodiscard]] auto + InvokeWithoutArgs(Function function) + { + return [function = std::move(function)](auto &&...) mutable + -> decltype(auto) { + return std::invoke(function); + }; + } + + /// Runs `action` with no arguments: InvokeWithoutArgs for any action. + template<typename Inner> + [[nodiscard]] auto + WithoutArgs(Inner action) + { + return Detail::WithArgsAction<Inner>(std::move(action)); + } + + /// Throws `exception` from the call. + template<typename Exception> + [[nodiscard]] auto + Throw(Exception exception) + { + return Detail::ThrowAction<Exception>(std::move(exception)); + } + + /// Runs every action in order with the arguments of the call, and returns + /// what the last one returns. + template<typename... Steps> + [[nodiscard]] auto + DoAll(Steps... steps) + { + static_assert(sizeof...(Steps) >= 1, "DoAll needs an action."); + return Detail::MakeDoAll( + std::make_tuple(std::move(steps)...), + std::make_index_sequence<sizeof...(Steps) - 1>{}); + } + + /// Sets what the argument `Index`, a pointer, points to. + template<std::size_t Index, typename Value> + [[nodiscard]] auto + SetArgPointee(Value value) + { + return [value = std::move(value)](auto &&...values) { + *Detail::Argument<Index>(values...) = value; + }; + } + + /// Sets the argument `Index`, a reference. + template<std::size_t Index, typename Value> + [[nodiscard]] auto + SetArgReferee(Value value) + { + return [value = std::move(value)](auto &&...values) { + auto &&target = Detail::Argument<Index>(values...); + static_assert(std::is_lvalue_reference_v<decltype(target)> + && !std::is_const_v<std::remove_reference_t< + decltype(target)>>, + "SetArgReferee needs a parameter that is a " + "non-const reference."); + target = value; + }; + } + + /// Stores the argument `Index` in `*target`. + template<std::size_t Index, typename Target> + [[nodiscard]] auto + SaveArg(Target *target) + { + return [target](auto &&...values) { + *target = Detail::Argument<Index>(values...); + }; + } + + /// Stores what the argument `Index`, a pointer, points to in `*target`. + template<std::size_t Index, typename Target> + [[nodiscard]] auto + SaveArgPointee(Target *target) + { + return [target](auto &&...values) { + *target = *Detail::Argument<Index>(values...); + }; + } + + /// Sets `*target` to `value`. + template<typename Target, typename Value> + [[nodiscard]] auto + Assign(Target *target, Value value) + { + return [target, value = std::move(value)](auto &&...) { + *target = value; + }; + } + + /// Runs `action` and drops what it returns, for a step of DoAll or a + /// mock of a void function. + template<typename Inner> + [[nodiscard]] auto + IgnoreResult(Inner action) + { + return [action = std::move(action)](auto &&...values) mutable { + static_cast<void>( + action(std::forward<decltype(values)>(values)...)); + }; + } + + /// Runs `action` with only the argument `Index` of the call. + template<std::size_t Index, typename Inner> + [[nodiscard]] auto + WithArg(Inner action) + { + return Detail::WithArgsAction<Inner, Index>(std::move(action)); + } + + /// Runs `action` with the arguments `Indices...` of the call, in that + /// order. + template<std::size_t... Indices, typename Inner> + [[nodiscard]] auto + WithArgs(Inner action) + { + return Detail::WithArgsAction<Inner, Indices...>(std::move(action)); + } +} // namespace Progmasoft::Catch3::Actions // Copyright (c) 2026 Progmasoft. // SPDX-License-Identifier: LGPL-3.0-or-later diff --git a/src/Progmasoft/Catch3/Mock.hpp b/src/Progmasoft/Catch3/Mock.hpp index 53cb652f..4a8ff995 100644 --- a/src/Progmasoft/Catch3/Mock.hpp +++ b/src/Progmasoft/Catch3/Mock.hpp @@ -9,6 +9,7 @@ #include <Progmasoft/Catch3/Matchers/Vector.hpp> #include <Progmasoft/Catch3/ToString.hpp> #include <cstddef> +#include <cstdlib> #include <exception> #include <functional> #include <limits> @@ -58,6 +59,12 @@ namespace Progmasoft::Catch3 std::size_t Maximum = 1; std::size_t Calls = 0; bool Retired = false; + // Set by Times and its siblings; until then WillOnce and + // WillRepeatedly decide how many calls are wanted. + bool CallsGiven = false; + // Once it has all the calls it wants, it takes no more and the + // calls go on to the other expectations. + bool RetiresOnSaturation = false; std::vector<std::shared_ptr<MockSequence>> Sequences; MockExpectationState(std::string description, @@ -410,6 +417,50 @@ namespace Progmasoft::Catch3 namespace Detail { + template<typename Action, typename = void> + struct NeverReturns: std::false_type + {}; + + template<typename Action> + struct NeverReturns<Action, + std::void_t<typename Action::Catch3NeverReturns>> + : std::true_type + {}; + + /// `work`, an action that takes the arguments of a call, as the + /// function a mock of `Result(Arguments...)` calls: its result is + /// converted, or dropped for a void mock. + template<typename Result, typename... Arguments, typename Work> + [[nodiscard]] std::function<Result(Arguments...)> + AdaptAction(Work &&work) + { + using Held = std::decay_t<Work>; + return [held = Held(std::forward<Work>(work))]( + Arguments... arguments) mutable -> Result { + if constexpr (std::is_void_v<Result>) + { + static_cast<void>( + held(static_cast<Arguments &&>(arguments)...)); + } + else if constexpr (NeverReturns<Held>::value) + { + held(static_cast<Arguments &&>(arguments)...); + // Not reached: the action throws. + std::abort(); + } + else + { + using Produced = decltype(held( + static_cast<Arguments &&>(arguments)...)); + static_assert(!std::is_reference_v<Result> + || std::is_reference_v<Produced>, + "A mock that returns a reference needs an " + "action that returns one: use ReturnRef."); + return held(static_cast<Arguments &&>(arguments)...); + } + }; + } + /// What a call does, set the same way on an expectation and on a /// default action: `Returns`, `Does` or `Throws`. template<typename Derived, typename Result, typename... Arguments> @@ -460,9 +511,12 @@ namespace Progmasoft::Catch3 Derived & Does(Work &&work) { + auto adapted + = std::make_shared<std::function<Result(Arguments...)>>( + AdaptAction<Result, Arguments...>( + std::forward<Work>(work))); const auto lock = LockMocks(); - action = std::make_shared<std::function<Result(Arguments...)>>( - std::forward<Work>(work)); + action = std::move(adapted); return static_cast<Derived &>(*this); } @@ -555,6 +609,7 @@ namespace Progmasoft::Catch3 const auto lock = Detail::LockMocks(); state->Minimum = minimum; state->Maximum = maximum; + state->CallsGiven = true; return *this; } @@ -568,6 +623,48 @@ namespace Progmasoft::Catch3 return *this; } + /// Answers the next call with `action`: the first WillOnce the first + /// call, the second the second, and so on. Without Times and its + /// siblings, n of them want exactly n calls, or at least n with + /// WillRepeatedly. + template<typename Action> + MockExpectation & + WillOnce(Action &&work) + { + auto adapted + = std::make_shared<std::function<Result(Arguments...)>>( + Detail::AdaptAction<Result, Arguments...>( + std::forward<Action>(work))); + const auto lock = Detail::LockMocks(); + once.push_back(std::move(adapted)); + InferCalls(); + return *this; + } + + /// Answers every call after the WillOnce ones with `action`. Without + /// Times and its siblings, it wants any number of calls after them. + template<typename Action> + MockExpectation & + WillRepeatedly(Action &&work) + { + this->Does(std::forward<Action>(work)); + const auto lock = Detail::LockMocks(); + repeated = true; + InferCalls(); + return *this; + } + + /// Once the expectation has all the calls it wants, it is retired: + /// it takes no more, and a call goes on to the other expectations + /// instead of being one too many. + MockExpectation & + RetiresOnSaturation() + { + const auto lock = Detail::LockMocks(); + state->RetiresOnSaturation = true; + return *this; + } + /// What the arguments of a call have to match. using Matchers = std::tuple<Detail::ArgumentMatcher<std::decay_t<Arguments>>...>; @@ -576,6 +673,25 @@ namespace Progmasoft::Catch3 template<typename Signature> friend class MockFunction; + void + InferCalls() + { + if (state->CallsGiven) + { + return; + } + state->Minimum = once.size(); + state->Maximum = repeated ? Detail::kUnlimitedCalls : once.size(); + } + + /// Whether a call can no longer reach this expectation at all. + [[nodiscard]] bool + Saturated() const noexcept + { + return state->RetiresOnSaturation + && state->Calls >= state->Maximum; + } + MockExpectation(std::string description, const Catch::SourceLineInfo &line, std::unique_ptr<Matchers> accepted) @@ -595,6 +711,9 @@ namespace Progmasoft::Catch3 std::shared_ptr<Detail::MockExpectationState> state; // Empty when any arguments will do. std::unique_ptr<Matchers> matchers; + // The actions of WillOnce, one per call, in order. + std::vector<std::shared_ptr<std::function<Result(Arguments...)>>> once; + bool repeated = false; }; /// What a mock does for calls whose arguments match, when nothing more @@ -609,6 +728,14 @@ namespace Progmasoft::Catch3 Arguments...> { public: + /// What the calls this default covers do: the same as Does. + template<typename Action> + MockDefault & + WillByDefault(Action &&work) + { + return this->Does(std::forward<Action>(work)); + } + using Matchers = std::tuple<Detail::ArgumentMatcher<std::decay_t<Arguments>>...>; @@ -929,7 +1056,7 @@ namespace Progmasoft::Catch3 const Expectation *used = nullptr; for (const auto &expectation : expectations) { - if (!expectation->Accepts(values)) + if (expectation->Saturated() || !expectation->Accepts(values)) { continue; } @@ -965,10 +1092,12 @@ namespace Progmasoft::Catch3 const std::tuple<const std::decay_t<Arguments> &...> &values) { auto &state = *expectation.state; - ++state.Calls; + const auto index = state.Calls++; Decision decision; decision.line = state.Line; - decision.action = expectation.action != nullptr + decision.action = index < expectation.once.size() + ? expectation.once[index] + : expectation.action != nullptr ? expectation.action : DefaultFor(values); for (const auto &sequence : state.Sequences) @@ -1309,3 +1438,6 @@ namespace Progmasoft::Catch3 /// matchers, `Any` or `Where`, or nothing to accept any. It takes `Returns`, /// `Does` or `Throws`, expects nothing and is never verified. #define CATCH3_ON_CALL(mock) (mock).OnCall() + +// The actions to compose come with the mocks. +#include <Progmasoft/Catch3/MockActions.hpp> diff --git a/src/Progmasoft/Catch3/MockActions.hpp b/src/Progmasoft/Catch3/MockActions.hpp new file mode 100644 index 00000000..43351604 --- /dev/null +++ b/src/Progmasoft/Catch3/MockActions.hpp @@ -0,0 +1,369 @@ +// Copyright (c) 2026 Progmasoft. +// SPDX-License-Identifier: LGPL-3.0-or-later +#pragma once + +#include <Progmasoft/Catch3/Mock.hpp> +#include <cstddef> +#include <functional> +#include <memory> +#include <tuple> +#include <type_traits> +#include <utility> + +// Actions to pass to WillOnce, WillRepeatedly, WillByDefault and Does, and to +// compose: each takes the arguments of the call it answers. +// +// using namespace Progmasoft::Catch3::Actions; +// CATCH3_EXPECT_CALL(store.ReadMock)(Any, Any) +// .WillOnce(DoAll(SetArgReferee<1>(42), Return(true))) +// .WillOnce(Return(false)); + +namespace Progmasoft::Catch3::Actions +{ + namespace Detail + { + /// The argument `Index` of a call, as the reference it was passed by. + template<std::size_t Index, typename... Values> + [[nodiscard]] decltype(auto) + Argument(Values &&...values) + { + static_assert(Index < sizeof...(Values), + "The action names an argument the mock does not " + "have."); + return std::get<Index>( + std::forward_as_tuple(std::forward<Values>(values)...)); + } + + template<typename Value> + class ReturnAction final + { + public: + explicit ReturnAction(Value value) + : held(std::make_shared<Value>(std::move(value))) + {} + + template<typename... Values> + Value + operator()(Values &&...) const + { + if constexpr (std::is_copy_constructible_v<Value>) + { + return *held; + } + else + { + // Moved out on the first call; calls can come from + // several threads. + const auto lock = Catch3::Detail::LockMocks(); + return std::move(*held); + } + } + + private: + std::shared_ptr<Value> held; + }; + + template<typename Exception> + class ThrowAction final + { + public: + using Catch3NeverReturns = void; + + explicit ThrowAction(Exception thrown) + : exception(std::move(thrown)) + {} + + template<typename... Values> + [[noreturn]] void + operator()(Values &&...) const + { + Catch::throw_exception(exception); + } + + private: + Exception exception; + }; + + template<typename Last, typename = void> + struct NeverReturnsTag + {}; + + template<typename Last> + struct NeverReturnsTag<Last, std::void_t<typename Last::Catch3NeverReturns>> + { + using Catch3NeverReturns = void; + }; + + template<typename Last, typename... First> + class DoAllAction final: public NeverReturnsTag<Last> + { + public: + DoAllAction(std::tuple<First...> first, Last last) + : steps(std::move(first)) + , final(std::move(last)) + {} + + template<typename... Values> + decltype(auto) + operator()(Values &&...values) + { + // Every step but the last sees the arguments as they are; the + // last one may take them. + std::apply( + [&values...](auto &...step) { + (static_cast<void>(step(values...)), ...); + }, + steps); + return final(std::forward<Values>(values)...); + } + + private: + std::tuple<First...> steps; + Last final; + }; + + template<typename Inner, std::size_t... Indices> + class WithArgsAction final: public NeverReturnsTag<Inner> + { + public: + explicit WithArgsAction(Inner action) + : inner(std::move(action)) + {} + + template<typename... Values> + decltype(auto) + operator()(Values &&...values) + { + return inner(Argument<Indices>(values...)...); + } + + private: + Inner inner; + }; + + /// The DoAll of the actions in `all`: every one but the last is a + /// step, the last one answers. + template<typename All, std::size_t... Indices> + [[nodiscard]] auto + MakeDoAll(All &&all, std::index_sequence<Indices...>) + { + constexpr auto count = std::tuple_size_v<std::decay_t<All>>; + using Last = std::tuple_element_t<count - 1, std::decay_t<All>>; + return DoAllAction< + Last, + std::tuple_element_t<Indices, std::decay_t<All>>...>( + std::make_tuple(std::get<Indices>(std::move(all))...), + std::get<count - 1>(std::move(all))); + } + } // namespace Detail + + /// Returns `value`, converted to the mock's result. A value that cannot be + /// copied is moved out on the first call. For a reference result, use + /// ReturnRef. + template<typename Value> + [[nodiscard]] auto + Return(Value &&value) + { + return Detail::ReturnAction<std::decay_t<Value>>( + std::forward<Value>(value)); + } + + /// Returns a reference to `object`, which has to outlive the mock. + template<typename Object> + [[nodiscard]] auto + ReturnRef(Object &object) + { + return [target = &object](auto &&...) -> Object & { + return *target; + }; + } + + template<typename Object> + void + ReturnRef(const Object &&) = delete; + + /// Returns the argument `Index` of the call, copied. + template<std::size_t Index> + [[nodiscard]] auto + ReturnArg() + { + return [](auto &&...values) { + return std::decay_t<decltype(Detail::Argument<Index>(values...))>( + Detail::Argument<Index>(values...)); + }; + } + + /// Returns what `pointer` points to at the time of the call. + template<typename Object> + [[nodiscard]] auto + ReturnPointee(const Object *pointer) + { + return [pointer](auto &&...) { + return *pointer; + }; + } + + /// Returns `new Object(arguments...)`, a new object for every call. + template<typename Object, typename... Parameters> + [[nodiscard]] auto + ReturnNew(Parameters &&...parameters) + { + return [held = std::make_tuple(std::forward<Parameters>(parameters)...)]( + auto &&...) { + return std::apply( + [](const auto &...values) { + return new Object(values...); + }, + held); + }; + } + + /// Calls `function` with the arguments of the call and returns what it + /// returns. + template<typename Function> + [[nodiscard]] auto + Invoke(Function function) + { + return [function = std::move(function)](auto &&...values) mutable + -> decltype(auto) { + return std::invoke(function, + std::forward<decltype(values)>(values)...); + }; + } + + /// Calls the member `method` of `object` with the arguments of the call. + template<typename Object, typename Method> + [[nodiscard]] auto + Invoke(Object *object, Method method) + { + return [object, method](auto &&...values) -> decltype(auto) { + return std::invoke(method, + object, + std::forward<decltype(values)>(values)...); + }; + } + + /// Calls `function` with no arguments and returns what it returns. + template<typename Function> + [[nodiscard]] auto + InvokeWithoutArgs(Function function) + { + return [function = std::move(function)](auto &&...) mutable + -> decltype(auto) { + return std::invoke(function); + }; + } + + /// Runs `action` with no arguments: InvokeWithoutArgs for any action. + template<typename Inner> + [[nodiscard]] auto + WithoutArgs(Inner action) + { + return Detail::WithArgsAction<Inner>(std::move(action)); + } + + /// Throws `exception` from the call. + template<typename Exception> + [[nodiscard]] auto + Throw(Exception exception) + { + return Detail::ThrowAction<Exception>(std::move(exception)); + } + + /// Runs every action in order with the arguments of the call, and returns + /// what the last one returns. + template<typename... Steps> + [[nodiscard]] auto + DoAll(Steps... steps) + { + static_assert(sizeof...(Steps) >= 1, "DoAll needs an action."); + return Detail::MakeDoAll( + std::make_tuple(std::move(steps)...), + std::make_index_sequence<sizeof...(Steps) - 1>{}); + } + + /// Sets what the argument `Index`, a pointer, points to. + template<std::size_t Index, typename Value> + [[nodiscard]] auto + SetArgPointee(Value value) + { + return [value = std::move(value)](auto &&...values) { + *Detail::Argument<Index>(values...) = value; + }; + } + + /// Sets the argument `Index`, a reference. + template<std::size_t Index, typename Value> + [[nodiscard]] auto + SetArgReferee(Value value) + { + return [value = std::move(value)](auto &&...values) { + auto &&target = Detail::Argument<Index>(values...); + static_assert(std::is_lvalue_reference_v<decltype(target)> + && !std::is_const_v<std::remove_reference_t< + decltype(target)>>, + "SetArgReferee needs a parameter that is a " + "non-const reference."); + target = value; + }; + } + + /// Stores the argument `Index` in `*target`. + template<std::size_t Index, typename Target> + [[nodiscard]] auto + SaveArg(Target *target) + { + return [target](auto &&...values) { + *target = Detail::Argument<Index>(values...); + }; + } + + /// Stores what the argument `Index`, a pointer, points to in `*target`. + template<std::size_t Index, typename Target> + [[nodiscard]] auto + SaveArgPointee(Target *target) + { + return [target](auto &&...values) { + *target = *Detail::Argument<Index>(values...); + }; + } + + /// Sets `*target` to `value`. + template<typename Target, typename Value> + [[nodiscard]] auto + Assign(Target *target, Value value) + { + return [target, value = std::move(value)](auto &&...) { + *target = value; + }; + } + + /// Runs `action` and drops what it returns, for a step of DoAll or a + /// mock of a void function. + template<typename Inner> + [[nodiscard]] auto + IgnoreResult(Inner action) + { + return [action = std::move(action)](auto &&...values) mutable { + static_cast<void>( + action(std::forward<decltype(values)>(values)...)); + }; + } + + /// Runs `action` with only the argument `Index` of the call. + template<std::size_t Index, typename Inner> + [[nodiscard]] auto + WithArg(Inner action) + { + return Detail::WithArgsAction<Inner, Index>(std::move(action)); + } + + /// Runs `action` with the arguments `Indices...` of the call, in that + /// order. + template<std::size_t... Indices, typename Inner> + [[nodiscard]] auto + WithArgs(Inner action) + { + return Detail::WithArgsAction<Inner, Indices...>(std::move(action)); + } +} // namespace Progmasoft::Catch3::Actions diff --git a/src/Progmasoft/meson.build b/src/Progmasoft/meson.build index 29ec4c56..a2e2d3ca 100644 --- a/src/Progmasoft/meson.build +++ b/src/Progmasoft/meson.build @@ -16,6 +16,7 @@ if get_option('install') install_headers('Catch3/Runner.hpp', subdir: 'Progmasoft/Catch3') install_headers('Catch3/Version.hpp', subdir: 'Progmasoft/Catch3') install_headers('Catch3/Mock.hpp', subdir: 'Progmasoft/Catch3') + install_headers('Catch3/MockActions.hpp', subdir: 'Progmasoft/Catch3') install_headers('Catch3/Snapshot.hpp', subdir: 'Progmasoft/Catch3') install_headers('Catch3/Death.hpp', subdir: 'Progmasoft/Catch3') install_headers('Catch3/XmlWriter.hpp', subdir: 'Progmasoft/Catch3') diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 6ee65a34..bca6dc01 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -157,6 +157,7 @@ add_executable(ProgmasoftSelfTest Progmasoft/Comparisons.tests.cpp Progmasoft/Generators.tests.cpp Progmasoft/Mock.tests.cpp + Progmasoft/MockActions.tests.cpp Progmasoft/Property.tests.cpp Progmasoft/ForAll.tests.cpp Progmasoft/Results.tests.cpp diff --git a/tests/Progmasoft/BUILD.bazel b/tests/Progmasoft/BUILD.bazel index b2cede38..8ac7a517 100644 --- a/tests/Progmasoft/BUILD.bazel +++ b/tests/Progmasoft/BUILD.bazel @@ -11,6 +11,7 @@ cc_test( "ForAll.tests.cpp", "Generators.tests.cpp", "Mock.tests.cpp", + "MockActions.tests.cpp", "Property.tests.cpp", "Results.tests.cpp", "Runner.tests.cpp", diff --git a/tests/Progmasoft/Mock.tests.cpp b/tests/Progmasoft/Mock.tests.cpp index d948f0b0..df34d731 100644 --- a/tests/Progmasoft/Mock.tests.cpp +++ b/tests/Progmasoft/Mock.tests.cpp @@ -455,6 +455,12 @@ TEST_CASE("Failures of mocks fail the test case that owns them", "sequence has passed")); CHECK_THAT(message("fixture mock with nothing to return"), ContainsSubstring("nothing to return from name")); + CHECK_THAT(message("fixture mock fewer calls than WillOnce"), + ContainsSubstring("unmet expectation: Next(any) needs exactly 2 " + "calls, called once")); + CHECK_THAT(message("fixture mock call after retirement"), + ContainsSubstring("unexpected call: Next(9), expected\n" + " Next(any)")); CHECK_THAT(message("fixture mock strict uninteresting call"), ContainsSubstring("unexpected call: Next(1), nothing was " "expected of this mock")); diff --git a/tests/Progmasoft/MockActions.tests.cpp b/tests/Progmasoft/MockActions.tests.cpp new file mode 100644 index 00000000..64bc99d3 --- /dev/null +++ b/tests/Progmasoft/MockActions.tests.cpp @@ -0,0 +1,226 @@ +// Copyright (c) 2026 Progmasoft. +// SPDX-License-Identifier: LGPL-3.0-or-later + +#include <Progmasoft/Catch3/Matchers/String.hpp> +#include <Progmasoft/Catch3/Mock.hpp> +#include <Progmasoft/Catch3/TestMacros.hpp> +#include <memory> +#include <stdexcept> +#include <string> +#include <vector> + +namespace +{ + using Progmasoft::Catch3::Any; + using Progmasoft::Catch3::MockFunction; + using Progmasoft::Catch3::NiceMock; + using namespace Progmasoft::Catch3::Actions; + + class Reader + { + public: + CATCH3_MOCK_METHOD(bool, Read, (const std::string &, int &)); + CATCH3_MOCK_METHOD(void, Fill, (int *, int)); + CATCH3_MOCK_METHOD(int, Add, (int, int)); + CATCH3_MOCK_METHOD(std::string &, Name, ()); + CATCH3_MOCK_METHOD(std::unique_ptr<int>, Make, ()); + CATCH3_MOCK_METHOD(int *, New, ()); + }; + + struct Accumulator + { + int total = 0; + + int + Add(int value) + { + total += value; + return total; + } + }; +} // namespace + +TEST_CASE("WillOnce answers calls in order and sets how many are wanted", + "[progmasoft][mock][mock-actions]") +{ + Reader reader; + CATCH3_EXPECT_CALL(reader.AddMock)(Any, Any) + .WillOnce(Return(1)) + .WillOnce(Return(2)) + .WillOnce(Return(3)); + CHECK(reader.Add(0, 0) == 1); + CHECK(reader.Add(0, 0) == 2); + CHECK(reader.Add(0, 0) == 3); +} + +TEST_CASE("WillRepeatedly answers every call after the WillOnce ones", + "[progmasoft][mock][mock-actions]") +{ + Reader reader; + CATCH3_EXPECT_CALL(reader.AddMock)(Any, Any) + .WillOnce(Return(10)) + .WillRepeatedly(Invoke([](int a, int b) { + return a + b; + })); + CHECK(reader.Add(1, 1) == 10); + CHECK(reader.Add(2, 3) == 5); + CHECK(reader.Add(4, 5) == 9); +} + +TEST_CASE("WillRepeatedly alone wants any number of calls", + "[progmasoft][mock][mock-actions]") +{ + Reader reader; + CATCH3_EXPECT_CALL(reader.AddMock)(Any, Any).WillRepeatedly(Return(7)); + // Never called is fine too: nothing to verify against. + reader.AddMock.Verify(); + CATCH3_EXPECT_CALL(reader.AddMock)(Any, Any).WillRepeatedly(Return(7)); + CHECK(reader.Add(0, 0) == 7); + CHECK(reader.Add(0, 0) == 7); +} + +TEST_CASE("Times given explicitly wins over the WillOnce count", + "[progmasoft][mock][mock-actions]") +{ + Reader reader; + CATCH3_EXPECT_CALL(reader.AddMock)(Any, Any) + .Times(3) + .WillOnce(Return(1)) + .WillRepeatedly(Return(2)); + CHECK(reader.Add(0, 0) == 1); + CHECK(reader.Add(0, 0) == 2); + CHECK(reader.Add(0, 0) == 2); +} + +TEST_CASE("A retired expectation passes calls on to the next one", + "[progmasoft][mock][mock-actions]") +{ + Reader reader; + // The first takes two calls and retires; the rest go to the second. + CATCH3_EXPECT_CALL(reader.AddMock)(Any, Any) + .Times(2) + .WillRepeatedly(Return(1)) + .RetiresOnSaturation(); + CATCH3_EXPECT_CALL(reader.AddMock)(Any, Any).WillRepeatedly(Return(2)); + CHECK(reader.Add(0, 0) == 1); + CHECK(reader.Add(0, 0) == 1); + CHECK(reader.Add(0, 0) == 2); + CHECK(reader.Add(0, 0) == 2); +} + +TEST_CASE("DoAll runs every step and returns what the last one returns", + "[progmasoft][mock][mock-actions]") +{ + Reader reader; + int saved = 0; + std::vector<std::string> seen; + CATCH3_EXPECT_CALL(reader.ReadMock)(Any, Any) + .WillOnce(DoAll(SetArgReferee<1>(42), + SaveArg<1>(&saved), + Invoke([&seen](const std::string &key, int &) { + seen.push_back(key); + }), + Return(true))) + .WillOnce(Return(false)); + int value = 0; + CHECK(reader.Read("a", value)); + CHECK(value == 42); + CHECK(saved == 42); + CHECK(seen == std::vector<std::string>{ "a" }); + CHECK_FALSE(reader.Read("b", value)); +} + +TEST_CASE("Pointer arguments are written and read through", + "[progmasoft][mock][mock-actions]") +{ + Reader reader; + int seen = 0; + int assigned = 0; + CATCH3_EXPECT_CALL(reader.FillMock)(Any, 5) + .WillOnce(DoAll(SetArgPointee<0>(9), + SaveArgPointee<0>(&seen), + Assign(&assigned, 3))); + int target = 0; + reader.Fill(&target, 5); + CHECK(target == 9); + CHECK(seen == 9); + CHECK(assigned == 3); +} + +TEST_CASE("Arguments can be picked, ignored or left out", + "[progmasoft][mock][mock-actions]") +{ + Reader reader; + Accumulator sum; + int calls = 0; + CATCH3_EXPECT_CALL(reader.AddMock)(Any, Any) + .WillOnce(ReturnArg<1>()) + .WillOnce(WithArg<0>(Invoke(&sum, &Accumulator::Add))) + .WillOnce(WithArgs<1, 0>(Invoke([](int b, int a) { + return b - a; + }))) + .WillOnce(DoAll(IgnoreResult(Return(99)), + InvokeWithoutArgs([&calls] { + return ++calls; + }))) + .WillOnce(WithoutArgs(Return(5))); + CHECK(reader.Add(1, 2) == 2); + CHECK(reader.Add(4, 0) == 4); + CHECK(reader.Add(1, 10) == 9); + CHECK(reader.Add(0, 0) == 1); + CHECK(reader.Add(0, 0) == 5); +} + +TEST_CASE("References, pointees, new objects and moves come back", + "[progmasoft][mock][mock-actions]") +{ + Reader reader; + std::string name = "ada"; + int counter = 3; + CATCH3_EXPECT_CALL(reader.NameMock)().WillOnce(ReturnRef(name)); + CATCH3_EXPECT_CALL(reader.AddMock)(Any, Any) + .WillOnce(ReturnPointee(&counter)); + CATCH3_EXPECT_CALL(reader.NewMock)().WillOnce(ReturnNew<int>(8)); + CATCH3_EXPECT_CALL(reader.MakeMock)().WillOnce( + Return(std::make_unique<int>(6))); + CHECK(&reader.Name() == &name); + counter = 4; + CHECK(reader.Add(0, 0) == 4); + const std::unique_ptr<int> made{ reader.New() }; + CHECK(*made == 8); + CHECK(*reader.Make() == 6); +} + +TEST_CASE("Throw throws from the call, also as the last step of DoAll", + "[progmasoft][mock][mock-actions]") +{ + Reader reader; + int saved = 0; + CATCH3_EXPECT_CALL(reader.AddMock)(Any, Any) + .WillOnce(Throw(std::runtime_error("one"))) + .WillOnce(DoAll(SaveArg<0>(&saved), Throw(std::logic_error("two")))); + CHECK_THROWS_AS(reader.Add(1, 0), std::runtime_error); + CHECK_THROWS_AS(reader.Add(2, 0), std::logic_error); + CHECK(saved == 2); +} + +TEST_CASE("WillByDefault takes composed actions", + "[progmasoft][mock][mock-actions]") +{ + NiceMock<Reader> reader; + CATCH3_ON_CALL(reader.ReadMock)(Any, Any) + .WillByDefault(DoAll(SetArgReferee<1>(1), Return(true))); + int value = 0; + CHECK(reader.Read("x", value)); + CHECK(value == 1); +} + +TEST_CASE("A mock function takes the actions too", + "[progmasoft][mock][mock-actions]") +{ + MockFunction<int(int)> twice{ "twice" }; + CATCH3_EXPECT_CALL(twice)(Any).WillRepeatedly(Invoke([](int value) { + return value * 2; + })); + CHECK(twice(21) == 42); +} diff --git a/tests/Progmasoft/RunnerFixture.cpp b/tests/Progmasoft/RunnerFixture.cpp index b93b915a..2e82a0cb 100644 --- a/tests/Progmasoft/RunnerFixture.cpp +++ b/tests/Progmasoft/RunnerFixture.cpp @@ -278,6 +278,25 @@ TEST_CASE("fixture mock nice unexpected arguments", "[fixture][mock]") CHECK(counter.Next(5) == 0); } +TEST_CASE("fixture mock fewer calls than WillOnce", "[fixture][mock]") +{ + FixtureCounter counter; + CATCH3_EXPECT_CALL(counter.NextMock)(Progmasoft::Catch3::Any) + .WillOnce(Progmasoft::Catch3::Actions::Return(1)) + .WillOnce(Progmasoft::Catch3::Actions::Return(2)); + CHECK(counter.Next(0) == 1); +} + +TEST_CASE("fixture mock call after retirement", "[fixture][mock]") +{ + FixtureCounter counter; + CATCH3_EXPECT_CALL(counter.NextMock)(Progmasoft::Catch3::Any) + .WillOnce(Progmasoft::Catch3::Actions::Return(1)) + .RetiresOnSaturation(); + CHECK(counter.Next(0) == 1); + CHECK(counter.Next(9) == 0); +} + TEST_CASE("fixture mock naggy uninteresting call", "[fixture][mock-naggy]") { Progmasoft::Catch3::NaggyMock<FixtureCounter> counter; diff --git a/tests/meson.build b/tests/meson.build index 7caf74ea..b55e873e 100644 --- a/tests/meson.build +++ b/tests/meson.build @@ -75,6 +75,7 @@ progmasoft_property_tests = executable( 'Progmasoft/Comparisons.tests.cpp', 'Progmasoft/Generators.tests.cpp', 'Progmasoft/Mock.tests.cpp', + 'Progmasoft/MockActions.tests.cpp', 'Progmasoft/Property.tests.cpp', 'Progmasoft/ForAll.tests.cpp', 'Progmasoft/Results.tests.cpp', diff --git a/tools/Amalgamation.cpp b/tools/Amalgamation.cpp index 25d54250..30749619 100644 --- a/tools/Amalgamation.cpp +++ b/tools/Amalgamation.cpp @@ -68,6 +68,12 @@ namespace Progmasoft::Catch3::Tools constexpr std::string_view kComparisons = "Progmasoft/Catch3/Comparisons.hpp"; + /// The mocks, and the actions Mock.hpp includes at its end, which + /// include it back: each is put in place of its include once. + constexpr std::string_view kMock = "Progmasoft/Catch3/Mock.hpp"; + constexpr std::string_view kMockActions + = "Progmasoft/Catch3/MockActions.hpp"; + const std::map<std::string, std::string> & ThirdPartyFiles() { @@ -180,8 +186,10 @@ namespace Progmasoft::Catch3::Tools out += "#define CATCH_AMALGAMATED_HPP_INCLUDED\n"; Concatenate(out, source / "Progmasoft/Catch3/All.hpp", true); // Mocks are Progmasoft's own, and tests use them through - // this header. - Concatenate(out, source / "Progmasoft/Catch3/Mock.hpp", true); + // this header. Marked first, so that the include of it in + // MockActions.hpp is not expanded a second time. + concatenatedHeaders.insert(std::string{ kMock }); + Concatenate(out, source / kMock, true); // Death tests too: they rest on the runner's processes. Concatenate(out, source / "Progmasoft/Catch3/Death.hpp", true); out += "#endif // CATCH_AMALGAMATED_HPP_INCLUDED\n"; @@ -333,7 +341,8 @@ namespace Progmasoft::Catch3::Tools } if (upstream.count("src/" + include->Name) != 0 || include->Name == kUserConfig - || include->Name == kComparisons) + || include->Name == kComparisons + || include->Name == kMock || include->Name == kMockActions) { return include->Name; }