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/promise/match_promise.h"
16
17 #include <memory>
18
19 #include "absl/strings/str_cat.h"
20 #include "gtest/gtest.h"
21 #include "src/core/lib/promise/promise.h"
22 #include "test/core/promise/poll_matcher.h"
23
24 namespace grpc_core {
25
TEST(MatchPromiseTest,Works)26 TEST(MatchPromiseTest, Works) {
27 struct Int {
28 int x;
29 };
30 struct Float {
31 float x;
32 };
33 using V = absl::variant<Int, Float, std::string>;
34 auto make_promise = [](V v) -> Promise<std::string> {
35 return MatchPromise(
36 std::move(v),
37 [](Float x) mutable {
38 return [n = 3, x]() mutable -> Poll<std::string> {
39 --n;
40 if (n > 0) return Pending{};
41 return absl::StrCat(x.x);
42 };
43 },
44 [](Int x) {
45 return []() mutable -> Poll<std::string> { return Pending{}; };
46 },
47 [](std::string x) { return x; });
48 };
49 auto promise = make_promise(V(Float{3.0f}));
50 EXPECT_THAT(promise(), IsPending());
51 EXPECT_THAT(promise(), IsPending());
52 EXPECT_THAT(promise(), IsReady("3"));
53 promise = make_promise(V(Int{42}));
54 for (int i = 0; i < 10000; i++) {
55 EXPECT_THAT(promise(), IsPending());
56 }
57 promise = make_promise(V("hello"));
58 EXPECT_THAT(promise(), IsReady("hello"));
59 }
60
61 } // namespace grpc_core
62
main(int argc,char ** argv)63 int main(int argc, char** argv) {
64 ::testing::InitGoogleTest(&argc, argv);
65 return RUN_ALL_TESTS();
66 }
67