diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 4304463..f6aae2b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -17,12 +17,10 @@ jobs: fail-fast: false matrix: compiler: [native, llvm-20, gcc-14] - os: [ubuntu-latest, windows-latest, macos-14, macos-15] + os: [ubuntu-latest, windows-latest, macos-15] exclude: - os: windows-latest compiler: gcc-14 - - os: macos-14 - compiler: native # AppleClang is too old steps: - name: Checkout code @@ -39,7 +37,7 @@ jobs: echo "CC=$LLVM_PREFIX/bin/clang" >> $GITHUB_ENV echo "CXX=$LLVM_PREFIX/bin/clang++" >> $GITHUB_ENV echo "LDFLAGS=-L$LLVM_PREFIX/lib/c++ -Wl,-rpath,$LLVM_PREFIX/lib/c++" >> $GITHUB_ENV - if: ${{ matrix.compiler == 'llvm-20' && (matrix.os == 'macos-14' || matrix.os == 'macos-15') }} + if: ${{ matrix.compiler == 'llvm-20' && matrix.os == 'macos-15' }} - name: Install LLVM and Clang (Ubuntu) run: | diff --git a/CMakeLists.txt b/CMakeLists.txt index 83e23cf..37f135b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,7 @@ cmake_minimum_required(VERSION 3.27 FATAL_ERROR) project(c++spec - VERSION 1.0.0 + VERSION 1.1.0 DESCRIPTION "BDD testing for C++" LANGUAGES CXX ) diff --git a/docs/syntax/expect.md b/docs/syntax/expect.md index dd2a6ee..23b5569 100644 --- a/docs/syntax/expect.md +++ b/docs/syntax/expect.md @@ -41,3 +41,76 @@ This allows creating delayed "thunks" that can be created earlier and then passe auto val = [] { return 5; }; expect(val).to_equal(5); ``` + +## C strings + +`expect` keeps a C string (a `char*`, a `const char*`, or a char array, which decays to one) as +the pointer it is, so pointer matchers such as `to_be_null` work on it: + +```cpp +const char* name = nullptr; +expect(name).to_be_null(); +``` + +The string matchers (`to_equal`, `to_contain`, `to_start_with`, `to_end_with`, `to_match` and +`to_partially_match`) read every piece of text through `CppSpec::string_view_of()`, whatever +form it is in: a `std::string`, a `std::string_view`, a char array or a char pointer. Two C +strings are therefore compared by their text, not by their addresses, and a C string equals a +`std::string` holding the same text. + +A null C string is not text: + +- it equals only another null C string, and differs from every piece of text, the empty string + included, so `expect(name).not_().to_equal("")` passes; +- the matchers that search text (`to_contain`, `to_start_with`, `to_end_with`, `to_match`, + `to_partially_match`) fail on it **both** positive and negated, whether it is the actual + value or the text or pattern looked for, and say so below their message + (`nullptr is not text, so there is nothing to search` or `... nothing to look for`); +- it prints as `nullptr`. + +A char array given to `expect` decays to a pointer, so it is read as a C string, up to its first +NUL: it must be NUL-terminated. Wrap a fixed-size buffer that may not be in a +`std::string_view(buffer, size)`. + +A `volatile char*`, a `signed char*`, an `unsigned char*` and a pointer to a wide character +type are not C strings: they are compared as pointers and printed as addresses (`nullptr` when +null). + +## Custom messages + +Every matcher takes an optional last argument, a message that describes the expectation. When +the expectation fails, the message is printed **above** the matcher's own text, which still +shows both values: + +```cpp +expect(gain).to_equal(2, "the gain"); +``` + +``` +the gain +expected (int) => 2 + got (int) => 1 +Compared using `==` +``` + +## How values are printed + +A failure message prints each value by its `operator<<` where it has one, with these +exceptions, which also apply to the elements of a standard container, built-in array, pair or +tuple, and of any other range with no `operator<<` of its own (a range type with its own +`operator<<` is printed through it): + +| Value | Printed as | +| ----- | ---------- | +| `bool` | `true` / `false` | +| `std::int8_t`, `std::uint8_t` (`signed char`, `unsigned char`) | the number: `65`, `-3` | +| `wchar_t`, `char8_t`, `char16_t`, `char32_t` | the number of the code unit: `97` | +| `char` | the character: `A` | +| an enum with no `operator<<` (scoped, `std::byte` included) | its type and number: `Colour(2)`, `std::byte(65)` | +| `std::optional` | its value, or `std::nullopt` | +| `std::optional>` holding an optional | `std::optional(...)`, so `std::optional(std::nullopt)` reads apart from `std::nullopt` | +| a C string | its text, or `nullptr` | +| a pointer to `signed char`, `unsigned char` or a wide character | its address, or `nullptr` | + +So a failed comparison of two byte buffers reads `[65, 67]` against `[65, 66]`, and a container +keeps its delimiters: `[1, 2]`, `{1, 2}` for a set, `(1, 2)` for a pair or tuple. diff --git a/docs/syntax/matchers.md b/docs/syntax/matchers.md index a6ee7b6..f41bbd0 100644 --- a/docs/syntax/matchers.md +++ b/docs/syntax/matchers.md @@ -8,6 +8,17 @@ expect(x).to_equal(0); // passes when x == 0 expect(x).not_().to_equal(0); // passes when x != 0 ``` +Every matcher also takes an optional last argument, a message printed above the matcher's own +text when the expectation fails (see [Expect](expect.md#custom-messages)): + +```cpp +expect(gain).to_equal(2, "the gain"); +``` + +Text in any form (`std::string`, `std::string_view`, a char array or a C string) is read +through `CppSpec::string_view_of()`; see [Expect](expect.md#c-strings) for how C strings, null +ones included, are compared and printed. + --- ## Equality & boolean @@ -21,6 +32,9 @@ expect(1 + 1).to_equal(2); expect(std::string{"hi"}).to_equal("hi"); ``` +Two pieces of text are compared as text, whatever form each is in, so two C strings with the same +text at different addresses are equal. A null C string equals only another null C string. + ### to_be_true / to_be_false Strict boolean check (value must be exactly `true` or `false`): @@ -50,6 +64,9 @@ expect(p).to_be_null(); int x = 1; expect(&x).not_().to_be_null(); + +const char* name = nullptr; // a C string stays a pointer, so this works too +expect(name).to_be_null(); ``` --- @@ -63,8 +80,13 @@ Passes when the container holds the given element (uses `std::ranges::find`): ```cpp expect(std::vector{1, 2, 3}).to_contain(2); expect(std::string{"hello"}).to_contain('e'); +expect("hello").to_contain("ell"); ``` +On text, a null C string, as the text searched or the text looked for, fails both positive and +negated. In a container that is not text, such as `std::vector`, a null pointer is an +element like any other. + ### to_contain (multiple elements) Passes when **all** listed elements are present. Negated form passes when **none** are present: @@ -80,9 +102,16 @@ For strings, checks the leading prefix. For containers, checks the leading sub-s ```cpp expect(std::string{"hello world"}).to_start_with("hello"); +expect(std::string_view{"hello world"}).to_start_with(std::string{"hello"}); expect(std::vector{1, 2, 3, 4}).to_start_with({1, 2}); +expect(std::vector{'a', 'b', 'c'}).to_start_with("ab"); ``` +The text may be in any form `string_view_of()` reads. Of the ranges that are not text, only a range +of `char`, such as `std::vector`, takes text to compare with; for any other range, +`to_start_with("ab")` does not compile. A null C string, on either side, fails both positive and +negated. + ### to_end_with For strings, checks the trailing suffix. For containers, checks the trailing sub-sequence: @@ -92,6 +121,8 @@ expect(std::string{"hello world"}).to_end_with("world"); expect(std::vector{1, 2, 3, 4}).to_end_with({3, 4}); ``` +As with `to_start_with`, a null C string on either side fails both positive and negated. + --- ## Numeric @@ -105,6 +136,8 @@ expect(5).to_be_between(1, 10); expect(5).to_be_between(1, 10, RangeMode::exclusive); // strict bounds ``` +Negated, it passes only for a value below the lower bound or above the upper one. + ### to_be_within Floating-point proximity check. Use `.of(expected)` to specify the target: @@ -120,6 +153,12 @@ expect(3).to_be_less_than(5); expect(7).to_be_greater_than(4); ``` +`to_be_less_than`, `to_be_greater_than` and `to_be_between` compare two integers by value, as `std::cmp_less` does, +so a negative number is below every unsigned one: `expect(-1).to_be_less_than(0u)` passes. `bool` and the character +types, and every non-integer type, are compared with the operators instead. Negated, each checks the strict opposite +(`not_().to_be_greater_than(x)` is `actual <= x`), so NaN fails these matchers negated or not, and a type compared +negated needs that opposite operator too. + --- ## Strings @@ -136,6 +175,17 @@ expect(std::string{"HELLO"}).to_match(std::regex("hello", std::regex::icase)); Note: `to_match` uses `std::regex_match` which requires the **entire** string to match the pattern. +### to_partially_match + +Passes when the pattern matches **somewhere** in the string (`std::regex_search`): + +```cpp +expect(std::string{"hello123"}).to_partially_match("[0-9]+"); +``` + +For both, the pattern may be given as text in any form `string_view_of()` reads. A null C string, +as the text or as the pattern, fails both positive and negated. + --- ## Custom predicate diff --git a/docs/testing.md b/docs/testing.md index 25ea757..455cec1 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -17,6 +17,19 @@ Pass a formatter to `CppSpec::parse`: CppSpec::parse(argc, argv, CppSpec::Formatters::verbose) ``` +`verbose` and `progress` (the default) start each failure message with the file and line of the +failing expectation, so an editor or terminal can jump to it: + +``` +spec/gain_spec.cpp:12: the gain +expected (int) => 2 + got (int) => 1 +Compared using `==` +``` + +`progress` lists only the expectations that failed. The `tap` and `junit` formatters report the +file and line in their own fields. + ## Example ```cpp diff --git a/include/argparse.hpp b/include/argparse.hpp index ba2c2c4..4df6d4b 100644 --- a/include/argparse.hpp +++ b/include/argparse.hpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include "formatters/junit_xml.hpp" @@ -22,6 +23,19 @@ inline std::string file_name(std::string_view path) { return std::string{file}; } +/** + * @brief The file that --output-junit names, with the JUnit XML formatter that writes to it + * + * The formatter is declared after the stream, so it is destroyed first: its destructor writes the XML to a stream + * that is still open, and the stream is closed after it. + */ +struct JUnitOutputFile { + std::ofstream stream; + Formatters::JUnitXML formatter{stream, false}; + + explicit JUnitOutputFile(const std::string& path) : stream(path) {} +}; + inline Runner parse(int argc, char** const argv) { std::filesystem::path executable_path = argv[0]; std::string executable_name = executable_path.filename().string(); @@ -61,9 +75,8 @@ inline Runner parse(int argc, char** const argv) { auto junit_output_filepath = program.get("--output-junit"); if (!junit_output_filepath.empty()) { - // open file stream - auto* file_stream = new std::ofstream(junit_output_filepath); - auto junit_output = std::make_shared(*file_stream, false); + auto junit_file = std::make_shared(junit_output_filepath); + std::shared_ptr junit_output{junit_file, &junit_file->formatter}; return Runner{formatter, junit_output}; } return Runner{formatter}; diff --git a/include/expectations/expectation.hpp b/include/expectations/expectation.hpp index 6985d56..4a8c65a 100755 --- a/include/expectations/expectation.hpp +++ b/include/expectations/expectation.hpp @@ -110,17 +110,23 @@ class Expectation { /*-------- to... ----------*/ - void to_end_with(std::string ending, std::string msg = ""); + template + requires Util::compares_start_and_end + void to_end_with(T ending, std::string msg = ""); void to_fail(std::string msg = ""); void to_fail_with(std::string failure_message, std::string msg = ""); void to_match(std::regex regex, std::string msg = ""); - void to_match(std::string str, std::string msg = ""); + template + void to_match(T pattern, std::string msg = ""); void to_partially_match(std::regex regex, std::string msg = ""); - void to_partially_match(std::string str, std::string msg = ""); + template + void to_partially_match(T pattern, std::string msg = ""); template requires std::invocable && std::convertible_to, bool> void to_satisfy(F test, std::string msg = ""); - void to_start_with(std::string start, std::string msg = ""); + template + requires Util::compares_start_and_end + void to_start_with(T start, std::string msg = ""); template void to_contain(std::initializer_list expected, std::string msg = ""); @@ -328,9 +334,16 @@ void Expectation::to_fail_with(std::string failure_message, std::string msg) Matchers::FailWith(*this, failure_message).set_message(std::move(msg)).run(); } +/** + * @brief Match using the Matchers::Match matcher, with a pattern given as text. + * + * @param pattern the pattern, in any form string_view_of() reads; a null C string fails, negated or not. + * @param msg Optional message to give on failure. + */ template -void Expectation::to_match(std::string str, std::string msg) { - Matchers::Match(*this, str).set_message(std::move(msg)).run(); +template +void Expectation::to_match(T pattern, std::string msg) { + Matchers::Match(*this, pattern).set_message(std::move(msg)).run(); } template @@ -338,9 +351,16 @@ void Expectation::to_match(std::regex regex, std::string msg) { Matchers::Match(*this, regex).set_message(std::move(msg)).run(); } +/** + * @brief Match using the Matchers::MatchPartial matcher, with a pattern given as text. + * + * @param pattern the pattern, in any form string_view_of() reads; a null C string fails, negated or not. + * @param msg Optional message to give on failure. + */ template -void Expectation::to_partially_match(std::string str, std::string msg) { - Matchers::MatchPartial(*this, str).set_message(std::move(msg)).run(); +template +void Expectation::to_partially_match(T pattern, std::string msg) { + Matchers::MatchPartial(*this, pattern).set_message(std::move(msg)).run(); } template @@ -364,9 +384,17 @@ void Expectation::to_satisfy(F test, std::string msg) { Matchers::Satisfy(*this, std::function(std::move(test))).set_message(std::move(msg)).run(); } +/** + * @brief Match using the Matchers::StartWith matcher, with the start given as text. + * + * @param start the text, in any form string_view_of() reads; a null C string fails, negated or not. + * @param msg Optional message to give on failure. + */ template -void Expectation::to_start_with(std::string start, std::string msg) { - Matchers::StartWith(*this, start).set_message(std::move(msg)).run(); +template + requires Util::compares_start_and_end +void Expectation::to_start_with(T start, std::string msg) { + Matchers::StartWith(*this, start).set_message(std::move(msg)).run(); } template @@ -375,9 +403,17 @@ void Expectation::to_start_with(std::initializer_list start_sequence, std: Matchers::StartWith>(*this, start_sequence).set_message(std::move(msg)).run(); } +/** + * @brief Match using the Matchers::EndWith matcher, with the ending given as text. + * + * @param ending the text, in any form string_view_of() reads; a null C string fails, negated or not. + * @param msg Optional message to give on failure. + */ template -void Expectation::to_end_with(std::string ending, std::string msg) { - Matchers::EndWith(*this, ending).set_message(std::move(msg)).run(); +template + requires Util::compares_start_and_end +void Expectation::to_end_with(T ending, std::string msg) { + Matchers::EndWith(*this, ending).set_message(std::move(msg)).run(); } template 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/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 b31d9cc..e7f8d44 100644 --- a/include/formatters/verbose.hpp +++ b/include/formatters/verbose.hpp @@ -41,7 +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); - out_stream << result.get_message() << std::endl; + out_stream << located_message(result) << std::endl; out_stream << reset_color(); } } 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..98e3c70 100755 --- a/include/it_base.hpp +++ b/include/it_base.hpp @@ -75,6 +75,11 @@ 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. Because a char array decays to a pointer, it is read as a C + * string, up to its first NUL, so it must be NUL-terminated; pass `std::string_view(buffer, size)` for a fixed-size + * buffer that may not be. + * * @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 +128,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/let.hpp b/include/let.hpp index 015ec72..d3738a9 100755 --- a/include/let.hpp +++ b/include/let.hpp @@ -20,6 +20,11 @@ class LetBase { public: constexpr LetBase() noexcept = default; LetBase(const LetBase& copy) = default; + LetBase(LetBase&& other) noexcept = default; + LetBase& operator=(const LetBase& copy) = default; + LetBase& operator=(LetBase&& other) noexcept = default; + /** @brief Virtual, as a Description owns its lets through `std::unique_ptr` */ + virtual ~LetBase() = default; void reset() noexcept { delivered = false; } [[nodiscard]] constexpr bool has_result() const noexcept { return this->delivered; } }; diff --git a/include/matchers/contain.hpp b/include/matchers/contain.hpp index 4424699..bffbe96 100644 --- a/include/matchers/contain.hpp +++ b/include/matchers/contain.hpp @@ -1,5 +1,10 @@ /** @file */ #pragma once +#include +#include +#include +#include + #include "matcher_base.hpp" namespace CppSpec::Matchers { @@ -26,6 +31,24 @@ class ContainBase : public MatcherBase { protected: bool actual_collection_includes(U expected_item); + + /** + * @brief Whether the actual value is a null C string, which is no text, so the matcher fails it negated as well as + * positive + */ + bool actual_is_null_text(); + + /** + * @brief Whether the actual value is text and a piece of text to look for in it is a null C string, which is + * nothing to look for, so the matcher fails it negated as well as positive + */ + bool expected_is_null_text(); + + /** @brief The lines that say why there is no text to search or nothing to look for, or an empty string */ + std::string null_text_notes(); + + private: + bool collection_includes(U expected_item); }; template @@ -36,21 +59,68 @@ 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()) + null_text_notes(); } 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()) + null_text_notes(); } +template +std::string ContainBase::null_text_notes() { + return no_text_to_search(this->actual()) + + (expected_is_null_text() ? std::string(nothing_to_look_for) : std::string()); +} + +// 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) { - auto actual = this->actual(); - auto last = *(actual.begin()); - static_assert(Util::verbose_assert>::value, + 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); + } +} + +template +bool ContainBase::actual_is_null_text() { + if constexpr (Util::is_string_like) { + return !string_view_of(this->actual()); + } else { + return false; + } +} + +// In a collection that is not text, a null C string is an element like any other, and is looked for as one. +template +bool ContainBase::expected_is_null_text() { + if constexpr (Util::is_string_like && Util::is_string_like) { + if constexpr (std::same_as) { + return !string_view_of(this->expected()); + } else { + return std::ranges::any_of(this->expected(), [](const U& item) { return !string_view_of(item); }); + } + } else { + return false; + } +} + +// The element type is checked from the range's type alone, so an empty collection is searched without reading an +// element. +template +bool ContainBase::collection_includes(U expected_item) { + static_assert(Util::verbose_assert>>::value, "Expected item is not comparable against what is inside container."); - return std::ranges::find(actual, expected_item) != actual.end(); + auto& actual = this->actual(); + return std::ranges::find(actual, expected_item) != std::ranges::end(actual); } /** @@ -72,12 +142,14 @@ class Contain : public ContainBase { template bool Contain::match() { - return perform_match(Predicate::all, Predicate::all); + return !this->actual_is_null_text() && !this->expected_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() && !this->expected_is_null_text() && + perform_match(Predicate::none, Predicate::any); } // TODO: support std::map @@ -122,6 +194,7 @@ class Contain : public ContainBase { Contain(Expectation& expectation, U expected) : ContainBase(expectation, expected) {}; bool match() override; + bool negated_match() override; }; template @@ -129,4 +202,9 @@ bool Contain::match() { return this->actual_collection_includes(this->expected()); } +template +bool Contain::negated_match() { + return !this->actual_is_null_text() && !this->expected_is_null_text() && !match(); +} + } // namespace CppSpec::Matchers diff --git a/include/matchers/equal.hpp b/include/matchers/equal.hpp index c7fc82d..8a6f690 100644 --- a/include/matchers/equal.hpp +++ b/include/matchers/equal.hpp @@ -18,6 +18,12 @@ class Equal : public MatcherBase { public: Equal(Expectation& expectation, E expected) : MatcherBase(expectation, expected) {} + /** + * @brief Whether the two values are compared as text, through string_view_of(), 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 +32,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 +53,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 +62,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 +71,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 fc5b4e1..2dcb506 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" @@ -23,6 +24,45 @@ 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 line a matcher that searches text puts below its own message when the text or pattern it looks for is + * a null C string, which is nothing to look for, so the matcher fails it negated as well as positive + */ +inline constexpr std::string_view nothing_to_look_for = "\nnullptr is not text, so there is nothing to look for"; + +/** + * @brief The line nothing_to_look_for when the expected value is a null C string + * + * @param expected the expected value + * @return the line, led by a newline, or an empty string when the expected value is not a null C string + */ +template +[[nodiscard]] std::string no_text_to_look_for(const E& expected) { + if constexpr (Util::is_string_like) { + if (!string_view_of(expected)) { + return std::string(nothing_to_look_for); + } + } + return {}; +} + /** * @brief the base class for all Matcher classes and objects * @@ -37,6 +77,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 +126,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 +172,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()); } @@ -140,7 +202,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_)); } /** @@ -159,11 +222,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/include/matchers/numeric/be_between.hpp b/include/matchers/numeric/be_between.hpp index 0c9ee2c..9d386ac 100644 --- a/include/matchers/numeric/be_between.hpp +++ b/include/matchers/numeric/be_between.hpp @@ -2,11 +2,17 @@ #pragma once #include "matchers/matcher_base.hpp" +#include "util.hpp" namespace CppSpec::Matchers { enum class RangeMode { exclusive, inclusive }; +/** + * @brief Matches a value between two bounds, inclusive or exclusive, compared by value when both sides are integers + * (`-1` is not between `0u` and `10u`). Under `not_()` it matches a value below the lower bound or above the + * upper one, so NaN, which is neither, fails both ways. + */ template class BeBetween : public MatcherBase { E min; @@ -34,32 +40,25 @@ class BeBetween : public MatcherBase { } bool match() override; + bool negated_match() override; std::string verb() override { return "be between"; } std::string description() override; }; template bool BeBetween::match() { - auto actual = this->actual(); - bool result1; - switch (gt_op) { - case GtOp::gt: - result1 = actual > min; - break; - case GtOp::gt_eq: - result1 = actual >= min; - break; - } - bool result2; - switch (lt_op) { - case LtOp::lt: - result2 = actual < max; - break; - case LtOp::lt_eq: - result2 = actual <= max; - break; - } - return result1 && result2; + const auto& actual = this->actual(); + const bool above_min = gt_op == GtOp::gt ? Util::greater(actual, min) : Util::greater_equal(actual, min); + const bool below_max = lt_op == LtOp::lt ? Util::less(actual, max) : Util::less_equal(actual, max); + return above_min && below_max; +} + +template +bool BeBetween::negated_match() { + const auto& actual = this->actual(); + const bool below_min = gt_op == GtOp::gt ? Util::less_equal(actual, min) : Util::less(actual, min); + const bool above_max = lt_op == LtOp::lt ? Util::greater_equal(actual, max) : Util::greater(actual, max); + return below_min || above_max; } template diff --git a/include/matchers/numeric/be_greater_than.hpp b/include/matchers/numeric/be_greater_than.hpp index 0f47638..17a3fdb 100644 --- a/include/matchers/numeric/be_greater_than.hpp +++ b/include/matchers/numeric/be_greater_than.hpp @@ -3,14 +3,21 @@ #include #include "matchers/matcher_base.hpp" +#include "util.hpp" namespace CppSpec::Matchers { +/** + * @brief Matches a value above the expected one: `actual > expected`, compared by value when both are integers + * (`-1` is not above `0u`). Under `not_()` it matches `actual <= expected`, so NaN, which neither holds for, + * fails both ways. + */ template class BeGreaterThan : public MatcherBase { public: BeGreaterThan(Expectation& expectation, E expected) : MatcherBase(expectation, expected) {} - bool match() override { return this->actual() > this->expected(); } + bool match() override { return Util::greater(this->actual(), this->expected()); } + bool negated_match() override { return Util::less_equal(this->actual(), this->expected()); } std::string verb() override { return "be greater than"; } }; diff --git a/include/matchers/numeric/be_less_than.hpp b/include/matchers/numeric/be_less_than.hpp index 8cf972e..158ca68 100644 --- a/include/matchers/numeric/be_less_than.hpp +++ b/include/matchers/numeric/be_less_than.hpp @@ -3,14 +3,21 @@ #include #include "matchers/matcher_base.hpp" +#include "util.hpp" namespace CppSpec::Matchers { +/** + * @brief Matches a value below the expected one: `actual < expected`, compared by value when both are integers + * (`-1` is below `0u`). Under `not_()` it matches `actual >= expected`, so NaN, which neither holds for, fails + * both ways. + */ template class BeLessThan : public MatcherBase { public: BeLessThan(Expectation& expectation, E expected) : MatcherBase(expectation, expected) {} - bool match() override { return this->actual() < this->expected(); } + bool match() override { return Util::less(this->actual(), this->expected()); } + bool negated_match() override { return Util::greater_equal(this->actual(), this->expected()); } std::string verb() override { return "be less than"; } }; diff --git a/include/matchers/pretty_matchers.hpp b/include/matchers/pretty_matchers.hpp index 22bb2e0..50461f1 100755 --- a/include/matchers/pretty_matchers.hpp +++ b/include/matchers/pretty_matchers.hpp @@ -2,9 +2,26 @@ #pragma once #include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include +#include #include +#include +#include #include +#include +#include +#include +#include +#include #include #include @@ -16,14 +33,102 @@ // 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 {}; -} // namespace pretty_print +} // namespace pretty_print 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