• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 The Android Open Source Project
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 "RateLimiter.h"
17 
18 #include <gtest/gtest.h>
19 #include <utils/Timers.h>
20 
21 namespace {
22 
23 using hardware::google::pixelstats::V1_0::implementation::RateLimiter;
24 
25 class RateLimiterTest : public ::testing::Test {};
26 
TEST_F(RateLimiterTest,RateLimiterStartZero)27 TEST_F(RateLimiterTest, RateLimiterStartZero) {
28     RateLimiter limiter;
29     EXPECT_FALSE(limiter.RateLimit(0, 2));
30     EXPECT_FALSE(limiter.RateLimit(0, 2));
31     EXPECT_TRUE(limiter.RateLimit(0, 2));
32 }
33 
TEST_F(RateLimiterTest,RateLimiterTwoBins)34 TEST_F(RateLimiterTest, RateLimiterTwoBins) {
35     RateLimiter limiter;
36     EXPECT_FALSE(limiter.RateLimit(0, 2));
37     EXPECT_FALSE(limiter.RateLimit(1, 2));
38     EXPECT_FALSE(limiter.RateLimit(1, 2));
39     EXPECT_TRUE(limiter.RateLimit(1, 2));
40     EXPECT_FALSE(limiter.RateLimit(0, 2));
41     EXPECT_TRUE(limiter.RateLimit(1, 2));
42     EXPECT_TRUE(limiter.RateLimit(0, 2));
43 }
44 
TEST_F(RateLimiterTest,RateLimiterTimeReset)45 TEST_F(RateLimiterTest, RateLimiterTimeReset) {
46     RateLimiter limiter;
47     EXPECT_FALSE(limiter.RateLimit(0, 2));
48     EXPECT_FALSE(limiter.RateLimit(0, 2));
49     EXPECT_TRUE(limiter.RateLimit(0, 2));
50 
51     // Still ratelimit after 23 hrs have passed
52     limiter.TurnBackHours(23);
53     EXPECT_TRUE(limiter.RateLimit(0, 2));
54 
55     // Expect reset after 25hrs have passed
56     limiter.TurnBackHours(25);
57     EXPECT_FALSE(limiter.RateLimit(0, 2));
58     EXPECT_FALSE(limiter.RateLimit(0, 2));
59     EXPECT_TRUE(limiter.RateLimit(0, 2));
60 }
61 
TEST_F(RateLimiterTest,AllActionLimit)62 TEST_F(RateLimiterTest, AllActionLimit) {
63     RateLimiter limiter(2);
64 
65     // Log three actions, expect the third to be
66     // ratelimited due to the daily overall ratelimit of 2.
67     EXPECT_FALSE(limiter.RateLimit(1, 6));
68     EXPECT_FALSE(limiter.RateLimit(2, 6));
69     EXPECT_TRUE(limiter.RateLimit(3, 6));
70 
71     // Still ratelimit after 23 hrs have passed
72     limiter.TurnBackHours(23);
73     EXPECT_TRUE(limiter.RateLimit(4, 6));
74 
75     // Expect reset after 25hrs have passed
76     limiter.TurnBackHours(25);
77     EXPECT_FALSE(limiter.RateLimit(5, 6));
78 }
79 
80 }  // namespace
81