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/loop.h"
16
17 #include <memory>
18 #include <utility>
19
20 #include "gtest/gtest.h"
21
22 #include "src/core/lib/promise/seq.h"
23
24 namespace grpc_core {
25
TEST(LoopTest,CountToFive)26 TEST(LoopTest, CountToFive) {
27 int i = 0;
28 Loop([&i]() -> LoopCtl<int> {
29 i++;
30 if (i < 5) return Continue();
31 return i;
32 })();
33 EXPECT_EQ(i, 5);
34 }
35
TEST(LoopTest,FactoryCountToFive)36 TEST(LoopTest, FactoryCountToFive) {
37 int i = 0;
38 Loop([&i]() {
39 return [&i]() -> LoopCtl<int> {
40 i++;
41 if (i < 5) return Continue();
42 return i;
43 };
44 })();
45 EXPECT_EQ(i, 5);
46 }
47
TEST(LoopTest,LoopOfSeq)48 TEST(LoopTest, LoopOfSeq) {
49 auto x =
50 Loop(Seq([]() { return 42; }, [](int i) -> LoopCtl<int> { return i; }))();
51 EXPECT_EQ(x, Poll<int>(42));
52 }
53
TEST(LoopTest,CanAccessFactoryLambdaVariables)54 TEST(LoopTest, CanAccessFactoryLambdaVariables) {
55 int i = 0;
56 auto x = Loop([p = &i]() {
57 return [q = &p]() -> Poll<LoopCtl<int>> {
58 ++**q;
59 return Pending{};
60 };
61 });
62 auto y = std::move(x);
63 auto z = std::move(y);
64 z();
65 EXPECT_EQ(i, 1);
66 }
67
68 } // namespace grpc_core
69
main(int argc,char ** argv)70 int main(int argc, char** argv) {
71 ::testing::InitGoogleTest(&argc, argv);
72 return RUN_ALL_TESTS();
73 }
74