Progmasoft Git

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 tests for assertion thread safety

Commit
e849735e11f23ce9ec819e053b107f2ec3c3c1c4
Author
Martin Hořeňovský ·
Parents
d26f763180c0

Files · Download .tar.gz

Changes

 tests/ExtraTests/CMakeLists.txt            | 14 ++++++++++
 tests/ExtraTests/X94-ThreadSafetyTests.cpp | 43 ++++++++++++++++++++++++++++++
 2 files changed, 57 insertions(+)

diff --git a/tests/ExtraTests/CMakeLists.txt b/tests/ExtraTests/CMakeLists.txt
index e7965fa9..94eab4f0 100644
--- a/tests/ExtraTests/CMakeLists.txt
+++ b/tests/ExtraTests/CMakeLists.txt
@@ -566,3 +566,17 @@ set_tests_properties(AmalgamatedFileTest
   PROPERTIES
     PASS_REGULAR_EXPRESSION "All tests passed \\(14 assertions in 3 test cases\\)"
 )
+
+add_executable(ThreadSafetyTests
+  ${TESTS_DIR}/X94-ThreadSafetyTests.cpp
+)
+target_link_libraries(ThreadSafetyTests Catch2_buildall_interface)
+target_compile_definitions(ThreadSafetyTests PUBLIC CATCH_CONFIG_EXPERIMENTAL_THREAD_SAFE_ASSERTIONS)
+add_test(NAME ThreadSafetyTests
+  COMMAND ThreadSafetyTests -r compact "Failed REQUIRE in the main thread is fine"
+)
+set_tests_properties(ThreadSafetyTests
+  PROPERTIES
+    PASS_REGULAR_EXPRESSION "assertions: 801 | 400 passed | 401 failed"
+    RUN_SERIAL ON
+)
diff --git a/tests/ExtraTests/X94-ThreadSafetyTests.cpp b/tests/ExtraTests/X94-ThreadSafetyTests.cpp
new file mode 100644
index 00000000..d391417b
--- /dev/null
+++ b/tests/ExtraTests/X94-ThreadSafetyTests.cpp
@@ -0,0 +1,43 @@
+
+//              Copyright Catch2 Authors
+// Distributed under the Boost Software License, Version 1.0.
+//   (See accompanying file LICENSE.txt or copy at
+//        https://www.boost.org/LICENSE_1_0.txt)
+
+// SPDX-License-Identifier: BSL-1.0
+
+/**\file
+ * Test that assertions and messages are thread-safe.
+ *
+ * This is done by spamming assertions and messages on multiple subthreads.
+ * In manual, this reliably causes segfaults if the test is linked against
+ * a non-thread-safe version of Catch2.
+ *
+ * The CTest test definition should also verify that the final assertion
+ * count is correct.
+ */
+
+#include <catch2/catch_test_macros.hpp>
+
+#include <thread>
+#include <vector>
+
+TEST_CASE( "Failed REQUIRE in the main thread is fine", "[!shouldfail]" ) {
+    std::vector<std::thread> threads;
+    for ( size_t t = 0; t < 4; ++t) {
+        threads.emplace_back( [t]() {
+            CAPTURE(t);
+            for (size_t i = 0; i < 100; ++i) {
+                CAPTURE(i);
+                CHECK( false );
+                CHECK( true );
+            }
+        } );
+    }
+
+    for (auto& t : threads) {
+        t.join();
+    }
+
+    REQUIRE( false );
+}