1 /*
2  * Copyright (C) 2020 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 <aidl/Gtest.h>
17 #include <aidl/Vintf.h>
18 
19 #include <aidl/android/hardware/power/stats/IPowerStats.h>
20 #include <android-base/properties.h>
21 #include <android/binder_manager.h>
22 #include <android/binder_process.h>
23 
24 #include <algorithm>
25 #include <iterator>
26 #include <random>
27 #include <unordered_map>
28 
29 using aidl::android::hardware::power::stats::Channel;
30 using aidl::android::hardware::power::stats::EnergyConsumer;
31 using aidl::android::hardware::power::stats::EnergyConsumerAttribution;
32 using aidl::android::hardware::power::stats::EnergyConsumerResult;
33 using aidl::android::hardware::power::stats::EnergyConsumerType;
34 using aidl::android::hardware::power::stats::EnergyMeasurement;
35 using aidl::android::hardware::power::stats::IPowerStats;
36 using aidl::android::hardware::power::stats::PowerEntity;
37 using aidl::android::hardware::power::stats::State;
38 using aidl::android::hardware::power::stats::StateResidency;
39 using aidl::android::hardware::power::stats::StateResidencyResult;
40 
41 using ndk::SpAIBinder;
42 
43 #define ASSERT_OK(a)                                     \
44     do {                                                 \
45         auto ret = a;                                    \
46         ASSERT_TRUE(ret.isOk()) << ret.getDescription(); \
47     } while (0)
48 
49 class PowerStatsAidl : public testing::TestWithParam<std::string> {
50   public:
SetUp()51     virtual void SetUp() override {
52         powerstats = IPowerStats::fromBinder(
53                 SpAIBinder(AServiceManager_waitForService(GetParam().c_str())));
54         ASSERT_NE(nullptr, powerstats.get());
55     }
56 
57     template <typename T>
58     std::vector<T> getRandomSubset(std::vector<T> const& collection);
59 
60     void testNameValid(const std::string& name);
61 
62     template <typename T, typename S>
63     void testUnique(std::vector<T> const& collection, S T::*field);
64 
65     template <typename T, typename S, typename R>
66     void testMatching(std::vector<T> const& c1, R T::*f1, std::vector<S> const& c2, R S::*f2);
67 
68     std::shared_ptr<IPowerStats> powerstats;
69 };
70 
71 // Returns a random subset from a collection
72 template <typename T>
getRandomSubset(std::vector<T> const & collection)73 std::vector<T> PowerStatsAidl::getRandomSubset(std::vector<T> const& collection) {
74     if (collection.empty()) {
75         return {};
76     }
77 
78     std::vector<T> selected;
79     std::sample(collection.begin(), collection.end(), std::back_inserter(selected),
80                 rand() % collection.size() + 1, std::mt19937{std::random_device{}()});
81 
82     return selected;
83 }
84 
85 // Tests whether a name is valid
testNameValid(const std::string & name)86 void PowerStatsAidl::testNameValid(const std::string& name) {
87     EXPECT_NE(name, "");
88 }
89 
90 // Tests whether the fields in a given collection are unique
91 template <typename T, typename S>
testUnique(std::vector<T> const & collection,S T::* field)92 void PowerStatsAidl::testUnique(std::vector<T> const& collection, S T::*field) {
93     std::set<S> cSet;
94     for (auto const& elem : collection) {
95         EXPECT_TRUE(cSet.insert(elem.*field).second);
96     }
97 }
98 
99 template <typename T, typename S, typename R>
testMatching(std::vector<T> const & c1,R T::* f1,std::vector<S> const & c2,R S::* f2)100 void PowerStatsAidl::testMatching(std::vector<T> const& c1, R T::*f1, std::vector<S> const& c2,
101                                   R S::*f2) {
102     std::set<R> c1fields, c2fields;
103     for (auto elem : c1) {
104         c1fields.insert(elem.*f1);
105     }
106 
107     for (auto elem : c2) {
108         c2fields.insert(elem.*f2);
109     }
110 
111     EXPECT_EQ(c1fields, c2fields);
112 }
113 
114 // Each PowerEntity must have a valid name
TEST_P(PowerStatsAidl,ValidatePowerEntityNames)115 TEST_P(PowerStatsAidl, ValidatePowerEntityNames) {
116     std::vector<PowerEntity> infos;
117     ASSERT_OK(powerstats->getPowerEntityInfo(&infos));
118 
119     for (auto info : infos) {
120         testNameValid(info.name);
121     }
122 }
123 
124 // Each power entity must have a unique name
TEST_P(PowerStatsAidl,ValidatePowerEntityUniqueNames)125 TEST_P(PowerStatsAidl, ValidatePowerEntityUniqueNames) {
126     std::vector<PowerEntity> entities;
127     ASSERT_OK(powerstats->getPowerEntityInfo(&entities));
128 
129     testUnique(entities, &PowerEntity::name);
130 }
131 
132 // Each PowerEntity must have a unique ID
TEST_P(PowerStatsAidl,ValidatePowerEntityIds)133 TEST_P(PowerStatsAidl, ValidatePowerEntityIds) {
134     std::vector<PowerEntity> entities;
135     ASSERT_OK(powerstats->getPowerEntityInfo(&entities));
136 
137     testUnique(entities, &PowerEntity::id);
138 }
139 
140 // Each power entity must have at least one state
TEST_P(PowerStatsAidl,ValidateStateSize)141 TEST_P(PowerStatsAidl, ValidateStateSize) {
142     std::vector<PowerEntity> entities;
143     ASSERT_OK(powerstats->getPowerEntityInfo(&entities));
144 
145     for (auto entity : entities) {
146         EXPECT_GT(entity.states.size(), 0);
147     }
148 }
149 
150 // Each state must have a valid name
TEST_P(PowerStatsAidl,ValidateStateNames)151 TEST_P(PowerStatsAidl, ValidateStateNames) {
152     std::vector<PowerEntity> entities;
153     ASSERT_OK(powerstats->getPowerEntityInfo(&entities));
154 
155     for (auto entity : entities) {
156         for (auto state : entity.states) {
157             testNameValid(state.name);
158         }
159     }
160 }
161 
162 // Each state must have a name that is unique to the given PowerEntity
TEST_P(PowerStatsAidl,ValidateStateUniqueNames)163 TEST_P(PowerStatsAidl, ValidateStateUniqueNames) {
164     std::vector<PowerEntity> entities;
165     ASSERT_OK(powerstats->getPowerEntityInfo(&entities));
166 
167     for (auto entity : entities) {
168         testUnique(entity.states, &State::name);
169     }
170 }
171 
172 // Each state must have an ID that is unique to the given PowerEntity
TEST_P(PowerStatsAidl,ValidateStateUniqueIds)173 TEST_P(PowerStatsAidl, ValidateStateUniqueIds) {
174     std::vector<PowerEntity> entities;
175     ASSERT_OK(powerstats->getPowerEntityInfo(&entities));
176 
177     for (auto entity : entities) {
178         testUnique(entity.states, &State::id);
179     }
180 }
181 
182 // State residency must return a valid status
TEST_P(PowerStatsAidl,TestGetStateResidency)183 TEST_P(PowerStatsAidl, TestGetStateResidency) {
184     std::vector<StateResidencyResult> results;
185     ASSERT_OK(powerstats->getStateResidency({}, &results));
186 }
187 
188 // State residency must return all results
TEST_P(PowerStatsAidl,TestGetStateResidencyAllResults)189 TEST_P(PowerStatsAidl, TestGetStateResidencyAllResults) {
190     std::vector<PowerEntity> entities;
191     ASSERT_OK(powerstats->getPowerEntityInfo(&entities));
192 
193     std::vector<StateResidencyResult> results;
194     ASSERT_OK(powerstats->getStateResidency({}, &results));
195 
196     testMatching(entities, &PowerEntity::id, results, &StateResidencyResult::id);
197 }
198 
199 // Each result must contain all state residencies
TEST_P(PowerStatsAidl,TestGetStateResidencyAllStateResidencies)200 TEST_P(PowerStatsAidl, TestGetStateResidencyAllStateResidencies) {
201     std::vector<PowerEntity> entities;
202     ASSERT_OK(powerstats->getPowerEntityInfo(&entities));
203 
204     std::vector<StateResidencyResult> results;
205     ASSERT_OK(powerstats->getStateResidency({}, &results));
206 
207     for (auto entity : entities) {
208         auto it = std::find_if(results.begin(), results.end(),
209                                [&entity](const auto& x) { return x.id == entity.id; });
210         ASSERT_NE(it, results.end());
211 
212         testMatching(entity.states, &State::id, it->stateResidencyData, &StateResidency::id);
213     }
214 }
215 
216 // State residency must return results for each requested power entity
TEST_P(PowerStatsAidl,TestGetStateResidencySelectedResults)217 TEST_P(PowerStatsAidl, TestGetStateResidencySelectedResults) {
218     std::vector<PowerEntity> entities;
219     ASSERT_OK(powerstats->getPowerEntityInfo(&entities));
220     if (entities.empty()) {
221         return;
222     }
223 
224     std::vector<PowerEntity> selectedEntities = getRandomSubset(entities);
225     std::vector<int32_t> selectedIds;
226     for (auto const& entity : selectedEntities) {
227         selectedIds.push_back(entity.id);
228     }
229 
230     std::vector<StateResidencyResult> selectedResults;
231     ASSERT_OK(powerstats->getStateResidency(selectedIds, &selectedResults));
232 
233     testMatching(selectedEntities, &PowerEntity::id, selectedResults, &StateResidencyResult::id);
234 }
235 
236 // Energy meter info must return a valid status
TEST_P(PowerStatsAidl,TestGetEnergyMeterInfo)237 TEST_P(PowerStatsAidl, TestGetEnergyMeterInfo) {
238     std::vector<Channel> info;
239     ASSERT_OK(powerstats->getEnergyMeterInfo(&info));
240 }
241 
242 // Each channel must have a valid name
TEST_P(PowerStatsAidl,ValidateChannelNames)243 TEST_P(PowerStatsAidl, ValidateChannelNames) {
244     std::vector<Channel> channels;
245     ASSERT_OK(powerstats->getEnergyMeterInfo(&channels));
246 
247     for (auto channel : channels) {
248         testNameValid(channel.name);
249     }
250 }
251 
252 // Each channel must have a valid subsystem
TEST_P(PowerStatsAidl,ValidateSubsystemNames)253 TEST_P(PowerStatsAidl, ValidateSubsystemNames) {
254     std::vector<Channel> channels;
255     ASSERT_OK(powerstats->getEnergyMeterInfo(&channels));
256 
257     for (auto channel : channels) {
258         testNameValid(channel.subsystem);
259     }
260 }
261 
262 // Each channel must have a unique name
TEST_P(PowerStatsAidl,ValidateChannelUniqueNames)263 TEST_P(PowerStatsAidl, ValidateChannelUniqueNames) {
264     std::vector<Channel> channels;
265     ASSERT_OK(powerstats->getEnergyMeterInfo(&channels));
266 
267     testUnique(channels, &Channel::name);
268 }
269 
270 // Each channel must have a unique ID
TEST_P(PowerStatsAidl,ValidateChannelUniqueIds)271 TEST_P(PowerStatsAidl, ValidateChannelUniqueIds) {
272     std::vector<Channel> channels;
273     ASSERT_OK(powerstats->getEnergyMeterInfo(&channels));
274 
275     testUnique(channels, &Channel::id);
276 }
277 
278 // Reading energy meter must return a valid status
TEST_P(PowerStatsAidl,TestReadEnergyMeter)279 TEST_P(PowerStatsAidl, TestReadEnergyMeter) {
280     std::vector<EnergyMeasurement> data;
281     ASSERT_OK(powerstats->readEnergyMeter({}, &data));
282 }
283 
284 // Reading energy meter must return results for all available channels
TEST_P(PowerStatsAidl,TestGetAllEnergyMeasurements)285 TEST_P(PowerStatsAidl, TestGetAllEnergyMeasurements) {
286     std::vector<Channel> channels;
287     ASSERT_OK(powerstats->getEnergyMeterInfo(&channels));
288 
289     std::vector<EnergyMeasurement> measurements;
290     ASSERT_OK(powerstats->readEnergyMeter({}, &measurements));
291 
292     testMatching(channels, &Channel::id, measurements, &EnergyMeasurement::id);
293 }
294 
295 // Reading energy must must return results for each selected channel
TEST_P(PowerStatsAidl,TestGetSelectedEnergyMeasurements)296 TEST_P(PowerStatsAidl, TestGetSelectedEnergyMeasurements) {
297     std::vector<Channel> channels;
298     ASSERT_OK(powerstats->getEnergyMeterInfo(&channels));
299     if (channels.empty()) {
300         return;
301     }
302 
303     std::vector<Channel> selectedChannels = getRandomSubset(channels);
304     std::vector<int32_t> selectedIds;
305     for (auto const& channel : selectedChannels) {
306         selectedIds.push_back(channel.id);
307     }
308 
309     std::vector<EnergyMeasurement> selectedMeasurements;
310     ASSERT_OK(powerstats->readEnergyMeter(selectedIds, &selectedMeasurements));
311 
312     testMatching(selectedChannels, &Channel::id, selectedMeasurements, &EnergyMeasurement::id);
313 }
314 
315 // Energy consumer info must return a valid status
TEST_P(PowerStatsAidl,TestGetEnergyConsumerInfo)316 TEST_P(PowerStatsAidl, TestGetEnergyConsumerInfo) {
317     std::vector<EnergyConsumer> consumers;
318     ASSERT_OK(powerstats->getEnergyConsumerInfo(&consumers));
319 }
320 
321 // Each energy consumer must have a unique id
TEST_P(PowerStatsAidl,TestGetEnergyConsumerUniqueId)322 TEST_P(PowerStatsAidl, TestGetEnergyConsumerUniqueId) {
323     std::vector<EnergyConsumer> consumers;
324     ASSERT_OK(powerstats->getEnergyConsumerInfo(&consumers));
325 
326     testUnique(consumers, &EnergyConsumer::id);
327 }
328 
329 // Each energy consumer must have a valid name
TEST_P(PowerStatsAidl,ValidateEnergyConsumerNames)330 TEST_P(PowerStatsAidl, ValidateEnergyConsumerNames) {
331     std::vector<EnergyConsumer> consumers;
332     ASSERT_OK(powerstats->getEnergyConsumerInfo(&consumers));
333 
334     for (auto consumer : consumers) {
335         testNameValid(consumer.name);
336     }
337 }
338 
339 // Each energy consumer must have a unique name
TEST_P(PowerStatsAidl,ValidateEnergyConsumerUniqueNames)340 TEST_P(PowerStatsAidl, ValidateEnergyConsumerUniqueNames) {
341     std::vector<EnergyConsumer> consumers;
342     ASSERT_OK(powerstats->getEnergyConsumerInfo(&consumers));
343 
344     testUnique(consumers, &EnergyConsumer::name);
345 }
346 
347 // Energy consumers of the same type must have ordinals that are 0,1,2,..., N - 1
TEST_P(PowerStatsAidl,ValidateEnergyConsumerOrdinals)348 TEST_P(PowerStatsAidl, ValidateEnergyConsumerOrdinals) {
349     std::vector<EnergyConsumer> consumers;
350     ASSERT_OK(powerstats->getEnergyConsumerInfo(&consumers));
351 
352     std::unordered_map<EnergyConsumerType, std::set<int32_t>> ordinalMap;
353 
354     // Ordinals must be unique for each type
355     for (auto consumer : consumers) {
356         EXPECT_TRUE(ordinalMap[consumer.type].insert(consumer.ordinal).second);
357     }
358 
359     // Min ordinal must be 0, max ordinal must be N - 1
360     for (const auto& [unused, ordinals] : ordinalMap) {
361         EXPECT_EQ(0, *std::min_element(ordinals.begin(), ordinals.end()));
362         EXPECT_EQ(ordinals.size() - 1, *std::max_element(ordinals.begin(), ordinals.end()));
363     }
364 }
365 
366 // Energy consumed must return a valid status
TEST_P(PowerStatsAidl,TestGetEnergyConsumed)367 TEST_P(PowerStatsAidl, TestGetEnergyConsumed) {
368     std::vector<EnergyConsumerResult> results;
369     ASSERT_OK(powerstats->getEnergyConsumed({}, &results));
370 }
371 
372 // Energy consumed must return data for all energy consumers
TEST_P(PowerStatsAidl,TestGetAllEnergyConsumed)373 TEST_P(PowerStatsAidl, TestGetAllEnergyConsumed) {
374     std::vector<EnergyConsumer> consumers;
375     ASSERT_OK(powerstats->getEnergyConsumerInfo(&consumers));
376 
377     std::vector<EnergyConsumerResult> results;
378     ASSERT_OK(powerstats->getEnergyConsumed({}, &results));
379 
380     testMatching(consumers, &EnergyConsumer::id, results, &EnergyConsumerResult::id);
381 }
382 
383 // Energy consumed must return data for each selected energy consumer
TEST_P(PowerStatsAidl,TestGetSelectedEnergyConsumed)384 TEST_P(PowerStatsAidl, TestGetSelectedEnergyConsumed) {
385     std::vector<EnergyConsumer> consumers;
386     ASSERT_OK(powerstats->getEnergyConsumerInfo(&consumers));
387     if (consumers.empty()) {
388         return;
389     }
390 
391     std::vector<EnergyConsumer> selectedConsumers = getRandomSubset(consumers);
392     std::vector<int32_t> selectedIds;
393     for (auto const& consumer : selectedConsumers) {
394         selectedIds.push_back(consumer.id);
395     }
396 
397     std::vector<EnergyConsumerResult> selectedResults;
398     ASSERT_OK(powerstats->getEnergyConsumed(selectedIds, &selectedResults));
399 
400     testMatching(selectedConsumers, &EnergyConsumer::id, selectedResults,
401                  &EnergyConsumerResult::id);
402 }
403 
404 // Energy consumed attribution uids must be unique for a given energy consumer
TEST_P(PowerStatsAidl,ValidateEnergyConsumerAttributionUniqueUids)405 TEST_P(PowerStatsAidl, ValidateEnergyConsumerAttributionUniqueUids) {
406     std::vector<EnergyConsumerResult> results;
407     ASSERT_OK(powerstats->getEnergyConsumed({}, &results));
408 
409     for (auto result : results) {
410         testUnique(result.attribution, &EnergyConsumerAttribution::uid);
411     }
412 }
413 
414 // Energy consumed total energy >= sum total of uid-attributed energy
TEST_P(PowerStatsAidl,TestGetEnergyConsumedAttributedEnergy)415 TEST_P(PowerStatsAidl, TestGetEnergyConsumedAttributedEnergy) {
416     std::vector<EnergyConsumerResult> results;
417     ASSERT_OK(powerstats->getEnergyConsumed({}, &results));
418 
419     for (auto result : results) {
420         int64_t totalAttributedEnergyUWs = 0;
421         for (auto attribution : result.attribution) {
422             totalAttributedEnergyUWs += attribution.energyUWs;
423         }
424         EXPECT_TRUE(result.energyUWs >= totalAttributedEnergyUWs);
425     }
426 }
427 
428 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(PowerStatsAidl);
429 INSTANTIATE_TEST_SUITE_P(
430         PowerStats, PowerStatsAidl,
431         testing::ValuesIn(android::getAidlHalInstanceNames(IPowerStats::descriptor)),
432         android::PrintInstanceNameToString);
433 
main(int argc,char ** argv)434 int main(int argc, char** argv) {
435     ::testing::InitGoogleTest(&argc, argv);
436     ABinderProcess_setThreadPoolMaxThreadCount(1);
437     ABinderProcess_startThreadPool();
438     return RUN_ALL_TESTS();
439 }
440