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
17 #define LOG_TAG "health_aidl_hal_test"
18
19 #include <chrono>
20 #include <memory>
21 #include <thread>
22
23 #include <aidl/Gtest.h>
24 #include <aidl/Vintf.h>
25 #include <aidl/android/hardware/health/BnHealthInfoCallback.h>
26 #include <aidl/android/hardware/health/IHealth.h>
27 #include <android/binder_auto_utils.h>
28 #include <android/binder_enums.h>
29 #include <android/binder_interface_utils.h>
30 #include <android/binder_manager.h>
31 #include <android/binder_process.h>
32 #include <gmock/gmock.h>
33 #include <gtest/gtest.h>
34 #include <health-test/TestUtils.h>
35
36 using android::getAidlHalInstanceNames;
37 using android::PrintInstanceNameToString;
38 using android::hardware::health::test_utils::SucceedOnce;
39 using ndk::enum_range;
40 using ndk::ScopedAStatus;
41 using ndk::SharedRefBase;
42 using ndk::SpAIBinder;
43 using testing::AllOf;
44 using testing::AnyOf;
45 using testing::AnyOfArray;
46 using testing::AssertionFailure;
47 using testing::AssertionResult;
48 using testing::AssertionSuccess;
49 using testing::Contains;
50 using testing::Each;
51 using testing::Eq;
52 using testing::ExplainMatchResult;
53 using testing::Ge;
54 using testing::Gt;
55 using testing::Le;
56 using testing::Lt;
57 using testing::Matcher;
58 using testing::Not;
59 using namespace std::string_literals;
60 using namespace std::chrono_literals;
61
62 namespace aidl::android::hardware::health {
63
64 static constexpr int32_t kFullChargeDesignCapMinUah = 100 * 1000;
65 static constexpr int32_t kFullChargeDesignCapMaxUah = 100 * 1000 * 1000;
66
67 MATCHER(IsOk, "") {
68 *result_listener << "status is " << arg.getDescription();
69 return arg.isOk();
70 }
71
72 MATCHER_P(ExceptionIs, exception_code, "") {
73 *result_listener << "status is " << arg.getDescription();
74 return arg.getExceptionCode() == exception_code;
75 }
76
77 template <typename T>
InClosedRange(const T & lo,const T & hi)78 Matcher<T> InClosedRange(const T& lo, const T& hi) {
79 return AllOf(Ge(lo), Le(hi));
80 }
81
82 template <typename T>
IsValidEnum()83 Matcher<T> IsValidEnum() {
84 return AnyOfArray(enum_range<T>().begin(), enum_range<T>().end());
85 }
86
87 MATCHER(IsValidSerialNumber, "") {
88 if (!arg) {
89 return true;
90 }
91 if (arg->size() < 6) {
92 return false;
93 }
94 for (const auto& c : *arg) {
95 if (!isalnum(c)) {
96 return false;
97 }
98 }
99 return true;
100 }
101
102 class HealthAidl : public testing::TestWithParam<std::string> {
103 public:
SetUp()104 void SetUp() override {
105 SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
106 health = IHealth::fromBinder(binder);
107 ASSERT_NE(health, nullptr);
108 }
109 std::shared_ptr<IHealth> health;
110 };
111
112 class Callback : public BnHealthInfoCallback {
113 public:
healthInfoChanged(const HealthInfo &)114 ScopedAStatus healthInfoChanged(const HealthInfo&) override {
115 {
116 std::lock_guard<std::mutex> lock(mutex_);
117 invoked_ = true;
118 }
119 invoked_notify_.notify_all();
120 return ScopedAStatus::ok();
121 }
122 template <typename R, typename P>
waitInvoke(std::chrono::duration<R,P> duration)123 [[nodiscard]] bool waitInvoke(std::chrono::duration<R, P> duration) {
124 std::unique_lock<std::mutex> lock(mutex_);
125 bool r = invoked_notify_.wait_for(lock, duration, [this] { return this->invoked_; });
126 invoked_ = false;
127 return r;
128 }
129
130 private:
131 std::mutex mutex_;
132 std::condition_variable invoked_notify_;
133 bool invoked_ = false;
134 };
135
TEST_P(HealthAidl,Callbacks)136 TEST_P(HealthAidl, Callbacks) {
137 auto first_callback = SharedRefBase::make<Callback>();
138 auto second_callback = SharedRefBase::make<Callback>();
139
140 ASSERT_THAT(health->registerCallback(first_callback), IsOk());
141 ASSERT_THAT(health->registerCallback(second_callback), IsOk());
142
143 // registerCallback may or may not invoke the callback immediately, so the test needs
144 // to wait for the invocation. If the implementation chooses not to invoke the callback
145 // immediately, just wait for some time.
146 (void)first_callback->waitInvoke(200ms);
147 (void)second_callback->waitInvoke(200ms);
148
149 // assert that the first callback is invoked when update is called.
150 ASSERT_THAT(health->update(), IsOk());
151
152 ASSERT_TRUE(first_callback->waitInvoke(1s));
153 ASSERT_TRUE(second_callback->waitInvoke(1s));
154
155 ASSERT_THAT(health->unregisterCallback(first_callback), IsOk());
156
157 // clear any potentially pending callbacks result from wakealarm / kernel events
158 // If there is none, just wait for some time.
159 (void)first_callback->waitInvoke(200ms);
160 (void)second_callback->waitInvoke(200ms);
161
162 // assert that the second callback is still invoked even though the first is unregistered.
163 ASSERT_THAT(health->update(), IsOk());
164
165 ASSERT_FALSE(first_callback->waitInvoke(200ms));
166 ASSERT_TRUE(second_callback->waitInvoke(1s));
167
168 ASSERT_THAT(health->unregisterCallback(second_callback), IsOk());
169 }
170
TEST_P(HealthAidl,UnregisterNonExistentCallback)171 TEST_P(HealthAidl, UnregisterNonExistentCallback) {
172 auto callback = SharedRefBase::make<Callback>();
173 auto ret = health->unregisterCallback(callback);
174 ASSERT_THAT(ret, ExceptionIs(EX_ILLEGAL_ARGUMENT));
175 }
176
177 /*
178 * Tests the values returned by getChargeCounterUah() from interface IHealth.
179 */
TEST_P(HealthAidl,getChargeCounterUah)180 TEST_P(HealthAidl, getChargeCounterUah) {
181 int32_t value;
182 auto status = health->getChargeCounterUah(&value);
183 ASSERT_THAT(status, AnyOf(IsOk(), ExceptionIs(EX_UNSUPPORTED_OPERATION)));
184 if (!status.isOk()) return;
185 ASSERT_THAT(value, Ge(0));
186 }
187
188 /*
189 * Tests the values returned by getCurrentNowMicroamps() from interface IHealth.
190 */
TEST_P(HealthAidl,getCurrentNowMicroamps)191 TEST_P(HealthAidl, getCurrentNowMicroamps) {
192 int32_t value;
193 auto status = health->getCurrentNowMicroamps(&value);
194 ASSERT_THAT(status, AnyOf(IsOk(), ExceptionIs(EX_UNSUPPORTED_OPERATION)));
195 if (!status.isOk()) return;
196 ASSERT_THAT(value, Not(INT32_MIN));
197 }
198
199 /*
200 * Tests the values returned by getCurrentAverageMicroamps() from interface IHealth.
201 */
TEST_P(HealthAidl,getCurrentAverageMicroamps)202 TEST_P(HealthAidl, getCurrentAverageMicroamps) {
203 int32_t value;
204 auto status = health->getCurrentAverageMicroamps(&value);
205 ASSERT_THAT(status, AnyOf(IsOk(), ExceptionIs(EX_UNSUPPORTED_OPERATION)));
206 if (!status.isOk()) return;
207 ASSERT_THAT(value, Not(INT32_MIN));
208 }
209
210 /*
211 * Tests the values returned by getCapacity() from interface IHealth.
212 */
TEST_P(HealthAidl,getCapacity)213 TEST_P(HealthAidl, getCapacity) {
214 int32_t value;
215 auto status = health->getCapacity(&value);
216 ASSERT_THAT(status, AnyOf(IsOk(), ExceptionIs(EX_UNSUPPORTED_OPERATION)));
217 if (!status.isOk()) return;
218 ASSERT_THAT(value, InClosedRange(0, 100));
219 }
220
221 /*
222 * Tests the values returned by getEnergyCounterNwh() from interface IHealth.
223 */
TEST_P(HealthAidl,getEnergyCounterNwh)224 TEST_P(HealthAidl, getEnergyCounterNwh) {
225 int64_t value;
226 auto status = health->getEnergyCounterNwh(&value);
227 ASSERT_THAT(status, AnyOf(IsOk(), ExceptionIs(EX_UNSUPPORTED_OPERATION)));
228 if (!status.isOk()) return;
229 ASSERT_THAT(value, Not(INT64_MIN));
230 }
231
232 /*
233 * Tests the values returned by getChargeStatus() from interface IHealth.
234 */
TEST_P(HealthAidl,getChargeStatus)235 TEST_P(HealthAidl, getChargeStatus) {
236 BatteryStatus value;
237 auto status = health->getChargeStatus(&value);
238 ASSERT_THAT(status, AnyOf(IsOk(), ExceptionIs(EX_UNSUPPORTED_OPERATION)));
239 if (!status.isOk()) return;
240 ASSERT_THAT(value, IsValidEnum<BatteryStatus>());
241 }
242
243 /*
244 * Tests the values returned by getChargingPolicy() from interface IHealth.
245 */
TEST_P(HealthAidl,getChargingPolicy)246 TEST_P(HealthAidl, getChargingPolicy) {
247 int32_t version = 0;
248 auto status = health->getInterfaceVersion(&version);
249 ASSERT_TRUE(status.isOk()) << status;
250 if (version < 2) {
251 GTEST_SKIP() << "Support in health hal v2 for EU Ecodesign";
252 }
253 BatteryChargingPolicy value;
254 status = health->getChargingPolicy(&value);
255 ASSERT_THAT(status, AnyOf(IsOk(), ExceptionIs(EX_UNSUPPORTED_OPERATION)));
256 if (!status.isOk()) return;
257 ASSERT_THAT(value, IsValidEnum<BatteryChargingPolicy>());
258 }
259
260 /*
261 * Tests that setChargingPolicy() writes the value and compared the returned
262 * value by getChargingPolicy() from interface IHealth.
263 */
TEST_P(HealthAidl,setChargingPolicy)264 TEST_P(HealthAidl, setChargingPolicy) {
265 int32_t version = 0;
266 auto status = health->getInterfaceVersion(&version);
267 ASSERT_TRUE(status.isOk()) << status;
268 if (version < 2) {
269 GTEST_SKIP() << "Support in health hal v2 for EU Ecodesign";
270 }
271
272 BatteryChargingPolicy value;
273
274 /* set ChargingPolicy*/
275 status = health->setChargingPolicy(BatteryChargingPolicy::LONG_LIFE);
276 ASSERT_THAT(status, AnyOf(IsOk(), ExceptionIs(EX_UNSUPPORTED_OPERATION)));
277 if (!status.isOk()) return;
278
279 /* get ChargingPolicy*/
280 status = health->getChargingPolicy(&value);
281 ASSERT_THAT(status, AnyOf(IsOk(), ExceptionIs(EX_UNSUPPORTED_OPERATION)));
282 if (!status.isOk()) return;
283 // the result of getChargingPolicy will be one of default(1), ADAPTIVE_AON(2)
284 // ADAPTIVE_AC(3) or LONG_LIFE(4). default(1) means NOT_SUPPORT
285 ASSERT_THAT(static_cast<int>(value), AnyOf(Eq(1), Eq(4)));
286 }
287
288 MATCHER_P(IsValidHealthData, version, "") {
289 *result_listener << "value is " << arg.toString() << ".";
290 if (!ExplainMatchResult(Ge(-1), arg.batteryManufacturingDateSeconds, result_listener)) {
291 *result_listener << " for batteryManufacturingDateSeconds.";
292 return false;
293 }
294 if (!ExplainMatchResult(Ge(-1), arg.batteryFirstUsageSeconds, result_listener)) {
295 *result_listener << " for batteryFirstUsageSeconds.";
296 return false;
297 }
298 if (!ExplainMatchResult(Ge(-1), arg.batteryStateOfHealth, result_listener)) {
299 *result_listener << " for batteryStateOfHealth.";
300 return false;
301 }
302 if (!ExplainMatchResult(IsValidSerialNumber(), arg.batterySerialNumber, result_listener)) {
303 *result_listener << " for batterySerialNumber.";
304 return false;
305 }
306 if (!ExplainMatchResult(IsValidEnum<BatteryPartStatus>(), arg.batteryPartStatus,
307 result_listener)) {
308 *result_listener << " for batteryPartStatus.";
309 return false;
310 }
311
312 return true;
313 }
314
315 /* @VsrTest = 3.2.015
316 *
317 * Tests the values returned by getBatteryHealthData() from interface IHealth.
318 */
TEST_P(HealthAidl,getBatteryHealthData)319 TEST_P(HealthAidl, getBatteryHealthData) {
320 int32_t version = 0;
321 auto status = health->getInterfaceVersion(&version);
322 ASSERT_TRUE(status.isOk()) << status;
323 if (version < 2) {
324 GTEST_SKIP() << "Support in health hal v2 for EU Ecodesign";
325 }
326
327 BatteryHealthData value;
328 status = health->getBatteryHealthData(&value);
329 ASSERT_THAT(status, AnyOf(IsOk(), ExceptionIs(EX_UNSUPPORTED_OPERATION)));
330 if (!status.isOk()) return;
331 ASSERT_THAT(value, IsValidHealthData(version));
332 }
333
334 MATCHER(IsValidStorageInfo, "") {
335 *result_listener << "value is " << arg.toString() << ".";
336 if (!ExplainMatchResult(InClosedRange(0, 3), arg.eol, result_listener)) {
337 *result_listener << " for eol.";
338 return false;
339 }
340 if (!ExplainMatchResult(InClosedRange(0, 0x0B), arg.lifetimeA, result_listener)) {
341 *result_listener << " for lifetimeA.";
342 return false;
343 }
344 if (!ExplainMatchResult(InClosedRange(0, 0x0B), arg.lifetimeB, result_listener)) {
345 *result_listener << " for lifetimeB.";
346 return false;
347 }
348 return true;
349 }
350
351 /*
352 * Tests the values returned by getStorageInfo() from interface IHealth.
353 */
TEST_P(HealthAidl,getStorageInfo)354 TEST_P(HealthAidl, getStorageInfo) {
355 std::vector<StorageInfo> value;
356 auto status = health->getStorageInfo(&value);
357 ASSERT_THAT(status, AnyOf(IsOk(), ExceptionIs(EX_UNSUPPORTED_OPERATION)));
358 if (!status.isOk()) return;
359 ASSERT_THAT(value, Each(IsValidStorageInfo()));
360 }
361
362 /*
363 * Tests the values returned by getHingeInfo() from interface IHealth.
364 */
TEST_P(HealthAidl,getHingeInfo)365 TEST_P(HealthAidl, getHingeInfo) {
366 std::vector<HingeInfo> value;
367 auto status = health->getHingeInfo(&value);
368 ASSERT_THAT(status, AnyOf(IsOk(), ExceptionIs(EX_UNSUPPORTED_OPERATION)));
369 if (!status.isOk()) return;
370 for (auto& hinge : value) {
371 ASSERT_TRUE(hinge.expectedHingeLifespan >= 0);
372 ASSERT_TRUE(hinge.numTimesFolded >= 0);
373 }
374 }
375
376 /*
377 * Tests the values returned by getDiskStats() from interface IHealth.
378 */
TEST_P(HealthAidl,getDiskStats)379 TEST_P(HealthAidl, getDiskStats) {
380 std::vector<DiskStats> value;
381 auto status = health->getDiskStats(&value);
382 ASSERT_THAT(status, AnyOf(IsOk(), ExceptionIs(EX_UNSUPPORTED_OPERATION)));
383 }
384
385 MATCHER(IsValidHealthInfo, "") {
386 *result_listener << "value is " << arg.toString() << ".";
387 if (!ExplainMatchResult(Each(IsValidStorageInfo()), arg.storageInfos, result_listener)) {
388 *result_listener << " for storageInfos.";
389 return false;
390 }
391
392 if (!ExplainMatchResult(Not(INT32_MIN), arg.batteryCurrentMicroamps, result_listener)) {
393 *result_listener << " for batteryCurrentMicroamps.";
394 return false;
395 }
396
397 if (!ExplainMatchResult(InClosedRange(0, 100), arg.batteryLevel, result_listener)) {
398 *result_listener << " for batteryLevel.";
399 return false;
400 }
401
402 if (!ExplainMatchResult(IsValidEnum<BatteryHealth>(), arg.batteryHealth, result_listener)) {
403 *result_listener << " for batteryHealth.";
404 return false;
405 }
406
407 if (!ExplainMatchResult(IsValidEnum<BatteryStatus>(), arg.batteryStatus, result_listener)) {
408 *result_listener << " for batteryStatus.";
409 return false;
410 }
411
412 if (arg.batteryPresent) {
413 if (!ExplainMatchResult(Gt(0), arg.batteryChargeCounterUah, result_listener)) {
414 *result_listener << " for batteryChargeCounterUah when battery is present.";
415 return false;
416 }
417 if (!ExplainMatchResult(Not(BatteryStatus::UNKNOWN), arg.batteryStatus, result_listener)) {
418 *result_listener << " for batteryStatus when battery is present.";
419 return false;
420 }
421 }
422
423 if (!ExplainMatchResult(IsValidEnum<BatteryCapacityLevel>(), arg.batteryCapacityLevel,
424 result_listener)) {
425 *result_listener << " for batteryCapacityLevel.";
426 return false;
427 }
428 if (!ExplainMatchResult(Ge(-1), arg.batteryChargeTimeToFullNowSeconds, result_listener)) {
429 *result_listener << " for batteryChargeTimeToFullNowSeconds.";
430 return false;
431 }
432
433 if (!ExplainMatchResult(
434 AnyOf(Eq(0), AllOf(Gt(kFullChargeDesignCapMinUah), Lt(kFullChargeDesignCapMaxUah))),
435 arg.batteryFullChargeDesignCapacityUah, result_listener)) {
436 *result_listener << " for batteryFullChargeDesignCapacityUah. It should be greater than "
437 "100 mAh and less than 100,000 mAh, or 0 if unknown";
438 return false;
439 }
440
441 return true;
442 }
443
444 /*
445 * Tests the values returned by getHealthInfo() from interface IHealth.
446 */
TEST_P(HealthAidl,getHealthInfo)447 TEST_P(HealthAidl, getHealthInfo) {
448 HealthInfo value;
449 auto status = health->getHealthInfo(&value);
450 ASSERT_THAT(status, AnyOf(IsOk(), ExceptionIs(EX_UNSUPPORTED_OPERATION)));
451 if (!status.isOk()) return;
452 ASSERT_THAT(value, IsValidHealthInfo());
453 }
454
455 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(HealthAidl);
456 INSTANTIATE_TEST_SUITE_P(Health, HealthAidl,
457 testing::ValuesIn(getAidlHalInstanceNames(IHealth::descriptor)),
458 PrintInstanceNameToString);
459
460 // For battery current tests, value may not be stable if the battery current has fluctuated.
461 // Retry in a bit more time (with the following timeout) and consider the test successful if it
462 // has succeed once.
463 static constexpr auto gBatteryTestTimeout = 1min;
464 static constexpr double gCurrentCompareFactor = 0.50;
465 class BatteryTest : public HealthAidl {};
466
467 // Tuple for all IHealth::get* API return values.
468 template <typename T>
469 struct HalResult {
470 std::shared_ptr<ScopedAStatus> result = std::make_shared<ScopedAStatus>();
471 T value;
472 };
473
474 // Needs to be called repeatedly within a period of time to ensure values are initialized.
IsBatteryCurrentSignCorrect(const HalResult<BatteryStatus> & status,const HalResult<int32_t> & current,bool acceptZeroCurrentAsUnknown)475 static AssertionResult IsBatteryCurrentSignCorrect(const HalResult<BatteryStatus>& status,
476 const HalResult<int32_t>& current,
477 bool acceptZeroCurrentAsUnknown) {
478 // getChargeStatus / getCurrentNow / getCurrentAverage / getHealthInfo already tested above.
479 // Here, just skip if not ok.
480 if (!status.result->isOk()) {
481 return AssertionSuccess() << "getChargeStatus / getHealthInfo returned "
482 << status.result->getDescription() << ", skipping";
483 }
484
485 if (!current.result->isOk()) {
486 return AssertionSuccess() << "getCurrentNow / getCurrentAverage returned "
487 << current.result->getDescription() << ", skipping";
488 }
489
490 return ::android::hardware::health::test_utils::IsBatteryCurrentSignCorrect(
491 status.value, current.value, acceptZeroCurrentAsUnknown,
492 [](BatteryStatus status) { return toString(status); });
493 }
494
IsBatteryCurrentSimilar(const HalResult<BatteryStatus> & status,const HalResult<int32_t> & current_now,const HalResult<int32_t> & current_average)495 static AssertionResult IsBatteryCurrentSimilar(const HalResult<BatteryStatus>& status,
496 const HalResult<int32_t>& current_now,
497 const HalResult<int32_t>& current_average) {
498 if (status.result->isOk() && status.value == BatteryStatus::FULL) {
499 // No reason to test on full battery because battery current load fluctuates.
500 return AssertionSuccess() << "Battery is full, skipping";
501 }
502
503 // getCurrentNow / getCurrentAverage / getHealthInfo already tested above. Here, just skip if
504 // not SUCCESS or value 0.
505 if (!current_now.result->isOk() || current_now.value == 0) {
506 return AssertionSuccess() << "getCurrentNow returned "
507 << current_now.result->getDescription() << " with value "
508 << current_now.value << ", skipping";
509 }
510
511 if (!current_average.result->isOk() || current_average.value == 0) {
512 return AssertionSuccess() << "getCurrentAverage returned "
513 << current_average.result->getDescription() << " with value "
514 << current_average.value << ", skipping";
515 }
516
517 return ::android::hardware::health::test_utils::IsBatteryCurrentSimilar(
518 current_now.value, current_average.value, gCurrentCompareFactor);
519 }
520
TEST_P(BatteryTest,InstantCurrentAgainstChargeStatusInHealthInfo)521 TEST_P(BatteryTest, InstantCurrentAgainstChargeStatusInHealthInfo) {
522 auto testOnce = [&]() -> AssertionResult {
523 HalResult<HealthInfo> health_info;
524 *health_info.result = health->getHealthInfo(&health_info.value);
525
526 return IsBatteryCurrentSignCorrect(
527 {health_info.result, health_info.value.batteryStatus},
528 {health_info.result, health_info.value.batteryCurrentMicroamps},
529 true /* accept zero current as unknown */);
530 };
531 EXPECT_TRUE(SucceedOnce(gBatteryTestTimeout, testOnce))
532 << "You may want to try again later when current_now becomes stable.";
533 }
534
TEST_P(BatteryTest,AverageCurrentAgainstChargeStatusInHealthInfo)535 TEST_P(BatteryTest, AverageCurrentAgainstChargeStatusInHealthInfo) {
536 auto testOnce = [&]() -> AssertionResult {
537 HalResult<HealthInfo> health_info;
538 *health_info.result = health->getHealthInfo(&health_info.value);
539 return IsBatteryCurrentSignCorrect(
540 {health_info.result, health_info.value.batteryStatus},
541 {health_info.result, health_info.value.batteryCurrentAverageMicroamps},
542 true /* accept zero current as unknown */);
543 };
544
545 EXPECT_TRUE(SucceedOnce(gBatteryTestTimeout, testOnce))
546 << "You may want to try again later when current_average becomes stable.";
547 }
548
TEST_P(BatteryTest,InstantCurrentAgainstAverageCurrentInHealthInfo)549 TEST_P(BatteryTest, InstantCurrentAgainstAverageCurrentInHealthInfo) {
550 auto testOnce = [&]() -> AssertionResult {
551 HalResult<HealthInfo> health_info;
552 *health_info.result = health->getHealthInfo(&health_info.value);
553 return IsBatteryCurrentSimilar(
554 {health_info.result, health_info.value.batteryStatus},
555 {health_info.result, health_info.value.batteryCurrentMicroamps},
556 {health_info.result, health_info.value.batteryCurrentAverageMicroamps});
557 };
558
559 EXPECT_TRUE(SucceedOnce(gBatteryTestTimeout, testOnce))
560 << "You may want to try again later when current_now and current_average becomes "
561 "stable.";
562 }
563
TEST_P(BatteryTest,InstantCurrentAgainstChargeStatusFromHal)564 TEST_P(BatteryTest, InstantCurrentAgainstChargeStatusFromHal) {
565 auto testOnce = [&]() -> AssertionResult {
566 HalResult<BatteryStatus> status;
567 *status.result = health->getChargeStatus(&status.value);
568 HalResult<int32_t> current_now;
569 *current_now.result = health->getCurrentNowMicroamps(¤t_now.value);
570 return IsBatteryCurrentSignCorrect(status, current_now,
571 false /* accept zero current as unknown */);
572 };
573
574 EXPECT_TRUE(SucceedOnce(gBatteryTestTimeout, testOnce))
575 << "You may want to try again later when current_now becomes stable.";
576 }
577
TEST_P(BatteryTest,AverageCurrentAgainstChargeStatusFromHal)578 TEST_P(BatteryTest, AverageCurrentAgainstChargeStatusFromHal) {
579 auto testOnce = [&]() -> AssertionResult {
580 HalResult<BatteryStatus> status;
581 *status.result = health->getChargeStatus(&status.value);
582 HalResult<int32_t> current_average;
583 *current_average.result = health->getCurrentAverageMicroamps(¤t_average.value);
584 return IsBatteryCurrentSignCorrect(status, current_average,
585 false /* accept zero current as unknown */);
586 };
587
588 EXPECT_TRUE(SucceedOnce(gBatteryTestTimeout, testOnce))
589 << "You may want to try again later when current_average becomes stable.";
590 }
591
TEST_P(BatteryTest,InstantCurrentAgainstAverageCurrentFromHal)592 TEST_P(BatteryTest, InstantCurrentAgainstAverageCurrentFromHal) {
593 auto testOnce = [&]() -> AssertionResult {
594 HalResult<BatteryStatus> status;
595 *status.result = health->getChargeStatus(&status.value);
596 HalResult<int32_t> current_now;
597 *current_now.result = health->getCurrentNowMicroamps(¤t_now.value);
598 HalResult<int32_t> current_average;
599 *current_average.result = health->getCurrentAverageMicroamps(¤t_average.value);
600 return IsBatteryCurrentSimilar(status, current_now, current_average);
601 };
602
603 EXPECT_TRUE(SucceedOnce(gBatteryTestTimeout, testOnce))
604 << "You may want to try again later when current_average becomes stable.";
605 }
606
IsBatteryStatusCorrect(const HalResult<BatteryStatus> & status,const HalResult<HealthInfo> & health_info)607 AssertionResult IsBatteryStatusCorrect(const HalResult<BatteryStatus>& status,
608 const HalResult<HealthInfo>& health_info) {
609 // getChargetStatus / getHealthInfo is already tested above. Here, just skip if not ok.
610 if (!health_info.result->isOk()) {
611 return AssertionSuccess() << "getHealthInfo returned "
612 << health_info.result->getDescription() << ", skipping";
613 }
614 if (!status.result->isOk()) {
615 return AssertionSuccess() << "getChargeStatus returned " << status.result->getDescription()
616 << ", skipping";
617 }
618 return ::android::hardware::health::test_utils::IsBatteryStatusCorrect(
619 status.value, health_info.value, [](BatteryStatus status) { return toString(status); });
620 }
621
TEST_P(BatteryTest,ConnectedAgainstStatusFromHal)622 TEST_P(BatteryTest, ConnectedAgainstStatusFromHal) {
623 auto testOnce = [&]() -> AssertionResult {
624 HalResult<BatteryStatus> status;
625 *status.result = health->getChargeStatus(&status.value);
626 HalResult<HealthInfo> health_info;
627 *health_info.result = health->getHealthInfo(&health_info.value);
628 return IsBatteryStatusCorrect(status, health_info);
629 };
630
631 EXPECT_TRUE(SucceedOnce(gBatteryTestTimeout, testOnce))
632 << "You may want to try again later when battery_status becomes stable.";
633 }
634
TEST_P(BatteryTest,ConnectedAgainstStatusInHealthInfo)635 TEST_P(BatteryTest, ConnectedAgainstStatusInHealthInfo) {
636 auto testOnce = [&]() -> AssertionResult {
637 HalResult<HealthInfo> health_info;
638 *health_info.result = health->getHealthInfo(&health_info.value);
639 return IsBatteryStatusCorrect({health_info.result, health_info.value.batteryStatus},
640 health_info);
641 };
642
643 EXPECT_TRUE(SucceedOnce(gBatteryTestTimeout, testOnce))
644 << "You may want to try again later when getHealthInfo becomes stable.";
645 }
646
647 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(BatteryTest);
648 INSTANTIATE_TEST_SUITE_P(Health, BatteryTest,
649 testing::ValuesIn(getAidlHalInstanceNames(IHealth::descriptor)),
650 PrintInstanceNameToString);
651
652 } // namespace aidl::android::hardware::health
653
main(int argc,char ** argv)654 int main(int argc, char** argv) {
655 ::testing::InitGoogleTest(&argc, argv);
656 ABinderProcess_setThreadPoolMaxThreadCount(1);
657 ABinderProcess_startThreadPool();
658 return RUN_ALL_TESTS();
659 }
660