1 // Copyright 2022 The 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/gprpp/notification.h"
16
17 #include <memory>
18 #include <thread>
19
20 #include "gtest/gtest.h"
21
22 namespace grpc_core {
23 namespace testing {
24 namespace {
25
TEST(Notification,Works)26 TEST(Notification, Works) {
27 Notification n;
28 EXPECT_FALSE(n.HasBeenNotified());
29 n.Notify();
30 EXPECT_TRUE(n.HasBeenNotified());
31 n.WaitForNotification();
32 EXPECT_TRUE(n.HasBeenNotified());
33 }
34
TEST(Notification,Waits)35 TEST(Notification, Waits) {
36 Notification n;
37 auto start = absl::Now();
38 std::thread t([&n] {
39 absl::SleepFor(absl::Seconds(6));
40 n.Notify();
41 });
42 n.WaitForNotification();
43 auto end = absl::Now();
44 EXPECT_GE(end - start, absl::Seconds(5));
45 t.join();
46 }
47
TEST(Notification,WaitsWithTimeout)48 TEST(Notification, WaitsWithTimeout) {
49 Notification n;
50 auto start = absl::Now();
51 std::thread t([&n] {
52 absl::SleepFor(absl::Seconds(6));
53 n.Notify();
54 });
55 EXPECT_TRUE(n.WaitForNotificationWithTimeout(absl::Seconds(10)));
56 auto end = absl::Now();
57 EXPECT_GE(end - start, absl::Seconds(5));
58 EXPECT_LE(end - start, absl::Seconds(10));
59 t.join();
60 }
61
TEST(Notification,WaitWithTimeoutCanFinishEarly)62 TEST(Notification, WaitWithTimeoutCanFinishEarly) {
63 Notification n;
64 auto start = absl::Now();
65 std::thread t([&n] {
66 absl::SleepFor(absl::Seconds(6));
67 n.Notify();
68 });
69 EXPECT_FALSE(n.WaitForNotificationWithTimeout(absl::Seconds(1)));
70 auto end = absl::Now();
71 EXPECT_GE(end - start, absl::Seconds(1));
72 EXPECT_LE(end - start, absl::Seconds(5));
73 n.WaitForNotification();
74 end = absl::Now();
75 EXPECT_GE(end - start, absl::Seconds(5));
76 t.join();
77 }
78
79 } // namespace
80 } // namespace testing
81 } // namespace grpc_core
82
main(int argc,char ** argv)83 int main(int argc, char** argv) {
84 ::testing::InitGoogleTest(&argc, argv);
85 return RUN_ALL_TESTS();
86 }
87