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): default actions, nice/naggy/strict mocks, non-virtual mocking
- Commit
9f0ba1d32e2d2c2dd22ebcf16643d9b766380855- Author
- Leitwolf11 ·
- Parents
280f56330e9b
Changes
docs/progmasoft-mocking.md | 105 +++++++- docs/progmasoft-roadmap.md | 8 +- extras/catch_amalgamated.cpp | 48 ++++ extras/catch_amalgamated.hpp | 486 +++++++++++++++++++++++++++++-------- src/Progmasoft/Catch3/Mock.hpp | 486 +++++++++++++++++++++++++++++-------- src/Progmasoft/Mock.cpp | 48 ++++ tests/Progmasoft/Mock.tests.cpp | 180 ++++++++++++++ tests/Progmasoft/RunnerFixture.cpp | 34 +++ 8 files changed, 1182 insertions(+), 213 deletions(-) diff --git a/docs/progmasoft-mocking.md b/docs/progmasoft-mocking.md index 69043646..6b77eb07 100644 --- a/docs/progmasoft-mocking.md +++ b/docs/progmasoft-mocking.md @@ -92,13 +92,106 @@ The result of `CATCH3_EXPECT_CALL` takes these, in any order: 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 -accept when all of them are used up. When the result cannot be made that way, a -reference for example, the test case ends there; the same happens to an -expectation with no `Returns` or `Does`. A `noexcept` function cannot leave the -test case that way, so such a call ends the process. +accept when all of them are used up. An expectation with no `Returns`, `Does` or +`Throws` takes the mock's [default action](#default-actions) for the call, and +without one returns a value-initialized result. When the result cannot be made +that way, a reference for example, the test case ends there. A `noexcept` +function cannot leave the test case that way, so such a call ends the process. -A mock with no expectation for a call treats it as a failure. An expectation -with `AnyTimes()` is how to allow calls that do not matter to the test. +A mock with no expectation at all is strict: a call of it fails the test case. +An expectation with `AnyTimes()` allows calls that do not matter to the test, +and a [nice or naggy mock](#nice-naggy-and-strict-mocks) allows every call of +a function nothing was expected of. + +## Default actions + +`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`: + +```cpp +CATCH3_ON_CALL(store.GetMock)(Any).Returns(0); +CATCH3_ON_CALL(store.GetMock)(StartsWith("admin")).Throws(Denied{}); +CATCH3_EXPECT_CALL(store.GetMock)("ada").Times(2); // returns 0 twice +``` + +A default is used by an expectation without an action of its own, and by a +call of a nice or naggy mock that no expectation is set for. Of the defaults +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. + +## Nice, naggy and strict mocks + +A call of a function nothing was expected of, one with no expectation at all, +is an uninteresting call. How a mock takes it is its strictness: + +| Mock | An uninteresting call | +| --- | --- | +| `StrictMock<MockStore>`, and every mock not wrapped | fails the test case, as described above | +| `NaggyMock<MockStore>` | warns, then answers with the default action | +| `NiceMock<MockStore>` | answers with the default action, silently | + +```cpp +NiceMock<MockStore> store; +CATCH3_ON_CALL(store.GetMock)(Any).Returns(1); +CATCH3_EXPECT_CALL(store.PutMock)("ada", 2); + +AddPoint(store, "ada"); // Get is uninteresting: allowed, returns 1 +``` + +Strictness covers uninteresting calls only. A call of a function that has +expectations, none of which takes it, fails whatever the strictness, and so do +unmet expectations and calls out of order. Without a default an allowed call +returns a value-initialized result; one whose result cannot be made that way +ends the test case, which says to give it a `CATCH3_ON_CALL`. + +The wrappers derive from the mock class, so it cannot be `final`, and they take +its constructor arguments. They apply to the mocks the class holds as it is +constructed; mocks made elsewhere stay strict. A naggy warning is a passed +result: the runner records it with `--success`, like Catch's `WARN`. A +`MockFunction` on its own, such as one of `CATCH3_MOCK_FUNCTION`, takes +`SetStrictness(MockStrictness::Nice)`, `Naggy` or `Strict`. + +## Non-virtual functions + +A mock overrides nothing that is not virtual, so code that calls a non-virtual +function reaches the mock only if it is written against the type it calls. Code +under test that takes its dependency as a template parameter gets the real +type in production and the mock in the test; the mock declares the same +functions without `override`: + +```cpp +class Clock +{ +public: + long Now() const; // not virtual +}; + +class MockClock +{ +public: + CATCH3_MOCK_METHOD(long, Now, (), const); +}; + +template<typename AnyClock> +long Elapsed(const AnyClock &clock, long start) +{ + return clock.Now() - start; +} + +TEST_CASE("Elapsed time") +{ + MockClock clock; + CATCH3_EXPECT_CALL(clock.NowMock)().Returns(50L); + CHECK(Elapsed(clock, 20) == 30); +} +``` + +Everything else is the same as for virtual functions: expectations, defaults, +sequences and strictness. The mock class has no base, so nothing follows its +parameters but `const` or `noexcept`. A free function or a static member +function is reached through a [seam](#free-functions) instead. ## Sequences diff --git a/docs/progmasoft-roadmap.md b/docs/progmasoft-roadmap.md index 3561803e..42c48862 100644 --- a/docs/progmasoft-roadmap.md +++ b/docs/progmasoft-roadmap.md @@ -73,9 +73,11 @@ Catch3 runner replaced Catch2's in every test binary: ## 3. Mocking Mocks report through Catch2's assertion path: expectations with call counts, -argument matchers built on Catch2's matchers, sequences, and actions, for -virtual interfaces and for free functions behind a seam. Unexpected calls and -unmet expectations fail the test case that owns the mock. See +argument matchers built on Catch2's matchers, sequences, actions and default +actions (`CATCH3_ON_CALL`), for virtual interfaces, for non-virtual functions +reached through a template parameter, and for free functions behind a seam. +Unexpected calls and unmet expectations fail the test case that owns the mock; +`NiceMock` and `NaggyMock` allow calls nothing was expected of. See [Mocking](progmasoft-mocking.md#top). ## 4. Per-test code coverage diff --git a/extras/catch_amalgamated.cpp b/extras/catch_amalgamated.cpp index 47e44619..2489f97b 100644 --- a/extras/catch_amalgamated.cpp +++ b/extras/catch_amalgamated.cpp @@ -9423,6 +9423,54 @@ namespace Progmasoft::Catch3::Detail } } + void + ReportMockWarning(const Catch::SourceLineInfo &line, + const std::string &mock, + std::string message) + { + if (!InTestCase()) + { + WriteToStandardError(line, mock, message); + return; + } + CATCH_TRY + { + Report(line, + mock, + Catch::ResultWas::Warning, + std::move(message), + Catch::ResultDisposition::ContinueOnFailure); + } + CATCH_CATCH_ALL + {} + } + + namespace + { + // Trivially destructible, so no thread has anything to tear down. + thread_local MockStrictness currentStrictness = MockStrictness::Strict; + } // namespace + + MockStrictness + CurrentMockStrictness() noexcept + { + return currentStrictness; + } + + MockStrictness + BeginMockStrictness(MockStrictness strictness) noexcept + { + const auto previous = currentStrictness; + currentStrictness = strictness; + return previous; + } + + void + EndMockStrictness(MockStrictness previous) noexcept + { + currentStrictness = previous; + } + std::string DescribeCalls(std::size_t minimum, std::size_t maximum) { diff --git a/extras/catch_amalgamated.hpp b/extras/catch_amalgamated.hpp index c011d772..d6b28e59 100644 --- a/extras/catch_amalgamated.hpp +++ b/extras/catch_amalgamated.hpp @@ -11984,8 +11984,21 @@ namespace Progmasoft::Catch3 template<typename Signature> class MockExpectation; template<typename Signature> + class MockDefault; + template<typename Signature> class MockFunction; + /// How a mock takes a call of a function nothing was expected of, an + /// uninteresting call: as a failure, with a warning, or silently. The + /// last two answer it with the default action. A call that expectations + /// exist for and none of them takes fails whatever the strictness. + enum class MockStrictness + { + Strict, + Naggy, + Nice, + }; + namespace Detail { inline constexpr std::size_t kUnlimitedCalls @@ -12076,6 +12089,28 @@ namespace Progmasoft::Catch3 [[nodiscard]] std::string DescribeCount(std::size_t calls); + /// Reports a warning in the running test case; outside of one, the + /// message goes to standard error. Never throws. + void + ReportMockWarning(const Catch::SourceLineInfo &line, + const std::string &mock, + std::string message); + + /// The strictness mocks made on this thread start with: what the + /// innermost NiceMock, NaggyMock or StrictMock under construction + /// set, else strict. + [[nodiscard]] MockStrictness + CurrentMockStrictness() noexcept; + + /// Sets the strictness of mocks made on this thread from now on, and + /// returns the one it replaces, for EndMockStrictness. + [[nodiscard]] MockStrictness + BeginMockStrictness(MockStrictness strictness) noexcept; + + /// Puts back the strictness BeginMockStrictness returned. + void + EndMockStrictness(MockStrictness previous) noexcept; + template<std::size_t Index, typename Signature> struct MockArgumentOf; @@ -12331,10 +12366,112 @@ namespace Progmasoft::Catch3 std::shared_ptr<Detail::MockSequence> state; }; + namespace Detail + { + /// 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> + class MockActions + { + public: + /// Returns `value`. A type that cannot be copied is moved out on + /// the first call; a reference result refers to `value`, which + /// has to outlive the mock. + template<typename Value> + Derived & + Returns(Value &&value) + { + static_assert(!std::is_void_v<Result>, + "A mock of a void function returns nothing."); + if constexpr (std::is_reference_v<Result>) + { + static_assert(std::is_lvalue_reference_v<Value>, + "A reference result needs an object that " + "outlives the mock."); + auto *target = &value; + return Does([target](Arguments...) -> Result { + return static_cast<Result>(*target); + }); + } + else if constexpr (std::is_copy_constructible_v<Result>) + { + return Does([held = static_cast<Result>(std::forward<Value>( + value))](Arguments...) -> Result { + return held; + }); + } + else + { + auto held + = std::make_shared<Result>(std::forward<Value>(value)); + return Does([held](Arguments...) -> Result { + // Calls can come from several threads. + const auto lock = LockMocks(); + return std::move(*held); + }); + } + } + + /// Runs `work` with the arguments of each call; what it returns + /// is what the call returns. + template<typename Work> + Derived & + Does(Work &&work) + { + const auto lock = LockMocks(); + action = std::make_shared<std::function<Result(Arguments...)>>( + std::forward<Work>(work)); + return static_cast<Derived &>(*this); + } + + /// Throws `exception` from each call. + template<typename Exception> + Derived & + Throws(Exception exception) + { + return Does( + [exception = std::move(exception)](Arguments...) -> Result { + Catch::throw_exception(exception); + }); + } + + protected: + MockActions() = default; + + // Empty until Returns, Does or Throws. + std::shared_ptr<std::function<Result(Arguments...)>> action; + }; + + template<typename Matchers, typename Values, std::size_t... Indices> + [[nodiscard]] bool + AcceptsEach([[maybe_unused]] const Matchers &matchers, + [[maybe_unused]] const Values &values, + std::index_sequence<Indices...>) + { + return (std::get<Indices>(matchers).Test(std::get<Indices>(values)) + && ...); + } + + /// Whether every argument of a call matches; no matchers accept any. + template<typename Matchers, typename Values> + [[nodiscard]] bool + AcceptsAll(const Matchers *matchers, const Values &values) + { + return matchers == nullptr + || AcceptsEach( + *matchers, + values, + std::make_index_sequence<std::tuple_size_v<Values>>{}); + } + } // namespace Detail + /// One expected kind of call of a mock. It expects one call until told /// otherwise. template<typename Result, typename... Arguments> class MockExpectation<Result(Arguments...)> final + : public Detail::MockActions<MockExpectation<Result(Arguments...)>, + Result, + Arguments...> { public: MockExpectation & @@ -12389,67 +12526,6 @@ namespace Progmasoft::Catch3 return *this; } - /// Returns `value`. A type that cannot be copied is moved out on the - /// first call; a reference result refers to `value`, which has to - /// outlive the mock. - template<typename Value> - MockExpectation & - Returns(Value &&value) - { - static_assert(!std::is_void_v<Result>, - "A mock of a void function returns nothing."); - if constexpr (std::is_reference_v<Result>) - { - static_assert(std::is_lvalue_reference_v<Value>, - "A reference result needs an object that " - "outlives the mock."); - auto *target = &value; - return Does([target](Arguments...) -> Result { - return static_cast<Result>(*target); - }); - } - else if constexpr (std::is_copy_constructible_v<Result>) - { - return Does([held = static_cast<Result>(std::forward<Value>( - value))](Arguments...) -> Result { - return held; - }); - } - else - { - auto held - = std::make_shared<Result>(std::forward<Value>(value)); - return Does([held](Arguments...) -> Result { - // Calls can come from several threads. - const auto lock = Detail::LockMocks(); - return std::move(*held); - }); - } - } - - /// Runs `action` with the arguments of each call; what it returns is - /// what the call returns. - template<typename Action> - MockExpectation & - Does(Action &&work) - { - const auto lock = Detail::LockMocks(); - action = std::make_shared<std::function<Result(Arguments...)>>( - std::forward<Action>(work)); - return *this; - } - - /// Throws `exception` from each call. - template<typename Exception> - MockExpectation & - Throws(Exception exception) - { - return Does( - [exception = std::move(exception)](Arguments...) -> Result { - Catch::throw_exception(exception); - }); - } - /// What the arguments of a call have to match. using Matchers = std::tuple<Detail::ArgumentMatcher<std::decay_t<Arguments>>...>; @@ -12467,28 +12543,50 @@ namespace Progmasoft::Catch3 , matchers(std::move(accepted)) {} - template<std::size_t... Indices> [[nodiscard]] bool - Accepts([[maybe_unused]] const std::tuple< - const std::decay_t<Arguments> &...> &values, - std::index_sequence<Indices...>) const + Accepts( + const std::tuple<const std::decay_t<Arguments> &...> &values) const { - return (std::get<Indices>(*matchers).Test(std::get<Indices>(values)) - && ...); + return Detail::AcceptsAll(matchers.get(), values); } + std::shared_ptr<Detail::MockExpectationState> state; + // Empty when any arguments will do. + std::unique_ptr<Matchers> matchers; + }; + + /// What a mock does for calls whose arguments match, when nothing more + /// particular says: an expectation without Returns, Does or Throws, and + /// an uninteresting call of a nice or naggy mock. Set with + /// `CATCH3_ON_CALL`; of the defaults that match a call, the one declared + /// last wins. It expects nothing and is never verified. + template<typename Result, typename... Arguments> + class MockDefault<Result(Arguments...)> final + : public Detail::MockActions<MockDefault<Result(Arguments...)>, + Result, + Arguments...> + { + public: + using Matchers + = std::tuple<Detail::ArgumentMatcher<std::decay_t<Arguments>>...>; + + private: + template<typename Signature> + friend class MockFunction; + + explicit MockDefault(std::unique_ptr<Matchers> accepted) + : matchers(std::move(accepted)) + {} + [[nodiscard]] bool Accepts( const std::tuple<const std::decay_t<Arguments> &...> &values) const { - return matchers == nullptr - || Accepts(values, std::index_sequence_for<Arguments...>{}); + return Detail::AcceptsAll(matchers.get(), values); } - std::shared_ptr<Detail::MockExpectationState> state; // Empty when any arguments will do. std::unique_ptr<Matchers> matchers; - std::shared_ptr<std::function<Result(Arguments...)>> action; }; /// A mock of one function: a callable that checks its calls against the @@ -12500,6 +12598,30 @@ namespace Progmasoft::Catch3 class MockFunction<Result(Arguments...)> final { using Expectation = MockExpectation<Result(Arguments...)>; + using Default = MockDefault<Result(Arguments...)>; + using Matchers = typename Expectation::Matchers; + + /// The matchers of `expected`, or none when it is empty. + template<typename... Expected> + [[nodiscard]] static std::unique_ptr<Matchers> + MakeMatchers([[maybe_unused]] Expected &&...expected) + { + constexpr auto arguments = sizeof...(Arguments); + static_assert(sizeof...(Expected) == 0 + || sizeof...(Expected) == arguments, + "Match every argument of the mock, or none to " + "accept any."); + if constexpr (sizeof...(Expected) == arguments && arguments != 0) + { + return std::make_unique<Matchers>( + Detail::MakeArgumentMatcher<std::decay_t<Arguments>>( + std::forward<Expected>(expected))...); + } + else + { + return nullptr; + } + } public: /// Declares an expectation at `line`; called with what the arguments @@ -12511,25 +12633,8 @@ namespace Progmasoft::Catch3 Expectation & operator()(Expected &&...expected) { - constexpr auto arguments = sizeof...(Arguments); - static_assert(sizeof...(Expected) == 0 - || sizeof...(Expected) == arguments, - "Match every argument of the mock, or none to " - "accept any."); - if constexpr (sizeof...(Expected) == arguments - && arguments != 0) - { - return mock.Add( - line, - std::make_unique<typename Expectation::Matchers>( - Detail::MakeArgumentMatcher< - std::decay_t<Arguments>>( - std::forward<Expected>(expected))...)); - } - else - { - return mock.Add(line, nullptr); - } + return mock.Add( + line, MakeMatchers(std::forward<Expected>(expected)...)); } private: @@ -12545,14 +12650,39 @@ namespace Progmasoft::Catch3 Catch::SourceLineInfo line; }; + /// Declares a default action; called with what the arguments have + /// to match. See `CATCH3_ON_CALL`. + class DefaultStart final + { + public: + template<typename... Expected> + Default & + operator()(Expected &&...expected) + { + return mock.AddDefault( + MakeMatchers(std::forward<Expected>(expected)...)); + } + + private: + friend class MockFunction; + + explicit DefaultStart(MockFunction &function) + : mock(function) + {} + + MockFunction &mock; + }; + /// `place` is where a call no expectation takes is reported when the - /// mock has no expectations to point at. + /// mock has no expectations to point at. The mock is strict unless it + /// is made inside a NiceMock or a NaggyMock. explicit MockFunction(std::string mockName = "mock", const Catch::SourceLineInfo &place = CATCH_INTERNAL_LINEINFO) : name(std::move(mockName)) , declared(place) , exceptions(std::uncaught_exceptions()) + , strictness(Detail::CurrentMockStrictness()) {} MockFunction(const MockFunction &) = delete; @@ -12575,6 +12705,20 @@ namespace Progmasoft::Catch3 return { *this, line }; } + [[nodiscard]] DefaultStart + OnCall() + { + return DefaultStart{ *this }; + } + + /// How this mock takes calls nothing was expected of. + void + SetStrictness(MockStrictness value) + { + const auto lock = Detail::LockMocks(); + strictness = value; + } + /// Checks the expectations now and forgets them, so that a test case /// can go on with new ones. void @@ -12594,9 +12738,18 @@ namespace Progmasoft::Catch3 } if (!decision.message.empty()) { - Detail::ReportMockFailure(*decision.line, - name, - decision.message); + if (decision.uninteresting) + { + Detail::ReportMockWarning(*decision.line, + name, + decision.message); + } + else + { + Detail::ReportMockFailure(*decision.line, + name, + decision.message); + } } if (decision.action != nullptr) { @@ -12613,11 +12766,14 @@ namespace Progmasoft::Catch3 } else { - Detail::AbortMockCall(*decision.line, - name, - "nothing to return from " + name - + ": give the expectation Returns " - "or Does"); + Detail::AbortMockCall( + *decision.line, + name, + "nothing to return from " + name + + (decision.uninteresting + ? ": give it a default with CATCH3_ON_CALL" + : ": give the expectation Returns or Does, or " + "the mock a default with CATCH3_ON_CALL")); } } @@ -12637,8 +12793,38 @@ namespace Progmasoft::Catch3 std::optional<Catch::SourceLineInfo> line; std::shared_ptr<std::function<Result(Arguments...)>> action; std::string message; + // A call nothing was expected of, which the strictness allows: + // the message is a warning. + bool uninteresting = false; }; + Default & + AddDefault(std::unique_ptr<Matchers> matchers) + { + const auto lock = Detail::LockMocks(); + defaults.push_back( + std::unique_ptr<Default>(new Default(std::move(matchers)))); + return *defaults.back(); + } + + /// The action of the last declared default that accepts the call and + /// has one; none when there is no such default. + [[nodiscard]] std::shared_ptr<std::function<Result(Arguments...)>> + DefaultFor( + const std::tuple<const std::decay_t<Arguments> &...> &values) const + { + for (auto candidate = defaults.rbegin(); candidate != defaults.rend(); + ++candidate) + { + if ((*candidate)->action != nullptr + && (*candidate)->Accepts(values)) + { + return (*candidate)->action; + } + } + return nullptr; + } + Expectation & Add(const Catch::SourceLineInfo &line, std::unique_ptr<typename Expectation::Matchers> matchers) @@ -12707,12 +12893,25 @@ namespace Progmasoft::Catch3 } if (expectation->state->Available()) { - return Take(*expectation); + return Take(*expectation, values); } used = expectation.get(); } const auto call = DescribeCall(values, std::index_sequence_for<Arguments...>{}); + if (expectations.empty() && strictness != MockStrictness::Strict) + { + Decision allowed; + allowed.line = declared; + allowed.action = DefaultFor(values); + allowed.uninteresting = true; + if (strictness == MockStrictness::Naggy) + { + allowed.message = "uninteresting call: " + call + + ", nothing was expected of this mock"; + } + return allowed; + } Decision refused; refused.message = used != nullptr ? DescribeUsed(call, *used->state) : DescribeUnexpected(call); @@ -12720,13 +12919,16 @@ namespace Progmasoft::Catch3 } [[nodiscard]] Decision - Take(const Expectation &expectation) + Take(const Expectation &expectation, + const std::tuple<const std::decay_t<Arguments> &...> &values) { auto &state = *expectation.state; ++state.Calls; Decision decision; decision.line = state.Line; - decision.action = expectation.action; + decision.action = expectation.action != nullptr + ? expectation.action + : DefaultFor(values); for (const auto &sequence : state.Sequences) { decision.message += sequence->Enter(state); @@ -12826,9 +13028,83 @@ namespace Progmasoft::Catch3 std::string name; Catch::SourceLineInfo declared; int exceptions; + MockStrictness strictness; std::vector<std::unique_ptr<Expectation>> expectations; + // Kept by Verify: defaults are not expectations. + std::vector<std::unique_ptr<Default>> defaults; }; + namespace Detail + { + /// Makes the mocks of a base class, constructed while it is open, of + /// one strictness. A NiceMock, NaggyMock or StrictMock closes it as + /// soon as its base is made; its destructor closes it when the base + /// throws instead. + template<MockStrictness Strictness> + class MockStrictnessScope + { + public: + MockStrictnessScope(const MockStrictnessScope &) = delete; + MockStrictnessScope & + operator=(const MockStrictnessScope &) = delete; + + protected: + MockStrictnessScope() noexcept + : catch3PreviousStrictness(BeginMockStrictness(Strictness)) + {} + + ~MockStrictnessScope() + { + CloseCatch3MockStrictness(); + } + + void + CloseCatch3MockStrictness() noexcept + { + if (catch3StrictnessOpen) + { + catch3StrictnessOpen = false; + EndMockStrictness(catch3PreviousStrictness); + } + } + + private: + MockStrictness catch3PreviousStrictness; + bool catch3StrictnessOpen = true; + }; + + /// `Base`, a mock class, with every mock it holds of `Strictness`. + template<MockStrictness Strictness, typename Base> + class MockWithStrictness final + : private MockStrictnessScope<Strictness> + , public Base + { + public: + template<typename... Parameters> + explicit MockWithStrictness(Parameters &&...parameters) + : MockStrictnessScope<Strictness>() + , Base(std::forward<Parameters>(parameters)...) + { + this->CloseCatch3MockStrictness(); + } + }; + } // namespace Detail + + /// `Base`, a mock class, whose mocks take calls nothing was expected of + /// silently, with their default actions. + template<typename Base> + using NiceMock = Detail::MockWithStrictness<MockStrictness::Nice, Base>; + + /// `Base`, a mock class, whose mocks take calls nothing was expected of + /// with a warning, and their default actions. + template<typename Base> + using NaggyMock = Detail::MockWithStrictness<MockStrictness::Naggy, Base>; + + /// `Base`, a mock class, whose mocks fail calls nothing was expected of: + /// what every mock does unless it is made nice or naggy. + template<typename Base> + using StrictMock = Detail::MockWithStrictness<MockStrictness::Strict, Base>; + /// Points a seam, a `std::function` or a function pointer that production /// code calls through, at `replacement` until the end of the scope. template<typename Seam> @@ -12985,6 +13261,12 @@ namespace Progmasoft::Catch3 /// have to match: values, Catch matchers, `Any` or `Where`, or nothing to /// accept any. Failures of the expectation point at this line. #define CATCH3_EXPECT_CALL(mock) (mock).Expect(CATCH_INTERNAL_LINEINFO) + +/// Sets the default action of `mock`, a `MockFunction`, for calls whose +/// arguments match what follows, as `CATCH3_EXPECT_CALL` does: values, Catch +/// 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() // 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 dac59861..53cb652f 100644 --- a/src/Progmasoft/Catch3/Mock.hpp +++ b/src/Progmasoft/Catch3/Mock.hpp @@ -26,8 +26,21 @@ namespace Progmasoft::Catch3 template<typename Signature> class MockExpectation; template<typename Signature> + class MockDefault; + template<typename Signature> class MockFunction; + /// How a mock takes a call of a function nothing was expected of, an + /// uninteresting call: as a failure, with a warning, or silently. The + /// last two answer it with the default action. A call that expectations + /// exist for and none of them takes fails whatever the strictness. + enum class MockStrictness + { + Strict, + Naggy, + Nice, + }; + namespace Detail { inline constexpr std::size_t kUnlimitedCalls @@ -118,6 +131,28 @@ namespace Progmasoft::Catch3 [[nodiscard]] std::string DescribeCount(std::size_t calls); + /// Reports a warning in the running test case; outside of one, the + /// message goes to standard error. Never throws. + void + ReportMockWarning(const Catch::SourceLineInfo &line, + const std::string &mock, + std::string message); + + /// The strictness mocks made on this thread start with: what the + /// innermost NiceMock, NaggyMock or StrictMock under construction + /// set, else strict. + [[nodiscard]] MockStrictness + CurrentMockStrictness() noexcept; + + /// Sets the strictness of mocks made on this thread from now on, and + /// returns the one it replaces, for EndMockStrictness. + [[nodiscard]] MockStrictness + BeginMockStrictness(MockStrictness strictness) noexcept; + + /// Puts back the strictness BeginMockStrictness returned. + void + EndMockStrictness(MockStrictness previous) noexcept; + template<std::size_t Index, typename Signature> struct MockArgumentOf; @@ -373,10 +408,112 @@ namespace Progmasoft::Catch3 std::shared_ptr<Detail::MockSequence> state; }; + namespace Detail + { + /// 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> + class MockActions + { + public: + /// Returns `value`. A type that cannot be copied is moved out on + /// the first call; a reference result refers to `value`, which + /// has to outlive the mock. + template<typename Value> + Derived & + Returns(Value &&value) + { + static_assert(!std::is_void_v<Result>, + "A mock of a void function returns nothing."); + if constexpr (std::is_reference_v<Result>) + { + static_assert(std::is_lvalue_reference_v<Value>, + "A reference result needs an object that " + "outlives the mock."); + auto *target = &value; + return Does([target](Arguments...) -> Result { + return static_cast<Result>(*target); + }); + } + else if constexpr (std::is_copy_constructible_v<Result>) + { + return Does([held = static_cast<Result>(std::forward<Value>( + value))](Arguments...) -> Result { + return held; + }); + } + else + { + auto held + = std::make_shared<Result>(std::forward<Value>(value)); + return Does([held](Arguments...) -> Result { + // Calls can come from several threads. + const auto lock = LockMocks(); + return std::move(*held); + }); + } + } + + /// Runs `work` with the arguments of each call; what it returns + /// is what the call returns. + template<typename Work> + Derived & + Does(Work &&work) + { + const auto lock = LockMocks(); + action = std::make_shared<std::function<Result(Arguments...)>>( + std::forward<Work>(work)); + return static_cast<Derived &>(*this); + } + + /// Throws `exception` from each call. + template<typename Exception> + Derived & + Throws(Exception exception) + { + return Does( + [exception = std::move(exception)](Arguments...) -> Result { + Catch::throw_exception(exception); + }); + } + + protected: + MockActions() = default; + + // Empty until Returns, Does or Throws. + std::shared_ptr<std::function<Result(Arguments...)>> action; + }; + + template<typename Matchers, typename Values, std::size_t... Indices> + [[nodiscard]] bool + AcceptsEach([[maybe_unused]] const Matchers &matchers, + [[maybe_unused]] const Values &values, + std::index_sequence<Indices...>) + { + return (std::get<Indices>(matchers).Test(std::get<Indices>(values)) + && ...); + } + + /// Whether every argument of a call matches; no matchers accept any. + template<typename Matchers, typename Values> + [[nodiscard]] bool + AcceptsAll(const Matchers *matchers, const Values &values) + { + return matchers == nullptr + || AcceptsEach( + *matchers, + values, + std::make_index_sequence<std::tuple_size_v<Values>>{}); + } + } // namespace Detail + /// One expected kind of call of a mock. It expects one call until told /// otherwise. template<typename Result, typename... Arguments> class MockExpectation<Result(Arguments...)> final + : public Detail::MockActions<MockExpectation<Result(Arguments...)>, + Result, + Arguments...> { public: MockExpectation & @@ -431,67 +568,6 @@ namespace Progmasoft::Catch3 return *this; } - /// Returns `value`. A type that cannot be copied is moved out on the - /// first call; a reference result refers to `value`, which has to - /// outlive the mock. - template<typename Value> - MockExpectation & - Returns(Value &&value) - { - static_assert(!std::is_void_v<Result>, - "A mock of a void function returns nothing."); - if constexpr (std::is_reference_v<Result>) - { - static_assert(std::is_lvalue_reference_v<Value>, - "A reference result needs an object that " - "outlives the mock."); - auto *target = &value; - return Does([target](Arguments...) -> Result { - return static_cast<Result>(*target); - }); - } - else if constexpr (std::is_copy_constructible_v<Result>) - { - return Does([held = static_cast<Result>(std::forward<Value>( - value))](Arguments...) -> Result { - return held; - }); - } - else - { - auto held - = std::make_shared<Result>(std::forward<Value>(value)); - return Does([held](Arguments...) -> Result { - // Calls can come from several threads. - const auto lock = Detail::LockMocks(); - return std::move(*held); - }); - } - } - - /// Runs `action` with the arguments of each call; what it returns is - /// what the call returns. - template<typename Action> - MockExpectation & - Does(Action &&work) - { - const auto lock = Detail::LockMocks(); - action = std::make_shared<std::function<Result(Arguments...)>>( - std::forward<Action>(work)); - return *this; - } - - /// Throws `exception` from each call. - template<typename Exception> - MockExpectation & - Throws(Exception exception) - { - return Does( - [exception = std::move(exception)](Arguments...) -> Result { - Catch::throw_exception(exception); - }); - } - /// What the arguments of a call have to match. using Matchers = std::tuple<Detail::ArgumentMatcher<std::decay_t<Arguments>>...>; @@ -509,28 +585,50 @@ namespace Progmasoft::Catch3 , matchers(std::move(accepted)) {} - template<std::size_t... Indices> [[nodiscard]] bool - Accepts([[maybe_unused]] const std::tuple< - const std::decay_t<Arguments> &...> &values, - std::index_sequence<Indices...>) const + Accepts( + const std::tuple<const std::decay_t<Arguments> &...> &values) const { - return (std::get<Indices>(*matchers).Test(std::get<Indices>(values)) - && ...); + return Detail::AcceptsAll(matchers.get(), values); } + std::shared_ptr<Detail::MockExpectationState> state; + // Empty when any arguments will do. + std::unique_ptr<Matchers> matchers; + }; + + /// What a mock does for calls whose arguments match, when nothing more + /// particular says: an expectation without Returns, Does or Throws, and + /// an uninteresting call of a nice or naggy mock. Set with + /// `CATCH3_ON_CALL`; of the defaults that match a call, the one declared + /// last wins. It expects nothing and is never verified. + template<typename Result, typename... Arguments> + class MockDefault<Result(Arguments...)> final + : public Detail::MockActions<MockDefault<Result(Arguments...)>, + Result, + Arguments...> + { + public: + using Matchers + = std::tuple<Detail::ArgumentMatcher<std::decay_t<Arguments>>...>; + + private: + template<typename Signature> + friend class MockFunction; + + explicit MockDefault(std::unique_ptr<Matchers> accepted) + : matchers(std::move(accepted)) + {} + [[nodiscard]] bool Accepts( const std::tuple<const std::decay_t<Arguments> &...> &values) const { - return matchers == nullptr - || Accepts(values, std::index_sequence_for<Arguments...>{}); + return Detail::AcceptsAll(matchers.get(), values); } - std::shared_ptr<Detail::MockExpectationState> state; // Empty when any arguments will do. std::unique_ptr<Matchers> matchers; - std::shared_ptr<std::function<Result(Arguments...)>> action; }; /// A mock of one function: a callable that checks its calls against the @@ -542,6 +640,30 @@ namespace Progmasoft::Catch3 class MockFunction<Result(Arguments...)> final { using Expectation = MockExpectation<Result(Arguments...)>; + using Default = MockDefault<Result(Arguments...)>; + using Matchers = typename Expectation::Matchers; + + /// The matchers of `expected`, or none when it is empty. + template<typename... Expected> + [[nodiscard]] static std::unique_ptr<Matchers> + MakeMatchers([[maybe_unused]] Expected &&...expected) + { + constexpr auto arguments = sizeof...(Arguments); + static_assert(sizeof...(Expected) == 0 + || sizeof...(Expected) == arguments, + "Match every argument of the mock, or none to " + "accept any."); + if constexpr (sizeof...(Expected) == arguments && arguments != 0) + { + return std::make_unique<Matchers>( + Detail::MakeArgumentMatcher<std::decay_t<Arguments>>( + std::forward<Expected>(expected))...); + } + else + { + return nullptr; + } + } public: /// Declares an expectation at `line`; called with what the arguments @@ -553,25 +675,8 @@ namespace Progmasoft::Catch3 Expectation & operator()(Expected &&...expected) { - constexpr auto arguments = sizeof...(Arguments); - static_assert(sizeof...(Expected) == 0 - || sizeof...(Expected) == arguments, - "Match every argument of the mock, or none to " - "accept any."); - if constexpr (sizeof...(Expected) == arguments - && arguments != 0) - { - return mock.Add( - line, - std::make_unique<typename Expectation::Matchers>( - Detail::MakeArgumentMatcher< - std::decay_t<Arguments>>( - std::forward<Expected>(expected))...)); - } - else - { - return mock.Add(line, nullptr); - } + return mock.Add( + line, MakeMatchers(std::forward<Expected>(expected)...)); } private: @@ -587,14 +692,39 @@ namespace Progmasoft::Catch3 Catch::SourceLineInfo line; }; + /// Declares a default action; called with what the arguments have + /// to match. See `CATCH3_ON_CALL`. + class DefaultStart final + { + public: + template<typename... Expected> + Default & + operator()(Expected &&...expected) + { + return mock.AddDefault( + MakeMatchers(std::forward<Expected>(expected)...)); + } + + private: + friend class MockFunction; + + explicit DefaultStart(MockFunction &function) + : mock(function) + {} + + MockFunction &mock; + }; + /// `place` is where a call no expectation takes is reported when the - /// mock has no expectations to point at. + /// mock has no expectations to point at. The mock is strict unless it + /// is made inside a NiceMock or a NaggyMock. explicit MockFunction(std::string mockName = "mock", const Catch::SourceLineInfo &place = CATCH_INTERNAL_LINEINFO) : name(std::move(mockName)) , declared(place) , exceptions(std::uncaught_exceptions()) + , strictness(Detail::CurrentMockStrictness()) {} MockFunction(const MockFunction &) = delete; @@ -617,6 +747,20 @@ namespace Progmasoft::Catch3 return { *this, line }; } + [[nodiscard]] DefaultStart + OnCall() + { + return DefaultStart{ *this }; + } + + /// How this mock takes calls nothing was expected of. + void + SetStrictness(MockStrictness value) + { + const auto lock = Detail::LockMocks(); + strictness = value; + } + /// Checks the expectations now and forgets them, so that a test case /// can go on with new ones. void @@ -636,9 +780,18 @@ namespace Progmasoft::Catch3 } if (!decision.message.empty()) { - Detail::ReportMockFailure(*decision.line, - name, - decision.message); + if (decision.uninteresting) + { + Detail::ReportMockWarning(*decision.line, + name, + decision.message); + } + else + { + Detail::ReportMockFailure(*decision.line, + name, + decision.message); + } } if (decision.action != nullptr) { @@ -655,11 +808,14 @@ namespace Progmasoft::Catch3 } else { - Detail::AbortMockCall(*decision.line, - name, - "nothing to return from " + name - + ": give the expectation Returns " - "or Does"); + Detail::AbortMockCall( + *decision.line, + name, + "nothing to return from " + name + + (decision.uninteresting + ? ": give it a default with CATCH3_ON_CALL" + : ": give the expectation Returns or Does, or " + "the mock a default with CATCH3_ON_CALL")); } } @@ -679,8 +835,38 @@ namespace Progmasoft::Catch3 std::optional<Catch::SourceLineInfo> line; std::shared_ptr<std::function<Result(Arguments...)>> action; std::string message; + // A call nothing was expected of, which the strictness allows: + // the message is a warning. + bool uninteresting = false; }; + Default & + AddDefault(std::unique_ptr<Matchers> matchers) + { + const auto lock = Detail::LockMocks(); + defaults.push_back( + std::unique_ptr<Default>(new Default(std::move(matchers)))); + return *defaults.back(); + } + + /// The action of the last declared default that accepts the call and + /// has one; none when there is no such default. + [[nodiscard]] std::shared_ptr<std::function<Result(Arguments...)>> + DefaultFor( + const std::tuple<const std::decay_t<Arguments> &...> &values) const + { + for (auto candidate = defaults.rbegin(); candidate != defaults.rend(); + ++candidate) + { + if ((*candidate)->action != nullptr + && (*candidate)->Accepts(values)) + { + return (*candidate)->action; + } + } + return nullptr; + } + Expectation & Add(const Catch::SourceLineInfo &line, std::unique_ptr<typename Expectation::Matchers> matchers) @@ -749,12 +935,25 @@ namespace Progmasoft::Catch3 } if (expectation->state->Available()) { - return Take(*expectation); + return Take(*expectation, values); } used = expectation.get(); } const auto call = DescribeCall(values, std::index_sequence_for<Arguments...>{}); + if (expectations.empty() && strictness != MockStrictness::Strict) + { + Decision allowed; + allowed.line = declared; + allowed.action = DefaultFor(values); + allowed.uninteresting = true; + if (strictness == MockStrictness::Naggy) + { + allowed.message = "uninteresting call: " + call + + ", nothing was expected of this mock"; + } + return allowed; + } Decision refused; refused.message = used != nullptr ? DescribeUsed(call, *used->state) : DescribeUnexpected(call); @@ -762,13 +961,16 @@ namespace Progmasoft::Catch3 } [[nodiscard]] Decision - Take(const Expectation &expectation) + Take(const Expectation &expectation, + const std::tuple<const std::decay_t<Arguments> &...> &values) { auto &state = *expectation.state; ++state.Calls; Decision decision; decision.line = state.Line; - decision.action = expectation.action; + decision.action = expectation.action != nullptr + ? expectation.action + : DefaultFor(values); for (const auto &sequence : state.Sequences) { decision.message += sequence->Enter(state); @@ -868,9 +1070,83 @@ namespace Progmasoft::Catch3 std::string name; Catch::SourceLineInfo declared; int exceptions; + MockStrictness strictness; std::vector<std::unique_ptr<Expectation>> expectations; + // Kept by Verify: defaults are not expectations. + std::vector<std::unique_ptr<Default>> defaults; }; + namespace Detail + { + /// Makes the mocks of a base class, constructed while it is open, of + /// one strictness. A NiceMock, NaggyMock or StrictMock closes it as + /// soon as its base is made; its destructor closes it when the base + /// throws instead. + template<MockStrictness Strictness> + class MockStrictnessScope + { + public: + MockStrictnessScope(const MockStrictnessScope &) = delete; + MockStrictnessScope & + operator=(const MockStrictnessScope &) = delete; + + protected: + MockStrictnessScope() noexcept + : catch3PreviousStrictness(BeginMockStrictness(Strictness)) + {} + + ~MockStrictnessScope() + { + CloseCatch3MockStrictness(); + } + + void + CloseCatch3MockStrictness() noexcept + { + if (catch3StrictnessOpen) + { + catch3StrictnessOpen = false; + EndMockStrictness(catch3PreviousStrictness); + } + } + + private: + MockStrictness catch3PreviousStrictness; + bool catch3StrictnessOpen = true; + }; + + /// `Base`, a mock class, with every mock it holds of `Strictness`. + template<MockStrictness Strictness, typename Base> + class MockWithStrictness final + : private MockStrictnessScope<Strictness> + , public Base + { + public: + template<typename... Parameters> + explicit MockWithStrictness(Parameters &&...parameters) + : MockStrictnessScope<Strictness>() + , Base(std::forward<Parameters>(parameters)...) + { + this->CloseCatch3MockStrictness(); + } + }; + } // namespace Detail + + /// `Base`, a mock class, whose mocks take calls nothing was expected of + /// silently, with their default actions. + template<typename Base> + using NiceMock = Detail::MockWithStrictness<MockStrictness::Nice, Base>; + + /// `Base`, a mock class, whose mocks take calls nothing was expected of + /// with a warning, and their default actions. + template<typename Base> + using NaggyMock = Detail::MockWithStrictness<MockStrictness::Naggy, Base>; + + /// `Base`, a mock class, whose mocks fail calls nothing was expected of: + /// what every mock does unless it is made nice or naggy. + template<typename Base> + using StrictMock = Detail::MockWithStrictness<MockStrictness::Strict, Base>; + /// Points a seam, a `std::function` or a function pointer that production /// code calls through, at `replacement` until the end of the scope. template<typename Seam> @@ -1027,3 +1303,9 @@ namespace Progmasoft::Catch3 /// have to match: values, Catch matchers, `Any` or `Where`, or nothing to /// accept any. Failures of the expectation point at this line. #define CATCH3_EXPECT_CALL(mock) (mock).Expect(CATCH_INTERNAL_LINEINFO) + +/// Sets the default action of `mock`, a `MockFunction`, for calls whose +/// arguments match what follows, as `CATCH3_EXPECT_CALL` does: values, Catch +/// 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() diff --git a/src/Progmasoft/Mock.cpp b/src/Progmasoft/Mock.cpp index 4374f05e..0d777258 100644 --- a/src/Progmasoft/Mock.cpp +++ b/src/Progmasoft/Mock.cpp @@ -156,6 +156,54 @@ namespace Progmasoft::Catch3::Detail } } + void + ReportMockWarning(const Catch::SourceLineInfo &line, + const std::string &mock, + std::string message) + { + if (!InTestCase()) + { + WriteToStandardError(line, mock, message); + return; + } + CATCH_TRY + { + Report(line, + mock, + Catch::ResultWas::Warning, + std::move(message), + Catch::ResultDisposition::ContinueOnFailure); + } + CATCH_CATCH_ALL + {} + } + + namespace + { + // Trivially destructible, so no thread has anything to tear down. + thread_local MockStrictness currentStrictness = MockStrictness::Strict; + } // namespace + + MockStrictness + CurrentMockStrictness() noexcept + { + return currentStrictness; + } + + MockStrictness + BeginMockStrictness(MockStrictness strictness) noexcept + { + const auto previous = currentStrictness; + currentStrictness = strictness; + return previous; + } + + void + EndMockStrictness(MockStrictness previous) noexcept + { + currentStrictness = previous; + } + std::string DescribeCalls(std::size_t minimum, std::size_t maximum) { diff --git a/tests/Progmasoft/Mock.tests.cpp b/tests/Progmasoft/Mock.tests.cpp index 9542a166..d948f0b0 100644 --- a/tests/Progmasoft/Mock.tests.cpp +++ b/tests/Progmasoft/Mock.tests.cpp @@ -25,6 +25,10 @@ namespace using FixtureClient::Scratch; using Progmasoft::Catch3::Any; using Progmasoft::Catch3::MockFunction; + using Progmasoft::Catch3::MockStrictness; + using Progmasoft::Catch3::NaggyMock; + using Progmasoft::Catch3::NiceMock; + using Progmasoft::Catch3::StrictMock; using Progmasoft::Catch3::ScopedSeam; using Progmasoft::Catch3::Sequence; using Progmasoft::Catch3::Where; @@ -77,6 +81,59 @@ namespace CATCH3_MOCK_METHOD(int, Twice, (int)); }; + /// A dependency with no virtual functions, as code that takes it as a + /// template parameter sees it. + class Clock + { + public: + [[nodiscard]] long + Now() const + { + return 0; + } + }; + + /// The same functions, not virtual: a mock of a non-virtual interface. + class MockClock + { + public: + CATCH3_MOCK_METHOD(long, Now, (), const); + }; + + /// Code under test that takes its dependency as a template parameter, so + /// that a test can give it a mock without virtual functions. + template<typename AnyClock> + [[nodiscard]] long + Elapsed(const AnyClock &clock, long start) + { + return clock.Now() - start; + } + + /// A mock class whose constructor can throw, for the strictness that a + /// failed construction leaves. + class ThrowingCounter + { + public: + explicit ThrowingCounter(bool fail) + { + if (fail) + { + throw std::runtime_error("construction failed"); + } + } + + CATCH3_MOCK_METHOD(int, Twice, (int)); + }; + + /// A mock class for the strictness tests; not final. + class Counter + { + public: + CATCH3_MOCK_METHOD(int, Twice, (int)); + CATCH3_MOCK_METHOD(void, Reset, ()); + CATCH3_MOCK_METHOD(std::string &, Label, ()); + }; + /// A seam production code calls a free function through. std::function<long()> & ClockSeam() @@ -398,8 +455,131 @@ 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 strict uninteresting call"), + ContainsSubstring("unexpected call: Next(1), nothing was " + "expected of this mock")); + CHECK_THAT(message("fixture mock nice unexpected arguments"), + ContainsSubstring("unexpected call: Next(5), expected\n" + " Next(1)")); const auto leaving = message("fixture mock left by a failure"); CHECK_THAT(leaving, ContainsSubstring("the test's own failure")); CHECK_FALSE(ContainsSubstring("unmet").match(leaving)); } + +TEST_CASE("A default answers an expectation that has no action", + "[progmasoft][mock]") +{ + MockStore store; + CATCH3_ON_CALL(store.GetMock)(Any).Returns(1); + CATCH3_ON_CALL(store.GetMock)(StartsWith("a")).Returns(2); + // The last default that matches wins. + CATCH3_EXPECT_CALL(store.GetMock)(Any).Times(2); + // An action of the expectation wins over every default. + CATCH3_EXPECT_CALL(store.GetMock)("cid").Returns(9); + CHECK(store.Get("ada") == 2); + CHECK(store.Get("bob") == 1); + CHECK(store.Get("cid") == 9); +} + +TEST_CASE("Defaults outlive Verify", "[progmasoft][mock]") +{ + MockCounter counter; + CATCH3_ON_CALL(counter.TwiceMock)(Any).Does([](int value) { + return value * 2; + }); + CATCH3_EXPECT_CALL(counter.TwiceMock)(3); + CHECK(counter.Twice(3) == 6); + counter.TwiceMock.Verify(); + CATCH3_EXPECT_CALL(counter.TwiceMock)(4); + CHECK(counter.Twice(4) == 8); +} + +TEST_CASE("A nice mock answers uninteresting calls with its defaults", + "[progmasoft][mock]") +{ + NiceMock<Counter> counter; + std::string label = "kept"; + CATCH3_ON_CALL(counter.TwiceMock)(Any).Does([](int value) { + return value * 2; + }); + CATCH3_ON_CALL(counter.LabelMock)().Returns(label); + CHECK(counter.Twice(21) == 42); + counter.Reset(); + CHECK(&counter.Label() == &label); + // Without a default, a value-initialized result. + NiceMock<Counter> plain; + CHECK(plain.Twice(5) == 0); +} + +TEST_CASE("A nice mock still checks what it expects", "[progmasoft][mock]") +{ + NiceMock<Counter> counter; + CATCH3_EXPECT_CALL(counter.TwiceMock)(2).Returns(4); + CHECK(counter.Twice(2) == 4); + // Reset has no expectation: uninteresting, so allowed. + counter.Reset(); +} + +TEST_CASE("Strictness covers the mocks of the wrapped class only", + "[progmasoft][mock]") +{ + CHECK(Progmasoft::Catch3::Detail::CurrentMockStrictness() + == MockStrictness::Strict); + NiceMock<Counter> nice; + NaggyMock<Counter> naggy; + StrictMock<Counter> strict; + CHECK(Progmasoft::Catch3::Detail::CurrentMockStrictness() + == MockStrictness::Strict); + MockCounter later; + CATCH3_EXPECT_CALL(later.TwiceMock)(1).Returns(2); + CHECK(later.Twice(1) == 2); + CHECK_THROWS_AS(NiceMock<ThrowingCounter>(true), std::runtime_error); + CHECK(Progmasoft::Catch3::Detail::CurrentMockStrictness() + == MockStrictness::Strict); + NiceMock<ThrowingCounter> built(false); + CHECK(built.Twice(1) == 0); +} + +TEST_CASE("A mock function can be made nice on its own", "[progmasoft][mock]") +{ + CATCH3_MOCK_FUNCTION(tick, int()); + tick.SetStrictness(MockStrictness::Nice); + CATCH3_ON_CALL(tick)().Returns(3); + CHECK(tick() == 3); +} + +TEST_CASE("A non-virtual function is mocked through a template parameter", + "[progmasoft][mock]") +{ + CHECK(Elapsed(Clock{}, 0) == 0); + MockClock clock; + CATCH3_EXPECT_CALL(clock.NowMock)().Returns(50L); + CHECK(Elapsed(clock, 20) == 30); + + NiceMock<MockClock> quiet; + CATCH3_ON_CALL(quiet.NowMock)().Returns(7L); + CHECK(Elapsed(quiet, 0) == 7); +} + +TEST_CASE("Nice, naggy and strict mocks report as they should", + "[progmasoft][mock]") +{ + const Scratch scratch; + // A warning is a passed result, recorded with --success. + const auto run + = RunFixture(scratch, { "--no-history", "--success", "[mock-naggy]" }); + INFO(run.output); + CHECK(ExitCode(run) == 0); + const auto &naggy = run.Test("fixture mock naggy uninteresting call"); + CHECK(naggy["outcome"].AsString() == "passed"); + std::string text; + for (const auto &assertion : + naggy["attempts"].Items().front()["assertions"].Items()) + { + text += assertion["message"].AsString() + "\n"; + } + CHECK_THAT(text, + ContainsSubstring("uninteresting call: Next(3), nothing was " + "expected of this mock")); +} diff --git a/tests/Progmasoft/RunnerFixture.cpp b/tests/Progmasoft/RunnerFixture.cpp index 0c65ddbd..b93b915a 100644 --- a/tests/Progmasoft/RunnerFixture.cpp +++ b/tests/Progmasoft/RunnerFixture.cpp @@ -251,6 +251,40 @@ TEST_CASE("fixture mock left by a failure", "[fixture][mock]") FAIL("the test's own failure"); } +namespace +{ + /// A mock class for the strictness fixtures; not final, so that + /// NiceMock and its siblings can wrap it. + class FixtureCounter + { + public: + CATCH3_MOCK_METHOD(int, Next, (int)); + }; +} // namespace + +TEST_CASE("fixture mock strict uninteresting call", "[fixture][mock]") +{ + Progmasoft::Catch3::StrictMock<FixtureCounter> counter; + CHECK(counter.Next(1) == 0); +} + +TEST_CASE("fixture mock nice unexpected arguments", "[fixture][mock]") +{ + // Nice allows calls of a function nothing was expected of, not calls an + // expectation of that function refuses. + Progmasoft::Catch3::NiceMock<FixtureCounter> counter; + CATCH3_EXPECT_CALL(counter.NextMock)(1).Returns(2); + CHECK(counter.Next(1) == 2); + CHECK(counter.Next(5) == 0); +} + +TEST_CASE("fixture mock naggy uninteresting call", "[fixture][mock-naggy]") +{ + Progmasoft::Catch3::NaggyMock<FixtureCounter> counter; + CATCH3_ON_CALL(counter.NextMock)(Progmasoft::Catch3::Any).Returns(7); + CHECK(counter.Next(3) == 7); +} + TEST_CASE("fixture mock outlives the run", "[fixture][mock-exit]") { static auto *mock = new Progmasoft::Catch3::MockFunction<void()>{ "late" };