xref: /aosp_15_r20/external/perfetto/src/base/test/status_matchers.h (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
1 /*
2  * Copyright (C) 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef SRC_BASE_TEST_STATUS_MATCHERS_H_
18 #define SRC_BASE_TEST_STATUS_MATCHERS_H_
19 
20 #include <ostream>
21 
22 #include "perfetto/base/status.h"
23 #include "test/gtest_and_gmock.h"
24 
25 namespace perfetto::base {
26 namespace gtest_matchers {
27 
28 // Returns a gMock matcher that matches a Status or StatusOr<> which is OK.
29 MATCHER(IsOk, negation ? "is not OK" : "is OK") {
30   return arg.ok();
31 }
32 
33 // Returns a gMock matcher that matches a Status or StatusOr<> which is an
34 // error.
35 MATCHER(IsError, negation ? "is not error" : "is error") {
36   return !arg.ok();
37 }
38 
39 // Macros for testing the results of functions that return base::Status or
40 // base::StatusOr<T> (for any type T).
41 #define EXPECT_OK(expression) \
42   EXPECT_THAT(expression, ::perfetto::base::gtest_matchers::IsOk())
43 #define ASSERT_OK(expression) \
44   ASSERT_THAT(expression, ::perfetto::base::gtest_matchers::IsOk())
45 
46 // Macros for testing the results of function returning base::StatusOr<T>.
47 #define PERFETTO_TEST_STATUS_MATCHER_CONCAT(x, y) x##y
48 #define PERFETTO_TEST_STATUS_MATCHER_CONCAT2(x, y) \
49   PERFETTO_TEST_STATUS_MATCHER_CONCAT(x, y)
50 #define ASSERT_OK_AND_ASSIGN(lhs, rhs)                                     \
51   PERFETTO_TEST_STATUS_MATCHER_CONCAT2(auto status_or, __LINE__) = rhs;    \
52   ASSERT_OK(                                                               \
53       PERFETTO_TEST_STATUS_MATCHER_CONCAT2(status_or, __LINE__).status()); \
54   lhs = std::move(                                                         \
55       PERFETTO_TEST_STATUS_MATCHER_CONCAT2(status_or, __LINE__).value())
56 
57 }  // namespace gtest_matchers
58 
59 // Add a |PrintTo| function to allow easily determining what the cause of the
60 // failure is.
PrintTo(const Status & status,std::ostream * os)61 inline void PrintTo(const Status& status, std::ostream* os) {
62   if (status.ok()) {
63     *os << "OK";
64   } else {
65     *os << "Error(message=" << status.message() << ")";
66   }
67 }
68 
69 }  // namespace perfetto::base
70 
71 #endif  // SRC_BASE_TEST_STATUS_MATCHERS_H_
72