Repository navigation
Release 1.1.0: readable failure messages, C strings as pointers - #13
Merged
Merged
Conversation
…cted 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".
…ts 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.
Failure messages printed these values unreadably: - an enum with no operator<< printed as an object address, `#<Colour:0x7ffd…>`, 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.
…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.
…ing 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<std::string>; it yields ExpectationValue<const char*>
for a string literal or a const char pointer or array, and
ExpectationValue<char*> 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.
…st 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.
…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.
…d 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<std::uint8_t>{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.
…instead of ending the run to_start_with, to_end_with, to_match and to_partially_match took the text they look for as a std::string, so a null const char* built a std::string from null before any matcher ran, which threw and ended the whole run. They now take any string-like value (std::string, std::string_view, a char array or a char pointer) and read it through string_view_of(). A null C string as the text or pattern to look for is nothing to look for: the matcher fails, negated or not, the example's next expectation still runs, and the message adds "nullptr is not text, so there is nothing to look for". to_contain on text does the same; in a collection that is not text, a null C string is still an element like any other. to_start_with and to_end_with on a range of characters, such as std::vector<char>, compare it with text in any of those forms. Any other range given text is refused at the constraint (Util::compares_start_and_end), so a std::vector<int> is never compared with characters. string_view_of() refuses a temporary std::string, whose view would outlive its text. The documentation of expect() and string_view_of() says that a char array given to expect() decays to a pointer and is read as a C string, so it must be NUL-terminated. Equal::compares_text and the new ContainBase members carry Doxygen comments.
…values are printed The expect guide gains three sections: - C strings: expect() keeps a C string as its pointer; the string matchers read every form of text through string_view_of(); a null C string equals only another null one, fails every search matcher both ways, as the actual value or as the text looked for, and prints as nullptr; a char array decays to a pointer and must be NUL-terminated. - Custom messages: the message is printed above the matcher's own text. - How values are printed: the exceptions to operator<<, which apply to the elements of a standard container, built-in array, pair or tuple, and of a range with no operator<< of its own, too. The matchers guide notes the custom message argument and the null rules on each string matcher, that to_start_with takes text only on a range of char, and documents to_partially_match. The testing guide shows the file:line that verbose and progress print before each failure message.
expect() on a C string now keeps the pointer, which changes the expectation's type, so this release is a minor version, not a patch.
… and fail NaN either way
to_be_greater_than, to_be_less_than and to_be_between compared with the plain operators, so a
signed value met an unsigned one after conversion: expect(-1).to_be_greater_than(0u) passed and
expect(std::size_t{3}).to_be_less_than(-1) passed. When both sides are integers other than bool
and the character types, they now compare with std::cmp_less and its kin; every other type still
uses the operators. Both modes of to_be_between follow the same rule.
Negated, each matcher used !match(), which passes NaN. Each now checks the strict opposite:
not_().to_be_greater_than(x) is actual <= x, not_().to_be_less_than(x) is actual >= x, and
not_().to_be_between(a, b) is a value below a or above b. NaN satisfies none of these, so it
fails either way. A user type compared negated needs that opposite operator as well.
The results of specs that compare a negative value with an unsigned one change. The comparisons
are Util::less, less_equal, greater and greater_equal, gated by the concept Util::is_cmp_integer.
…ding an element
ContainBase::collection_includes dereferenced the collection's first
element before searching, only to name its type for the check that the
item looked for is convertible to it. On an empty collection that read is
undefined behaviour: an empty std::vector crashed, and a span over a
static array read past its end.
The check now takes the element type from the range's type
(std::ranges::range_value_t), and the search reads only the elements that
are there, so expect(std::vector<int>{}).to_contain(1) fails and
not_().to_contain(1) passes. The same check still rejects an item that is
not convertible to the element type at compile time.
Pretty::last called back() on an empty list for a string with no pieces
between its delimiters, such as ""; it now returns an empty string.
Specs: to_contain and its negation on an empty vector, span, list and
vector of strings, with one or several items, and on empty text; a
bounds-counting range that reads nothing when empty; an empty container
printing as its delimiters; Pretty::last on "" and "::".
A Description owns each of its lets as std::unique_ptr<LetBase> and so deletes every Let<T> through LetBase, which had no virtual destructor. That is undefined behaviour: the Let's memoized value and its block were never destroyed, and AddressSanitizer reported new-delete-type-mismatch in every spec that uses let (dsl_spec, expectation_spec, let_spec) with clang and with GCC. LetBase's destructor is now virtual, and its copy and move operations are declared defaulted beside it so that declaring the destructor removes none of them. No other polymorphic base in CppSpec is deleted through a base pointer: Runnable, BaseFormatter and MatcherBase already have virtual destructors, and expectations are held by value. Specs: LetBase has a virtual destructor, and deleting a Let through LetBase destroys its value.
parse() opened the file that --output-junit names with a bare new std::ofstream and handed the JUnit XML formatter a reference to it, so the stream was never freed or closed. LeakSanitizer reported it in every run that passed the flag, which is every spec run through ctest, with clang and with GCC. The stream and its formatter now live together in a JUnitOutputFile, which the Runner holds through a shared_ptr to the formatter that shares ownership of the whole object. The formatter is declared after the stream, so its destructor writes the XML to a stream that is still open, and the stream closes after it. The command line, what is printed and the file's contents are unchanged.
Contributor
…n keywords MSVC writes before each type
…orm, MSVC included
…e under libc++, whose elements are proxies
…, which Clang 19 and earlier do not misread
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Release 1.1.0: failure messages show both values, say where the failure is, and print bytes, enums, optionals and C strings readably.
expect()keeps a C string as its pointer, which breaks source compatibility, hence a minor release. After merging, tag the mergev1.1.0.Breaking change
expect()on a C string keeps the pointer.expect(const char*)used to yieldExpectationValue<std::string>. It now yieldsExpectationValue<const char*>for a stringliteral or a
const charpointer or array, andExpectationValue<char*>for a non-const one.std::stringtype, or callsstd::stringmembers on the target, mustbuild the
std::stringitself:to_be_null()now works on a C string. A null C string used to throw insideexpect(),which ended the whole run.
to_equalcompares two char pointers by their text, not their addresses.Behaviour changes
expect(x).to_equal(2, "the gain"),"the gain" used to replace the failure message. It is now printed on the line above it, so
the values still show.
MatcherBase::failure_message()andfailure_message_when_negated()now return only the matcher's own text. A custom handler or formatter, or a test of a
matcher, that wants the custom message too should call the new
full_failure_message()/full_failure_message_when_negated().piece of text, the empty string included. It prints as
nullptr. The search matchers(
to_contain,to_start_with,to_end_with,to_match,to_partially_match) fail on itboth positive and negated, and the run continues. The null can be the actual value
("nullptr is not text, so there is nothing to search") or the text or pattern looked for
("... nothing to look for"). A null expected value given to
to_start_with,to_end_with,to_matchorto_partially_matchused to end the run. In a container that is not text,such as
std::vector<const char*>,to_containgiven a nullconst char*still looks forthe null pointer as an element.
to_start_with,to_end_with,to_matchandto_partially_matchtake astd::string,std::string_view, char array orchar pointer as the text to look for, and read it through the new public
CppSpec::string_view_of().expect()and the matchers take their arguments byvalue, so a char array decays to a pointer and is read up to its first NUL. It must be
NUL-terminated. Pass
std::string_view(buffer, size)for a fixed-size buffer.signed char,unsigned char,wchar_t,char8_t,char16_tandchar32_tare comparedas pointers and print as addresses (
nullptrwhen null).Output changes
Formatters say where each failure is.
verboseandprogress(the default) start eachfailure message with
file:line:.progressno longer prints an empty line for each passingexpectation in a failed example, and lists neither a passing nor a skipped (
ignore()d)expectation.
Values print by value. These rules apply at the top level and also inside containers,
pairs and tuples, at any depth:
std::uint8_t{65},std::int8_t{-3}A, a raw byte65,-3std::vector<std::uint8_t>{65, 66}[A, B][65, 66]operator<<#<Colour:0x7ffd…>Colour(2)(alsostd::byte(65),Big(-5000000000))std::optional<int>{5},std::nullopt5,std::nulloptstd::optional<std::optional<int>>{std::optional<int>{}}std::optional(std::nullopt)std::vector<bool>{true, false}[1, 0][true, false]L'a',u8'a',u'a',U'a'97const char*nullptrInside a value, these rules reach the elements of standard containers, built-in arrays, pairs,
tuples, and ranges with no
operator<<of their own. A plaincharstill prints as acharacter. An enum with its own
operator<<still uses it, and a range type with its ownoperator<<keeps it. Containers keep their delimiters:[…],{…}for sets,(…)forpairs and tuples. A
std::vector<bool>printstrueandfalsewith libc++ too, whoseelements are proxies rather than
bools.Type names and addresses read the same on every platform. On MSVC, type names no longer
carry the
enum,class,structandunionkeywords MSVC writes before each type: anenum prints
Colour(2), notenum Colour(2), and a type line readsstd::vector<Colour,std::allocator<Colour> >. Addresses, both in the#<Type:0x…>form of avalue with no
operator<<and for pointers that are not C strings, print as0xand lowercasehex everywhere; MSVC printed
000000E75CB8F322.One space. The default matcher description no longer prints two spaces before the
expected value ("to be less than 2").
to_equalnow compiles on containers of enums withoutoperator<<and on containers ofoptionals.
New
to_containon text.expect("hello").to_contain("ell"), and astd::stringin a
std::string, now compile and look for the text as a substring.to_start_withandto_end_with. Astd::string_viewor a C string works as well as a
std::string.std::vector<char>against text.to_start_with/to_end_withcompare a range ofchar, such asstd::vector<char>, with text in any formstring_view_of()reads. Any otherrange given text does not compile.
CppSpec::string_view_of()views any text, and givesstd::nulloptfor a null C string.MatcherBase::full_failure_message()andfull_failure_message_when_negated()return thecustom message with the matcher's own text below it.
BaseFormatter::located_message()gives a result's message led by itsfile:line:.Formatters::Progresstakes an output stream in its constructor, like the otherformatters.
Util::is_c_string,Util::is_string_likeandUtil::compares_start_and_endsay which types the text matchers read as text.Util::less,less_equal,greaterandgreater_equalcompare by value when both sidessatisfy the concept
Util::is_cmp_integer, and with the operator otherwise.Util::strip_type_keywords()removes MSVC'senum/class/struct/unionkeywordsfrom a type name, and
Pretty::address_of()formats an address as0xand lowercase hex.Fixes
to_start_with/to_end_withon a range no longer read past an actual range that is shorterthan the expected one.
to_containon an empty collection searches without reading an element. It read the firstelement to check the type of what was looked for, which on an empty collection was undefined
behaviour (a crash on an empty
std::vector). The type is now checked from the range's type,so
expect(std::vector<int>{}).to_contain(1)fails andnot_().to_contain(1)passes.Pretty::laston a string with no pieces between its delimiters (such as"") returns anempty string instead of reading past an empty list.
empty" diagnostic.
string_view_of()refuses a temporarystd::string, whose view would dangle.to_be_greater_than,to_be_less_thanandto_be_betweencompare mixed-sign integers byvalue. They used the plain operators, so
expect(-1).to_be_greater_than(0u)passed andexpect(std::size_t{3}).to_be_less_than(-1)passed. When both sides are integers (notboolor a character type) they now use
std::cmp_lessand its kin; other types still use theoperators. Both modes of
to_be_betweenare covered.not_()used to pass whenever the comparison wasfalse, so
expect(NAN).not_().to_be_greater_than(0.0)passed. Negated, each now checks thestrict opposite (
not_().to_be_greater_than(x)isactual <= x;not_().to_be_between(a, b)is below
aor aboveb), which NaN does not satisfy either. A user type compared negatedtherefore needs that opposite operator (
<=,>=,<,>) too.letis destroyed properly. A describe owns its lets throughLetBase, which had novirtual destructor, so deleting each
Let<T>was undefined behaviour and never destroyed thememoized value (AddressSanitizer reported new-delete-type-mismatch).
LetBase's destructor isnow virtual.
--output-junitno longer leaks its file. The stream it opened was never freed or closed,which LeakSanitizer reported in every run that passed the flag. The stream is now owned beside
its formatter and closed once the XML is written. The file's contents are unchanged.
Upgrading
expect(onconst char*/char*values whose target you treated as astd::string.failure_message()directly.to_be_greater_than,to_be_less_thanorto_be_betweento change result.optionals, the
file:line:prefix and the custom-message placement.🤖 Generated with Claude Code