1 // Copyright (C) 2018 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "src/anomaly/AlarmTracker.h"
16 
17 #include <gtest/gtest.h>
18 #include <stdio.h>
19 #include <vector>
20 
21 using namespace testing;
22 using android::sp;
23 using std::set;
24 using std::unordered_map;
25 using std::vector;
26 
27 #ifdef __ANDROID__
28 
29 namespace android {
30 namespace os {
31 namespace statsd {
32 
33 const ConfigKey kConfigKey(0, 12345);
34 
TEST(AlarmTrackerTest,TestTriggerTimestamp)35 TEST(AlarmTrackerTest, TestTriggerTimestamp) {
36     sp<AlarmMonitor> subscriberAlarmMonitor =
37         new AlarmMonitor(100, [](const sp<IStatsCompanionService>&, int64_t){},
38                          [](const sp<IStatsCompanionService>&){});
39     Alarm alarm;
40     alarm.set_offset_millis(15 * MS_PER_SEC);
41     alarm.set_period_millis(60 * 60 * MS_PER_SEC);  // 1hr
42     int64_t startMillis = 100000000 * MS_PER_SEC;
43     AlarmTracker tracker(startMillis, startMillis, alarm, kConfigKey, subscriberAlarmMonitor);
44 
45     EXPECT_EQ(tracker.mAlarmSec, (int64_t)(startMillis / MS_PER_SEC + 15));
46 
47     uint64_t currentTimeSec = startMillis / MS_PER_SEC + 10;
48     std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> firedAlarmSet =
49         subscriberAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
50     EXPECT_TRUE(firedAlarmSet.empty());
51     tracker.informAlarmsFired(currentTimeSec * NS_PER_SEC, firedAlarmSet);
52     EXPECT_EQ(tracker.mAlarmSec, (int64_t)(startMillis / MS_PER_SEC + 15));
53 
54     currentTimeSec = startMillis / MS_PER_SEC + 7000;
55     firedAlarmSet = subscriberAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
56     EXPECT_EQ(firedAlarmSet.size(), 1u);
57     tracker.informAlarmsFired(currentTimeSec * NS_PER_SEC, firedAlarmSet);
58     EXPECT_TRUE(firedAlarmSet.empty());
59     EXPECT_EQ(tracker.mAlarmSec, (int64_t)(startMillis / MS_PER_SEC + 15 + 2 * 60 * 60));
60 }
61 
62 }  // namespace statsd
63 }  // namespace os
64 }  // namespace android
65 #else
66 GTEST_LOG_(INFO) << "This test does nothing.\n";
67 #endif
68