xref: /aosp_15_r20/system/chre/util/tests/throttle_test.cc (revision 84e339476a462649f82315436d70fd732297a399)
1 /*
2  * Copyright (C) 2024 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 
17 #include <cmath>
18 #include <cstdint>
19 
20 #include "gtest/gtest.h"
21 
22 #include "chre/platform/linux/system_time.h"
23 #include "chre/platform/system_time.h"
24 #include "chre/util/throttle.h"
25 #include "chre/util/time.h"
26 
27 using ::chre::Milliseconds;
28 using ::chre::Nanoseconds;
29 using ::chre::Seconds;
30 using ::chre::SystemTime;
31 using ::chre::platform_linux::SystemTimeOverride;
32 
TEST(Throttle,ThrottlesActionLessThanOneInterval)33 TEST(Throttle, ThrottlesActionLessThanOneInterval) {
34   uint32_t count = 0;
35   constexpr uint32_t kMaxCount = 10;
36   constexpr uint64_t kCallCount = 1000;
37   constexpr Seconds kInterval(1);
38   static_assert(kCallCount < kInterval.toRawNanoseconds());
39 
40   for (uint64_t i = 0; i < kCallCount; ++i) {
41     SystemTimeOverride override(i);
42     CHRE_THROTTLE(++count, kInterval, kMaxCount,
43                   SystemTime::getMonotonicTime());
44   }
45 
46   EXPECT_EQ(count, kMaxCount);
47 }
48 
TEST(Throttle,ThrottlesActionMoreThanOneInterval)49 TEST(Throttle, ThrottlesActionMoreThanOneInterval) {
50   uint32_t count = 0;
51   constexpr uint32_t kMaxCount = 10;
52   constexpr uint64_t kCallCount = 1000;
53   constexpr Nanoseconds kInterval(100);
54   static_assert(kCallCount > kInterval.toRawNanoseconds());
55 
56   for (uint64_t i = 0; i < kCallCount; ++i) {
57     SystemTimeOverride override(i);
58     CHRE_THROTTLE(++count, kInterval, kMaxCount,
59                   SystemTime::getMonotonicTime());
60   }
61 
62   EXPECT_EQ(count, (kCallCount / kInterval.toRawNanoseconds()) * kMaxCount);
63 }
64