blob: 3e071888cda89a346863a904eae8287fa7ad4d25 [file] [log] [blame]
Yifan Hong2200cff2021-10-28 12:18:35 -07001/*
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
36using android::getAidlHalInstanceNames;
37using android::PrintInstanceNameToString;
38using android::hardware::health::test_utils::SucceedOnce;
39using ndk::enum_range;
40using ndk::ScopedAStatus;
41using ndk::SharedRefBase;
42using ndk::SpAIBinder;
43using testing::AllOf;
44using testing::AnyOf;
45using testing::AnyOfArray;
46using testing::AssertionFailure;
47using testing::AssertionResult;
48using testing::AssertionSuccess;
49using testing::Contains;
50using testing::Each;
51using testing::Eq;
52using testing::ExplainMatchResult;
53using testing::Ge;
54using testing::Gt;
55using testing::Le;
56using testing::Lt;
57using testing::Matcher;
58using testing::Not;
59using namespace std::string_literals;
60using namespace std::chrono_literals;
61
62namespace aidl::android::hardware::health {
63
64static constexpr int32_t kFullChargeDesignCapMinUah = 100 * 1000;
65static constexpr int32_t kFullChargeDesignCapMaxUah = 100 * 1000 * 1000;
66
67MATCHER(IsOk, "") {
68 *result_listener << "status is " << arg.getDescription();
69 return arg.isOk();
70}
71
72MATCHER_P(ExceptionIs, exception_code, "") {
73 *result_listener << "status is " << arg.getDescription();
74 return arg.getExceptionCode() == exception_code;
75}
76
77template <typename T>
78Matcher<T> InClosedRange(const T& lo, const T& hi) {
79 return AllOf(Ge(lo), Le(hi));
80}
81
82template <typename T>
83Matcher<T> IsValidEnum() {
84 return AnyOfArray(enum_range<T>().begin(), enum_range<T>().end());
85}
86
87class HealthAidl : public testing::TestWithParam<std::string> {
88 public:
89 void SetUp() override {
90 SpAIBinder binder(AServiceManager_waitForService(GetParam().c_str()));
91 health = IHealth::fromBinder(binder);
92 ASSERT_NE(health, nullptr);
93 }
94 std::shared_ptr<IHealth> health;
95};
96
97class Callback : public BnHealthInfoCallback {
98 public:
99 ScopedAStatus healthInfoChanged(const HealthInfo&) override {
100 {
101 std::lock_guard<std::mutex> lock(mutex_);
102 invoked_ = true;
103 }
104 invoked_notify_.notify_all();
105 return ScopedAStatus::ok();
106 }
107 template <typename R, typename P>
108 [[nodiscard]] bool waitInvoke(std::chrono::duration<R, P> duration) {
109 std::unique_lock<std::mutex> lock(mutex_);
110 bool r = invoked_notify_.wait_for(lock, duration, [this] { return this->invoked_; });
111 invoked_ = false;
112 return r;
113 }
114
115 private:
116 std::mutex mutex_;
117 std::condition_variable invoked_notify_;
118 bool invoked_ = false;
119};
120
121TEST_P(HealthAidl, Callbacks) {
122 auto first_callback = SharedRefBase::make<Callback>();
123 auto second_callback = SharedRefBase::make<Callback>();
124
125 ASSERT_THAT(health->registerCallback(first_callback), IsOk());
126 ASSERT_THAT(health->registerCallback(second_callback), IsOk());
127
128 // registerCallback may or may not invoke the callback immediately, so the test needs
129 // to wait for the invocation. If the implementation chooses not to invoke the callback
130 // immediately, just wait for some time.
131 (void)first_callback->waitInvoke(200ms);
132 (void)second_callback->waitInvoke(200ms);
133
134 // assert that the first callback is invoked when update is called.
135 ASSERT_THAT(health->update(), IsOk());
136
137 ASSERT_TRUE(first_callback->waitInvoke(1s));
138 ASSERT_TRUE(second_callback->waitInvoke(1s));
139
140 ASSERT_THAT(health->unregisterCallback(first_callback), IsOk());
141
142 // clear any potentially pending callbacks result from wakealarm / kernel events
143 // If there is none, just wait for some time.
144 (void)first_callback->waitInvoke(200ms);
145 (void)second_callback->waitInvoke(200ms);
146
147 // assert that the second callback is still invoked even though the first is unregistered.
148 ASSERT_THAT(health->update(), IsOk());
149
150 ASSERT_FALSE(first_callback->waitInvoke(200ms));
151 ASSERT_TRUE(second_callback->waitInvoke(1s));
152
153 ASSERT_THAT(health->unregisterCallback(second_callback), IsOk());
154}
155
156TEST_P(HealthAidl, UnregisterNonExistentCallback) {
157 auto callback = SharedRefBase::make<Callback>();
158 auto ret = health->unregisterCallback(callback);
159 ASSERT_THAT(ret, ExceptionIs(EX_ILLEGAL_ARGUMENT));
160}
161
162/*
163 * Tests the values returned by getChargeCounterUah() from interface IHealth.
164 */
165TEST_P(HealthAidl, getChargeCounterUah) {
166 int32_t value;
167 auto status = health->getChargeCounterUah(&value);
168 ASSERT_THAT(status, AnyOf(IsOk(), ExceptionIs(EX_UNSUPPORTED_OPERATION)));
169 if (!status.isOk()) return;
170 ASSERT_THAT(value, Ge(0));
171}
172
173/*
174 * Tests the values returned by getCurrentNowMicroamps() from interface IHealth.
175 */
176TEST_P(HealthAidl, getCurrentNowMicroamps) {
177 int32_t value;
178 auto status = health->getCurrentNowMicroamps(&value);
179 ASSERT_THAT(status, AnyOf(IsOk(), ExceptionIs(EX_UNSUPPORTED_OPERATION)));
180 if (!status.isOk()) return;
181 ASSERT_THAT(value, Not(INT32_MIN));
182}
183
184/*
185 * Tests the values returned by getCurrentAverageMicroamps() from interface IHealth.
186 */
187TEST_P(HealthAidl, getCurrentAverageMicroamps) {
188 int32_t value;
189 auto status = health->getCurrentAverageMicroamps(&value);
190 ASSERT_THAT(status, AnyOf(IsOk(), ExceptionIs(EX_UNSUPPORTED_OPERATION)));
191 if (!status.isOk()) return;
192 ASSERT_THAT(value, Not(INT32_MIN));
193}
194
195/*
196 * Tests the values returned by getCapacity() from interface IHealth.
197 */
198TEST_P(HealthAidl, getCapacity) {
199 int32_t value;
200 auto status = health->getCapacity(&value);
201 ASSERT_THAT(status, AnyOf(IsOk(), ExceptionIs(EX_UNSUPPORTED_OPERATION)));
202 if (!status.isOk()) return;
203 ASSERT_THAT(value, InClosedRange(0, 100));
204}
205
206/*
207 * Tests the values returned by getEnergyCounterNwh() from interface IHealth.
208 */
209TEST_P(HealthAidl, getEnergyCounterNwh) {
210 int64_t value;
211 auto status = health->getEnergyCounterNwh(&value);
212 ASSERT_THAT(status, AnyOf(IsOk(), ExceptionIs(EX_UNSUPPORTED_OPERATION)));
213 if (!status.isOk()) return;
214 ASSERT_THAT(value, Not(INT64_MIN));
215}
216
217/*
218 * Tests the values returned by getChargeStatus() from interface IHealth.
219 */
220TEST_P(HealthAidl, getChargeStatus) {
221 BatteryStatus value;
222 auto status = health->getChargeStatus(&value);
223 ASSERT_THAT(status, AnyOf(IsOk(), ExceptionIs(EX_UNSUPPORTED_OPERATION)));
224 if (!status.isOk()) return;
225 ASSERT_THAT(value, IsValidEnum<BatteryStatus>());
226}
227
228MATCHER(IsValidStorageInfo, "") {
229 *result_listener << "value is " << arg.toString() << ".";
230 if (!ExplainMatchResult(InClosedRange(0, 3), arg.eol, result_listener)) {
231 *result_listener << " for eol.";
232 return false;
233 }
234 if (!ExplainMatchResult(InClosedRange(0, 0x0B), arg.lifetimeA, result_listener)) {
235 *result_listener << " for lifetimeA.";
236 return false;
237 }
238 if (!ExplainMatchResult(InClosedRange(0, 0x0B), arg.lifetimeB, result_listener)) {
239 *result_listener << " for lifetimeB.";
240 return false;
241 }
242 return true;
243}
244
245/*
246 * Tests the values returned by getStorageInfo() from interface IHealth.
247 */
248TEST_P(HealthAidl, getStorageInfo) {
249 std::vector<StorageInfo> value;
250 auto status = health->getStorageInfo(&value);
251 ASSERT_THAT(status, AnyOf(IsOk(), ExceptionIs(EX_UNSUPPORTED_OPERATION)));
252 if (!status.isOk()) return;
253 ASSERT_THAT(value, Each(IsValidStorageInfo()));
254}
255
256/*
257 * Tests the values returned by getDiskStats() from interface IHealth.
258 */
259TEST_P(HealthAidl, getDiskStats) {
260 std::vector<DiskStats> value;
261 auto status = health->getDiskStats(&value);
262 ASSERT_THAT(status, AnyOf(IsOk(), ExceptionIs(EX_UNSUPPORTED_OPERATION)));
263}
264
265MATCHER(IsValidHealthInfo, "") {
266 *result_listener << "value is " << arg.toString() << ".";
267 if (!ExplainMatchResult(Each(IsValidStorageInfo()), arg.storageInfos, result_listener)) {
268 *result_listener << " for storageInfos.";
269 return false;
270 }
271
272 if (!ExplainMatchResult(Not(INT32_MIN), arg.batteryCurrentMicroamps, result_listener)) {
273 *result_listener << " for batteryCurrentMicroamps.";
274 return false;
275 }
276
277 if (!ExplainMatchResult(InClosedRange(0, 100), arg.batteryLevel, result_listener)) {
278 *result_listener << " for batteryLevel.";
279 return false;
280 }
281
282 if (!ExplainMatchResult(IsValidEnum<BatteryHealth>(), arg.batteryHealth, result_listener)) {
283 *result_listener << " for batteryHealth.";
284 return false;
285 }
286
287 if (!ExplainMatchResult(IsValidEnum<BatteryStatus>(), arg.batteryStatus, result_listener)) {
288 *result_listener << " for batteryStatus.";
289 return false;
290 }
291
292 if (arg.batteryPresent) {
293 if (!ExplainMatchResult(Gt(0), arg.batteryChargeCounterUah, result_listener)) {
294 *result_listener << " for batteryChargeCounterUah when battery is present.";
295 return false;
296 }
297 if (!ExplainMatchResult(Not(BatteryStatus::UNKNOWN), arg.batteryStatus, result_listener)) {
298 *result_listener << " for batteryStatus when battery is present.";
299 return false;
300 }
301 }
302
303 if (!ExplainMatchResult(IsValidEnum<BatteryCapacityLevel>(), arg.batteryCapacityLevel,
304 result_listener)) {
305 *result_listener << " for batteryCapacityLevel.";
306 return false;
307 }
308 if (!ExplainMatchResult(Ge(-1), arg.batteryChargeTimeToFullNowSeconds, result_listener)) {
309 *result_listener << " for batteryChargeTimeToFullNowSeconds.";
310 return false;
311 }
312
313 if (!ExplainMatchResult(
314 AnyOf(Eq(0), AllOf(Gt(kFullChargeDesignCapMinUah), Lt(kFullChargeDesignCapMaxUah))),
315 arg.batteryFullChargeDesignCapacityUah, result_listener)) {
316 *result_listener << " for batteryFullChargeDesignCapacityUah. It should be greater than "
317 "100 mAh and less than 100,000 mAh, or 0 if unknown";
318 return false;
319 }
320
321 return true;
322}
323
324/*
325 * Tests the values returned by getHealthInfo() from interface IHealth.
326 */
327TEST_P(HealthAidl, getHealthInfo) {
328 HealthInfo value;
329 auto status = health->getHealthInfo(&value);
330 ASSERT_THAT(status, AnyOf(IsOk(), ExceptionIs(EX_UNSUPPORTED_OPERATION)));
331 if (!status.isOk()) return;
332 ASSERT_THAT(value, IsValidHealthInfo());
333}
334
335GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(HealthAidl);
336INSTANTIATE_TEST_SUITE_P(Health, HealthAidl,
337 testing::ValuesIn(getAidlHalInstanceNames(IHealth::descriptor)),
338 PrintInstanceNameToString);
339
340// For battery current tests, value may not be stable if the battery current has fluctuated.
341// Retry in a bit more time (with the following timeout) and consider the test successful if it
342// has succeed once.
343static constexpr auto gBatteryTestTimeout = 1min;
344static constexpr double gCurrentCompareFactor = 0.50;
345class BatteryTest : public HealthAidl {};
346
347// Tuple for all IHealth::get* API return values.
348template <typename T>
349struct HalResult {
350 std::shared_ptr<ScopedAStatus> result = std::make_shared<ScopedAStatus>();
351 T value;
352};
353
354// Needs to be called repeatedly within a period of time to ensure values are initialized.
355static AssertionResult IsBatteryCurrentSignCorrect(const HalResult<BatteryStatus>& status,
356 const HalResult<int32_t>& current,
357 bool acceptZeroCurrentAsUnknown) {
358 // getChargeStatus / getCurrentNow / getCurrentAverage / getHealthInfo already tested above.
359 // Here, just skip if not ok.
360 if (!status.result->isOk()) {
361 return AssertionSuccess() << "getChargeStatus / getHealthInfo returned "
362 << status.result->getDescription() << ", skipping";
363 }
364
365 if (!current.result->isOk()) {
366 return AssertionSuccess() << "getCurrentNow / getCurrentAverage returned "
367 << current.result->getDescription() << ", skipping";
368 }
369
370 return ::android::hardware::health::test_utils::IsBatteryCurrentSignCorrect(
371 status.value, current.value, acceptZeroCurrentAsUnknown,
372 [](BatteryStatus status) { return toString(status); });
373}
374
375static AssertionResult IsBatteryCurrentSimilar(const HalResult<BatteryStatus>& status,
376 const HalResult<int32_t>& current_now,
377 const HalResult<int32_t>& current_average) {
378 if (status.result->isOk() && status.value == BatteryStatus::FULL) {
379 // No reason to test on full battery because battery current load fluctuates.
380 return AssertionSuccess() << "Battery is full, skipping";
381 }
382
383 // getCurrentNow / getCurrentAverage / getHealthInfo already tested above. Here, just skip if
384 // not SUCCESS or value 0.
385 if (!current_now.result->isOk() || current_now.value == 0) {
386 return AssertionSuccess() << "getCurrentNow returned "
387 << current_now.result->getDescription() << " with value "
388 << current_now.value << ", skipping";
389 }
390
391 if (!current_average.result->isOk() || current_average.value == 0) {
392 return AssertionSuccess() << "getCurrentAverage returned "
393 << current_average.result->getDescription() << " with value "
394 << current_average.value << ", skipping";
395 }
396
397 return ::android::hardware::health::test_utils::IsBatteryCurrentSimilar(
398 current_now.value, current_average.value, gCurrentCompareFactor);
399}
400
401TEST_P(BatteryTest, InstantCurrentAgainstChargeStatusInHealthInfo) {
402 auto testOnce = [&]() -> AssertionResult {
403 HalResult<HealthInfo> health_info;
404 *health_info.result = health->getHealthInfo(&health_info.value);
405
406 return IsBatteryCurrentSignCorrect(
407 {health_info.result, health_info.value.batteryStatus},
408 {health_info.result, health_info.value.batteryCurrentMicroamps},
409 true /* accept zero current as unknown */);
410 };
411 EXPECT_TRUE(SucceedOnce(gBatteryTestTimeout, testOnce))
412 << "You may want to try again later when current_now becomes stable.";
413}
414
415TEST_P(BatteryTest, AverageCurrentAgainstChargeStatusInHealthInfo) {
416 auto testOnce = [&]() -> AssertionResult {
417 HalResult<HealthInfo> health_info;
418 *health_info.result = health->getHealthInfo(&health_info.value);
419 return IsBatteryCurrentSignCorrect(
420 {health_info.result, health_info.value.batteryStatus},
421 {health_info.result, health_info.value.batteryCurrentAverageMicroamps},
422 true /* accept zero current as unknown */);
423 };
424
425 EXPECT_TRUE(SucceedOnce(gBatteryTestTimeout, testOnce))
426 << "You may want to try again later when current_average becomes stable.";
427}
428
429TEST_P(BatteryTest, InstantCurrentAgainstAverageCurrentInHealthInfo) {
430 auto testOnce = [&]() -> AssertionResult {
431 HalResult<HealthInfo> health_info;
432 *health_info.result = health->getHealthInfo(&health_info.value);
433 return IsBatteryCurrentSimilar(
434 {health_info.result, health_info.value.batteryStatus},
435 {health_info.result, health_info.value.batteryCurrentMicroamps},
436 {health_info.result, health_info.value.batteryCurrentAverageMicroamps});
437 };
438
439 EXPECT_TRUE(SucceedOnce(gBatteryTestTimeout, testOnce))
440 << "You may want to try again later when current_now and current_average becomes "
441 "stable.";
442}
443
444TEST_P(BatteryTest, InstantCurrentAgainstChargeStatusFromHal) {
445 auto testOnce = [&]() -> AssertionResult {
446 HalResult<BatteryStatus> status;
447 *status.result = health->getChargeStatus(&status.value);
448 HalResult<int32_t> current_now;
449 *current_now.result = health->getCurrentNowMicroamps(&current_now.value);
450 return IsBatteryCurrentSignCorrect(status, current_now,
451 false /* accept zero current as unknown */);
452 };
453
454 EXPECT_TRUE(SucceedOnce(gBatteryTestTimeout, testOnce))
455 << "You may want to try again later when current_now becomes stable.";
456}
457
458TEST_P(BatteryTest, AverageCurrentAgainstChargeStatusFromHal) {
459 auto testOnce = [&]() -> AssertionResult {
460 HalResult<BatteryStatus> status;
461 *status.result = health->getChargeStatus(&status.value);
462 HalResult<int32_t> current_average;
463 *current_average.result = health->getCurrentAverageMicroamps(&current_average.value);
464 return IsBatteryCurrentSignCorrect(status, current_average,
465 false /* accept zero current as unknown */);
466 };
467
468 EXPECT_TRUE(SucceedOnce(gBatteryTestTimeout, testOnce))
469 << "You may want to try again later when current_average becomes stable.";
470}
471
472TEST_P(BatteryTest, InstantCurrentAgainstAverageCurrentFromHal) {
473 auto testOnce = [&]() -> AssertionResult {
474 HalResult<BatteryStatus> status;
475 *status.result = health->getChargeStatus(&status.value);
476 HalResult<int32_t> current_now;
477 *current_now.result = health->getCurrentNowMicroamps(&current_now.value);
478 HalResult<int32_t> current_average;
479 *current_average.result = health->getCurrentAverageMicroamps(&current_average.value);
480 return IsBatteryCurrentSimilar(status, current_now, current_average);
481 };
482
483 EXPECT_TRUE(SucceedOnce(gBatteryTestTimeout, testOnce))
484 << "You may want to try again later when current_average becomes stable.";
485}
486
487AssertionResult IsBatteryStatusCorrect(const HalResult<BatteryStatus>& status,
488 const HalResult<HealthInfo>& health_info) {
489 // getChargetStatus / getHealthInfo is already tested above. Here, just skip if not ok.
490 if (!health_info.result->isOk()) {
491 return AssertionSuccess() << "getHealthInfo returned "
492 << health_info.result->getDescription() << ", skipping";
493 }
494 if (!status.result->isOk()) {
495 return AssertionSuccess() << "getChargeStatus returned " << status.result->getDescription()
496 << ", skipping";
497 }
498 return ::android::hardware::health::test_utils::IsBatteryStatusCorrect(
499 status.value, health_info.value, [](BatteryStatus status) { return toString(status); });
500}
501
502TEST_P(BatteryTest, ConnectedAgainstStatusFromHal) {
503 auto testOnce = [&]() -> AssertionResult {
504 HalResult<BatteryStatus> status;
505 *status.result = health->getChargeStatus(&status.value);
506 HalResult<HealthInfo> health_info;
507 *health_info.result = health->getHealthInfo(&health_info.value);
508 return IsBatteryStatusCorrect(status, health_info);
509 };
510
511 EXPECT_TRUE(SucceedOnce(gBatteryTestTimeout, testOnce))
512 << "You may want to try again later when battery_status becomes stable.";
513}
514
515TEST_P(BatteryTest, ConnectedAgainstStatusInHealthInfo) {
516 auto testOnce = [&]() -> AssertionResult {
517 HalResult<HealthInfo> health_info;
518 *health_info.result = health->getHealthInfo(&health_info.value);
519 return IsBatteryStatusCorrect({health_info.result, health_info.value.batteryStatus},
520 health_info);
521 };
522
523 EXPECT_TRUE(SucceedOnce(gBatteryTestTimeout, testOnce))
524 << "You may want to try again later when getHealthInfo becomes stable.";
525}
526
527GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(BatteryTest);
528INSTANTIATE_TEST_SUITE_P(Health, BatteryTest,
529 testing::ValuesIn(getAidlHalInstanceNames(IHealth::descriptor)),
530 PrintInstanceNameToString);
531
532} // namespace aidl::android::hardware::health
533
534int main(int argc, char** argv) {
535 ::testing::InitGoogleTest(&argc, argv);
536 ABinderProcess_setThreadPoolMaxThreadCount(1);
537 ABinderProcess_startThreadPool();
538 return RUN_ALL_TESTS();
539}