2 * Copyright 2016 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include <folly/TimeoutQueue.h>
19 #include <folly/portability/GTest.h>
21 using namespace folly;
23 TEST(TimeoutQueue, Simple) {
24 typedef std::vector<TimeoutQueue::Id> EventVec;
28 TimeoutQueue::Callback cb = [&events](
29 TimeoutQueue::Id id, int64_t /* now */) { events.push_back(id); };
31 EXPECT_EQ(1, q.add(0, 10, cb));
32 EXPECT_EQ(2, q.add(0, 11, cb));
33 EXPECT_EQ(3, q.addRepeating(0, 9, cb));
35 EXPECT_TRUE(events.empty());
36 EXPECT_EQ(21, q.runOnce(12)); // now+9
38 bool r = (EventVec{3,1,2} == events);
42 EXPECT_EQ(49, q.runOnce(40));
43 r = (EventVec{3} == events);
47 TEST(TimeoutQueue, Erase) {
48 typedef std::vector<TimeoutQueue::Id> EventVec;
52 TimeoutQueue::Callback cb =
53 [&events, &q](TimeoutQueue::Id id, int64_t /* now */) {
60 EXPECT_EQ(1, q.addRepeating(0, 10, cb));
61 EXPECT_EQ(2, q.add(0, 35, cb));
64 while (now < std::numeric_limits<int64_t>::max()) {
68 bool r = (EventVec{1,1,1,2} == events);
72 TEST(TimeoutQueue, RunOnceRepeating) {
75 TimeoutQueue::Callback cb =
76 [&count, &q](TimeoutQueue::Id id, int64_t /* now */) {
78 EXPECT_TRUE(q.erase(id));
82 EXPECT_EQ(1, q.addRepeating(0, 0, cb));
84 EXPECT_EQ(0, q.runOnce(0));
86 EXPECT_EQ(0, q.runOnce(0));
88 EXPECT_EQ(std::numeric_limits<int64_t>::max(), q.runLoop(0));
89 EXPECT_EQ(100, count);
92 TEST(TimeoutQueue, RunOnceReschedule) {
95 TimeoutQueue::Callback cb;
96 cb = [&count, &q, &cb](TimeoutQueue::Id id, int64_t now) {
98 EXPECT_LT(id, q.add(now, 0, cb));
102 EXPECT_EQ(1, q.add(0, 0, cb));
104 EXPECT_EQ(0, q.runOnce(0));
106 EXPECT_EQ(0, q.runOnce(0));
108 EXPECT_EQ(std::numeric_limits<int64_t>::max(), q.runLoop(0));
109 EXPECT_EQ(100, count);