xref: /aosp_15_r20/external/llvm-libc/test/UnitTest/FPExceptMatcher.h (revision 71db0c75aadcf003ffe3238005f61d7618a3fead)
1 //===-- FPExceptMatcher.h ---------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLVM_LIBC_TEST_UNITTEST_FPEXCEPTMATCHER_H
10 #define LLVM_LIBC_TEST_UNITTEST_FPEXCEPTMATCHER_H
11 
12 #include "src/__support/macros/config.h"
13 #include "test/UnitTest/Test.h"
14 #include "test/UnitTest/TestLogger.h"
15 
16 #if LIBC_TEST_HAS_MATCHERS()
17 
18 namespace LIBC_NAMESPACE_DECL {
19 namespace testing {
20 
21 // TODO: Make the matcher match specific exceptions instead of just identifying
22 // that an exception was raised.
23 class FPExceptMatcher : public Matcher<bool> {
24   bool exceptionRaised;
25 
26 public:
27   class FunctionCaller {
28   public:
~FunctionCaller()29     virtual ~FunctionCaller() {}
30     virtual void call() = 0;
31   };
32 
getFunctionCaller(Func func)33   template <typename Func> static FunctionCaller *getFunctionCaller(Func func) {
34     struct Callable : public FunctionCaller {
35       Func f;
36       explicit Callable(Func theFunc) : f(theFunc) {}
37       void call() override { f(); }
38     };
39 
40     return new Callable(func);
41   }
42 
43   // Takes ownership of func.
44   explicit FPExceptMatcher(FunctionCaller *func);
45 
match(bool unused)46   bool match(bool unused) { return exceptionRaised; }
47 
explainError()48   void explainError() override {
49     tlog << "A floating point exception should have been raised but it "
50          << "wasn't\n";
51   }
52 };
53 
54 } // namespace testing
55 } // namespace LIBC_NAMESPACE_DECL
56 
57 #define ASSERT_RAISES_FP_EXCEPT(func)                                          \
58   ASSERT_THAT(                                                                 \
59       true,                                                                    \
60       LIBC_NAMESPACE::testing::FPExceptMatcher(                                \
61           LIBC_NAMESPACE::testing::FPExceptMatcher::getFunctionCaller(func)))
62 
63 #else // !LIBC_TEST_HAS_MATCHERS()
64 
65 #define ASSERT_RAISES_FP_EXCEPT(func) ASSERT_DEATH(func, WITH_SIGNAL(SIGFPE))
66 
67 #endif // LIBC_TEST_HAS_MATCHERS()
68 
69 #endif // LLVM_LIBC_TEST_UNITTEST_FPEXCEPTMATCHER_H
70