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