• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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     bool containsTimedEntity(const std::string& str);
69 
70     void excludeTimedEntities(std::vector<PowerEntity>* entities,
71                               std::vector<StateResidencyResult>* results);
72 
73     std::shared_ptr<IPowerStats> powerstats;
74 };
75 
76 // Returns a random subset from a collection
77 template <typename T>
getRandomSubset(std::vector<T> const & collection)78 std::vector<T> PowerStatsAidl::getRandomSubset(std::vector<T> const& collection) {
79     if (collection.empty()) {
80         return {};
81     }
82 
83     std::vector<T> selected;
84     std::sample(collection.begin(), collection.end(), std::back_inserter(selected),
85                 rand() % collection.size() + 1, std::mt19937{std::random_device{}()});
86 
87     return selected;
88 }
89 
90 // Tests whether a name is valid
testNameValid(const std::string & name)91 void PowerStatsAidl::testNameValid(const std::string& name) {
92     EXPECT_NE(name, "");
93 }
94 
95 // Tests whether the fields in a given collection are unique
96 template <typename T, typename S>
testUnique(std::vector<T> const & collection,S T::* field)97 void PowerStatsAidl::testUnique(std::vector<T> const& collection, S T::*field) {
98     std::set<S> cSet;
99     for (auto const& elem : collection) {
100         EXPECT_TRUE(cSet.insert(elem.*field).second);
101     }
102 }
103 
104 template <typename T, typename S, typename R>
testMatching(std::vector<T> const & c1,R T::* f1,std::vector<S> const & c2,R S::* f2)105 void PowerStatsAidl::testMatching(std::vector<T> const& c1, R T::*f1, std::vector<S> const& c2,
106                                   R S::*f2) {
107     std::set<R> c1fields, c2fields;
108     for (auto elem : c1) {
109         c1fields.insert(elem.*f1);
110     }
111 
112     for (auto elem : c2) {
113         c2fields.insert(elem.*f2);
114     }
115 
116     EXPECT_EQ(c1fields, c2fields);
117 }
118 
containsTimedEntity(const std::string & str)119 bool PowerStatsAidl::containsTimedEntity(const std::string& str) {
120     // TODO(b/229698505): Extend PowerEntityInfo to identify timed power entity
121     return str.find("AoC") != std::string::npos;
122 }
123 
excludeTimedEntities(std::vector<PowerEntity> * entities,std::vector<StateResidencyResult> * results)124 void PowerStatsAidl::excludeTimedEntities(std::vector<PowerEntity>* entities,
125                                           std::vector<StateResidencyResult>* results) {
126     for (auto it = entities->begin(); it != entities->end(); it++) {
127         if (containsTimedEntity((*it).name)) {
128             auto entityId = (*it).id;
129             entities->erase(it--);
130 
131             // Erase result element matching the entity ID
132             for (auto resultsIt = results->begin(); resultsIt != results->end(); resultsIt++) {
133                 if ((*resultsIt).id == entityId) {
134                     results->erase(resultsIt--);
135                     break;
136                 }
137             }
138         }
139     }
140 }
141 
142 // Each PowerEntity must have a valid name
TEST_P(PowerStatsAidl,ValidatePowerEntityNames)143 TEST_P(PowerStatsAidl, ValidatePowerEntityNames) {
144     std::vector<PowerEntity> infos;
145     ASSERT_OK(powerstats->getPowerEntityInfo(&infos));
146 
147     for (auto info : infos) {
148         testNameValid(info.name);
149     }
150 }
151 
152 // Each power entity must have a unique name
TEST_P(PowerStatsAidl,ValidatePowerEntityUniqueNames)153 TEST_P(PowerStatsAidl, ValidatePowerEntityUniqueNames) {
154     std::vector<PowerEntity> entities;
155     ASSERT_OK(powerstats->getPowerEntityInfo(&entities));
156 
157     testUnique(entities, &PowerEntity::name);
158 }
159 
160 // Each PowerEntity must have a unique ID
TEST_P(PowerStatsAidl,ValidatePowerEntityIds)161 TEST_P(PowerStatsAidl, ValidatePowerEntityIds) {
162     std::vector<PowerEntity> entities;
163     ASSERT_OK(powerstats->getPowerEntityInfo(&entities));
164 
165     testUnique(entities, &PowerEntity::id);
166 }
167 
168 // Each power entity must have at least one state
TEST_P(PowerStatsAidl,ValidateStateSize)169 TEST_P(PowerStatsAidl, ValidateStateSize) {
170     std::vector<PowerEntity> entities;
171     ASSERT_OK(powerstats->getPowerEntityInfo(&entities));
172 
173     for (auto entity : entities) {
174         EXPECT_GT(entity.states.size(), 0);
175     }
176 }
177 
178 // Each state must have a valid name
TEST_P(PowerStatsAidl,ValidateStateNames)179 TEST_P(PowerStatsAidl, ValidateStateNames) {
180     std::vector<PowerEntity> entities;
181     ASSERT_OK(powerstats->getPowerEntityInfo(&entities));
182 
183     for (auto entity : entities) {
184         for (auto state : entity.states) {
185             testNameValid(state.name);
186         }
187     }
188 }
189 
190 // Each state must have a name that is unique to the given PowerEntity
TEST_P(PowerStatsAidl,ValidateStateUniqueNames)191 TEST_P(PowerStatsAidl, ValidateStateUniqueNames) {
192     std::vector<PowerEntity> entities;
193     ASSERT_OK(powerstats->getPowerEntityInfo(&entities));
194 
195     for (auto entity : entities) {
196         testUnique(entity.states, &State::name);
197     }
198 }
199 
200 // Each state must have an ID that is unique to the given PowerEntity
TEST_P(PowerStatsAidl,ValidateStateUniqueIds)201 TEST_P(PowerStatsAidl, ValidateStateUniqueIds) {
202     std::vector<PowerEntity> entities;
203     ASSERT_OK(powerstats->getPowerEntityInfo(&entities));
204 
205     for (auto entity : entities) {
206         testUnique(entity.states, &State::id);
207     }
208 }
209 
210 // State residency must return a valid status
TEST_P(PowerStatsAidl,TestGetStateResidency)211 TEST_P(PowerStatsAidl, TestGetStateResidency) {
212     std::vector<StateResidencyResult> results;
213     ASSERT_OK(powerstats->getStateResidency({}, &results));
214 }
215 
216 // State residency must return all results except timed power entities
TEST_P(PowerStatsAidl,TestGetStateResidencyAllResultsExceptTimedEntities)217 TEST_P(PowerStatsAidl, TestGetStateResidencyAllResultsExceptTimedEntities) {
218     std::vector<PowerEntity> entities;
219     ASSERT_OK(powerstats->getPowerEntityInfo(&entities));
220 
221     std::vector<StateResidencyResult> results;
222     ASSERT_OK(powerstats->getStateResidency({}, &results));
223     excludeTimedEntities(&entities, &results);
224 
225     testMatching(entities, &PowerEntity::id, results, &StateResidencyResult::id);
226 }
227 
228 // Each result must contain all state residencies except timed power entities
TEST_P(PowerStatsAidl,TestGetStateResidencyAllStateResidenciesExceptTimedEntities)229 TEST_P(PowerStatsAidl, TestGetStateResidencyAllStateResidenciesExceptTimedEntities) {
230     std::vector<PowerEntity> entities;
231     ASSERT_OK(powerstats->getPowerEntityInfo(&entities));
232 
233     std::vector<StateResidencyResult> results;
234     ASSERT_OK(powerstats->getStateResidency({}, &results));
235 
236     for (auto entity : entities) {
237         if (!containsTimedEntity(entity.name)) {
238             auto it = std::find_if(results.begin(), results.end(),
239                                    [&entity](const auto& x) { return x.id == entity.id; });
240             ASSERT_NE(it, results.end());
241 
242             testMatching(entity.states, &State::id, it->stateResidencyData, &StateResidency::id);
243         }
244     }
245 }
246 
247 // State residency must return results for each requested power entity except timed power entities
TEST_P(PowerStatsAidl,TestGetStateResidencySelectedResultsExceptTimedEntities)248 TEST_P(PowerStatsAidl, TestGetStateResidencySelectedResultsExceptTimedEntities) {
249     std::vector<PowerEntity> entities;
250     ASSERT_OK(powerstats->getPowerEntityInfo(&entities));
251     if (entities.empty()) {
252         return;
253     }
254 
255     std::vector<PowerEntity> selectedEntities = getRandomSubset(entities);
256     std::vector<int32_t> selectedIds;
257     for (auto it = selectedEntities.begin(); it != selectedEntities.end(); it++) {
258         if (!containsTimedEntity((*it).name)) {
259             selectedIds.push_back((*it).id);
260         } else {
261             selectedEntities.erase(it--);
262         }
263     }
264 
265     std::vector<StateResidencyResult> selectedResults;
266     ASSERT_OK(powerstats->getStateResidency(selectedIds, &selectedResults));
267 
268     testMatching(selectedEntities, &PowerEntity::id, selectedResults, &StateResidencyResult::id);
269 }
270 
271 // Energy meter info must return a valid status
TEST_P(PowerStatsAidl,TestGetEnergyMeterInfo)272 TEST_P(PowerStatsAidl, TestGetEnergyMeterInfo) {
273     std::vector<Channel> info;
274     ASSERT_OK(powerstats->getEnergyMeterInfo(&info));
275 }
276 
277 // Each channel must have a valid name
TEST_P(PowerStatsAidl,ValidateChannelNames)278 TEST_P(PowerStatsAidl, ValidateChannelNames) {
279     std::vector<Channel> channels;
280     ASSERT_OK(powerstats->getEnergyMeterInfo(&channels));
281 
282     for (auto channel : channels) {
283         testNameValid(channel.name);
284     }
285 }
286 
287 // Each channel must have a valid subsystem
TEST_P(PowerStatsAidl,ValidateSubsystemNames)288 TEST_P(PowerStatsAidl, ValidateSubsystemNames) {
289     std::vector<Channel> channels;
290     ASSERT_OK(powerstats->getEnergyMeterInfo(&channels));
291 
292     for (auto channel : channels) {
293         testNameValid(channel.subsystem);
294     }
295 }
296 
297 // Each channel must have a unique name
TEST_P(PowerStatsAidl,ValidateChannelUniqueNames)298 TEST_P(PowerStatsAidl, ValidateChannelUniqueNames) {
299     std::vector<Channel> channels;
300     ASSERT_OK(powerstats->getEnergyMeterInfo(&channels));
301 
302     testUnique(channels, &Channel::name);
303 }
304 
305 // Each channel must have a unique ID
TEST_P(PowerStatsAidl,ValidateChannelUniqueIds)306 TEST_P(PowerStatsAidl, ValidateChannelUniqueIds) {
307     std::vector<Channel> channels;
308     ASSERT_OK(powerstats->getEnergyMeterInfo(&channels));
309 
310     testUnique(channels, &Channel::id);
311 }
312 
313 // Reading energy meter must return a valid status
TEST_P(PowerStatsAidl,TestReadEnergyMeter)314 TEST_P(PowerStatsAidl, TestReadEnergyMeter) {
315     std::vector<EnergyMeasurement> data;
316     ASSERT_OK(powerstats->readEnergyMeter({}, &data));
317 }
318 
319 // Reading energy meter must return results for all available channels
TEST_P(PowerStatsAidl,TestGetAllEnergyMeasurements)320 TEST_P(PowerStatsAidl, TestGetAllEnergyMeasurements) {
321     std::vector<Channel> channels;
322     ASSERT_OK(powerstats->getEnergyMeterInfo(&channels));
323 
324     std::vector<EnergyMeasurement> measurements;
325     ASSERT_OK(powerstats->readEnergyMeter({}, &measurements));
326 
327     testMatching(channels, &Channel::id, measurements, &EnergyMeasurement::id);
328 }
329 
330 // Reading energy must must return results for each selected channel
TEST_P(PowerStatsAidl,TestGetSelectedEnergyMeasurements)331 TEST_P(PowerStatsAidl, TestGetSelectedEnergyMeasurements) {
332     std::vector<Channel> channels;
333     ASSERT_OK(powerstats->getEnergyMeterInfo(&channels));
334     if (channels.empty()) {
335         return;
336     }
337 
338     std::vector<Channel> selectedChannels = getRandomSubset(channels);
339     std::vector<int32_t> selectedIds;
340     for (auto const& channel : selectedChannels) {
341         selectedIds.push_back(channel.id);
342     }
343 
344     std::vector<EnergyMeasurement> selectedMeasurements;
345     ASSERT_OK(powerstats->readEnergyMeter(selectedIds, &selectedMeasurements));
346 
347     testMatching(selectedChannels, &Channel::id, selectedMeasurements, &EnergyMeasurement::id);
348 }
349 
350 // Energy consumer info must return a valid status
TEST_P(PowerStatsAidl,TestGetEnergyConsumerInfo)351 TEST_P(PowerStatsAidl, TestGetEnergyConsumerInfo) {
352     std::vector<EnergyConsumer> consumers;
353     ASSERT_OK(powerstats->getEnergyConsumerInfo(&consumers));
354 }
355 
356 // Each energy consumer must have a unique id
TEST_P(PowerStatsAidl,TestGetEnergyConsumerUniqueId)357 TEST_P(PowerStatsAidl, TestGetEnergyConsumerUniqueId) {
358     std::vector<EnergyConsumer> consumers;
359     ASSERT_OK(powerstats->getEnergyConsumerInfo(&consumers));
360 
361     testUnique(consumers, &EnergyConsumer::id);
362 }
363 
364 // Each energy consumer must have a valid name
TEST_P(PowerStatsAidl,ValidateEnergyConsumerNames)365 TEST_P(PowerStatsAidl, ValidateEnergyConsumerNames) {
366     std::vector<EnergyConsumer> consumers;
367     ASSERT_OK(powerstats->getEnergyConsumerInfo(&consumers));
368 
369     for (auto consumer : consumers) {
370         testNameValid(consumer.name);
371     }
372 }
373 
374 // Each energy consumer must have a unique name
TEST_P(PowerStatsAidl,ValidateEnergyConsumerUniqueNames)375 TEST_P(PowerStatsAidl, ValidateEnergyConsumerUniqueNames) {
376     std::vector<EnergyConsumer> consumers;
377     ASSERT_OK(powerstats->getEnergyConsumerInfo(&consumers));
378 
379     testUnique(consumers, &EnergyConsumer::name);
380 }
381 
382 // Energy consumers of the same type must have ordinals that are 0,1,2,..., N - 1
TEST_P(PowerStatsAidl,ValidateEnergyConsumerOrdinals)383 TEST_P(PowerStatsAidl, ValidateEnergyConsumerOrdinals) {
384     std::vector<EnergyConsumer> consumers;
385     ASSERT_OK(powerstats->getEnergyConsumerInfo(&consumers));
386 
387     std::unordered_map<EnergyConsumerType, std::set<int32_t>> ordinalMap;
388 
389     // Ordinals must be unique for each type
390     for (auto consumer : consumers) {
391         EXPECT_TRUE(ordinalMap[consumer.type].insert(consumer.ordinal).second);
392     }
393 
394     // Min ordinal must be 0, max ordinal must be N - 1
395     for (const auto& [unused, ordinals] : ordinalMap) {
396         EXPECT_EQ(0, *std::min_element(ordinals.begin(), ordinals.end()));
397         EXPECT_EQ(ordinals.size() - 1, *std::max_element(ordinals.begin(), ordinals.end()));
398     }
399 }
400 
401 // Energy consumed must return a valid status
TEST_P(PowerStatsAidl,TestGetEnergyConsumed)402 TEST_P(PowerStatsAidl, TestGetEnergyConsumed) {
403     std::vector<EnergyConsumerResult> results;
404     ASSERT_OK(powerstats->getEnergyConsumed({}, &results));
405 }
406 
407 // Energy consumed must return data for all energy consumers
TEST_P(PowerStatsAidl,TestGetAllEnergyConsumed)408 TEST_P(PowerStatsAidl, TestGetAllEnergyConsumed) {
409     std::vector<EnergyConsumer> consumers;
410     ASSERT_OK(powerstats->getEnergyConsumerInfo(&consumers));
411 
412     std::vector<EnergyConsumerResult> results;
413     ASSERT_OK(powerstats->getEnergyConsumed({}, &results));
414 
415     testMatching(consumers, &EnergyConsumer::id, results, &EnergyConsumerResult::id);
416 }
417 
418 // Energy consumed must return data for each selected energy consumer
TEST_P(PowerStatsAidl,TestGetSelectedEnergyConsumed)419 TEST_P(PowerStatsAidl, TestGetSelectedEnergyConsumed) {
420     std::vector<EnergyConsumer> consumers;
421     ASSERT_OK(powerstats->getEnergyConsumerInfo(&consumers));
422     if (consumers.empty()) {
423         return;
424     }
425 
426     std::vector<EnergyConsumer> selectedConsumers = getRandomSubset(consumers);
427     std::vector<int32_t> selectedIds;
428     for (auto const& consumer : selectedConsumers) {
429         selectedIds.push_back(consumer.id);
430     }
431 
432     std::vector<EnergyConsumerResult> selectedResults;
433     ASSERT_OK(powerstats->getEnergyConsumed(selectedIds, &selectedResults));
434 
435     testMatching(selectedConsumers, &EnergyConsumer::id, selectedResults,
436                  &EnergyConsumerResult::id);
437 }
438 
439 // Energy consumed attribution uids must be unique for a given energy consumer
TEST_P(PowerStatsAidl,ValidateEnergyConsumerAttributionUniqueUids)440 TEST_P(PowerStatsAidl, ValidateEnergyConsumerAttributionUniqueUids) {
441     std::vector<EnergyConsumerResult> results;
442     ASSERT_OK(powerstats->getEnergyConsumed({}, &results));
443 
444     for (auto result : results) {
445         testUnique(result.attribution, &EnergyConsumerAttribution::uid);
446     }
447 }
448 
449 // Energy consumed total energy >= sum total of uid-attributed energy
TEST_P(PowerStatsAidl,TestGetEnergyConsumedAttributedEnergy)450 TEST_P(PowerStatsAidl, TestGetEnergyConsumedAttributedEnergy) {
451     std::vector<EnergyConsumerResult> results;
452     ASSERT_OK(powerstats->getEnergyConsumed({}, &results));
453 
454     for (auto result : results) {
455         int64_t totalAttributedEnergyUWs = 0;
456         for (auto attribution : result.attribution) {
457             totalAttributedEnergyUWs += attribution.energyUWs;
458         }
459         EXPECT_TRUE(result.energyUWs >= totalAttributedEnergyUWs);
460     }
461 }
462 
463 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(PowerStatsAidl);
464 INSTANTIATE_TEST_SUITE_P(
465         PowerStats, PowerStatsAidl,
466         testing::ValuesIn(android::getAidlHalInstanceNames(IPowerStats::descriptor)),
467         android::PrintInstanceNameToString);
468 
main(int argc,char ** argv)469 int main(int argc, char** argv) {
470     ::testing::InitGoogleTest(&argc, argv);
471     ABinderProcess_setThreadPoolMaxThreadCount(1);
472     ABinderProcess_startThreadPool();
473     return RUN_ALL_TESTS();
474 }
475