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