xref: /aosp_15_r20/external/grpc-grpc/test/core/gprpp/match_test.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 // Copyright 2021 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "src/core/lib/gprpp/match.h"
16 
17 #include <stdlib.h>
18 
19 #include <memory>
20 
21 #include "gtest/gtest.h"
22 
23 namespace grpc_core {
24 namespace testing {
25 
TEST(MatchTest,Test)26 TEST(MatchTest, Test) {
27   EXPECT_EQ(Match(
28                 absl::variant<int, double>(1.9), [](int) -> int { abort(); },
29                 [](double x) -> int {
30                   EXPECT_EQ(x, 1.9);
31                   return 42;
32                 }),
33             42);
34   EXPECT_EQ(Match(
35                 absl::variant<int, double>(3),
36                 [](int x) -> int {
37                   EXPECT_EQ(x, 3);
38                   return 42;
39                 },
40                 [](double) -> int { abort(); }),
41             42);
42 }
43 
TEST(MatchTest,TestVoidReturn)44 TEST(MatchTest, TestVoidReturn) {
45   bool triggered = false;
46   Match(
47       absl::variant<int, double>(1.9), [](int) { abort(); },
48       [&triggered](double x) {
49         EXPECT_EQ(x, 1.9);
50         triggered = true;
51       });
52   EXPECT_TRUE(triggered);
53 }
54 
TEST(MatchTest,TestMutable)55 TEST(MatchTest, TestMutable) {
56   absl::variant<int, double> v = 1.9;
57   MatchMutable(
58       &v, [](int*) { abort(); }, [](double* x) { *x = 0.0; });
59   EXPECT_EQ(v, (absl::variant<int, double>(0.0)));
60 }
61 
TEST(MatchTest,TestMutableWithReturn)62 TEST(MatchTest, TestMutableWithReturn) {
63   absl::variant<int, double> v = 1.9;
64   EXPECT_EQ(MatchMutable(
65                 &v, [](int*) -> int { abort(); },
66                 [](double* x) -> int {
67                   *x = 0.0;
68                   return 1;
69                 }),
70             1);
71   EXPECT_EQ(v, (absl::variant<int, double>(0.0)));
72 }
73 
74 }  // namespace testing
75 }  // namespace grpc_core
76 
main(int argc,char ** argv)77 int main(int argc, char** argv) {
78   ::testing::InitGoogleTest(&argc, argv);
79   return RUN_ALL_TESTS();
80 }
81