From 5f806ec53acf8e7127c07961e42f6c1585fe9129 Mon Sep 17 00:00:00 2001 From: Tim Schumacher Date: Wed, 5 Apr 2023 20:23:26 +0200 Subject: [PATCH] LibTest: Add a `TRY_OR_FAIL` macro This macro has the usual `TRY` semantics, but instead of returning the error, it will let the test fail with the formatted error as the fail message. --- Userland/Libraries/LibTest/Macros.h | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Userland/Libraries/LibTest/Macros.h b/Userland/Libraries/LibTest/Macros.h index 7fd1912c3e..dff131fccc 100644 --- a/Userland/Libraries/LibTest/Macros.h +++ b/Userland/Libraries/LibTest/Macros.h @@ -141,3 +141,17 @@ void current_test_case_did_fail(); if (!crash.run()) \ ::Test::current_test_case_did_fail(); \ } while (false) + +#define TRY_OR_FAIL(expression) \ + ({ \ + /* Ignore -Wshadow to allow nesting the macro. */ \ + AK_IGNORE_DIAGNOSTIC("-Wshadow", \ + auto&& _temporary_result = (expression)); \ + static_assert(!::AK::Detail::IsLvalueReference, \ + "Do not return a reference from a fallible expression"); \ + if (_temporary_result.is_error()) [[unlikely]] { \ + FAIL(_temporary_result.release_error()); \ + return; \ + } \ + _temporary_result.release_value(); \ + })