catch3
Progmasoft Catch3: an independently maintained C++17 test framework with a parallel runner, property checks, snapshots and structured results.
Clonegit clone https://git.progmasoft.com/catch3
Add death tests
- Commit
ca5c9ce534f98ec6f0034461a5419bea4be0c983- Author
- Leitwolf11 ·
- Parents
16cf55a45b4f
Changes
README.md | 4 + docs/Readme.md | 1 + docs/progmasoft-death-tests.md | 70 ++++++++++ docs/why-catch3.md | 1 + extras/catch_amalgamated.cpp | 259 +++++++++++++++++++++++++++++++++++++ extras/catch_amalgamated.hpp | 150 ++++++++++++++++++++++ premake5.lua | 2 + src/CMakeLists.txt | 1 + src/Progmasoft/Catch3.hpp | 1 + src/Progmasoft/Catch3/Death.hpp | 154 ++++++++++++++++++++++ src/Progmasoft/Catch3/meson.build | 1 + src/Progmasoft/Death.cpp | 262 ++++++++++++++++++++++++++++++++++++++ src/Progmasoft/meson.build | 1 + tests/CMakeLists.txt | 1 + tests/Progmasoft/BUILD.bazel | 1 + tests/Progmasoft/Death.tests.cpp | 89 +++++++++++++ tests/meson.build | 1 + tools/Amalgamation.cpp | 3 + xmake.lua | 4 +- 19 files changed, 1005 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3e8ca52c..55730cf0 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,10 @@ The site of Catch3 is [catch3.uk](https://catch3.uk). interfaces and of free functions behind a seam check call counts, arguments and order, and report through the same assertions as the rest of a test. +- **Death tests.** [Death tests](https://catch3.uk/docs/progmasoft-death-tests/) + check that a statement ends the process, by exit code, signal or what it + wrote to standard error; the statement runs in a child process, on Linux, + macOS and Windows alike. - **Deterministic property testing.** Generate values from a reproducible seed, check a predicate over multiple trials, and shrink a failing input to a smaller counterexample. diff --git a/docs/Readme.md b/docs/Readme.md index 15fe412d..e6eed7e8 100644 --- a/docs/Readme.md +++ b/docs/Readme.md @@ -39,6 +39,7 @@ Catch2 release. **Running:** * [The Catch3 runner](progmasoft-runner.md#top) * [Mocking](progmasoft-mocking.md#top) +* [Death tests](progmasoft-death-tests.md#top) * [Command line reference](command-line.md#top) * [Running specific section/generator](filtering-execution-path.md#top) diff --git a/docs/progmasoft-death-tests.md b/docs/progmasoft-death-tests.md new file mode 100644 index 00000000..baa5a086 --- /dev/null +++ b/docs/progmasoft-death-tests.md @@ -0,0 +1,70 @@ +<a id="top"></a> + +# Death tests + +`<Progmasoft/Catch3/Death.hpp>` checks that a statement ends the process: an +`abort()` on a broken invariant, an `exit(3)` on bad input, a crash on a null +pointer. The statement runs in a child process, so the test that checks it +goes on, and every other test of the binary is untouched. + +```cpp +#include <Progmasoft/Catch3/Death.hpp> +#include <Progmasoft/Catch3/Matchers/String.hpp> +#include <Progmasoft/Catch3/TestMacros.hpp> + +using namespace Progmasoft::Catch3; +using Catch::Matchers::ContainsSubstring; + +TEST_CASE("A broken invariant stops the program") +{ + Buffer buffer(4); + CATCH3_CHECK_DEATH(buffer.At(9)); + CATCH3_CHECK_DEATH_THAT(buffer.At(9), ContainsSubstring("out of range")); + CATCH3_CHECK_EXIT(Parse("--size=-1"), ExitedWith{2}); + CATCH3_CHECK_EXIT(buffer.Release(nullptr), KilledBySignal{SIGSEGV}); +} +``` + +## The macros + +| Macro | Passes when | +| --- | --- | +| `CATCH3_CHECK_DEATH(statement)` | the statement ends the process: it exits with a status other than 0, or a signal or an exception ends it | +| `CATCH3_CHECK_DEATH_THAT(statement, matcher)` | as above, and what the statement wrote to standard error matches `matcher` | +| `CATCH3_CHECK_EXIT(statement, ending)` | the statement ends the process as `ending` says: `ExitedWith{code}`, `KilledBySignal{signal}` (POSIX), or any callable that takes a `DeathResult` | + +Each has a `REQUIRE` form that ends the test case on failure. A statement +that returns or throws fails the check, and the report says which. Only an +exit with status 0 needs `CATCH3_CHECK_EXIT(statement, ExitedWith{0})`; +`CATCH3_CHECK_DEATH` does not count it as dying. + +`Detail::RunDeathStatement` returns the `DeathResult` itself, for code that +wants to inspect the ending, the code and the text. + +## How it works + +The test binary starts itself again with `--in-process` and the name of the +current test, and a variable that names the statement by its file, its line +and how many times the test has reached that line. The child runs the test up +to that statement, gives the fatal signals their default actions, runs the +statement and ends. Another death statement of the same test is skipped in +the child. The parent reads how the child ended and what the statement wrote +to standard error after it began. + +This works the same on Linux, macOS and Windows: no `fork`, so a test that +started threads before the statement is safe. It also means: + +- The test must reach the statement the same way every time. A statement + inside a condition that depends on the time or on randomness is reported as + not reached. +- What the test does before the statement runs again in the child. Its side + effects, such as files it writes, happen twice; keep them before the + statement idempotent, or put the statement first. +- The child reads no project file, keeps no history, writes no report, and + does not see the filter or shard Bazel gives the parent. +- A statement that never ends keeps the test waiting until the runner's time + limit ends it. +- On Windows `abort()` ends with exit code 3; `KilledBySignal` is for POSIX + systems, where a signal ends the process. + +The amalgamated `catch_amalgamated.hpp` and `.cpp` include death tests. diff --git a/docs/why-catch3.md b/docs/why-catch3.md index 871b6efc..931d41fc 100644 --- a/docs/why-catch3.md +++ b/docs/why-catch3.md @@ -21,6 +21,7 @@ Catch2's runner with [its own](progmasoft-runner.md#top). | Randomness | Catch2's existing behavior is unchanged | A specified SplitMix64 sequence provides deterministic trial seeds and unbiased bounded integer sampling | | Generated values | No change to existing Catch2 generators | Strategies for numbers, text, collections and structures with `Map`, `Filter` and `FlatMap`; shrinking of recorded choices, so every combination shrinks; replay tokens and an example database; state machines, `Classify`/`Cover` statistics, targeted search, and differential and metamorphic oracles | | Mocks | None | [`CATCH3_MOCK_METHOD`, `CATCH3_EXPECT_CALL`](progmasoft-mocking.md#top) and `Sequence`, reporting through the assertion path | +| Death tests | None | [`CATCH3_CHECK_DEATH`, `CATCH3_CHECK_DEATH_THAT`, `CATCH3_CHECK_EXIT`](progmasoft-death-tests.md#top): the statement runs in a child process, on every platform | | Build identity | One library: the `Catch3` CMake package with `Catch3::Catch3` and `Catch3::Catch3WithMain`, `//:catch3` in Bazel, `catch3` in Meson and pkg-config | The same library | | Source terms | Catch2-originated source retains its upstream BSL-1.0 terms | Progmasoft-authored additions state their own SPDX license in each file | diff --git a/extras/catch_amalgamated.cpp b/extras/catch_amalgamated.cpp index e09c8a56..8f59a2c8 100644 --- a/extras/catch_amalgamated.cpp +++ b/extras/catch_amalgamated.cpp @@ -8915,6 +8915,265 @@ namespace Catch { // Copyright (c) 2026 Progmasoft. // SPDX-License-Identifier: LGPL-3.0-or-later + +#include <cctype> +#include <csignal> +#include <cstdio> +#include <cstdlib> +#include <exception> +#include <map> +#include <string_view> +#include <utility> + +namespace Progmasoft::Catch3 { + + namespace { + + /// The variable that turns a run of the test binary into the child of + /// one death statement; its value names the statement. + constexpr const char* kStatementVariable = "CATCH3_DEATH_STATEMENT"; + + // What the child writes to standard error around the statement. Each + // starts a line, so text the statement wrote before cannot join it. + constexpr std::string_view kReached = "\n[catch3-death:reached]\n"; + constexpr std::string_view kReturned = "\n[catch3-death:returned]\n"; + constexpr std::string_view kThrew = "\n[catch3-death:threw]\n"; + + /// The status the child ends with when the statement returned or + /// threw; the markers above, not this number, say what happened. + constexpr int kChildSurvived = 0; + + /// Names each death statement of the current test by its place and + /// by how often the test has reached that place, so that a statement + /// in a loop or a section gets the same name in the child as in the + /// parent. + std::string NameStatement( const char* file, int line ) { + static thread_local std::string test; + static thread_local std::map<std::string, unsigned> seen; + const std::string current = + ::Catch::getResultCapture().getCurrentTestName(); + if ( current != test ) { + test = current; + seen.clear(); + } + std::string place = std::string( file ) + ":" + std::to_string( line ); + const unsigned count = ++seen[place]; + return place + "#" + std::to_string( count ); + } + + /// A test spec that matches exactly this name: every character + /// that is not a letter or a digit is escaped with a backslash. + std::string ExactSpec( const std::string& name ) { + std::string spec; + spec.reserve( name.size() * 2 ); + for ( const char character : name ) { + if ( !std::isalnum( static_cast<unsigned char>( character ) ) ) { + spec += '\\'; + } + spec += character; + } + return spec; + } + + void WriteError( std::string_view text ) { + std::fwrite( text.data(), 1, text.size(), stderr ); + std::fflush( stderr ); + } + + /// Gives the fatal signals back their default actions. The test + /// runner reports a crash from a handler of its own; in the child the + /// statement must end the process the way it would outside a test, + /// and nothing may write after it. + void RestoreDefaultEndings() { +#if defined( _WIN32 ) +# if defined( _MSC_VER ) + // abort() ends the process without a dialog or a report. + _set_abort_behavior( 0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT ); +# endif +#else + for ( const int signal : { SIGABRT, SIGBUS, SIGFPE, SIGILL, + SIGINT, SIGSEGV, SIGTERM } ) { + std::signal( signal, SIG_DFL ); + } +#endif + } + + /// The child's side: run the statement and end the process. + [[noreturn]] void RunInChild( const std::function<void()>& statement ) { + RestoreDefaultEndings(); + std::fflush( stdout ); + WriteError( kReached ); + try { + statement(); + } catch ( ... ) { + WriteError( kThrew ); + std::_Exit( kChildSurvived ); + } + WriteError( kReturned ); + std::_Exit( kChildSurvived ); + } + + DeathResult::Ending EndingOf( const Runner::ExitStatus& status ) { + switch ( status.kind ) { + case Runner::ExitStatus::Kind::kSignaled: + return DeathResult::Ending::kSignaled; + case Runner::ExitStatus::Kind::kException: + return DeathResult::Ending::kException; + case Runner::ExitStatus::Kind::kExited: + break; + } + return DeathResult::Ending::kExited; + } + + /// The parent's side: read what the child wrote and how it ended. + DeathResult Interpret( const Runner::CapturedRun& run ) { + DeathResult result; + const std::size_t reached = run.errors.find( kReached ); + if ( reached == std::string::npos ) { + result.kind = DeathResult::Kind::kNotReached; + result.errors = run.errors; + return result; + } + std::string after = run.errors.substr( reached + kReached.size() ); + const auto endsWith = [&after]( std::string_view marker ) { + return after.size() >= marker.size() && + std::string_view( after ).substr( + after.size() - marker.size() ) == marker; + }; + if ( endsWith( kReturned ) ) { + result.kind = DeathResult::Kind::kReturned; + after.resize( after.size() - kReturned.size() ); + } else if ( endsWith( kThrew ) ) { + result.kind = DeathResult::Kind::kThrew; + after.resize( after.size() - kThrew.size() ); + } else { + result.kind = DeathResult::Kind::kEnded; + result.ending = EndingOf( run.status ); + result.code = run.status.code; + } + result.errors = std::move( after ); + return result; + } + + } // namespace + + bool DeathResult::Died() const noexcept { + if ( kind == Kind::kSkipped ) { + return true; + } + return kind == Kind::kEnded && + !( ending == Ending::kExited && code == 0 ); + } + + std::string DeathResult::Describe() const { + switch ( kind ) { + case Kind::kEnded: { + Runner::ExitStatus status; + status.kind = ending == Ending::kSignaled + ? Runner::ExitStatus::Kind::kSignaled + : ending == Ending::kException + ? Runner::ExitStatus::Kind::kException + : Runner::ExitStatus::Kind::kExited; + status.code = code; + return "the statement ended the process with " + + status.Describe() + + ( errors.empty() ? std::string{} + : "; it wrote to standard error:\n" + + errors ); + } + case Kind::kReturned: + return "the statement returned instead of ending the process" + + ( errors.empty() ? std::string{} + : "; it wrote to standard error:\n" + + errors ); + case Kind::kThrew: + return "the statement threw an exception instead of ending the " + "process"; + case Kind::kNotReached: + return "the child process ran the test but did not reach the " + "statement; the test must reach it the same way every " + "time" + + ( errors.empty() ? std::string{} + : "; standard error:\n" + errors ); + case Kind::kNotStarted: + return "the child process could not be started: " + errors; + case Kind::kSkipped: + return "not run in the child of another death statement"; + } + return {}; + } + + bool ExitedWith::operator()( const DeathResult& result ) const { + return result.kind == DeathResult::Kind::kEnded && + result.ending == DeathResult::Ending::kExited && + result.code == code; + } + + std::string ExitedWith::Describe() const { + return "exit code " + std::to_string( code ); + } + + bool KilledBySignal::operator()( const DeathResult& result ) const { + return result.kind == DeathResult::Kind::kEnded && + result.ending == DeathResult::Ending::kSignaled && + result.code == signal; + } + + std::string KilledBySignal::Describe() const { + return "signal " + std::to_string( signal ); + } + + namespace Detail { + + DeathResult RunDeathStatement( const char* file, + int line, + const std::function<void()>& statement ) { + const std::string name = NameStatement( file, line ); + if ( Runner::HasEnvironment( kStatementVariable ) ) { + if ( Runner::ReadEnvironment( kStatementVariable ) == name ) { + RunInChild( statement ); + } + DeathResult skipped; + skipped.kind = DeathResult::Kind::kSkipped; + return skipped; + } + + Runner::ChildOptions child; + child.arguments = { + Runner::CurrentExecutable( nullptr ).string(), + "--in-process", + "--no-config", + "--no-history", + "--allow-no-tests", + ExactSpec( ::Catch::getResultCapture().getCurrentTestName() ), + }; + child.environment = { + { kStatementVariable, name }, + // What Bazel hands a test is for the parent only: the child + // writes no report, reads no filter and joins no shard. + { "XML_OUTPUT_FILE", "" }, + { "TESTBRIDGE_TEST_ONLY", "" }, + { "TEST_SHARD_INDEX", "" }, + { "TEST_TOTAL_SHARDS", "" }, + { "TEST_SHARD_STATUS_FILE", "" }, + { "TEST_PREMATURE_EXIT_FILE", "" }, + }; + auto run = Runner::RunAndCapture( child ); + if ( !run ) { + DeathResult failed; + failed.kind = DeathResult::Kind::kNotStarted; + failed.errors = run.GetError().Message(); + return failed; + } + return Interpret( *run ); + } + + } // namespace Detail + +} // namespace Progmasoft::Catch3 +// Copyright (c) 2026 Progmasoft. +// SPDX-License-Identifier: LGPL-3.0-or-later + #include <algorithm> #include <cstdio> #include <cstdlib> diff --git a/extras/catch_amalgamated.hpp b/extras/catch_amalgamated.hpp index 6889c53e..1817b86b 100644 --- a/extras/catch_amalgamated.hpp +++ b/extras/catch_amalgamated.hpp @@ -12759,4 +12759,154 @@ namespace Progmasoft::Catch3 /// have to match: values, Catch matchers, `Any` or `Where`, or nothing to /// accept any. Failures of the expectation point at this line. #define CATCH3_EXPECT_CALL(mock) (mock).Expect(CATCH_INTERNAL_LINEINFO) +// Copyright (c) 2026 Progmasoft. +// SPDX-License-Identifier: LGPL-3.0-or-later + + +#include <cstdint> +#include <functional> +#include <string> + +namespace Progmasoft::Catch3 { + + /// How the statement of a death test ended, as the parent saw it. + struct DeathResult final { + enum class Kind : std::uint8_t { + /// The process ended inside the statement; `status` says how. + kEnded, + /// The statement returned, so the process did not die. + kReturned, + /// The statement threw, so the process did not die. + kThrew, + /// The child ran the test but never reached the statement. + kNotReached, + /// The child could not be started; `errors` says why. + kNotStarted, + /// In the child of another death test: not run. + kSkipped, + }; + + /// How a process ended. + enum class Ending : std::uint8_t { + /// It called exit or returned from main; `code` is the status. + kExited, + /// A signal ended it (POSIX); `code` is the signal number. + kSignaled, + /// A structured exception ended it (Windows); `code` is the + /// exception code. + kException, + }; + + Kind kind = Kind::kNotStarted; + Ending ending = Ending::kExited; + std::int64_t code = 0; + /// What the statement wrote to standard error. + std::string errors; + + /// Whether the process died in the statement: it exited with a + /// status other than 0, or a signal or an exception ended it. + [[nodiscard]] bool Died() const noexcept; + + /// A sentence for the report, such as "the statement ended the + /// process with signal 6 (SIGABRT)". + [[nodiscard]] std::string Describe() const; + }; + + /// Expects the process to exit with `code`. + struct ExitedWith final { + std::int64_t code; + + [[nodiscard]] bool operator()( const DeathResult& result ) const; + [[nodiscard]] std::string Describe() const; + }; + + /// Expects a signal to end the process (POSIX), such as SIGABRT. + struct KilledBySignal final { + int signal; + + [[nodiscard]] bool operator()( const DeathResult& result ) const; + [[nodiscard]] std::string Describe() const; + }; + + namespace Detail { + /// Runs `statement` in a child: the test binary runs the current test + /// again in a process of its own and stops it at this statement. In + /// that child, this runs the statement and ends the process; another + /// death statement of the same test is skipped there. + [[nodiscard]] DeathResult RunDeathStatement( + const char* file, + int line, + const std::function<void()>& statement ); + } // namespace Detail + +} // namespace Progmasoft::Catch3 + +#define CATCH3_INTERNAL_DEATH( result, ... ) \ + const ::Progmasoft::Catch3::DeathResult result = \ + ::Progmasoft::Catch3::Detail::RunDeathStatement( \ + __FILE__, __LINE__, [&]() { __VA_ARGS__; } ); \ + INFO( result.Describe() ) + +/// Checks that `statement` ends the process: it exits with a status other +/// than 0, or a signal or an exception ends it. The statement runs in a child +/// process, so the test goes on either way. +#define CATCH3_CHECK_DEATH( ... ) \ + do { \ + CATCH3_INTERNAL_DEATH( catch3Death, __VA_ARGS__ ); \ + CHECK( catch3Death.Died() ); \ + } while ( false ) + +/// As CATCH3_CHECK_DEATH, but ends the test case on failure. +#define CATCH3_REQUIRE_DEATH( ... ) \ + do { \ + CATCH3_INTERNAL_DEATH( catch3Death, __VA_ARGS__ ); \ + REQUIRE( catch3Death.Died() ); \ + } while ( false ) + +/// As CATCH3_CHECK_DEATH, and what the statement wrote to standard error +/// matches `matcher`, such as ContainsSubstring( "out of range" ). +#define CATCH3_CHECK_DEATH_THAT( statement, matcher ) \ + do { \ + CATCH3_INTERNAL_DEATH( catch3Death, statement ); \ + CHECK( catch3Death.Died() ); \ + if ( catch3Death.kind != \ + ::Progmasoft::Catch3::DeathResult::Kind::kSkipped ) { \ + CHECK_THAT( catch3Death.errors, matcher ); \ + } \ + } while ( false ) + +/// As CATCH3_CHECK_DEATH_THAT, but ends the test case on failure. +#define CATCH3_REQUIRE_DEATH_THAT( statement, matcher ) \ + do { \ + CATCH3_INTERNAL_DEATH( catch3Death, statement ); \ + REQUIRE( catch3Death.Died() ); \ + if ( catch3Death.kind != \ + ::Progmasoft::Catch3::DeathResult::Kind::kSkipped ) { \ + REQUIRE_THAT( catch3Death.errors, matcher ); \ + } \ + } while ( false ) + +/// Checks how `statement` ends the process: `ending` is ExitedWith( code ) +/// or KilledBySignal( signal ), or any callable that takes a DeathResult. +/// Unlike CATCH3_CHECK_DEATH, an exit with status 0 can be expected. +#define CATCH3_CHECK_EXIT( statement, ending ) \ + do { \ + CATCH3_INTERNAL_DEATH( catch3Death, statement ); \ + CHECK( ( catch3Death.kind == \ + ::Progmasoft::Catch3::DeathResult::Kind::kSkipped || \ + ( catch3Death.kind == \ + ::Progmasoft::Catch3::DeathResult::Kind::kEnded && \ + ( ending )( catch3Death ) ) ) ); \ + } while ( false ) + +/// As CATCH3_CHECK_EXIT, but ends the test case on failure. +#define CATCH3_REQUIRE_EXIT( statement, ending ) \ + do { \ + CATCH3_INTERNAL_DEATH( catch3Death, statement ); \ + REQUIRE( ( catch3Death.kind == \ + ::Progmasoft::Catch3::DeathResult::Kind::kSkipped || \ + ( catch3Death.kind == \ + ::Progmasoft::Catch3::DeathResult::Kind::kEnded && \ + ( ending )( catch3Death ) ) ) ); \ + } while ( false ) #endif // CATCH_AMALGAMATED_HPP_INCLUDED diff --git a/premake5.lua b/premake5.lua index 9404eba8..374c7800 100644 --- a/premake5.lua +++ b/premake5.lua @@ -51,6 +51,7 @@ project "Catch3" "src/Progmasoft/StrategyContext.cpp", "src/Progmasoft/PropertyEngine.cpp", "src/Progmasoft/Snapshot.cpp", + "src/Progmasoft/Death.cpp", "src/Progmasoft/Catch3/**.hpp", "src/Progmasoft/Catch3.hpp", path.join(generated_include, "Progmasoft", "Catch3", "UserConfig.hpp"), @@ -97,6 +98,7 @@ project "ProgmasoftPropertyTests" "tests/Progmasoft/RunnerCoverage.tests.cpp", "tests/Progmasoft/RunnerOutput.tests.cpp", "tests/Progmasoft/Snapshot.tests.cpp", + "tests/Progmasoft/Death.tests.cpp", "tests/Progmasoft/Stateful.tests.cpp", "tests/Progmasoft/Strategy.tests.cpp", "src/Progmasoft/**.hpp", diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index f0de95b4..2e96ab4a 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -345,6 +345,7 @@ set(PROGMASOFT_RUNNER_FILES # Property testing and snapshots. set(PROGMASOFT_LIBRARY_FILES "${CATCH_DIR}/src/Progmasoft/ChoiceShrinker.cpp" + "${CATCH_DIR}/src/Progmasoft/Death.cpp" "${CATCH_DIR}/src/Progmasoft/Mock.cpp" "${CATCH_DIR}/src/Progmasoft/StrategyContext.cpp" "${CATCH_DIR}/src/Progmasoft/PropertyEngine.cpp" diff --git a/src/Progmasoft/Catch3.hpp b/src/Progmasoft/Catch3.hpp index 0c5227c0..6117107b 100644 --- a/src/Progmasoft/Catch3.hpp +++ b/src/Progmasoft/Catch3.hpp @@ -20,6 +20,7 @@ #include <Progmasoft/Catch3/Relations.hpp> #include <Progmasoft/Catch3/Results.hpp> #include <Progmasoft/Catch3/Snapshot.hpp> +#include <Progmasoft/Catch3/Death.hpp> #include <Progmasoft/Catch3/Stateful.hpp> #include <Progmasoft/Catch3/Strategy/ChoiceSource.hpp> #include <Progmasoft/Catch3/Strategy/Containers.hpp> diff --git a/src/Progmasoft/Catch3/Death.hpp b/src/Progmasoft/Catch3/Death.hpp new file mode 100644 index 00000000..56faa59e --- /dev/null +++ b/src/Progmasoft/Catch3/Death.hpp @@ -0,0 +1,154 @@ +// Copyright (c) 2026 Progmasoft. +// SPDX-License-Identifier: LGPL-3.0-or-later +#pragma once + +#include <Progmasoft/Catch3/Message.hpp> +#include <Progmasoft/Catch3/TestMacros.hpp> +#include <Progmasoft/Catch3/Matchers/Matchers.hpp> + +#include <cstdint> +#include <functional> +#include <string> + +namespace Progmasoft::Catch3 { + + /// How the statement of a death test ended, as the parent saw it. + struct DeathResult final { + enum class Kind : std::uint8_t { + /// The process ended inside the statement; `status` says how. + kEnded, + /// The statement returned, so the process did not die. + kReturned, + /// The statement threw, so the process did not die. + kThrew, + /// The child ran the test but never reached the statement. + kNotReached, + /// The child could not be started; `errors` says why. + kNotStarted, + /// In the child of another death test: not run. + kSkipped, + }; + + /// How a process ended. + enum class Ending : std::uint8_t { + /// It called exit or returned from main; `code` is the status. + kExited, + /// A signal ended it (POSIX); `code` is the signal number. + kSignaled, + /// A structured exception ended it (Windows); `code` is the + /// exception code. + kException, + }; + + Kind kind = Kind::kNotStarted; + Ending ending = Ending::kExited; + std::int64_t code = 0; + /// What the statement wrote to standard error. + std::string errors; + + /// Whether the process died in the statement: it exited with a + /// status other than 0, or a signal or an exception ended it. + [[nodiscard]] bool Died() const noexcept; + + /// A sentence for the report, such as "the statement ended the + /// process with signal 6 (SIGABRT)". + [[nodiscard]] std::string Describe() const; + }; + + /// Expects the process to exit with `code`. + struct ExitedWith final { + std::int64_t code; + + [[nodiscard]] bool operator()( const DeathResult& result ) const; + [[nodiscard]] std::string Describe() const; + }; + + /// Expects a signal to end the process (POSIX), such as SIGABRT. + struct KilledBySignal final { + int signal; + + [[nodiscard]] bool operator()( const DeathResult& result ) const; + [[nodiscard]] std::string Describe() const; + }; + + namespace Detail { + /// Runs `statement` in a child: the test binary runs the current test + /// again in a process of its own and stops it at this statement. In + /// that child, this runs the statement and ends the process; another + /// death statement of the same test is skipped there. + [[nodiscard]] DeathResult RunDeathStatement( + const char* file, + int line, + const std::function<void()>& statement ); + } // namespace Detail + +} // namespace Progmasoft::Catch3 + +#define CATCH3_INTERNAL_DEATH( result, ... ) \ + const ::Progmasoft::Catch3::DeathResult result = \ + ::Progmasoft::Catch3::Detail::RunDeathStatement( \ + __FILE__, __LINE__, [&]() { __VA_ARGS__; } ); \ + INFO( result.Describe() ) + +/// Checks that `statement` ends the process: it exits with a status other +/// than 0, or a signal or an exception ends it. The statement runs in a child +/// process, so the test goes on either way. +#define CATCH3_CHECK_DEATH( ... ) \ + do { \ + CATCH3_INTERNAL_DEATH( catch3Death, __VA_ARGS__ ); \ + CHECK( catch3Death.Died() ); \ + } while ( false ) + +/// As CATCH3_CHECK_DEATH, but ends the test case on failure. +#define CATCH3_REQUIRE_DEATH( ... ) \ + do { \ + CATCH3_INTERNAL_DEATH( catch3Death, __VA_ARGS__ ); \ + REQUIRE( catch3Death.Died() ); \ + } while ( false ) + +/// As CATCH3_CHECK_DEATH, and what the statement wrote to standard error +/// matches `matcher`, such as ContainsSubstring( "out of range" ). +#define CATCH3_CHECK_DEATH_THAT( statement, matcher ) \ + do { \ + CATCH3_INTERNAL_DEATH( catch3Death, statement ); \ + CHECK( catch3Death.Died() ); \ + if ( catch3Death.kind != \ + ::Progmasoft::Catch3::DeathResult::Kind::kSkipped ) { \ + CHECK_THAT( catch3Death.errors, matcher ); \ + } \ + } while ( false ) + +/// As CATCH3_CHECK_DEATH_THAT, but ends the test case on failure. +#define CATCH3_REQUIRE_DEATH_THAT( statement, matcher ) \ + do { \ + CATCH3_INTERNAL_DEATH( catch3Death, statement ); \ + REQUIRE( catch3Death.Died() ); \ + if ( catch3Death.kind != \ + ::Progmasoft::Catch3::DeathResult::Kind::kSkipped ) { \ + REQUIRE_THAT( catch3Death.errors, matcher ); \ + } \ + } while ( false ) + +/// Checks how `statement` ends the process: `ending` is ExitedWith( code ) +/// or KilledBySignal( signal ), or any callable that takes a DeathResult. +/// Unlike CATCH3_CHECK_DEATH, an exit with status 0 can be expected. +#define CATCH3_CHECK_EXIT( statement, ending ) \ + do { \ + CATCH3_INTERNAL_DEATH( catch3Death, statement ); \ + CHECK( ( catch3Death.kind == \ + ::Progmasoft::Catch3::DeathResult::Kind::kSkipped || \ + ( catch3Death.kind == \ + ::Progmasoft::Catch3::DeathResult::Kind::kEnded && \ + ( ending )( catch3Death ) ) ) ); \ + } while ( false ) + +/// As CATCH3_CHECK_EXIT, but ends the test case on failure. +#define CATCH3_REQUIRE_EXIT( statement, ending ) \ + do { \ + CATCH3_INTERNAL_DEATH( catch3Death, statement ); \ + REQUIRE( ( catch3Death.kind == \ + ::Progmasoft::Catch3::DeathResult::Kind::kSkipped || \ + ( catch3Death.kind == \ + ::Progmasoft::Catch3::DeathResult::Kind::kEnded && \ + ( ending )( catch3Death ) ) ) ); \ + } while ( false ) diff --git a/src/Progmasoft/Catch3/meson.build b/src/Progmasoft/Catch3/meson.build index 4bbab28e..fab40a6b 100644 --- a/src/Progmasoft/Catch3/meson.build +++ b/src/Progmasoft/Catch3/meson.build @@ -311,6 +311,7 @@ runner_sources = files( # Property testing and snapshots. property_sources = files( '../ChoiceShrinker.cpp', + '../Death.cpp', '../StrategyContext.cpp', '../Mock.cpp', '../PropertyEngine.cpp', diff --git a/src/Progmasoft/Death.cpp b/src/Progmasoft/Death.cpp new file mode 100644 index 00000000..deb34a59 --- /dev/null +++ b/src/Progmasoft/Death.cpp @@ -0,0 +1,262 @@ +// Copyright (c) 2026 Progmasoft. +// SPDX-License-Identifier: LGPL-3.0-or-later +#include <Progmasoft/Catch3/Death.hpp> + +#include <Progmasoft/Catch3/Interfaces/IResultCapture.hpp> +#include <Progmasoft/Runner/Process.hpp> + +#include <cctype> +#include <csignal> +#include <cstdio> +#include <cstdlib> +#include <exception> +#include <map> +#include <string_view> +#include <utility> + +namespace Progmasoft::Catch3 { + + namespace { + + /// The variable that turns a run of the test binary into the child of + /// one death statement; its value names the statement. + constexpr const char* kStatementVariable = "CATCH3_DEATH_STATEMENT"; + + // What the child writes to standard error around the statement. Each + // starts a line, so text the statement wrote before cannot join it. + constexpr std::string_view kReached = "\n[catch3-death:reached]\n"; + constexpr std::string_view kReturned = "\n[catch3-death:returned]\n"; + constexpr std::string_view kThrew = "\n[catch3-death:threw]\n"; + + /// The status the child ends with when the statement returned or + /// threw; the markers above, not this number, say what happened. + constexpr int kChildSurvived = 0; + + /// Names each death statement of the current test by its place and + /// by how often the test has reached that place, so that a statement + /// in a loop or a section gets the same name in the child as in the + /// parent. + std::string NameStatement( const char* file, int line ) { + static thread_local std::string test; + static thread_local std::map<std::string, unsigned> seen; + const std::string current = + ::Catch::getResultCapture().getCurrentTestName(); + if ( current != test ) { + test = current; + seen.clear(); + } + std::string place = std::string( file ) + ":" + std::to_string( line ); + const unsigned count = ++seen[place]; + return place + "#" + std::to_string( count ); + } + + /// A test spec that matches exactly this name: every character + /// that is not a letter or a digit is escaped with a backslash. + std::string ExactSpec( const std::string& name ) { + std::string spec; + spec.reserve( name.size() * 2 ); + for ( const char character : name ) { + if ( !std::isalnum( static_cast<unsigned char>( character ) ) ) { + spec += '\\'; + } + spec += character; + } + return spec; + } + + void WriteError( std::string_view text ) { + std::fwrite( text.data(), 1, text.size(), stderr ); + std::fflush( stderr ); + } + + /// Gives the fatal signals back their default actions. The test + /// runner reports a crash from a handler of its own; in the child the + /// statement must end the process the way it would outside a test, + /// and nothing may write after it. + void RestoreDefaultEndings() { +#if defined( _WIN32 ) +# if defined( _MSC_VER ) + // abort() ends the process without a dialog or a report. + _set_abort_behavior( 0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT ); +# endif +#else + for ( const int signal : { SIGABRT, SIGBUS, SIGFPE, SIGILL, + SIGINT, SIGSEGV, SIGTERM } ) { + std::signal( signal, SIG_DFL ); + } +#endif + } + + /// The child's side: run the statement and end the process. + [[noreturn]] void RunInChild( const std::function<void()>& statement ) { + RestoreDefaultEndings(); + std::fflush( stdout ); + WriteError( kReached ); + try { + statement(); + } catch ( ... ) { + WriteError( kThrew ); + std::_Exit( kChildSurvived ); + } + WriteError( kReturned ); + std::_Exit( kChildSurvived ); + } + + DeathResult::Ending EndingOf( const Runner::ExitStatus& status ) { + switch ( status.kind ) { + case Runner::ExitStatus::Kind::kSignaled: + return DeathResult::Ending::kSignaled; + case Runner::ExitStatus::Kind::kException: + return DeathResult::Ending::kException; + case Runner::ExitStatus::Kind::kExited: + break; + } + return DeathResult::Ending::kExited; + } + + /// The parent's side: read what the child wrote and how it ended. + DeathResult Interpret( const Runner::CapturedRun& run ) { + DeathResult result; + const std::size_t reached = run.errors.find( kReached ); + if ( reached == std::string::npos ) { + result.kind = DeathResult::Kind::kNotReached; + result.errors = run.errors; + return result; + } + std::string after = run.errors.substr( reached + kReached.size() ); + const auto endsWith = [&after]( std::string_view marker ) { + return after.size() >= marker.size() && + std::string_view( after ).substr( + after.size() - marker.size() ) == marker; + }; + if ( endsWith( kReturned ) ) { + result.kind = DeathResult::Kind::kReturned; + after.resize( after.size() - kReturned.size() ); + } else if ( endsWith( kThrew ) ) { + result.kind = DeathResult::Kind::kThrew; + after.resize( after.size() - kThrew.size() ); + } else { + result.kind = DeathResult::Kind::kEnded; + result.ending = EndingOf( run.status ); + result.code = run.status.code; + } + result.errors = std::move( after ); + return result; + } + + } // namespace + + bool DeathResult::Died() const noexcept { + if ( kind == Kind::kSkipped ) { + return true; + } + return kind == Kind::kEnded && + !( ending == Ending::kExited && code == 0 ); + } + + std::string DeathResult::Describe() const { + switch ( kind ) { + case Kind::kEnded: { + Runner::ExitStatus status; + status.kind = ending == Ending::kSignaled + ? Runner::ExitStatus::Kind::kSignaled + : ending == Ending::kException + ? Runner::ExitStatus::Kind::kException + : Runner::ExitStatus::Kind::kExited; + status.code = code; + return "the statement ended the process with " + + status.Describe() + + ( errors.empty() ? std::string{} + : "; it wrote to standard error:\n" + + errors ); + } + case Kind::kReturned: + return "the statement returned instead of ending the process" + + ( errors.empty() ? std::string{} + : "; it wrote to standard error:\n" + + errors ); + case Kind::kThrew: + return "the statement threw an exception instead of ending the " + "process"; + case Kind::kNotReached: + return "the child process ran the test but did not reach the " + "statement; the test must reach it the same way every " + "time" + + ( errors.empty() ? std::string{} + : "; standard error:\n" + errors ); + case Kind::kNotStarted: + return "the child process could not be started: " + errors; + case Kind::kSkipped: + return "not run in the child of another death statement"; + } + return {}; + } + + bool ExitedWith::operator()( const DeathResult& result ) const { + return result.kind == DeathResult::Kind::kEnded && + result.ending == DeathResult::Ending::kExited && + result.code == code; + } + + std::string ExitedWith::Describe() const { + return "exit code " + std::to_string( code ); + } + + bool KilledBySignal::operator()( const DeathResult& result ) const { + return result.kind == DeathResult::Kind::kEnded && + result.ending == DeathResult::Ending::kSignaled && + result.code == signal; + } + + std::string KilledBySignal::Describe() const { + return "signal " + std::to_string( signal ); + } + + namespace Detail { + + DeathResult RunDeathStatement( const char* file, + int line, + const std::function<void()>& statement ) { + const std::string name = NameStatement( file, line ); + if ( Runner::HasEnvironment( kStatementVariable ) ) { + if ( Runner::ReadEnvironment( kStatementVariable ) == name ) { + RunInChild( statement ); + } + DeathResult skipped; + skipped.kind = DeathResult::Kind::kSkipped; + return skipped; + } + + Runner::ChildOptions child; + child.arguments = { + Runner::CurrentExecutable( nullptr ).string(), + "--in-process", + "--no-config", + "--no-history", + "--allow-no-tests", + ExactSpec( ::Catch::getResultCapture().getCurrentTestName() ), + }; + child.environment = { + { kStatementVariable, name }, + // What Bazel hands a test is for the parent only: the child + // writes no report, reads no filter and joins no shard. + { "XML_OUTPUT_FILE", "" }, + { "TESTBRIDGE_TEST_ONLY", "" }, + { "TEST_SHARD_INDEX", "" }, + { "TEST_TOTAL_SHARDS", "" }, + { "TEST_SHARD_STATUS_FILE", "" }, + { "TEST_PREMATURE_EXIT_FILE", "" }, + }; + auto run = Runner::RunAndCapture( child ); + if ( !run ) { + DeathResult failed; + failed.kind = DeathResult::Kind::kNotStarted; + failed.errors = run.GetError().Message(); + return failed; + } + return Interpret( *run ); + } + + } // namespace Detail + +} // namespace Progmasoft::Catch3 diff --git a/src/Progmasoft/meson.build b/src/Progmasoft/meson.build index 4e47da5c..29ec4c56 100644 --- a/src/Progmasoft/meson.build +++ b/src/Progmasoft/meson.build @@ -17,6 +17,7 @@ if get_option('install') install_headers('Catch3/Version.hpp', subdir: 'Progmasoft/Catch3') install_headers('Catch3/Mock.hpp', subdir: 'Progmasoft/Catch3') install_headers('Catch3/Snapshot.hpp', subdir: 'Progmasoft/Catch3') + install_headers('Catch3/Death.hpp', subdir: 'Progmasoft/Catch3') install_headers('Catch3/XmlWriter.hpp', subdir: 'Progmasoft/Catch3') install_headers('Catch3/ForAll.hpp', subdir: 'Progmasoft/Catch3') install_headers('Catch3/Relations.hpp', subdir: 'Progmasoft/Catch3') diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 32d1ce57..478e5a24 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -169,6 +169,7 @@ add_executable(ProgmasoftSelfTest Progmasoft/RunnerCoverage.tests.cpp Progmasoft/RunnerOutput.tests.cpp Progmasoft/Snapshot.tests.cpp + Progmasoft/Death.tests.cpp Progmasoft/Stateful.tests.cpp Progmasoft/Strategy.tests.cpp ) diff --git a/tests/Progmasoft/BUILD.bazel b/tests/Progmasoft/BUILD.bazel index b95c5b44..fc1ff536 100644 --- a/tests/Progmasoft/BUILD.bazel +++ b/tests/Progmasoft/BUILD.bazel @@ -23,6 +23,7 @@ cc_test( "RunnerCoverage.tests.cpp", "RunnerOutput.tests.cpp", "Snapshot.tests.cpp", + "Death.tests.cpp", "Stateful.tests.cpp", "Strategy.tests.cpp", ], diff --git a/tests/Progmasoft/Death.tests.cpp b/tests/Progmasoft/Death.tests.cpp new file mode 100644 index 00000000..a410bb3a --- /dev/null +++ b/tests/Progmasoft/Death.tests.cpp @@ -0,0 +1,89 @@ +// Copyright (c) 2026 Progmasoft. +// SPDX-License-Identifier: LGPL-3.0-or-later +#include <Progmasoft/Catch3/Death.hpp> +#include <Progmasoft/Catch3/Matchers/String.hpp> +#include <Progmasoft/Catch3/TestMacros.hpp> + +#include <csignal> +#include <cstdio> +#include <cstdlib> +#include <stdexcept> + +using Catch::Matchers::ContainsSubstring; +using Progmasoft::Catch3::DeathResult; +using Progmasoft::Catch3::ExitedWith; +using Progmasoft::Catch3::KilledBySignal; +using Progmasoft::Catch3::Detail::RunDeathStatement; + +namespace { + [[noreturn]] void FailWithMessage( const char* message ) { + std::fputs( message, stderr ); + std::abort(); + } + + int Checked( int value ) { + if ( value < 0 ) { + std::fputs( "negative value\n", stderr ); + std::exit( 3 ); + } + return value; + } +} // namespace + +TEST_CASE( "A statement that aborts dies", "[progmasoft][death]" ) { + CATCH3_CHECK_DEATH( std::abort() ); + CATCH3_REQUIRE_DEATH( FailWithMessage( "invariant broken\n" ) ); +} + +TEST_CASE( "What the statement writes to standard error is matched", + "[progmasoft][death]" ) { + CATCH3_CHECK_DEATH_THAT( FailWithMessage( "index 7 out of range\n" ), + ContainsSubstring( "out of range" ) ); +} + +TEST_CASE( "How the process ends can be expected", "[progmasoft][death]" ) { + CATCH3_CHECK_EXIT( static_cast<void>( Checked( -1 ) ), ExitedWith{ 3 } ); + CATCH3_CHECK_EXIT( std::exit( 0 ), ExitedWith{ 0 } ); +#if !defined( _WIN32 ) + CATCH3_CHECK_EXIT( std::raise( SIGTERM ), KilledBySignal{ SIGTERM } ); +#endif +} + +TEST_CASE( "A statement that does not end the process is reported", + "[progmasoft][death]" ) { + int value = 0; + const DeathResult returned = + RunDeathStatement( __FILE__, __LINE__, [&] { value = Checked( 5 ); } ); + CHECK( returned.kind == DeathResult::Kind::kReturned ); + CHECK_FALSE( returned.Died() ); + CHECK_THAT( returned.Describe(), ContainsSubstring( "returned" ) ); + // The statement ran in the child; this process is untouched. + CHECK( value == 0 ); + + const DeathResult threw = RunDeathStatement( + __FILE__, __LINE__, [] { throw std::runtime_error( "boom" ); } ); + CHECK( threw.kind == DeathResult::Kind::kThrew ); + CHECK_FALSE( threw.Died() ); + + const DeathResult clean = + RunDeathStatement( __FILE__, __LINE__, [] { std::exit( 0 ); } ); + CHECK( clean.kind == DeathResult::Kind::kEnded ); + CHECK_FALSE( clean.Died() ); + CHECK( ExitedWith{ 0 }( clean ) ); +} + +TEST_CASE( "Death statements in a loop are told apart", "[progmasoft][death]" ) { + for ( int code = 1; code <= 3; ++code ) { + CATCH3_CHECK_EXIT( std::exit( code ), ExitedWith{ code } ); + } +} + +TEST_CASE( "Death statements in sections run in their section", + "[progmasoft][death]" ) { + SECTION( "the first" ) { + CATCH3_CHECK_EXIT( std::exit( 4 ), ExitedWith{ 4 } ); + } + SECTION( "the second" ) { + CATCH3_CHECK_EXIT( std::exit( 5 ), ExitedWith{ 5 } ); + } +} diff --git a/tests/meson.build b/tests/meson.build index f4953a19..6964422b 100644 --- a/tests/meson.build +++ b/tests/meson.build @@ -87,6 +87,7 @@ progmasoft_property_tests = executable( 'Progmasoft/RunnerCoverage.tests.cpp', 'Progmasoft/RunnerOutput.tests.cpp', 'Progmasoft/Snapshot.tests.cpp', + 'Progmasoft/Death.tests.cpp', 'Progmasoft/Stateful.tests.cpp', 'Progmasoft/Strategy.tests.cpp', ], diff --git a/tools/Amalgamation.cpp b/tools/Amalgamation.cpp index bb396cb1..8816eee9 100644 --- a/tools/Amalgamation.cpp +++ b/tools/Amalgamation.cpp @@ -176,6 +176,8 @@ namespace Progmasoft::Catch3::Tools // Mocks are Progmasoft's own, and tests use them through // this header. Concatenate(out, source / "Progmasoft/Catch3/Mock.hpp", true); + // Death tests too: they rest on the runner's processes. + Concatenate(out, source / "Progmasoft/Catch3/Death.hpp", true); out += "#endif // CATCH_AMALGAMATED_HPP_INCLUDED\n"; return out; } @@ -219,6 +221,7 @@ namespace Progmasoft::Catch3::Tools } } std::vector<std::string> files{ + "src/Progmasoft/Death.cpp", "src/Progmasoft/Mock.cpp", "src/Progmasoft/Results.cpp", "src/Progmasoft/XmlWriter.cpp" diff --git a/xmake.lua b/xmake.lua index 7e7fdaa4..a6bcdec1 100644 --- a/xmake.lua +++ b/xmake.lua @@ -38,7 +38,8 @@ target("catch3") "src/Progmasoft/Mock.cpp", "src/Progmasoft/StrategyContext.cpp", "src/Progmasoft/PropertyEngine.cpp", - "src/Progmasoft/Snapshot.cpp" + "src/Progmasoft/Snapshot.cpp", + "src/Progmasoft/Death.cpp" ) add_includedirs("src", {public = true}) add_headerfiles("src/(Progmasoft/**.hpp)") @@ -70,6 +71,7 @@ target("ProgmasoftPropertyTests") "tests/Progmasoft/RunnerCoverage.tests.cpp", "tests/Progmasoft/RunnerOutput.tests.cpp", "tests/Progmasoft/Snapshot.tests.cpp", + "tests/Progmasoft/Death.tests.cpp", "tests/Progmasoft/Stateful.tests.cpp", "tests/Progmasoft/Strategy.tests.cpp", "src/Progmasoft/Catch3/Internal/Main.cpp"