Debian Codegraph @

test/core/gprpp/notification_test.cc

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