• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/map.h"
16 
17 #include <memory>
18 
19 #include "absl/functional/any_invocable.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(MapTest,Works)26 TEST(MapTest, Works) {
27   Promise<int> x = Map([]() { return 42; }, [](int i) { return i / 2; });
28   EXPECT_THAT(x(), IsReady(21));
29 }
30 
TEST(MapTest,JustElem)31 TEST(MapTest, JustElem) {
32   std::tuple<int, double> t(1, 3.2);
33   EXPECT_EQ(JustElem<1>()(t), 3.2);
34   EXPECT_EQ(JustElem<0>()(t), 1);
35 }
36 
TEST(CheckDelayedTest,SeesImmediate)37 TEST(CheckDelayedTest, SeesImmediate) {
38   auto x = CheckDelayed([]() { return 42; });
39   EXPECT_THAT(x(), IsReady(std::make_tuple(42, false)));
40 }
41 
TEST(CheckDelayedTest,SeesDelayed)42 TEST(CheckDelayedTest, SeesDelayed) {
43   auto x = CheckDelayed([n = 1]() mutable -> Poll<int> {
44     if (n == 0) return 42;
45     --n;
46     return Pending{};
47   });
48   EXPECT_THAT(x(), IsPending());
49   EXPECT_THAT(x(), IsReady(std::make_tuple(42, true)));
50 }
51 
TEST(MapError,DoesntMapOk)52 TEST(MapError, DoesntMapOk) {
53   auto fail_on_call = [](const absl::Status&) {
54     LOG(FATAL) << "should never be called";
55     return absl::InternalError("unreachable");
56   };
57   promise_detail::MapError<decltype(fail_on_call)> map_on_error(
58       std::move(fail_on_call));
59   EXPECT_EQ(absl::OkStatus(), map_on_error(absl::OkStatus()));
60 }
61 
TEST(MapError,CanMapError)62 TEST(MapError, CanMapError) {
63   auto map_call = [](const absl::Status& status) {
64     EXPECT_EQ(status.code(), absl::StatusCode::kInternal);
65     EXPECT_EQ(status.message(), "hello");
66     return absl::UnavailableError("world");
67   };
68   promise_detail::MapError<decltype(map_call)> map_on_error(
69       std::move(map_call));
70   auto mapped = map_on_error(absl::InternalError("hello"));
71   EXPECT_EQ(mapped.code(), absl::StatusCode::kUnavailable);
72   EXPECT_EQ(mapped.message(), "world");
73 }
74 
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