logging: add new RateLimiter helper class
[folly.git] / folly / experimental / logging / test / RateLimiterTest.cpp
1 /*
2  * Copyright 2004-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 #include <thread>
17
18 #include <folly/Conv.h>
19 #include <folly/experimental/logging/RateLimiter.h>
20 #include <folly/portability/GTest.h>
21
22 using folly::logging::IntervalRateLimiter;
23 using std::chrono::duration_cast;
24 using namespace std::literals::chrono_literals;
25
26 void intervalTest(
27     uint64_t eventsPerInterval,
28     std::chrono::steady_clock::duration interval) {
29   SCOPED_TRACE(folly::to<std::string>(
30       eventsPerInterval,
31       " events every ",
32       duration_cast<std::chrono::milliseconds>(interval).count(),
33       "ms"));
34   IntervalRateLimiter limiter{eventsPerInterval, interval};
35   for (int iter = 0; iter < 4; ++iter) {
36     if (iter != 0) {
37       /* sleep override */
38       std::this_thread::sleep_for(interval);
39     }
40     for (uint64_t n = 0; n < eventsPerInterval * 2; ++n) {
41       if (n < eventsPerInterval) {
42         EXPECT_TRUE(limiter.check())
43             << "expected check success on loop " << iter << " event " << n;
44       } else {
45         EXPECT_FALSE(limiter.check())
46             << "expected check failure on loop " << iter << " event " << n;
47       }
48     }
49   }
50 }
51
52 TEST(RateLimiter, interval3per100ms) {
53   intervalTest(3, 100ms);
54 }
55
56 TEST(RateLimiter, interval1per100ms) {
57   intervalTest(1, 100ms);
58 }
59
60 TEST(RateLimiter, interval15per150ms) {
61   intervalTest(15, 150ms);
62 }