2 * Copyright 2017-present 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.
18 #include <folly/Conv.h>
19 #include <folly/experimental/logging/RateLimiter.h>
20 #include <folly/portability/GTest.h>
22 using folly::logging::IntervalRateLimiter;
23 using std::chrono::duration_cast;
24 using namespace std::literals::chrono_literals;
27 uint64_t eventsPerInterval,
28 std::chrono::steady_clock::duration interval) {
29 SCOPED_TRACE(folly::to<std::string>(
32 duration_cast<std::chrono::milliseconds>(interval).count(),
34 IntervalRateLimiter limiter{eventsPerInterval, interval};
35 for (int iter = 0; iter < 4; ++iter) {
38 std::this_thread::sleep_for(interval);
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;
45 EXPECT_FALSE(limiter.check())
46 << "expected check failure on loop " << iter << " event " << n;
52 TEST(RateLimiter, interval3per100ms) {
53 intervalTest(3, 100ms);
56 TEST(RateLimiter, interval1per100ms) {
57 intervalTest(1, 100ms);
60 TEST(RateLimiter, interval15per150ms) {
61 intervalTest(15, 150ms);