1 /*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "test_utils.h"
17
18 #include <dirent.h>
19 #include <fcntl.h>
20 #include <fstream>
21 #include <sys/stat.h>
22 #include <unistd.h>
23 #include <vector>
24
25 #include "battery_log.h"
26
27 using namespace std;
28
29 namespace OHOS {
30 namespace PowerMgr {
31 namespace {
32 constexpr const char* MOCK_PATH = "/data/service/el0/battery";
33 constexpr const char* POWER_SUPPLY_PATH = "/sys/class/power_supply";
34 vector<string> MOCK_DIR_NAME = {
35 "battery",
36 "USB",
37 "Wireless",
38 "Mains",
39 "ohos_charger",
40 "ohos-fgu"
41 };
42
43 vector<vector<string>> MOCK_FILE_NAME = {
44 { "capacity", "voltage_now", "temp", "health", "status", "present", "charge_counter", "technology" },
45 { "type", "online", "current_max", "voltage_max" },
46 { "type", "online" },
47 { "type", "online" },
48 { "type", "online" },
49 { "type", "online" }
50 };
51 }
52
WriteMock(const std::string & path,const std::string content)53 void TestUtils::WriteMock(const std::string& path, const std::string content)
54 {
55 std::ofstream stream(path.c_str());
56 if (!stream.is_open()) {
57 BATTERY_HILOGI(LABEL_TEST, "Cannot create file");
58 return;
59 }
60 stream << content.c_str() << std::endl;
61 stream.close();
62 }
63
InitTest()64 void TestUtils::InitTest()
65 {
66 mkdir(MOCK_PATH, S_IRWXU);
67 for (size_t i = 0; i < MOCK_DIR_NAME.size(); ++i) {
68 mkdir((std::string(MOCK_PATH) + "/" + MOCK_DIR_NAME[i]).c_str(), S_IRWXU);
69 }
70 }
71
ResetOnline()72 void TestUtils::ResetOnline()
73 {
74 for (size_t dInd = 0; dInd < MOCK_DIR_NAME.size(); ++dInd) {
75 for (size_t fInd = 0; fInd < MOCK_FILE_NAME[dInd].size(); ++fInd) {
76 if (MOCK_FILE_NAME[dInd][fInd] == "online") {
77 std::string file = std::string(MOCK_PATH) + "/" + MOCK_DIR_NAME[dInd] + "/" + "online";
78 WriteMock(file, "0");
79 }
80 }
81 }
82 }
83
IsMock()84 bool TestUtils::IsMock()
85 {
86 DIR* dir = opendir(POWER_SUPPLY_PATH);
87 if (dir == nullptr) {
88 return true;
89 }
90 struct dirent* ptr = nullptr;
91 while ((ptr = readdir(dir)) != nullptr) {
92 if (strcmp(".", ptr->d_name) != 0 && strcmp("..", ptr->d_name) != 0) {
93 closedir(dir);
94 return false;
95 }
96 }
97 closedir(dir);
98 return true;
99 }
100 } // namespace PowerMgr
101 } // namespace OHOS
102