From 1d61176a81da7f0d784de8e597a8a8c90559af61 Mon Sep 17 00:00:00 2001 From: Katherine Whitlock Date: Sat, 14 Nov 2026 11:22:05 -0500 Subject: [PATCH 01/20] fix(matchers): the default description puts one space before the expected value The default description joined the verb and the expected value with a space, but to_sentence() already leads with one, so every matcher that keeps the default description printed two: "expected 3 to be less than 2". It now prints one: "expected 3 to be less than 2". --- include/matchers/matcher_base.hpp | 3 ++- spec/matchers/description_spec.cpp | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 spec/matchers/description_spec.cpp diff --git a/include/matchers/matcher_base.hpp b/include/matchers/matcher_base.hpp index fc5b4e1..0c0a7f0 100644 --- a/include/matchers/matcher_base.hpp +++ b/include/matchers/matcher_base.hpp @@ -140,7 +140,8 @@ std::string MatcherBase::description() { // ss << "match " << // this->name_to_sentence(Util::demangle(typeid(*this).name())) // << "(" << pretty_expected.substr(1, pretty_expected.length()) << ")"; - return std::format("{} {}", verb(), Pretty::to_sentence(expected_)); + // to_sentence() leads with the space that separates it from the verb. + return std::format("{}{}", verb(), Pretty::to_sentence(expected_)); } /** diff --git a/spec/matchers/description_spec.cpp b/spec/matchers/description_spec.cpp new file mode 100644 index 0000000..65253a9 --- /dev/null +++ b/spec/matchers/description_spec.cpp @@ -0,0 +1,23 @@ +#include +#include + +#include "cppspec.hpp" + +using namespace CppSpec; + +// clang-format off +describe description_spec("A matcher's default description", $ { + it("puts one space between the verb and the expected value", _ { + auto ex = ExpectationValue(3, std::source_location::current()); + expect(Matchers::BeLessThan(ex, 2).description()).to_equal(std::string("be less than 2")); + expect(Matchers::BeGreaterThan(ex, 4).description()).to_equal(std::string("be greater than 4")); + }); + + it("reads as one sentence in the failure message", _ { + auto ex = ExpectationValue(3, std::source_location::current()); + expect(Matchers::BeLessThan(ex, 2).run().get_message()) + .to_equal(std::string("expected 3 to be less than 2")); + }); +}); + +CPPSPEC_MAIN(description_spec); From 128ddd056f353e62d84868733943a99624795720 Mon Sep 17 00:00:00 2001 From: Katherine Whitlock Date: Sat, 14 Nov 2026 11:20:10 -0500 Subject: [PATCH 02/20] fix(matchers): every matcher reports a custom failure message above its own A custom message given to a matcher replaced the matcher's own failure message, so `expect(x).to_equal(2, "the gain")` printed only "the gain" and neither value. The custom message is now printed on the line above the matcher's own message, which always shows the values: the gain expected (int) => 2 got (int) => 1 Compared using `==` failure_message() and failure_message_when_negated() return only the matcher's own text; the custom message is added above it by full_failure_message() and full_failure_message_when_negated(), which the expectation handlers report. Code that calls failure_message*() directly (a custom handler or formatter, or a test of a matcher) gets no custom message and should call full_failure_message*() instead. Those two members sit beside set_message(), are [[nodiscard]] and carry Doxygen comments. A custom message over a matcher whose own message is empty still shows the "Failure message is empty" diagnostic below it, not a blank line. The custom message spec covers Equal, Satisfy, BeWithin (including to_be_within(tolerance, message).of()), Throw, Contain, a matcher that keeps the base's messages and one that defines its own, each positive and negated, plus the empty-message case. --- include/expectations/handler.hpp | 4 +- include/matchers/matcher_base.hpp | 45 ++++-- spec/matchers/custom_message_spec.cpp | 197 ++++++++++++++++++++++++++ 3 files changed, 232 insertions(+), 14 deletions(-) create mode 100644 spec/matchers/custom_message_spec.cpp diff --git a/include/expectations/handler.hpp b/include/expectations/handler.hpp index 76dc679..c9742fc 100755 --- a/include/expectations/handler.hpp +++ b/include/expectations/handler.hpp @@ -49,7 +49,7 @@ Result PositiveExpectationHandler::handle_matcher(Matcher& matcher) { return Result::error_with(matcher.get_location(), "Unknown exception thrown during matcher execution."); } - return !matched ? Result::failure_with(matcher.get_location(), matcher.failure_message()) + return !matched ? Result::failure_with(matcher.get_location(), matcher.full_failure_message()) : Result::success(matcher.get_location()); } @@ -71,7 +71,7 @@ Result NegativeExpectationHandler::handle_matcher(Matcher& matcher) { } catch (...) { return Result::error_with(matcher.get_location(), "Unhandled exception thrown during matcher execution."); } - return !matched ? Result::failure_with(matcher.get_location(), matcher.failure_message_when_negated()) + return !matched ? Result::failure_with(matcher.get_location(), matcher.full_failure_message_when_negated()) : Result::success(matcher.get_location()); } diff --git a/include/matchers/matcher_base.hpp b/include/matchers/matcher_base.hpp index 0c0a7f0..fc16935 100644 --- a/include/matchers/matcher_base.hpp +++ b/include/matchers/matcher_base.hpp @@ -11,6 +11,7 @@ #include #include +#include #include "expectations/handler.hpp" #include "it_base.hpp" @@ -37,6 +38,15 @@ template class MatcherBase : public Pretty { std::string custom_failure_message; + // The custom message, when one was set, on the line above the matcher's own. An empty own message is replaced by + // a diagnostic here, so a custom message never sits above a blank line. + [[nodiscard]] std::string with_custom_message(std::string own) const { + if (own.empty()) { + own = empty_failure_message; + } + return custom_failure_message.empty() ? own : custom_failure_message + "\n" + own; + } + protected: Expected expected_; // The expected object contained by the matcher @@ -77,6 +87,25 @@ class MatcherBase : public Pretty { // Set the message to give on match failure virtual MatcherBase& set_message(std::string message); + /** + * @brief What a failed match reports: the custom message, when one was set, on the line above the matcher's own + * failure_message() + */ + [[nodiscard]] std::string full_failure_message() { return with_custom_message(failure_message()); } + + /** + * @brief What a failed negated match reports: the custom message, when one was set, on the line above the + * matcher's own failure_message_when_negated() + */ + [[nodiscard]] std::string full_failure_message_when_negated() { + return with_custom_message(failure_message_when_negated()); + } + + /** @brief What a failure reports in place of a matcher's own message that is empty */ + static constexpr std::string_view empty_failure_message = + "Failure message is empty. Does your matcher define the appropriate failure_message[_when_negated] method to " + "return a string?"; + [[nodiscard]] std::source_location get_location() const { return expectation_.get_location(); } /*--------- Primary functions -------------*/ @@ -104,28 +133,22 @@ MatcherBase& MatcherBase::set_message(std::string message) { } /** - * @brief Get message to give on match failure + * @brief Get the matcher's own message for a failed match; the handler puts any custom message above it * * @return the message */ template std::string MatcherBase::failure_message() { - if (not custom_failure_message.empty()) { - return this->custom_failure_message; - } return std::format("expected {} to {}", Pretty::to_word(actual()), description()); } /** - * @brief Get message to give on match failure when negated + * @brief Get the matcher's own message for a failed negated match; the handler puts any custom message above it * * @return the message */ template std::string MatcherBase::failure_message_when_negated() { - if (not custom_failure_message.empty()) { - return this->custom_failure_message; - } return std::format("expected {} to not {}", Pretty::to_word(actual()), description()); } @@ -160,11 +183,9 @@ Result MatcherBase::run() { // If our items didn't match, we obviously failed. // Only report the failure if we aren't actively ignoring it. + // A handler that does not build its message with full_failure_message*() can still report an empty one. if (result.is_failure() && result.get_message().empty()) { - result.set_message( - "Failure message is empty. Does your matcher define the " - "appropriate failure_message[_when_negated] method to " - "return a string?"); + result.set_message(std::string(empty_failure_message)); } if (expectation_.ignored()) { diff --git a/spec/matchers/custom_message_spec.cpp b/spec/matchers/custom_message_spec.cpp new file mode 100644 index 0000000..0c3fd0d --- /dev/null +++ b/spec/matchers/custom_message_spec.cpp @@ -0,0 +1,197 @@ +#include +#include +#include +#include +#include +#include + +#include "cppspec.hpp" + +using namespace CppSpec; + +namespace { + +// What a matcher reports when it fails, with the custom message set first when one is given. +template +std::string report(Matcher matcher, const std::string& message = "") { + if (!message.empty()) { + matcher.set_message(message); + } + return matcher.run().get_message(); +} + +// An expectation on a value that is negated before any matcher sees it. +template +ExpectationValue negated(T value) { + ExpectationValue expectation(value, std::source_location::current()); + expectation.not_(); + return expectation; +} + +// An expectation whose target throws when it is read, as a block that throws does. +class Throwing : public Expectation { + public: + Throwing() : Expectation(std::source_location::current()) {} + int& get_target() & override { throw std::runtime_error("boom"); } + Throwing& not_() override { + is_positive_ = !is_positive_; + return *this; + } + Throwing& ignore() override { + ignore_ = true; + return *this; + } +}; + +// A matcher as a user writes one: its own failure messages, and no word about a custom one. +class IsEven : public Matchers::MatcherBase { + public: + explicit IsEven(Expectation& expectation) : MatcherBase(expectation, 0) {} + std::string verb() override { return "be even"; } + std::string failure_message() override { return std::format("expected {} to be even", actual()); } + std::string failure_message_when_negated() override { return std::format("expected {} to be odd", actual()); } + bool match() override { return actual() % 2 == 0; } +}; + +// A matcher that forgets to say anything when it fails. +class Silent : public Matchers::MatcherBase { + public: + explicit Silent(Expectation& expectation) : MatcherBase(expectation, 0) {} + std::string failure_message() override { return ""; } + bool match() override { return false; } +}; + +const std::string empty_message_diagnostic = + "Failure message is empty. Does your matcher define the appropriate failure_message[_when_negated] method to " + "return a string?"; + +} // namespace + +// clang-format off +describe custom_message_spec("A matcher's custom failure message", $ { + context("on Equal", _ { + it("leads the own message, which still prints both values", _ { + auto ex = ExpectationValue(1, std::source_location::current()); + const std::string own = report(Matchers::Equal(ex, 2)); + expect(own).to_start_with(std::string("expected (int) => 2")); + expect(report(Matchers::Equal(ex, 2), "which button")).to_equal("which button\n" + own); + }); + + it("leads the negated message", _ { + auto ex = negated(1); + const std::string own = report(Matchers::Equal(ex, 1)); + expect(report(Matchers::Equal(ex, 1), "which button")).to_equal("which button\n" + own); + }); + }); + + context("on Satisfy", _ { + it("leads the own message", _ { + const auto above_five = [](int x) { return x > 5; }; + auto ex = ExpectationValue(3, std::source_location::current()); + const std::string own = report(Matchers::Satisfy(ex, above_five)); + expect(report(Matchers::Satisfy(ex, above_five), "the count")).to_equal("the count\n" + own); + }); + + it("leads the negated message", _ { + const auto above_five = [](int x) { return x > 5; }; + auto ex = negated(7); + const std::string own = report(Matchers::Satisfy(ex, above_five)); + expect(report(Matchers::Satisfy(ex, above_five), "the count")).to_equal("the count\n" + own); + }); + }); + + context("on BeWithin", _ { + it("leads the own message", _ { + auto ex = ExpectationValue(4.0, std::source_location::current()); + const std::string own = report(Matchers::BeWithin(ex, 0.5, 5.0, "")); + expect(report(Matchers::BeWithin(ex, 0.5, 5.0, ""), "the gain")).to_equal("the gain\n" + own); + }); + + it("leads the negated message", _ { + auto ex = negated(4.0); + const std::string own = report(Matchers::BeWithin(ex, 0.5, 4.2, "")); + expect(report(Matchers::BeWithin(ex, 0.5, 4.2, ""), "the gain")).to_equal("the gain\n" + own); + }); + + it("leads the own message when given to to_be_within(tolerance, message)", _ { + auto ex = ExpectationValue(4.0, std::source_location::current()); + const std::string own = report(Matchers::BeWithin(ex, 0.5, 5.0, "")); + Matchers::BeWithinHelper helper(ex, 0.5); + helper.set_message("the gain"); + expect(helper.of(5.0).full_failure_message()).to_equal("the gain\n" + own); + }); + }); + + context("on Throw", _ { + it("leads the own message", _ { + using NoThrow = Matchers::Throw, std::exception>; + auto ex = ExpectationValue(std::function([] { return 42; }), std::source_location::current()); + const std::string own = report(NoThrow(ex)); + expect(report(NoThrow(ex), "the load")).to_equal("the load\n" + own); + }); + + it("leads the negated message", _ { + Throwing ex; + ex.not_(); + const std::string own = report(Matchers::Throw(ex)); + expect(report(Matchers::Throw(ex), "the load")).to_equal("the load\n" + own); + }); + }); + + context("on Contain, which builds on the base's message", _ { + it("leads the own message once", _ { + using ContainInt = Matchers::Contain, int, int>; + auto ex = ExpectationValue(std::vector{1, 2, 3}, std::source_location::current()); + const std::string own = report(ContainInt(ex, 4)); + expect(report(ContainInt(ex, 4), "the pads")).to_equal("the pads\n" + own); + }); + + it("leads the negated message once", _ { + using ContainInt = Matchers::Contain, int, int>; + auto ex = negated(std::vector{1, 2, 3}); + const std::string own = report(ContainInt(ex, 2)); + expect(report(ContainInt(ex, 2), "the pads")).to_equal("the pads\n" + own); + }); + }); + + context("on a matcher that keeps the base's messages", _ { + it("leads the own message, which still prints its values", _ { + auto ex = ExpectationValue(3, std::source_location::current()); + const std::string own = report(Matchers::BeLessThan(ex, 2)); + expect(report(Matchers::BeLessThan(ex, 2), "the level")).to_equal("the level\n" + own); + }); + + it("leads the negated message, which still prints its values", _ { + auto ex = negated(1); + const std::string own = report(Matchers::BeLessThan(ex, 2)); + expect(own).to_equal(std::string("expected 1 to not be less than 2")); + expect(report(Matchers::BeLessThan(ex, 2), "the level")).to_equal("the level\n" + own); + }); + }); + + context("on a matcher that defines its own failure messages", _ { + it("leads the own message", _ { + auto ex = ExpectationValue(3, std::source_location::current()); + expect(report(IsEven(ex), "the step")).to_equal(std::string("the step\nexpected 3 to be even")); + }); + + it("leads the negated message", _ { + auto ex = negated(4); + expect(report(IsEven(ex), "the step")).to_equal(std::string("the step\nexpected 4 to be odd")); + }); + }); + + context("on a matcher whose own message is empty", _ { + it("is replaced by the empty-message diagnostic", _ { + auto ex = ExpectationValue(3, std::source_location::current()); + expect(report(Silent(ex))).to_equal(empty_message_diagnostic); + }); + + it("leaves the empty-message diagnostic below it, with no blank line", _ { + auto ex = ExpectationValue(3, std::source_location::current()); + expect(report(Silent(ex), "the step")).to_equal("the step\n" + empty_message_diagnostic); + }); + }); +}); + +CPPSPEC_MAIN(custom_message_spec); From 8a10f2994debfae6570bc66ab538eb57c8694276 Mon Sep 17 00:00:00 2001 From: Katherine Whitlock Date: Sat, 14 Nov 2026 11:23:06 -0500 Subject: [PATCH 03/20] feat(pretty): print enums, byte-sized integers and optionals by value MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Failure messages printed these values unreadably: - an enum with no operator<< printed as an object address, `#`, and one based on a character type as a character; - std::int8_t and std::uint8_t streamed as characters, so 65 printed as `A`, and a byte with no printable character printed nothing or a raw byte; - an optional printed as its type and address. Now an enum with no operator<< prints its type and underlying value as a number, `Colour(2)`, widened by its signedness first so a negative, 64-bit or char-based enum prints its number too (`Letter(65)`, `Big(-5000000000)`); an enum with an operator<< still uses it. A byte-sized integer prints as a number (`65`, `-3`), while a plain char still prints as a character. An optional prints its value, or `std::nullopt` when it holds none. --- include/matchers/pretty_matchers.hpp | 51 +++++++++++++++++++++++++++- spec/matchers/pretty_spec.cpp | 45 ++++++++++++++++++++++++ 2 files changed, 95 insertions(+), 1 deletion(-) create mode 100644 spec/matchers/pretty_spec.cpp diff --git a/include/matchers/pretty_matchers.hpp b/include/matchers/pretty_matchers.hpp index 22bb2e0..44a5ce4 100755 --- a/include/matchers/pretty_matchers.hpp +++ b/include/matchers/pretty_matchers.hpp @@ -2,9 +2,11 @@ #pragma once #include +#include #include #include #include +#include #include #include @@ -16,7 +18,7 @@ // container and tries to element-print its value_type — which hard-errors for // element types lacking operator<< (and is wrong regardless: an optional is not // a container). Exclude it from prettyprint's container detection so optionals -// fall back to the generic (non-streamable) to_word path. +// reach Pretty's own optional to_word overload. namespace pretty_print { template struct is_container> : std::false_type {}; @@ -51,6 +53,13 @@ struct Pretty { template static std::string to_word(const T& item); + template + requires std::is_enum_v && (!Util::is_streamable) + static std::string to_word(const T& item); + + template + static std::string to_word(const std::optional& item); + template static std::string to_word_type(const T& item); @@ -142,6 +151,17 @@ inline std::string Pretty::to_word(const bool& item) { return item ? "true" : "false"; } +// A byte-sized integer streams as a character; it is printed as the number it holds. +template <> +inline std::string Pretty::to_word(const unsigned char& item) { + return std::to_string(item); +} + +template <> +inline std::string Pretty::to_word(const signed char& item) { + return std::to_string(item); +} + template <> inline std::string Pretty::to_word(const std::true_type& /* item */) { return "true"; @@ -167,6 +187,35 @@ inline std::string Pretty::to_word(const T& item) { return ss.str(); } +/** + * @brief Formats an enum that has no operator<< as its type and underlying value as a number, e.g. `Colour(2)` + * + * The value is widened to the largest integer of its signedness first, so an enum based on a character type prints + * a number too, not a character. + * + * @param item the enumerator to be processed + * + * @return the string representation + */ +template + requires std::is_enum_v && (!Util::is_streamable) +inline std::string Pretty::to_word(const T& item) { + using Widest = std::conditional_t>, long long, unsigned long long>; + return std::format("{}({})", Util::demangle(typeid(T).name()), static_cast(std::to_underlying(item))); +} + +/** + * @brief Formats an optional as its value, or `std::nullopt` when it holds none + * + * @param item the optional to be processed + * + * @return the string representation + */ +template +inline std::string Pretty::to_word(const std::optional& item) { + return item.has_value() ? to_word(*item) : std::string("std::nullopt"); +} + /** * Formats a Matcher as a string * diff --git a/spec/matchers/pretty_spec.cpp b/spec/matchers/pretty_spec.cpp new file mode 100644 index 0000000..15dc5a9 --- /dev/null +++ b/spec/matchers/pretty_spec.cpp @@ -0,0 +1,45 @@ +#include +#include +#include +#include + +#include "cppspec.hpp" + +using namespace CppSpec; + +enum class Colour : std::uint8_t { Red = 2, Blue = 3 }; +enum class Letter : char { A = 'A' }; + +// clang-format off +describe pretty_spec("Pretty::to_word", $ { + it("prints a scoped enum with no operator<< as its type and value", _ { + expect(Pretty::to_word(Colour::Red)).to_equal(std::string("Colour(2)")); + }); + + it("prints a char-based enum with no operator<< as its type and number", _ { + expect(Pretty::to_word(Letter::A)).to_equal(std::string("Letter(65)")); + }); + + it("prints a byte-sized integer as a number, not a character", _ { + expect(Pretty::to_word(std::uint8_t{65})).to_equal(std::string("65")); + expect(Pretty::to_word(std::int8_t{-3})).to_equal(std::string("-3")); + }); + + it("still prints a char as a character", _ { + expect(Pretty::to_word('A')).to_equal(std::string("A")); + }); + + it("prints an empty optional as std::nullopt and a full one as its value", _ { + expect(Pretty::to_word(std::optional{})).to_equal(std::string("std::nullopt")); + expect(Pretty::to_word(std::optional{5})).to_equal(std::string("5")); + expect(Pretty::to_word(std::optional{Colour::Blue})).to_equal(std::string("Colour(3)")); + }); + + it("prints both enum values when Equal fails", _ { + auto ex = ExpectationValue(Colour::Red, std::source_location::current()); + expect(Matchers::Equal(ex, Colour::Blue).run().get_message()) + .to_equal(std::string("expected (Colour) => Colour(3)\n got (Colour) => Colour(2)\nCompared using `==`")); + }); +}); + +CPPSPEC_MAIN(pretty_spec); From 0579c65d8951a89916c2e4b1d07893ec7141bf82 Mon Sep 17 00:00:00 2001 From: Katherine Whitlock Date: Sat, 14 Nov 2026 11:25:23 -0500 Subject: [PATCH 04/20] fix(formatters): the verbose formatter prints a failed expectation's file and line beside its message The verbose formatter printed a failure's message with nothing to say where the failing expectation was. Each failure message now starts with its file and line, `file:line: `, so an editor or terminal can jump to it: spec/gain_spec.cpp:12: expected (int) => 2 got (int) => 1 A passing example prints as before. --- include/formatters/verbose.hpp | 4 +++- spec/formatters/verbose_spec.cpp | 41 ++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 spec/formatters/verbose_spec.cpp diff --git a/include/formatters/verbose.hpp b/include/formatters/verbose.hpp index b31d9cc..dcf87a7 100644 --- a/include/formatters/verbose.hpp +++ b/include/formatters/verbose.hpp @@ -41,7 +41,9 @@ inline void Verbose::format(const ItBase& it) { for (const Result& result : it.get_results()) { if (result.is_failure()) { out_stream << set_color(RED); - out_stream << result.get_message() << std::endl; + // file:line: leads the message, so an editor or terminal can jump to the failing expectation. + out_stream << result.get_location().file_name() << ':' << result.get_location().line() << ": " + << result.get_message() << std::endl; out_stream << reset_color(); } } diff --git a/spec/formatters/verbose_spec.cpp b/spec/formatters/verbose_spec.cpp new file mode 100644 index 0000000..6b4e2c9 --- /dev/null +++ b/spec/formatters/verbose_spec.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +#include + +#include "cppspec.hpp" +#include "formatters/verbose.hpp" + +using namespace CppSpec; + +namespace { +std::string format_verbose(const ItBase& example) { + std::ostringstream out; + Formatters::Verbose formatter(out); + formatter.set_color_output(false); + formatter.format(example); + return out.str(); +} +} // namespace + +// clang-format off +describe verbose_spec("Formatters::Verbose", $ { + it("prints a failed expectation's file and line beside its message", _ { + auto location = std::source_location::current(); + ItD example(location, "fails", [](ItD&) {}); + example.add_result(Result::failure_with(location, "expected 1\n got 2")); + + expect(format_verbose(example)) + .to_equal(std::format("fails\n{}:{}: expected 1\n got 2\n", location.file_name(), location.line())); + }); + + it("prints only the description of a passing example", _ { + auto location = std::source_location::current(); + ItD example(location, "passes", [](ItD&) {}); + example.add_result(Result::success(location)); + + expect(format_verbose(example)).to_equal(std::string("passes\n")); + }); +}); + +CPPSPEC_MAIN(verbose_spec); From a34cffd8bbcbb56bf64a7fbf412c02a0263f0564 Mon Sep 17 00:00:00 2001 From: Katherine Whitlock Date: Sat, 14 Nov 2026 11:40:08 -0500 Subject: [PATCH 05/20] feat(matchers)!: expect() keeps a C string as its pointer and the string matchers compare it as text expect(const char*) built a std::string, so to_be_null() did not compile on a C string, and a null one threw from inside expect(), outside any matcher, which aborted the whole run. A C string (a char pointer, const or not, or a char array, which decays to one) is now kept as the pointer it is: to_be_null() and not_().to_be_null() work on it. A pointer to volatile char is not a C string: it is printed and compared as a plain pointer, as before. Text is compared and printed through one projection, CppSpec::string_view_of(), which views a std::string, std::string_view, char array or char pointer, and gives std::nullopt for a null C string. Equal (when both sides are text, so two C strings compare by text and not by address), to_start_with, to_end_with, to_match, to_partially_match and to_contain read text through it, and so does Pretty. to_start_with and to_end_with also take any text as the actual value now, not only a std::string. A null C string is a value of its own: - it equals another null C string and differs from every piece of text, so expect(null).to_equal(null) and expect(null).not_().to_equal("abc") pass, and expect(null).to_equal("abc") fails printing nullptr against "abc", with a comparison line saying a null C string equals only another null C string; - to_start_with, to_end_with, to_match, to_partially_match and to_contain fail on it in both polarities, as one failed expectation, and the run continues; the message says, below the "expected nullptr to ..." line, "nullptr is not text, so there is nothing to search"; - it prints as nullptr. The c_string spec pins each of these cases. BREAKING CHANGE: expect(const char*) no longer yields ExpectationValue; it yields ExpectationValue for a string literal or a const char pointer or array, and ExpectationValue for a non-const one. Code that named the std::string type, or called std::string members on the target, needs to build the std::string itself. Two char pointers given to to_equal are compared by their text, not by their addresses. --- include/expectations/expectation.hpp | 4 +- include/it.hpp | 4 - include/it_base.hpp | 12 +- include/matchers/contain.hpp | 46 ++++- include/matchers/equal.hpp | 26 ++- include/matchers/matcher_base.hpp | 17 ++ include/matchers/pretty_matchers.hpp | 36 ++-- include/matchers/strings/end_with.hpp | 35 +++- include/matchers/strings/match.hpp | 31 +++- include/matchers/strings/start_with.hpp | 35 +++- include/util.hpp | 53 ++++++ spec/matchers/c_string_spec.cpp | 229 ++++++++++++++++++++++++ 12 files changed, 477 insertions(+), 51 deletions(-) create mode 100644 spec/matchers/c_string_spec.cpp diff --git a/include/expectations/expectation.hpp b/include/expectations/expectation.hpp index 6985d56..41d8ca4 100755 --- a/include/expectations/expectation.hpp +++ b/include/expectations/expectation.hpp @@ -366,7 +366,7 @@ void Expectation::to_satisfy(F test, std::string msg) { template void Expectation::to_start_with(std::string start, std::string msg) { - Matchers::StartWith(*this, start).set_message(std::move(msg)).run(); + Matchers::StartWith(*this, start).set_message(std::move(msg)).run(); } template @@ -377,7 +377,7 @@ void Expectation::to_start_with(std::initializer_list start_sequence, std: template void Expectation::to_end_with(std::string ending, std::string msg) { - Matchers::EndWith(*this, ending).set_message(std::move(msg)).run(); + Matchers::EndWith(*this, ending).set_message(std::move(msg)).run(); } template diff --git a/include/it.hpp b/include/it.hpp index d76fe15..120f461 100755 --- a/include/it.hpp +++ b/include/it.hpp @@ -153,8 +153,4 @@ ExpectationValue> ItBase::expect(std::initializer_list< return {*this, init_list, location}; } -inline ExpectationValue ItBase::expect(const char* str, std::source_location location) { - return {*this, std::string(str), location}; -} - } // namespace CppSpec diff --git a/include/it_base.hpp b/include/it_base.hpp index 4041476..55fc3e8 100755 --- a/include/it_base.hpp +++ b/include/it_base.hpp @@ -75,6 +75,9 @@ class ItBase : public Runnable { /** * @brief The `expect` object generator for objects and LiteralTypes * + * A C string (a char pointer, or a char array, which decays to one) is kept as the pointer it is, so to_be_null() + * works on it; the string matchers compare it as text. + * * @param value the item to wrap. This parameter is passed by value so * that statements like `expect(2)` or `expect(SomeClass())` * can be passed in @@ -123,15 +126,6 @@ class ItBase : public Runnable { template ExpectationValue expect(Let& let, std::source_location location = std::source_location::current()); - /** - * @brief The `expect` object generator for const char* - * - * @param string the string to wrap - * @return a ExpectationValue object containing a C++ string - */ - ExpectationValue expect(const char* string, - std::source_location location = std::source_location::current()); - void add_result(const Result& result) { results.push_back(result); } std::list& get_results() noexcept { return results; } [[nodiscard]] const std::list& get_results() const noexcept { return results; } diff --git a/include/matchers/contain.hpp b/include/matchers/contain.hpp index 4424699..6f43855 100644 --- a/include/matchers/contain.hpp +++ b/include/matchers/contain.hpp @@ -26,6 +26,10 @@ class ContainBase : public MatcherBase { protected: bool actual_collection_includes(U expected_item); + bool actual_is_null_text(); + + private: + bool collection_includes(U expected_item); }; template @@ -36,16 +40,44 @@ std::string ContainBase::description() { template std::string ContainBase::failure_message() { - return Pretty::improve_hash_formatting(MatcherBase::failure_message()); + return Pretty::improve_hash_formatting(MatcherBase::failure_message()) + no_text_to_search(this->actual()); } template std::string ContainBase::failure_message_when_negated() { - return Pretty::improve_hash_formatting(MatcherBase::failure_message_when_negated()); + return Pretty::improve_hash_formatting(MatcherBase::failure_message_when_negated()) + + no_text_to_search(this->actual()); } +// Text contains a piece of text or a character, both read through string_view_of(); any other collection contains +// an element. template bool ContainBase::actual_collection_includes(U expected_item) { + if constexpr (Util::is_string_like) { + const auto text = string_view_of(this->actual()); + if constexpr (Util::is_string_like) { + const auto part = string_view_of(expected_item); + return text && part && text->contains(*part); + } else { + return text && text->contains(expected_item); + } + } else { + return collection_includes(expected_item); + } +} + +// A null C string is no text, so it contains nothing, negated or not. +template +bool ContainBase::actual_is_null_text() { + if constexpr (Util::is_string_like) { + return !string_view_of(this->actual()); + } else { + return false; + } +} + +template +bool ContainBase::collection_includes(U expected_item) { auto actual = this->actual(); auto last = *(actual.begin()); static_assert(Util::verbose_assert>::value, @@ -72,12 +104,12 @@ class Contain : public ContainBase { template bool Contain::match() { - return perform_match(Predicate::all, Predicate::all); + return !this->actual_is_null_text() && perform_match(Predicate::all, Predicate::all); } template bool Contain::negated_match() { - return perform_match(Predicate::none, Predicate::any); + return !this->actual_is_null_text() && perform_match(Predicate::none, Predicate::any); } // TODO: support std::map @@ -122,6 +154,7 @@ class Contain : public ContainBase { Contain(Expectation& expectation, U expected) : ContainBase(expectation, expected) {}; bool match() override; + bool negated_match() override; }; template @@ -129,4 +162,9 @@ bool Contain::match() { return this->actual_collection_includes(this->expected()); } +template +bool Contain::negated_match() { + return !this->actual_is_null_text() && !match(); +} + } // namespace CppSpec::Matchers diff --git a/include/matchers/equal.hpp b/include/matchers/equal.hpp index c7fc82d..9eb35a7 100644 --- a/include/matchers/equal.hpp +++ b/include/matchers/equal.hpp @@ -18,6 +18,10 @@ class Equal : public MatcherBase { public: Equal(Expectation& expectation, E expected) : MatcherBase(expectation, expected) {} + // Two pieces of text are compared as strings, whatever form each is in, so two C strings are compared by their + // text and not by their addresses. + static constexpr bool compares_text = Util::is_string_like && Util::is_string_like; + std::string verb() override { return "equal"; } std::string failure_message() override; std::string failure_message_when_negated() override; @@ -26,6 +30,7 @@ class Equal : public MatcherBase { protected: bool match() override; bool expected_is_a_literal(); + std::string comparison(); std::string actual_inspected(); std::string simple_failure_message(); // std::string detailed_failure_message(); @@ -46,7 +51,7 @@ std::string Equal::failure_message_when_negated() { std::stringstream ss; ss << "expected not " << Pretty::inspect_object(MatcherBase::expected()) << std::endl; ss << " got " << actual_inspected() << std::endl; - ss << "Compared using `==`"; + ss << comparison(); return ss.str(); } @@ -55,7 +60,7 @@ std::string Equal::simple_failure_message() { std::stringstream ss; ss << "expected " << Pretty::inspect_object(MatcherBase::expected()) << std::endl; ss << " got " << actual_inspected() << std::endl; - ss << "Compared using `==`"; + ss << comparison(); return ss.str(); } @@ -64,9 +69,24 @@ bool Equal::diffable() { return !expected_is_a_literal(); } +// A null C string is a value of its own: it equals another null C string and differs from every piece of text. template bool Equal::match() { - return this->expected() == this->actual(); + if constexpr (compares_text) { + return string_view_of(this->actual()) == string_view_of(this->expected()); + } else { + return this->expected() == this->actual(); + } +} + +template +std::string Equal::comparison() { + if constexpr (compares_text) { + if (!string_view_of(this->actual()) || !string_view_of(this->expected())) { + return "A null C string equals only another null C string"; + } + } + return "Compared using `==`"; } template diff --git a/include/matchers/matcher_base.hpp b/include/matchers/matcher_base.hpp index fc16935..d77a425 100644 --- a/include/matchers/matcher_base.hpp +++ b/include/matchers/matcher_base.hpp @@ -24,6 +24,23 @@ class Expectation; // Forward declaration of Expectation namespace Matchers { +/** + * @brief The line a matcher that searches text puts below its own message when the actual value is a null C string, + * which has no text to search, so the matcher fails it negated as well as positive + * + * @param actual the actual value + * @return the line, led by a newline, or an empty string when the actual value is text + */ +template +[[nodiscard]] std::string no_text_to_search(const A& actual) { + if constexpr (Util::is_string_like) { + if (!string_view_of(actual)) { + return "\nnullptr is not text, so there is nothing to search"; + } + } + return {}; +} + /** * @brief the base class for all Matcher classes and objects * diff --git a/include/matchers/pretty_matchers.hpp b/include/matchers/pretty_matchers.hpp index 44a5ce4..c8ab106 100755 --- a/include/matchers/pretty_matchers.hpp +++ b/include/matchers/pretty_matchers.hpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -141,9 +142,15 @@ inline std::string Pretty::to_sentence(const T& item) { */ template inline std::string Pretty::to_word(const T& item) { - std::ostringstream oss; - oss << item; // use operator<< to convert and append - return oss.str(); + if constexpr (Util::is_c_string) { + // A C string is printed through its view, so a null one prints as nullptr instead of being read. + const auto text = string_view_of(item); + return text ? std::string(*text) : std::string("nullptr"); + } else { + std::ostringstream oss; + oss << item; // use operator<< to convert and append + return oss.str(); + } } template <> @@ -293,19 +300,16 @@ inline std::string Pretty::improve_hash_formatting(const std::string& inspect_st */ template inline std::string Pretty::inspect_object(const O& o) { - return std::format("({}) => {}", Util::demangle(typeid(o).name()), to_word(o)); -} - -/** - * @brief Specialization for C-style strings - * - * @param o the input string - * - * @return the generated string - */ -template <> -inline std::string Pretty::inspect_object(const char* const& o) { - return std::format("(const char *) => \"{}\"", o); + if constexpr (Util::is_c_string) { + // A C string is named by its type and printed quoted, or as nullptr when it is null. + constexpr std::string_view constness = std::is_const_v>> ? "const " : ""; + const std::string type = std::is_array_v ? std::format("{}char [{}]", constness, std::extent_v) + : std::format("{}char *", constness); + const auto text = string_view_of(o); + return text ? std::format("({}) => \"{}\"", type, *text) : std::format("({}) => nullptr", type); + } else { + return std::format("({}) => {}", Util::demangle(typeid(o).name()), to_word(o)); + } } /** diff --git a/include/matchers/strings/end_with.hpp b/include/matchers/strings/end_with.hpp index 6bf094d..ad2724c 100644 --- a/include/matchers/strings/end_with.hpp +++ b/include/matchers/strings/end_with.hpp @@ -8,17 +8,44 @@ namespace CppSpec::Matchers { -template +// Text is compared through string_view_of(), whatever form it is in; any other pair of ranges element by element. +template + requires(Util::is_string_like && Util::is_string_like) || (std::ranges::range && std::ranges::range) class EndWith : public MatcherBase { + static constexpr bool compares_text = Util::is_string_like && Util::is_string_like; + public: EndWith(Expectation& expectation, E start) : MatcherBase(expectation, start) {} std::string verb() override { return "end with"; } + std::string failure_message() override { + return MatcherBase::failure_message() + no_text_to_search(this->actual()); + } + std::string failure_message_when_negated() override { + return MatcherBase::failure_message_when_negated() + no_text_to_search(this->actual()); + } bool match() override { - A& actual = this->actual(); - E& expected = this->expected(); - return std::equal(std::ranges::rbegin(expected), std::ranges::rend(expected), std::ranges::rbegin(actual)); + if constexpr (compares_text) { + const auto actual = string_view_of(this->actual()); + const auto expected = string_view_of(this->expected()); + return actual && expected && actual->ends_with(*expected); + } else { + A& actual = this->actual(); + E& expected = this->expected(); + return std::equal(std::ranges::rbegin(expected), std::ranges::rend(expected), std::ranges::rbegin(actual)); + } + } + + // A null C string is no text, so it fails negated as well as positive. + bool negated_match() override { + if constexpr (compares_text) { + const auto actual = string_view_of(this->actual()); + const auto expected = string_view_of(this->expected()); + return actual && expected && !actual->ends_with(*expected); + } else { + return !match(); + } } }; diff --git a/include/matchers/strings/match.hpp b/include/matchers/strings/match.hpp index 58b780f..189f454 100644 --- a/include/matchers/strings/match.hpp +++ b/include/matchers/strings/match.hpp @@ -13,7 +13,9 @@ inline std::string describe_pattern(const std::string& pattern) { return pattern.empty() ? std::string{"a regex"} : "\"" + pattern + "\""; } -template +// The actual text is read through string_view_of(); a null C string is no text, so it fails negated as well as +// positive. +template class Match : public MatcherBase { std::string pattern_; @@ -26,14 +28,22 @@ class Match : public MatcherBase { std::string verb() override { return "match"; } std::string description() override { return verb() + " " + describe_pattern(pattern_); } + std::string failure_message() override { + return MatcherBase::failure_message() + no_text_to_search(this->actual()); + } + std::string failure_message_when_negated() override { + return MatcherBase::failure_message_when_negated() + no_text_to_search(this->actual()); + } bool match() override { - std::smatch temp_match; - return std::regex_match(this->actual(), temp_match, this->expected()); + const auto actual = string_view_of(this->actual()); + return actual && std::regex_match(actual->begin(), actual->end(), this->expected()); } + + bool negated_match() override { return string_view_of(this->actual()) && !match(); } }; -template +template class MatchPartial : public MatcherBase { std::string pattern_; @@ -45,9 +55,20 @@ class MatchPartial : public MatcherBase { : MatcherBase(expectation, expected) {} std::string description() override { return "partially match " + describe_pattern(pattern_); } + std::string failure_message() override { + return MatcherBase::failure_message() + no_text_to_search(this->actual()); + } + std::string failure_message_when_negated() override { + return MatcherBase::failure_message_when_negated() + no_text_to_search(this->actual()); + } // A partial match is a match anywhere in the string: a search, not a match of the whole. - bool match() override { return std::regex_search(this->actual(), this->expected()); } + bool match() override { + const auto actual = string_view_of(this->actual()); + return actual && std::regex_search(actual->begin(), actual->end(), this->expected()); + } + + bool negated_match() override { return string_view_of(this->actual()) && !match(); } }; } // namespace CppSpec::Matchers diff --git a/include/matchers/strings/start_with.hpp b/include/matchers/strings/start_with.hpp index 51d8fe2..551a536 100644 --- a/include/matchers/strings/start_with.hpp +++ b/include/matchers/strings/start_with.hpp @@ -8,17 +8,44 @@ namespace CppSpec::Matchers { -template +// Text is compared through string_view_of(), whatever form it is in; any other pair of ranges element by element. +template + requires(Util::is_string_like && Util::is_string_like) || (std::ranges::range && std::ranges::range) class StartWith : public MatcherBase { + static constexpr bool compares_text = Util::is_string_like && Util::is_string_like; + public: StartWith(Expectation& expectation, E start) : MatcherBase(expectation, start) {} std::string verb() override { return "start with"; } + std::string failure_message() override { + return MatcherBase::failure_message() + no_text_to_search(this->actual()); + } + std::string failure_message_when_negated() override { + return MatcherBase::failure_message_when_negated() + no_text_to_search(this->actual()); + } bool match() override { - A& actual = this->actual(); - E& expected = this->expected(); - return std::equal(expected.begin(), expected.end(), actual.begin()); + if constexpr (compares_text) { + const auto actual = string_view_of(this->actual()); + const auto expected = string_view_of(this->expected()); + return actual && expected && actual->starts_with(*expected); + } else { + A& actual = this->actual(); + E& expected = this->expected(); + return std::equal(expected.begin(), expected.end(), actual.begin()); + } + } + + // A null C string is no text, so it fails negated as well as positive. + bool negated_match() override { + if constexpr (compares_text) { + const auto actual = string_view_of(this->actual()); + const auto expected = string_view_of(this->expected()); + return actual && expected && !actual->starts_with(*expected); + } else { + return !match(); + } } }; diff --git a/include/util.hpp b/include/util.hpp index 287c5ba..3a23e18 100755 --- a/include/util.hpp +++ b/include/util.hpp @@ -3,10 +3,14 @@ * @brief Utility functions and classes */ #pragma once +#include +#include #include +#include #include #include #include +#include #include #ifdef __GNUG__ @@ -102,6 +106,26 @@ concept is_functional = template concept is_not_functional = !is_functional; +/** + * @brief Checks whether T is a C string: a pointer to char, const or not, or a char array, which decays to one. + * + * A pointer to volatile char is not a C string: it is printed and compared as a plain pointer. + * + * @tparam T a type to check + */ +template +concept is_c_string = std::is_pointer_v> && + std::same_as>>, char>; + +/** + * @brief Checks whether T is text that CppSpec::string_view_of() can view: a C string, or a type that converts to + * std::string_view, such as std::string and std::string_view. + * + * @tparam T a type to check + */ +template +concept is_string_like = is_c_string || std::convertible_to&, std::string_view>; + template concept not_c_string = !std::is_same_v && !std::is_same_v && !std::is_convertible_v && !std::is_convertible_v; @@ -143,3 +167,32 @@ concept not_c_string = !std::is_same_v && !std::is_same_v +[[nodiscard]] constexpr std::optional string_view_of(const T& text) { + if constexpr (std::is_array_v) { + return std::string_view(std::ranges::begin(text), std::ranges::find(text, '\0')); + } else if constexpr (Util::is_c_string) { + if (text == nullptr) { + return std::nullopt; + } + return std::string_view(text); + } else { + return std::string_view(text); + } +} + +} // namespace CppSpec diff --git a/spec/matchers/c_string_spec.cpp b/spec/matchers/c_string_spec.cpp new file mode 100644 index 0000000..a32eaf8 --- /dev/null +++ b/spec/matchers/c_string_spec.cpp @@ -0,0 +1,229 @@ +#include +#include +#include +#include + +#include "cppspec.hpp" + +using namespace CppSpec; + +namespace { + +const char* const null_text = nullptr; + +// The line a search matcher adds below its message when the actual value is a null C string. +const std::string null_text_note = "\nnullptr is not text, so there is nothing to search"; + +// The Result a matcher reports, outside any example. +template +Result outcome(Matcher matcher) { + return matcher.run(); +} + +// An expectation on a value that is negated before any matcher sees it. +template +ExpectationValue negated(T value) { + ExpectationValue expectation(value, std::source_location::current()); + expectation.not_(); + return expectation; +} + +} // namespace + +// clang-format off +describe c_string_spec("expect on a C string", $ { + context("as a pointer", _ { + it("passes to_be_null on a null C string", _ { + const char* s = nullptr; + expect(s).to_be_null(); + }); + + it("passes not_().to_be_null on a non-null C string", _ { + const char* s = "abc"; + expect(s).not_().to_be_null(); + }); + + it("keeps a volatile char pointer as a plain pointer", _ { + static_assert(!Util::is_c_string); + static_assert(!Util::is_c_string); + volatile char* none = nullptr; + volatile char c = 'a'; + volatile char* some = &c; + expect(none).to_be_null(); + expect(some).not_().to_be_null(); + }); + }); + + context("compared as a string", _ { + it("equals a std::string with the same text", _ { + std::string owner("abc"); + const char* s = owner.c_str(); + expect(s).to_equal(std::string("abc")); + expect(s).not_().to_equal(std::string("abd")); + expect(std::string("abc")).to_equal(s); + }); + + it("equals another C string with the same text at another address", _ { + std::string owner("abc"); + const char* s = owner.c_str(); + expect(s).to_equal("abc"); + expect(s).not_().to_equal("abd"); + }); + + it("compares a char array and a char pointer as strings", _ { + char text[] = "abc"; + char* s = text; + expect(text).to_equal("abc"); + expect(std::string("abc")).to_equal(s); + }); + + it("starts and ends with text", _ { + std::string owner("abc"); + const char* s = owner.c_str(); + expect(s).to_start_with("ab"); + expect(s).not_().to_start_with("bc"); + expect(s).to_end_with("bc"); + expect(s).not_().to_end_with("ab"); + }); + + it("matches and partially matches a pattern", _ { + const char* s = "abc"; + expect(s).to_match("a.c"); + expect(s).not_().to_match("b"); + expect(s).to_partially_match("b"); + expect(s).not_().to_partially_match("x"); + }); + + it("contains text and characters", _ { + const char* s = "abc"; + expect(s).to_contain("bc"); + expect(s).not_().to_contain("ca"); + expect(s).to_contain('b'); + expect(s).not_().to_contain('x'); + }); + + it("lets a std::string and a std::string_view start, end with and contain text", _ { + expect(std::string_view("abc")).to_start_with("ab"); + expect(std::string_view("abc")).to_end_with("bc"); + expect(std::string("abc")).to_contain("bc"); + expect(std::string("abc")).to_contain(std::string("ab")); + }); + }); + + context("when null", _ { + it("equals another null C string", _ { + const char* other = nullptr; + expect(null_text).to_equal(other); + }); + + it("differs from every string", _ { + expect(null_text).not_().to_equal("abc"); + expect(null_text).not_().to_equal(""); + expect(null_text).not_().to_equal(std::string("abc")); + expect("abc").not_().to_equal(null_text); + expect(std::string("abc")).not_().to_equal(null_text); + }); + + it("fails Equal against a string, printing nullptr and the string", _ { + auto ex = ExpectationValue(null_text, std::source_location::current()); + Result r = outcome(Matchers::Equal(ex, "abc")); + expect(r).to_fail(); + expect(r.get_message()) + .to_partially_match("expected \\(const char \\*\\) => \"abc\"\n +got \\(const char \\*\\) => nullptr"); + }); + + it("fails Equal against a null expected C string", _ { + auto ex = ExpectationValue(std::string("abc"), std::source_location::current()); + expect(outcome(Matchers::Equal(ex, null_text))).to_fail(); + }); + + it("fails negated Equal against another null C string", _ { + auto nex = negated(null_text); + Result r = outcome(Matchers::Equal(nex, null_text)); + expect(r).to_fail(); + expect(r.get_message()).to_partially_match("expected not \\(const char \\*\\) => nullptr"); + }); + + it("fails start_with and end_with either way, saying nullptr has no text", _ { + auto ex = ExpectationValue(null_text, std::source_location::current()); + auto nex = negated(null_text); + for (const Result& r : {outcome(Matchers::StartWith(ex, "ab")), + outcome(Matchers::StartWith(nex, "ab")), + outcome(Matchers::EndWith(ex, "bc")), + outcome(Matchers::EndWith(nex, "bc"))}) { + expect(r).to_fail(); + expect(r.get_message()).to_partially_match("expected nullptr to"); + expect(r.get_message()).to_partially_match(null_text_note); + } + }); + + it("fails match and partially_match either way, saying nullptr has no text", _ { + auto ex = ExpectationValue(null_text, std::source_location::current()); + auto nex = negated(null_text); + for (const Result& r : {outcome(Matchers::Match(ex, std::string("a"))), + outcome(Matchers::Match(nex, std::string("a"))), + outcome(Matchers::MatchPartial(ex, std::string("a"))), + outcome(Matchers::MatchPartial(nex, std::string("a")))}) { + expect(r).to_fail(); + expect(r.get_message()).to_partially_match("expected nullptr to"); + expect(r.get_message()).to_partially_match(null_text_note); + } + }); + + it("fails contain either way, saying nullptr has no text", _ { + auto ex = ExpectationValue(null_text, std::source_location::current()); + auto nex = negated(null_text); + for (const Result& r : {outcome(Matchers::Contain(ex, "b")), + outcome(Matchers::Contain(nex, "b")), + outcome(Matchers::Contain(ex, 'b')), + outcome(Matchers::Contain(nex, 'b'))}) { + expect(r).to_fail(); + expect(r.get_message()).to_partially_match("expected nullptr to"); + expect(r.get_message()).to_partially_match(null_text_note); + } + }); + }); + + context("printed", _ { + it("prints a null C string as nullptr", _ { + expect(Pretty::to_word(null_text)).to_equal(std::string("nullptr")); + expect(Pretty::inspect_object(null_text)).to_equal(std::string("(const char *) => nullptr")); + }); + + it("prints a C string as its quoted text", _ { + char text[] = "abc"; + char* s = text; + expect(Pretty::to_word(s)).to_equal(std::string("abc")); + expect(Pretty::inspect_object(static_cast(s))).to_equal(std::string("(const char *) => \"abc\"")); + expect(Pretty::inspect_object(s)).to_equal(std::string("(char *) => \"abc\"")); + }); + }); + + context("string_view_of", _ { + it("views a std::string, a std::string_view, a char array and a char pointer", _ { + const std::string owned("abc"); + const std::string_view view("abc"); + char text[] = "abc"; + char* pointer = text; + const std::optional abc("abc"); + expect(string_view_of(owned)).to_equal(abc); + expect(string_view_of(view)).to_equal(abc); + expect(string_view_of(text)).to_equal(abc); + expect(string_view_of(pointer)).to_equal(abc); + expect(string_view_of(static_cast(pointer))).to_equal(abc); + }); + + it("views nothing for a null C string", _ { + expect(string_view_of(null_text)).to_equal(std::optional{}); + }); + + it("reads a char array up to its first NUL and no further than its end", _ { + const char padded[8] = "ab"; + const char unterminated[3] = {'a', 'b', 'c'}; + expect(string_view_of(padded)).to_equal(std::optional("ab")); + expect(string_view_of(unterminated)).to_equal(std::optional("abc")); + }); + }); +}); + +CPPSPEC_MAIN(c_string_spec); From 0ca47e557b69202276c0c7462ddb4c8db1a005b3 Mon Sep 17 00:00:00 2001 From: Katherine Whitlock Date: Sat, 14 Nov 2026 12:10:31 -0500 Subject: [PATCH 06/20] fix(matchers): to_start_with and to_end_with on a range never read past a shorter actual range For any range that is not text, to_start_with and to_end_with called std::equal with the expected range's bounds and only the actual range's start, so an actual range shorter than the expected prefix or suffix was read past its end (or, for to_end_with, before its start). Both matchers now compare the two ranges' sizes first, and a shorter actual range fails without being read. The string spec gains a bidirectional sequence that counts every read outside its bounds; a negated to_start_with or to_end_with on one shorter than the expected sequence, or empty, now reads nothing outside it. --- include/matchers/strings/end_with.hpp | 5 +- include/matchers/strings/start_with.hpp | 5 +- spec/matchers/string_spec.cpp | 84 +++++++++++++++++++++++++ 3 files changed, 92 insertions(+), 2 deletions(-) diff --git a/include/matchers/strings/end_with.hpp b/include/matchers/strings/end_with.hpp index ad2724c..0ef3f4c 100644 --- a/include/matchers/strings/end_with.hpp +++ b/include/matchers/strings/end_with.hpp @@ -33,7 +33,10 @@ class EndWith : public MatcherBase { } else { A& actual = this->actual(); E& expected = this->expected(); - return std::equal(std::ranges::rbegin(expected), std::ranges::rend(expected), std::ranges::rbegin(actual)); + // std::equal reads as many elements of the actual range as the expected one has, so a shorter actual range + // fails before it is read. + return std::ranges::distance(expected) <= std::ranges::distance(actual) && + std::equal(std::ranges::rbegin(expected), std::ranges::rend(expected), std::ranges::rbegin(actual)); } } diff --git a/include/matchers/strings/start_with.hpp b/include/matchers/strings/start_with.hpp index 551a536..a485892 100644 --- a/include/matchers/strings/start_with.hpp +++ b/include/matchers/strings/start_with.hpp @@ -33,7 +33,10 @@ class StartWith : public MatcherBase { } else { A& actual = this->actual(); E& expected = this->expected(); - return std::equal(expected.begin(), expected.end(), actual.begin()); + // std::equal reads as many elements of the actual range as the expected one has, so a shorter actual range + // fails before it is read. + return std::ranges::distance(expected) <= std::ranges::distance(actual) && + std::equal(expected.begin(), expected.end(), actual.begin()); } } diff --git a/spec/matchers/string_spec.cpp b/spec/matchers/string_spec.cpp index 6108a92..5a6a923 100644 --- a/spec/matchers/string_spec.cpp +++ b/spec/matchers/string_spec.cpp @@ -1,11 +1,81 @@ +#include +#include +#include #include #include +#include #include #include "cppspec.hpp" using namespace CppSpec; +namespace { + +// A sequence of ints that counts every read outside its bounds, so a spec can show that a matcher reads only the +// elements that are there. A read outside gives -1, which no spec expects. +class Bounded { + public: + class iterator { + public: + using iterator_category = std::bidirectional_iterator_tag; + using value_type = int; + using difference_type = std::ptrdiff_t; + using pointer = const int*; + using reference = const int&; + + iterator() = default; + iterator(const Bounded* owner, difference_type index) : owner_(owner), index_(index) {} + + reference operator*() const { + if (index_ < 0 || index_ >= std::ssize(owner_->items_)) { + ++*owner_->overreads_; + return outside; + } + return owner_->items_[index_]; + } + iterator& operator++() { + ++index_; + return *this; + } + iterator operator++(int) { + iterator before = *this; + ++index_; + return before; + } + iterator& operator--() { + --index_; + return *this; + } + iterator operator--(int) { + iterator before = *this; + --index_; + return before; + } + bool operator==(const iterator&) const = default; + + private: + static constexpr int outside = -1; + const Bounded* owner_ = nullptr; + difference_type index_ = 0; + }; + + Bounded(std::vector items, int* overreads) : items_(std::move(items)), overreads_(overreads) {} + + [[nodiscard]] iterator begin() const { return {this, 0}; } + [[nodiscard]] iterator end() const { return {this, std::ssize(items_)}; } + + friend std::ostream& operator<<(std::ostream& os, const Bounded& bounded) { + return os << "Bounded(" << bounded.items_.size() << " items)"; + } + + private: + std::vector items_; + int* overreads_; +}; + +} // namespace + // clang-format off describe string_spec("string matchers", $ { context("to_start_with (string)", _ { @@ -64,6 +134,13 @@ describe string_spec("string matchers", $ { it("passes for single-element prefix", _ { expect(std::vector{7, 8, 9}).to_start_with({7}); }); + + it("reads nothing past the end of a sequence shorter than the prefix", _ { + int overreads = 0; + expect(Bounded({1}, &overreads)).not_().to_start_with({1, 2}); + expect(Bounded({}, &overreads)).not_().to_start_with({1}); + expect(overreads).to_equal(0); + }); }); context("to_end_with (container sequences)", _ { @@ -78,6 +155,13 @@ describe string_spec("string matchers", $ { it("passes for single-element suffix", _ { expect(std::vector{7, 8, 9}).to_end_with({9}); }); + + it("reads nothing before the start of a sequence shorter than the suffix", _ { + int overreads = 0; + expect(Bounded({2}, &overreads)).not_().to_end_with({1, 2}); + expect(Bounded({}, &overreads)).not_().to_end_with({1}); + expect(overreads).to_equal(0); + }); }); context("to_match (full regex)", _ { From c338d749f2aac208cee15fb0907145ec6d7b65b7 Mon Sep 17 00:00:00 2001 From: Katherine Whitlock Date: Sat, 14 Nov 2026 13:09:23 -0500 Subject: [PATCH 07/20] fix(formatters): progress lists each failure with its file and line, and nothing for a passing result The progress formatter, the default, listed the message of every result of a failed example, passing ones included, so each passing expectation added an empty line to the failure list, and no line said where the failure was. It now lists only the results that failed or raised an error, each as `file:line: message`, the same form the verbose formatter prints; a passing result, or one skipped by ignore(), adds nothing. Both formatters build that line with BaseFormatter::located_message(). Progress takes an output stream like the other formatters, so it can be tested on its own. --- include/formatters/formatters_base.hpp | 17 +++++++ include/formatters/progress.hpp | 12 +++-- include/formatters/verbose.hpp | 4 +- spec/formatters/progress_spec.cpp | 62 ++++++++++++++++++++++++++ 4 files changed, 89 insertions(+), 6 deletions(-) create mode 100644 spec/formatters/progress_spec.cpp diff --git a/include/formatters/formatters_base.hpp b/include/formatters/formatters_base.hpp index 623cc8e..4ce4de8 100644 --- a/include/formatters/formatters_base.hpp +++ b/include/formatters/formatters_base.hpp @@ -2,7 +2,9 @@ #pragma once #include +#include #include +#include #include "description.hpp" #include "it_base.hpp" @@ -96,6 +98,21 @@ class BaseFormatter { } const char* reset_color() { return color_output ? RESET : ""; } + + /** + * @brief Prefix a result's message with the file and line of the expectation that reported it. + * + * Every formatter that prints failure messages as text uses this, so an editor or terminal can jump from any of + * them to the failing expectation. + * + * @param result the result to describe + * + * @return `file:line: message` + */ + [[nodiscard]] static std::string located_message(const Result& result) { + return std::format("{}:{}: {}", result.get_location().file_name(), result.get_location().line(), + result.get_message()); + } }; inline BaseFormatter& BaseFormatter::set_color_output(bool value) { diff --git a/include/formatters/progress.hpp b/include/formatters/progress.hpp index b6eb5c6..aa54fda 100644 --- a/include/formatters/progress.hpp +++ b/include/formatters/progress.hpp @@ -3,6 +3,7 @@ #include #include +#include #include #include "term_colors.hpp" @@ -17,6 +18,8 @@ class Progress : public BaseFormatter { std::string prep_failure_helper(const ItBase& it); public: + using BaseFormatter::BaseFormatter; + ~Progress() override { format_failure_messages(); // Print any failures that we have } @@ -76,9 +79,12 @@ inline std::string Progress::prep_failure_helper(const ItBase& it) { } inline void Progress::prep_failure(const ItBase& it) { - std::list raw_failure_messages; // raw failure messages - std::ranges::transform(it.get_results(), std::back_inserter(raw_failure_messages), - [](const Result& result) { return result.get_message(); }); + // Only the expectations that failed or raised an error are listed, each led by its file and line; a passing or + // skipped one adds no line. + std::list raw_failure_messages; + std::ranges::transform( + it.get_results() | std::views::filter([](const Result& r) { return r.is_failure() || r.is_error(); }), + std::back_inserter(raw_failure_messages), &BaseFormatter::located_message); std::ostringstream string_builder; // oss is used as the local string builder string_builder << set_color(RED); // if we're doing color, make it red diff --git a/include/formatters/verbose.hpp b/include/formatters/verbose.hpp index dcf87a7..e7f8d44 100644 --- a/include/formatters/verbose.hpp +++ b/include/formatters/verbose.hpp @@ -41,9 +41,7 @@ inline void Verbose::format(const ItBase& it) { for (const Result& result : it.get_results()) { if (result.is_failure()) { out_stream << set_color(RED); - // file:line: leads the message, so an editor or terminal can jump to the failing expectation. - out_stream << result.get_location().file_name() << ':' << result.get_location().line() << ": " - << result.get_message() << std::endl; + out_stream << located_message(result) << std::endl; out_stream << reset_color(); } } diff --git a/spec/formatters/progress_spec.cpp b/spec/formatters/progress_spec.cpp new file mode 100644 index 0000000..2ab600b --- /dev/null +++ b/spec/formatters/progress_spec.cpp @@ -0,0 +1,62 @@ +#include +#include +#include +#include + +#include "cppspec.hpp" +#include "formatters/progress.hpp" + +using namespace CppSpec; + +namespace { +// Formats one example of a one-level group with the progress formatter and returns everything it prints: the status +// character, then the failure list. +std::string format_progress(const ItBase& example) { + std::ostringstream out; + Formatters::Progress formatter(out); + formatter.set_color_output(false); + formatter.format(example); + formatter.format_failure_messages(); + return out.str(); +} +} // namespace + +// clang-format off +describe progress_spec("Formatters::Progress", $ { + it("lists a failed expectation's file and line beside its message, and nothing for a passing one", _ { + auto location = std::source_location::current(); + Description group(location, std::string("group")); + auto* example = group.make_child(location, "fails", [](ItD&) {}); + example->add_result(Result::success(location)); + example->add_result(Result::failure_with(location, "the label\nexpected 1\n got 2")); + example->add_result(Result::success(location)); + + expect(format_progress(*example)) + .to_equal(std::format("F\nTest number 1 failed:group\n fails\n{}:{}: the label\nexpected 1\n got 2\n", + location.file_name(), location.line())); + }); + + it("lists nothing for a skipped expectation, with a message or without, beside a failure", _ { + auto location = std::source_location::current(); + Description group(location, std::string("group")); + auto* example = group.make_child(location, "fails", [](ItD&) {}); + example->add_result(Result::skipped(location)); + example->add_result(Result::skipped_with(location, "an ignored failure")); + example->add_result(Result::failure_with(location, "the failure")); + + expect(format_progress(*example)) + .to_equal(std::format("F\nTest number 1 failed:group\n fails\n{}:{}: the failure\n", location.file_name(), + location.line())); + }); + + it("lists nothing for a passing example", _ { + auto location = std::source_location::current(); + Description group(location, std::string("group")); + auto* example = group.make_child(location, "passes", [](ItD&) {}); + example->add_result(Result::success(location)); + + expect(format_progress(*example)).to_equal(std::string(".\n")); + }); +}); + +CPPSPEC_MAIN(progress_spec); From 4fbc540f41759cdac67bd3ed128ccc3474227278 Mon Sep 17 00:00:00 2001 From: Katherine Whitlock Date: Sat, 14 Nov 2026 13:13:51 -0500 Subject: [PATCH 08/20] fix(pretty): a container prints its bools, bytes, enums, optionals and C strings as they print alone Pretty printed a bool as true or false, a byte-sized integer as a number, an enum with no operator<< as Type(number), an optional by its value and a null C string as nullptr, but only at the top level: a container streamed its elements through cxx-prettyprint, so std::vector{65, 66} printed [A, B], a vector of int8_t printed raw bytes, a vector of bool printed [1, 0], a vector of const char* streamed a null element, and to_equal on a vector of such enums or of optionals did not compile. A standard container, a built-in array, a pair or a tuple that holds one of these, however deeply, is now printed element by element through Pretty, with cxx-prettyprint's delimiters: [65, 66], {1, 2} for a set, [(1, 65)] for a map. So is any other range type with no operator<< of its own; a range type with its own operator<< still prints through it. Every other container prints as before. Other character types print as numbers or addresses: - wchar_t, char8_t, char16_t and char32_t print the number of their code unit (u'a' prints 97); to_equal on them now compiles. - A pointer to signed char, unsigned char or a wide character prints as an address, and a null one as nullptr. Only a char pointer is read as text; a signed or unsigned char pointer used to be read up to a NUL, and a null one printed nothing. An optional holding another optional wraps the value it holds, so an optional holding an empty optional prints std::optional(std::nullopt) and no longer reads the same as an empty optional. The pretty spec also pins the enum cases: negative, 64-bit, with an operator<<, std::byte and unscoped, and a range type with its own operator<< and one with none. --- include/matchers/pretty_matchers.hpp | 206 ++++++++++++++++++++++++++- include/util.hpp | 39 +++++ spec/matchers/pretty_spec.cpp | 143 +++++++++++++++++++ 3 files changed, 385 insertions(+), 3 deletions(-) diff --git a/include/matchers/pretty_matchers.hpp b/include/matchers/pretty_matchers.hpp index c8ab106..2ff5dbd 100755 --- a/include/matchers/pretty_matchers.hpp +++ b/include/matchers/pretty_matchers.hpp @@ -2,12 +2,25 @@ #pragma once #include +#include +#include +#include +#include #include +#include +#include +#include #include +#include #include +#include +#include #include #include +#include #include +#include +#include #include #include @@ -27,6 +40,94 @@ struct is_container> : std::false_type {}; namespace CppSpec { +namespace Util { + +// Whether T is Template for some type arguments; std::array and std::span, which take a size, have their own. +template class Template> +inline constexpr bool is_specialization_of = false; + +template