1/*
2 * Copyright 2011-present Facebook, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <folly/TimeoutQueue.h>
18
19#include <folly/portability/GTest.h>
20
21using namespace folly;
22
23TEST(TimeoutQueue, Simple) {
24 typedef std::vector<TimeoutQueue::Id> EventVec;
25 EventVec events;
26
27 TimeoutQueue q;
28 TimeoutQueue::Callback cb = [&events](
29 TimeoutQueue::Id id, int64_t /* now */) {
30 events.push_back(id);
31 };
32
33 EXPECT_EQ(1, q.add(0, 10, cb));
34 EXPECT_EQ(2, q.add(0, 11, cb));
35 EXPECT_EQ(3, q.addRepeating(0, 9, cb));
36
37 EXPECT_TRUE(events.empty());
38 EXPECT_EQ(21, q.runOnce(12)); // now+9
39
40 bool r = (EventVec{3, 1, 2} == events);
41 EXPECT_TRUE(r);
42
43 events.clear();
44 EXPECT_EQ(49, q.runOnce(40));
45 r = (EventVec{3} == events);
46 EXPECT_TRUE(r);
47}
48
49TEST(TimeoutQueue, Erase) {
50 typedef std::vector<TimeoutQueue::Id> EventVec;
51 EventVec events;
52
53 TimeoutQueue q;
54 TimeoutQueue::Callback cb = [&events, &q](
55 TimeoutQueue::Id id, int64_t /* now */) {
56 events.push_back(id);
57 if (id == 2) {
58 q.erase(1);
59 }
60 };
61
62 EXPECT_EQ(1, q.addRepeating(0, 10, cb));
63 EXPECT_EQ(2, q.add(0, 35, cb));
64
65 int64_t now = 0;
66 while (now < std::numeric_limits<int64_t>::max()) {
67 now = q.runOnce(now);
68 }
69
70 bool r = (EventVec{1, 1, 1, 2} == events);
71 EXPECT_TRUE(r);
72}
73
74TEST(TimeoutQueue, RunOnceRepeating) {
75 int count = 0;
76 TimeoutQueue q;
77 TimeoutQueue::Callback cb = [&count, &q](
78 TimeoutQueue::Id id, int64_t /* now */) {
79 if (++count == 100) {
80 EXPECT_TRUE(q.erase(id));
81 }
82 };
83
84 EXPECT_EQ(1, q.addRepeating(0, 0, cb));
85
86 EXPECT_EQ(0, q.runOnce(0));
87 EXPECT_EQ(1, count);
88 EXPECT_EQ(0, q.runOnce(0));
89 EXPECT_EQ(2, count);
90 EXPECT_EQ(std::numeric_limits<int64_t>::max(), q.runLoop(0));
91 EXPECT_EQ(100, count);
92}
93
94TEST(TimeoutQueue, RunOnceReschedule) {
95 int count = 0;
96 TimeoutQueue q;
97 TimeoutQueue::Callback cb;
98 cb = [&count, &q, &cb](TimeoutQueue::Id id, int64_t now) {
99 if (++count < 100) {
100 EXPECT_LT(id, q.add(now, 0, cb));
101 }
102 };
103
104 EXPECT_EQ(1, q.add(0, 0, cb));
105
106 EXPECT_EQ(0, q.runOnce(0));
107 EXPECT_EQ(1, count);
108 EXPECT_EQ(0, q.runOnce(0));
109 EXPECT_EQ(2, count);
110 EXPECT_EQ(std::numeric_limits<int64_t>::max(), q.runLoop(0));
111 EXPECT_EQ(100, count);
112}
113