Add TimedDrivableExecutor to folly.
[folly.git] / folly / executors / test / TimedDrivableExecutorTest.cpp
1 /*
2  * Copyright 2018-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/executors/TimedDrivableExecutor.h>
18
19 #include <folly/futures/Future.h>
20 #include <folly/portability/GTest.h>
21 #include <folly/synchronization/Baton.h>
22
23 using namespace folly;
24
25 TEST(TimedDrivableExecutor, runIsStable) {
26   TimedDrivableExecutor x;
27   size_t count = 0;
28   auto f1 = [&]() { count++; };
29   auto f2 = [&]() {
30     x.add(f1);
31     x.add(f1);
32   };
33   x.add(f2);
34   x.run();
35   EXPECT_EQ(count, 0);
36 }
37
38 TEST(TimedDrivableExecutor, drainIsNotStable) {
39   TimedDrivableExecutor x;
40   size_t count = 0;
41   auto f1 = [&]() { count++; };
42   auto f2 = [&]() {
43     x.add(f1);
44     x.add(f1);
45   };
46   x.add(f2);
47   x.drain();
48   EXPECT_EQ(count, 2);
49 }
50
51 TEST(TimedDrivableExecutor, try_drive) {
52   TimedDrivableExecutor x;
53   size_t count = 0;
54   auto f1 = [&]() { count++; };
55   x.try_drive();
56   EXPECT_EQ(count, 0);
57   x.add(f1);
58   x.try_drive();
59   EXPECT_EQ(count, 1);
60 }
61
62 TEST(TimedDrivableExecutor, try_drive_for) {
63   TimedDrivableExecutor x;
64   size_t count = 0;
65   auto f1 = [&]() { count++; };
66   x.try_drive_for(std::chrono::milliseconds(100));
67   EXPECT_EQ(count, 0);
68   x.add(f1);
69   x.try_drive_for(std::chrono::milliseconds(100));
70   EXPECT_EQ(count, 1);
71 }
72
73 TEST(TimedDrivableExecutor, try_drive_until) {
74   TimedDrivableExecutor x;
75   size_t count = 0;
76   auto f1 = [&]() { count++; };
77   x.try_drive_until(
78       std::chrono::system_clock::now() + std::chrono::milliseconds(100));
79   EXPECT_EQ(count, 0);
80   x.add(f1);
81   x.try_drive_until(
82       std::chrono::system_clock::now() + std::chrono::milliseconds(100));
83   EXPECT_EQ(count, 1);
84 }