1 //===-- ErrnoSetterMatcher.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_ERRNOSETTERMATCHER_H
10 #define LLVM_LIBC_TEST_ERRNOSETTERMATCHER_H
11 
12 #include "utils/UnitTest/Test.h"
13 
14 #include <errno.h>
15 
16 namespace __llvm_libc {
17 namespace testing {
18 
19 namespace internal {
20 
21 extern "C" const char *strerror(int);
22 
23 template <typename T> class ErrnoSetterMatcher : public Matcher<T> {
24   T ExpectedReturn;
25   T ActualReturn;
26   int ExpectedErrno;
27   int ActualErrno;
28 
29 public:
ErrnoSetterMatcher(T ExpectedReturn,int ExpectedErrno)30   ErrnoSetterMatcher(T ExpectedReturn, int ExpectedErrno)
31       : ExpectedReturn(ExpectedReturn), ExpectedErrno(ExpectedErrno) {}
32 
explainError(testutils::StreamWrapper & OS)33   void explainError(testutils::StreamWrapper &OS) override {
34     if (ActualReturn != ExpectedReturn)
35       OS << "Expected return to be " << ExpectedReturn << " but got "
36          << ActualReturn << ".\nExpecte errno to be " << strerror(ExpectedErrno)
37          << " but got " << strerror(ActualErrno) << ".\n";
38     else
39       OS << "Correct value " << ExpectedReturn
40          << " was returned\nBut errno was unexpectely set to "
41          << strerror(ActualErrno) << ".\n";
42   }
43 
match(T Got)44   bool match(T Got) {
45     ActualReturn = Got;
46     ActualErrno = errno;
47     errno = 0;
48     return Got == ExpectedReturn && ActualErrno == ExpectedErrno;
49   }
50 };
51 
52 } // namespace internal
53 
54 namespace ErrnoSetterMatcher {
55 
56 template <typename RetT = int>
57 static internal::ErrnoSetterMatcher<RetT> Succeeds(RetT ExpectedReturn = 0,
58                                                    int ExpectedErrno = 0) {
59   return {ExpectedReturn, ExpectedErrno};
60 }
61 
62 template <typename RetT = int>
63 static internal::ErrnoSetterMatcher<RetT> Fails(int ExpectedErrno,
64                                                 RetT ExpectedReturn = -1) {
65   return {ExpectedReturn, ExpectedErrno};
66 }
67 
68 } // namespace ErrnoSetterMatcher
69 
70 } // namespace testing
71 } // namespace __llvm_libc
72 
73 #endif // LLVM_LIBC_TEST_ERRNOSETTERMATCHER_H
74