1 // Copyright 2023 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/prioritized_race.h"
16
17 #include <memory>
18
19 #include "gtest/gtest.h"
20
21 #include "src/core/lib/promise/poll.h"
22
23 namespace grpc_core {
24
instant()25 Poll<int> instant() { return 1; }
never()26 Poll<int> never() { return Pending(); }
27
TEST(PrioritizedRaceTest,Race1)28 TEST(PrioritizedRaceTest, Race1) {
29 EXPECT_EQ(PrioritizedRace(instant)(), Poll<int>(1));
30 }
31
TEST(PrioritizedRaceTest,Race2A)32 TEST(PrioritizedRaceTest, Race2A) {
33 EXPECT_EQ(PrioritizedRace(instant, never)(), Poll<int>(1));
34 }
35
TEST(PrioritizedRaceTest,Race2B)36 TEST(PrioritizedRaceTest, Race2B) {
37 EXPECT_EQ(PrioritizedRace(never, instant)(), Poll<int>(1));
38 }
39
TEST(PrioritizedRaceTest,PrioritizedCompletion2A)40 TEST(PrioritizedRaceTest, PrioritizedCompletion2A) {
41 int first_polls = 0;
42 int second_polls = 0;
43 auto r = PrioritizedRace(
44 [&first_polls]() -> Poll<int> {
45 ++first_polls;
46 return 1;
47 },
48 [&second_polls]() {
49 ++second_polls;
50 return 2;
51 })();
52 EXPECT_EQ(r, Poll<int>(1));
53 // First promise completes immediately, so second promise is never polled.
54 EXPECT_EQ(first_polls, 1);
55 EXPECT_EQ(second_polls, 0);
56 }
57
TEST(PrioritizedRaceTest,PrioritizedCompletion2B)58 TEST(PrioritizedRaceTest, PrioritizedCompletion2B) {
59 int first_polls = 0;
60 int second_polls = 0;
61 auto r = PrioritizedRace(
62 [&first_polls]() -> Poll<int> {
63 ++first_polls;
64 if (first_polls > 1) return 1;
65 return Pending{};
66 },
67 [&second_polls]() {
68 ++second_polls;
69 return 2;
70 })();
71 EXPECT_EQ(r, Poll<int>(1));
72 // First promise completes after second promise is polled.
73 EXPECT_EQ(first_polls, 2);
74 EXPECT_EQ(second_polls, 1);
75 }
76
77 } // namespace grpc_core
78
main(int argc,char ** argv)79 int main(int argc, char** argv) {
80 ::testing::InitGoogleTest(&argc, argv);
81 return RUN_ALL_TESTS();
82 }
83