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 #include <sysexits.h>
18 #include <unistd.h>
19 
20 #include <iostream>
21 #include <string>
22 
23 #include <android-base/file.h>
24 #include <android-base/logging.h>
25 #include <android-base/strings.h>
26 #include <gmock/gmock.h>
27 #include <gtest/gtest.h>
28 #include <health/utils.h>
29 
30 #include "healthd_mode_charger.h"
31 
32 using android::hardware::Return;
33 using android::hardware::health::InitHealthdConfig;
34 using std::string_literals::operator""s;
35 using testing::_;
36 using testing::Invoke;
37 using testing::NiceMock;
38 using testing::StrEq;
39 using testing::Test;
40 
41 namespace android {
42 
43 // A replacement to ASSERT_* to be used in a forked process. When the condition is not met,
44 // print a gtest message, then exit abnormally.
45 class ChildAssertHelper : public std::stringstream {
46   public:
ChildAssertHelper(bool res,const char * expr,const char * file,int line)47     ChildAssertHelper(bool res, const char* expr, const char* file, int line) : res_(res) {
48         (*this) << file << ":" << line << ": `" << expr << "` evaluates to false\n";
49     }
~ChildAssertHelper()50     ~ChildAssertHelper() {
51         EXPECT_TRUE(res_) << str();
52         if (!res_) exit(EX_SOFTWARE);
53     }
54 
55   private:
56     bool res_;
57     DISALLOW_COPY_AND_ASSIGN(ChildAssertHelper);
58 };
59 #define CHILD_ASSERT_TRUE(expr) ChildAssertHelper(expr, #expr, __FILE__, __LINE__)
60 
61 // Run |test_body| in a chroot jail in a forked process. |subdir| is a sub-directory in testdata.
62 // Within |test_body|,
63 // - non-fatal errors may be reported using EXPECT_* macro as usual.
64 // - fatal errors must be reported using CHILD_ASSERT_TRUE macro. ASSERT_* must not be used.
ForkTest(const std::string & subdir,const std::function<void (void)> & test_body)65 void ForkTest(const std::string& subdir, const std::function<void(void)>& test_body) {
66     pid_t pid = fork();
67     ASSERT_GE(pid, 0) << "Fork fails: " << strerror(errno);
68     if (pid == 0) {
69         // child
70         CHILD_ASSERT_TRUE(
71                 chroot((android::base::GetExecutableDirectory() + "/" + subdir).c_str()) != -1)
72                 << "Failed to chroot to " << subdir << ": " << strerror(errno);
73         test_body();
74         // EXPECT_* macros may set the HasFailure bit without calling exit(). Set exit status
75         // accordingly.
76         exit(::testing::Test::HasFailure() ? EX_SOFTWARE : EX_OK);
77     }
78     // parent
79     int status;
80     ASSERT_NE(-1, waitpid(pid, &status, 0)) << "waitpid() fails: " << strerror(errno);
81     ASSERT_TRUE(WIFEXITED(status)) << "Test fails, waitpid() returns " << status;
82     ASSERT_EQ(EX_OK, WEXITSTATUS(status)) << "Test fails, child process returns " << status;
83 }
84 
85 class MockHealth : public android::hardware::health::V2_1::IHealth {
86     MOCK_METHOD(Return<::android::hardware::health::V2_0::Result>, registerCallback,
87                 (const sp<::android::hardware::health::V2_0::IHealthInfoCallback>& callback));
88     MOCK_METHOD(Return<::android::hardware::health::V2_0::Result>, unregisterCallback,
89                 (const sp<::android::hardware::health::V2_0::IHealthInfoCallback>& callback));
90     MOCK_METHOD(Return<::android::hardware::health::V2_0::Result>, update, ());
91     MOCK_METHOD(Return<void>, getChargeCounter, (getChargeCounter_cb _hidl_cb));
92     MOCK_METHOD(Return<void>, getCurrentNow, (getCurrentNow_cb _hidl_cb));
93     MOCK_METHOD(Return<void>, getCurrentAverage, (getCurrentAverage_cb _hidl_cb));
94     MOCK_METHOD(Return<void>, getCapacity, (getCapacity_cb _hidl_cb));
95     MOCK_METHOD(Return<void>, getEnergyCounter, (getEnergyCounter_cb _hidl_cb));
96     MOCK_METHOD(Return<void>, getChargeStatus, (getChargeStatus_cb _hidl_cb));
97     MOCK_METHOD(Return<void>, getStorageInfo, (getStorageInfo_cb _hidl_cb));
98     MOCK_METHOD(Return<void>, getDiskStats, (getDiskStats_cb _hidl_cb));
99     MOCK_METHOD(Return<void>, getHealthInfo, (getHealthInfo_cb _hidl_cb));
100     MOCK_METHOD(Return<void>, getHealthConfig, (getHealthConfig_cb _hidl_cb));
101     MOCK_METHOD(Return<void>, getHealthInfo_2_1, (getHealthInfo_2_1_cb _hidl_cb));
102     MOCK_METHOD(Return<void>, shouldKeepScreenOn, (shouldKeepScreenOn_cb _hidl_cb));
103 };
104 
105 class TestCharger : public Charger {
106   public:
107     // Inherit constructor.
108     using Charger::Charger;
109     // Expose protected functions to be used in tests.
Init(struct healthd_config * config)110     void Init(struct healthd_config* config) override { Charger::Init(config); }
111     MOCK_METHOD(int, CreateDisplaySurface, (const std::string& name, GRSurface** surface));
112     MOCK_METHOD(int, CreateMultiDisplaySurface,
113                 (const std::string& name, int* frames, int* fps, GRSurface*** surface));
114 };
115 
116 // Intentionally leak TestCharger instance to avoid calling ~HealthLoop() because ~HealthLoop()
117 // should never be called. But still verify expected calls upon destruction.
118 class VerifiedTestCharger {
119   public:
VerifiedTestCharger(TestCharger * charger)120     VerifiedTestCharger(TestCharger* charger) : charger_(charger) {
121         testing::Mock::AllowLeak(charger_);
122     }
operator *()123     TestCharger& operator*() { return *charger_; }
operator ->()124     TestCharger* operator->() { return charger_; }
~VerifiedTestCharger()125     ~VerifiedTestCharger() { testing::Mock::VerifyAndClearExpectations(charger_); }
126 
127   private:
128     TestCharger* charger_;
129 };
130 
131 // Do not use SetUp and TearDown of a test suite, as they will be invoked in the parent process, not
132 // the child process. In particular, if the test suite contains mocks, they will not be verified in
133 // the child process. Instead, create mocks within closures in each tests.
ExpectChargerResAt(const std::string & root)134 void ExpectChargerResAt(const std::string& root) {
135     sp<NiceMock<MockHealth>> health(new NiceMock<MockHealth>());
136     VerifiedTestCharger charger(new NiceMock<TestCharger>(health));
137 
138     // Only one frame in all testdata/**/animation.txt
139     GRSurface* multi[] = {nullptr};
140 
141     EXPECT_CALL(*charger, CreateDisplaySurface(StrEq(root + "charger/battery_fail.png"), _))
142             .WillRepeatedly(Invoke([](const auto&, GRSurface** surface) {
143                 *surface = nullptr;
144                 return 0;
145             }));
146     EXPECT_CALL(*charger,
147                 CreateMultiDisplaySurface(StrEq(root + "charger/battery_scale.png"), _, _, _))
148             .WillRepeatedly(Invoke([&](const auto&, int* frames, int* fps, GRSurface*** surface) {
149                 *frames = arraysize(multi);
150                 *fps = 60;  // Unused fps value
151                 *surface = multi;
152                 return 0;
153             }));
154     struct healthd_config healthd_config;
155     InitHealthdConfig(&healthd_config);
156     charger->Init(&healthd_config);
157 };
158 
159 // Test that if resources does not exist in /res or in /product/etc/res, load from /system.
TEST(ChargerLoadAnimationRes,Empty)160 TEST(ChargerLoadAnimationRes, Empty) {
161     ForkTest("empty", std::bind(&ExpectChargerResAt, "/system/etc/res/images/"));
162 }
163 
164 // Test loading everything from /res
TEST(ChargerLoadAnimationRes,Legacy)165 TEST(ChargerLoadAnimationRes, Legacy) {
166     ForkTest("legacy", std::bind(&ExpectChargerResAt, "/res/images/"));
167 }
168 
169 // Test loading animation text from /res but images from /system if images does not exist under
170 // /res.
TEST(ChargerLoadAnimationRes,LegacyTextSystemImages)171 TEST(ChargerLoadAnimationRes, LegacyTextSystemImages) {
172     ForkTest("legacy_text_system_images",
173              std::bind(&ExpectChargerResAt, "/system/etc/res/images/"));
174 }
175 
176 // Test loading everything from /product
TEST(ChargerLoadAnimationRes,Product)177 TEST(ChargerLoadAnimationRes, Product) {
178     ForkTest("product", std::bind(&ExpectChargerResAt, "/product/etc/res/images/"));
179 }
180 
181 }  // namespace android
182