• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 ASSERT_OK_AND_ASSIGN(lhs, rhs)                                    \
49   PERFETTO_TEST_STATUS_MATCHER_CONCAT(auto status_or, __LINE__) = rhs;    \
50   ASSERT_OK(                                                              \
51       PERFETTO_TEST_STATUS_MATCHER_CONCAT(status_or, __LINE__).status()); \
52   lhs = std::move(                                                        \
53       PERFETTO_TEST_STATUS_MATCHER_CONCAT(status_or, __LINE__).value())
54 
55 }  // namespace gtest_matchers
56 
57 // Add a |PrintTo| function to allow easily determining what the cause of the
58 // failure is.
PrintTo(const Status & status,std::ostream * os)59 inline void PrintTo(const Status& status, std::ostream* os) {
60   if (status.ok()) {
61     *os << "OK";
62   } else {
63     *os << "Error(message=" << status.message() << ")";
64   }
65 }
66 
67 }  // namespace perfetto::base
68 
69 #endif  // SRC_BASE_TEST_STATUS_MATCHERS_H_
70