From 56ee1320da2dae9cb51bb725fcdce0edf728668d Mon Sep 17 00:00:00 2001 From: wangyantian Date: Thu, 23 Apr 2026 12:35:06 +0800 Subject: [PATCH] feat: add ohos-battery-manager CLI tool for battery capacity and energy queries Add a new CLI tool under tools/ohos-battery-manager/ that wraps BatterySrvClient inner API to provide battery information queries via command line interface. Commands: - capacity: query battery level percentage (0-100%) - total-energy: query battery total energy (mAh) - remain-energy: query battery remaining energy (mAh) The tool uses static command table dispatch (std::unordered_map), outputs JSON to stdout, logs to stderr, and is configured with CFI sanitize per battery_manager component requirements. Feature gate: battery_manager_feature_support_battery_cli (default: false) Co-Authored-By: Agent Change-Id: I11bbcad5db8189338df3b1d7982f9860868aaa7a Signed-off-by: wangyantian --- batterymgr.gni | 1 + bundle.json | 9 +- tools/BUILD.gn | 28 +++ tools/ohos-battery-manager/BUILD.gn | 50 ++++ tools/ohos-battery-manager/config.json | 84 +++++++ tools/ohos-battery-manager/docs/README.md | 34 +++ tools/ohos-battery-manager/docs/USAGE.md | 65 ++++++ .../ohos-battery-manager/src/cli_handler.cpp | 211 +++++++++++++++++ tools/ohos-battery-manager/src/cli_handler.h | 21 ++ tools/ohos-battery-manager/src/main.cpp | 21 ++ tools/ohos-battery-manager/tests/BUILD.gn | 46 ++++ .../ohos-battery-manager/tests/test_main.cpp | 215 ++++++++++++++++++ 12 files changed, 782 insertions(+), 3 deletions(-) create mode 100644 tools/BUILD.gn create mode 100644 tools/ohos-battery-manager/BUILD.gn create mode 100644 tools/ohos-battery-manager/config.json create mode 100644 tools/ohos-battery-manager/docs/README.md create mode 100644 tools/ohos-battery-manager/docs/USAGE.md create mode 100644 tools/ohos-battery-manager/src/cli_handler.cpp create mode 100644 tools/ohos-battery-manager/src/cli_handler.h create mode 100644 tools/ohos-battery-manager/src/main.cpp create mode 100644 tools/ohos-battery-manager/tests/BUILD.gn create mode 100644 tools/ohos-battery-manager/tests/test_main.cpp diff --git a/batterymgr.gni b/batterymgr.gni index 9f0b8a7a..d41a6c3b 100755 --- a/batterymgr.gni +++ b/batterymgr.gni @@ -20,6 +20,7 @@ declare_args() { battery_manager_feature_support_notification = false battery_manager_feature_support_notification_string = false battery_manager_feature_enable_wireless_charge = false + battery_manager_feature_support_battery_cli = false } defines = [] diff --git a/bundle.json b/bundle.json index a322aad4..9bdf1b6a 100644 --- a/bundle.json +++ b/bundle.json @@ -23,7 +23,8 @@ "battery_manager_feature_enable_charging_sound", "battery_manager_feature_enable_wireless_charge", "battery_manager_feature_set_low_capacity_threshold", - "battery_manager_feature_support_notification" + "battery_manager_feature_support_notification", + "battery_manager_feature_support_battery_cli" ], "adapted_system_type": [ "standard" @@ -81,7 +82,8 @@ "//base/powermgr/battery_manager/frameworks:battery_napi", "//base/powermgr/battery_manager/frameworks:battery_capi", "//base/powermgr/battery_manager/frameworks/ets/taihe:battery_manager_taihe", - "//base/powermgr/battery_manager/interfaces/inner_api:batterysrv_client" + "//base/powermgr/battery_manager/interfaces/inner_api:batterysrv_client", + "//base/powermgr/battery_manager/tools:cli_tool_group" ], "service_group": [ "//base/powermgr/battery_manager/sa_profile:batterymgr_sa_profile", @@ -125,7 +127,8 @@ "//base/powermgr/battery_manager/test:battery_fuzzertest", "//base/powermgr/battery_manager/test:battery_benchmarktest", "//base/powermgr/battery_manager/test:battery_apitest", - "//base/powermgr/battery_manager/frameworks/ets/taihe:battery_manager_taihe_test" + "//base/powermgr/battery_manager/frameworks/ets/taihe:battery_manager_taihe_test", + "//base/powermgr/battery_manager/tools:cli_test_group" ] } } diff --git a/tools/BUILD.gn b/tools/BUILD.gn new file mode 100644 index 00000000..0df28323 --- /dev/null +++ b/tools/BUILD.gn @@ -0,0 +1,28 @@ +# Copyright (c) 2026 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//base/powermgr/battery_manager/batterymgr.gni") + +group("cli_tool_group") { + if (battery_manager_feature_support_battery_cli) { + deps = [ "ohos-battery-manager:ohos-battery-manager" ] + } +} + +group("cli_test_group") { + testonly = true + if (battery_manager_feature_support_battery_cli) { + deps = [ "ohos-battery-manager/tests:test_ohos_battery_manager_cli" ] + } +} diff --git a/tools/ohos-battery-manager/BUILD.gn b/tools/ohos-battery-manager/BUILD.gn new file mode 100644 index 00000000..8d98e3a6 --- /dev/null +++ b/tools/ohos-battery-manager/BUILD.gn @@ -0,0 +1,50 @@ +# Copyright (c) 2026 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("../../batterymgr.gni") + +ohos_executable("ohos-battery-manager") { + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + + branch_protector_ret = "pac_ret" + + sources = [ + "src/cli_handler.cpp", + "src/main.cpp", + ] + + include_dirs = [ "${battery_inner_api}/native/include" ] + + deps = [ "${battery_inner_api}:batterysrv_client" ] + + configs = [ "${battery_utils}:coverage_flags" ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_core", + "samgr:samgr_proxy", + ] + + install_enable = true + install_images = [ "system" ] + relative_install_dir = "cli_tool/executable" + + part_name = "battery_manager" + subsystem_name = "powermgr" +} diff --git a/tools/ohos-battery-manager/config.json b/tools/ohos-battery-manager/config.json new file mode 100644 index 00000000..3f9e3eaa --- /dev/null +++ b/tools/ohos-battery-manager/config.json @@ -0,0 +1,84 @@ +{ + "$schema": "https://schemas.openharmony.org/cli/tool/v1", + "name": "ohos-battery-manager", + "version": "1.0.0", + "description": "Battery information query tool for capacity and energy status", + "executable": "/system/bin/cli_tool/executable/ohos-battery-manager", + "requirePermissions": [], + "hasSubcommands": true, + "subcommands": { + "capacity": { + "description": "Query battery capacity percentage (0-100%)", + "requirePermissions": [], + "input": { + "type": "object", + "properties": {}, + "required": [] + }, + "output": { + "type": "object", + "description": "Battery capacity result", + "properties": { + "capacity": { + "type": "integer", + "description": "Battery capacity in percent (0-100)", + "minimum": 0, + "maximum": 100 + } + } + }, + "argumentMapping": { + "type": "flag", + "templates": {} + } + }, + "total-energy": { + "description": "Query battery total energy (mAh)", + "requirePermissions": [], + "input": { + "type": "object", + "properties": {}, + "required": [] + }, + "output": { + "type": "object", + "description": "Battery total energy result", + "properties": { + "totalEnergy": { + "type": "integer", + "description": "Total battery energy in mAh" + } + } + }, + "argumentMapping": { + "type": "flag", + "templates": {} + } + }, + "remain-energy": { + "description": "Query battery remaining energy (mAh)", + "requirePermissions": [], + "input": { + "type": "object", + "properties": {}, + "required": [] + }, + "output": { + "type": "object", + "description": "Battery remaining energy result", + "properties": { + "remainEnergy": { + "type": "integer", + "description": "Remaining battery energy in mAh" + } + } + }, + "argumentMapping": { + "type": "flag", + "templates": {} + } + } + }, + "timeout": 10000, + "events": ["result"] +} diff --git a/tools/ohos-battery-manager/docs/README.md b/tools/ohos-battery-manager/docs/README.md new file mode 100644 index 00000000..4355357a --- /dev/null +++ b/tools/ohos-battery-manager/docs/README.md @@ -0,0 +1,34 @@ +# ohos-battery-manager + +Battery information query CLI tool for OpenHarmony. + +## Overview + +Query battery capacity and energy status via system SA (System Ability 3302). + +## Features + +- `capacity` - Query battery capacity percentage (0-100%) +- `total-energy` - Query battery total energy (mAh) +- `remain-energy` - Query battery remaining energy (mAh) + +## Dependencies + +- System Ability: BatteryService (SA 3302, process: powermgr) +- Inner API: `batterysrv_client` (`BatterySrvClient`) +- Permissions: `total-energy` and `remain-energy` require system caller identity (`Permission::IsSystem()`) + +## Build Target + +```bash +# Enable feature flag first (in product config or gn args) +battery_manager_feature_support_battery_cli=true + +# Build +./build.sh --product-name rk3568 \ + --build-target //base/powermgr/battery_manager/tools/ohos-battery-manager:ohos-battery-manager \ + --ccache + +# Install path +/system/bin/cli_tool/executable/ohos-battery-manager +``` diff --git a/tools/ohos-battery-manager/docs/USAGE.md b/tools/ohos-battery-manager/docs/USAGE.md new file mode 100644 index 00000000..fe552c15 --- /dev/null +++ b/tools/ohos-battery-manager/docs/USAGE.md @@ -0,0 +1,65 @@ +# Usage + +## Basic Usage + +```bash +ohos-battery-manager +``` + +## Commands + +| Command | Description | Parameters | Permissions | Dependencies | +|---------|-------------|------------|-------------|--------------| +| capacity | Query battery capacity (0-100%) | None | None | None | +| total-energy | Query battery total energy (mAh) | None | System caller identity | None | +| remain-energy | Query battery remaining energy (mAh) | None | System caller identity | None | + +## Examples + +```bash +# Query battery capacity +ohos-battery-manager capacity +# Output: {"success":true,"data":{"capacity":85}} + +# Query battery total energy +ohos-battery-manager total-energy +# Output: {"success":true,"data":{"totalEnergy":4000}} + +# Query battery remaining energy +ohos-battery-manager remain-energy +# Output: {"success":true,"data":{"remainEnergy":3200}} + +# Show help +ohos-battery-manager help +``` + +## Error Handling + +```bash +# Extra arguments are rejected +ohos-battery-manager capacity extra_arg +# stderr: [ERROR] Unexpected argument for 'capacity' command +# stderr: [INFO] Usage: ohos-battery-manager capacity + +# Unknown command +ohos-battery-manager unknown +# stderr: [ERROR] Unknown command: unknown +# stderr: [INFO] Usage: ohos-battery-manager [options] +``` + +## Output Format + +- **stdout**: JSON result +- **stderr**: Log and debug info + +### Success Response + +```json +{"success":true,"data":{"capacity":85}} +``` + +### Error Response + +```json +{"success":false,"error":{"code":"ERR_CONNECTION_FAIL","message":"Failed to get battery capacity."},"suggestion":"Check if powermgr process is running."} +``` diff --git a/tools/ohos-battery-manager/src/cli_handler.cpp b/tools/ohos-battery-manager/src/cli_handler.cpp new file mode 100644 index 00000000..a280f25e --- /dev/null +++ b/tools/ohos-battery-manager/src/cli_handler.cpp @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2026 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "cli_handler.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "battery_info.h" +#include "battery_srv_client.h" +#include "battery_srv_errors.h" + +namespace { +#define BATTERY_CLI_LOGI(fmt, ...) fprintf(stderr, "[INFO] " fmt "\n", ##__VA_ARGS__) +#define BATTERY_CLI_LOGE(fmt, ...) fprintf(stderr, "[ERROR] " fmt "\n", ##__VA_ARGS__) + +using CommandHandler = std::function; +struct Command { + const char* name; + const char* description; + CommandHandler handler; +}; + +static std::unordered_map g_commands; +static constexpr uint32_t CLI_CMD_MIN_PARAM_COUNT = 2; +} + +namespace json_builder { +std::string EscapeString(const std::string& s) +{ + std::ostringstream oss; + for (char c : s) { + switch (c) { + case '"': + oss << "\\\""; + break; + case '\\': + oss << "\\\\"; + break; + case '\n': + oss << "\\n"; + break; + case '\r': + oss << "\\r"; + break; + case '\t': + oss << "\\t"; + break; + default: + oss << c; + break; + } + } + return oss.str(); +} + +void PrintSuccess(const std::string& dataJson) +{ + std::cout << "{\"success\":true,\"data\":" << dataJson << "}" << std::endl; +} + +void PrintError(const std::string& code, const std::string& message, const std::string& suggestion = "") +{ + std::cout << "{\"success\":false,\"error\":{\"code\":\"" << EscapeString(code) << "\",\"message\":\"" << + EscapeString(message) << "\"}"; + if (!suggestion.empty()) { + std::cout << ",\"suggestion\":\"" << EscapeString(suggestion) << "\""; + } + std::cout << "}" << std::endl; +} + +} // namespace json_builder + +static void RegisterCommand(const char* name, const char* desc, CommandHandler handler) +{ + g_commands[name] = {name, desc, std::move(handler)}; +} + +static int CmdHelp([[maybe_unused]] int argc, [[maybe_unused]] char** argv) +{ + BATTERY_CLI_LOGI("Usage: ohos-battery-manager [options]"); + BATTERY_CLI_LOGI(""); + BATTERY_CLI_LOGI("Available commands:"); + for (const auto& pair : g_commands) { + BATTERY_CLI_LOGI(" %-20s %s", pair.first.c_str(), pair.second.description); + } + BATTERY_CLI_LOGI(""); + BATTERY_CLI_LOGI("Run 'ohos-battery-manager help ' for details on a specific command."); + return 0; +} + +static int CmdCapacity([[maybe_unused]] int argc, [[maybe_unused]] char** argv) +{ + if (argc > 0) { + BATTERY_CLI_LOGE("Unexpected argument for 'capacity' command"); + BATTERY_CLI_LOGI("Usage: ohos-battery-manager capacity"); + return 1; + } + auto& client = OHOS::DelayedRefSingleton::GetInstance(); + int32_t capacity = client.GetCapacity(); + if (capacity == OHOS::PowerMgr::INVALID_BATT_INT_VALUE) { + BATTERY_CLI_LOGE("Failed to get battery capacity, service may be unavailable"); + json_builder::PrintError("ERR_CONNECTION_FAIL", + "Failed to get battery capacity.", + "Check if powermgr process is running."); + return 1; + } + + std::ostringstream oss; + oss << "{\"capacity\":" << capacity << "}"; + json_builder::PrintSuccess(oss.str()); + return 0; +} + +static int CmdTotalEnergy([[maybe_unused]] int argc, [[maybe_unused]] char** argv) +{ + if (argc > 0) { + BATTERY_CLI_LOGE("Unexpected argument for 'total-energy' command"); + BATTERY_CLI_LOGI("Usage: ohos-battery-manager total-energy"); + return 1; + } + auto& client = OHOS::DelayedRefSingleton::GetInstance(); + int32_t totalEnergy = client.GetTotalEnergy(); + if (totalEnergy == OHOS::PowerMgr::INVALID_BATT_INT_VALUE) { + BATTERY_CLI_LOGE("Failed to get total battery energy, service may be unavailable or permission denied"); + json_builder::PrintError("ERR_CONNECTION_FAIL", + "Failed to get total battery energy.", + "Check if powermgr process is running and caller has system permission."); + return 1; + } + + std::ostringstream oss; + oss << "{\"totalEnergy\":" << totalEnergy << "}"; + json_builder::PrintSuccess(oss.str()); + return 0; +} + +static int CmdRemainEnergy([[maybe_unused]] int argc, [[maybe_unused]] char** argv) +{ + if (argc > 0) { + BATTERY_CLI_LOGE("Unexpected argument for 'remain-energy' command"); + BATTERY_CLI_LOGI("Usage: ohos-battery-manager remain-energy"); + return 1; + } + auto& client = OHOS::DelayedRefSingleton::GetInstance(); + int32_t remainEnergy = client.GetRemainEnergy(); + if (remainEnergy == OHOS::PowerMgr::INVALID_BATT_INT_VALUE) { + BATTERY_CLI_LOGE("Failed to get remaining battery energy, service may be unavailable or permission denied"); + json_builder::PrintError("ERR_CONNECTION_FAIL", + "Failed to get remaining battery energy.", + "Check if powermgr process is running and caller has system permission."); + return 1; + } + + std::ostringstream oss; + oss << "{\"remainEnergy\":" << remainEnergy << "}"; + json_builder::PrintSuccess(oss.str()); + return 0; +} + +static void InitCommands() +{ + RegisterCommand("help", "Show help message", CmdHelp); + RegisterCommand("capacity", "Query battery capacity percentage (0-100%)", CmdCapacity); + RegisterCommand("total-energy", "Query battery total energy (mAh)", CmdTotalEnergy); + RegisterCommand("remain-energy", "Query battery remaining energy (mAh)", CmdRemainEnergy); +} + +static void PrintUsage(const char* prog) +{ + BATTERY_CLI_LOGI("Usage: %s [options]", prog); + BATTERY_CLI_LOGI("Run '%s help' for more information.", prog); +} + +int HandleCommand(int argc, char** argv) +{ + if (argc < CLI_CMD_MIN_PARAM_COUNT) { + PrintUsage(argv[0]); + return 1; + } + + InitCommands(); + std::string cmdName = argv[1]; + auto it = g_commands.find(cmdName); + if (it == g_commands.end()) { + BATTERY_CLI_LOGE("Unknown command: %s", cmdName.c_str()); + PrintUsage(argv[0]); + return 1; + } + + int cmdArgc = argc - CLI_CMD_MIN_PARAM_COUNT; + char** cmdArgv = argv + CLI_CMD_MIN_PARAM_COUNT; + return it->second.handler(cmdArgc, cmdArgv); +} diff --git a/tools/ohos-battery-manager/src/cli_handler.h b/tools/ohos-battery-manager/src/cli_handler.h new file mode 100644 index 00000000..bc7375ab --- /dev/null +++ b/tools/ohos-battery-manager/src/cli_handler.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2026 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CLI_HANDLER_H +#define CLI_HANDLER_H + +int HandleCommand(int argc, char** argv); + +#endif // CLI_HANDLER_H diff --git a/tools/ohos-battery-manager/src/main.cpp b/tools/ohos-battery-manager/src/main.cpp new file mode 100644 index 00000000..d405aed4 --- /dev/null +++ b/tools/ohos-battery-manager/src/main.cpp @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2026 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "cli_handler.h" + +int main(int argc, char** argv) +{ + return HandleCommand(argc, argv); +} diff --git a/tools/ohos-battery-manager/tests/BUILD.gn b/tools/ohos-battery-manager/tests/BUILD.gn new file mode 100644 index 00000000..b40df0f6 --- /dev/null +++ b/tools/ohos-battery-manager/tests/BUILD.gn @@ -0,0 +1,46 @@ +# Copyright (c) 2026 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("../../../batterymgr.gni") + +module_output_path = "${module_output_path}" + +ohos_unittest("test_ohos_battery_manager_cli") { + module_out_path = module_output_path + + sources = [ + "../src/cli_handler.cpp", + "test_main.cpp", + ] + + include_dirs = [ + "../src", + "${battery_inner_api}/native/include", + ] + + configs = [ "${battery_utils}:coverage_flags" ] + + deps = [ "${battery_inner_api}:batterysrv_client" ] + + external_deps = [ + "c_utils:utils", + "googletest:gtest_main", + "hilog:libhilog", + "ipc:ipc_core", + "samgr:samgr_proxy", + ] + + part_name = "battery_manager" + subsystem_name = "powermgr" +} diff --git a/tools/ohos-battery-manager/tests/test_main.cpp b/tools/ohos-battery-manager/tests/test_main.cpp new file mode 100644 index 00000000..c72d5d0e --- /dev/null +++ b/tools/ohos-battery-manager/tests/test_main.cpp @@ -0,0 +1,215 @@ +/* + * Copyright (c) 2026 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "battery_info.h" +#include "battery_srv_client.h" +#include "cli_handler.h" + +using namespace testing::ext; + +namespace { +int32_t g_capacityRet = 0; +int32_t g_totalEnergyRet = 0; +int32_t g_remainEnergyRet = 0; +constexpr int32_t MOCK_CAPACITY = 85; +constexpr int32_t MOCK_TOTAL_ENERGY = 4000; +constexpr int32_t MOCK_REMAIN_ENERGY = 3200; +} + +namespace OHOS::PowerMgr { +int32_t BatterySrvClient::GetCapacity() +{ + return g_capacityRet; +} + +int32_t BatterySrvClient::GetTotalEnergy() +{ + return g_totalEnergyRet; +} + +int32_t BatterySrvClient::GetRemainEnergy() +{ + return g_remainEnergyRet; +} +} + +class BatteryManagerCliTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void BatteryManagerCliTest::SetUpTestCase() {} +void BatteryManagerCliTest::TearDownTestCase() {} +void BatteryManagerCliTest::SetUp() +{ + g_capacityRet = MOCK_CAPACITY; + g_totalEnergyRet = MOCK_TOTAL_ENERGY; + g_remainEnergyRet = MOCK_REMAIN_ENERGY; +} +void BatteryManagerCliTest::TearDown() {} + +/** + * @tc.name: BatteryManagerCliTest_001 + * @tc.desc: Test no arguments returns error + */ +HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_001, TestSize.Level1) +{ + char prog[] = "ohos-battery-manager"; + char* argv[] = { prog }; + EXPECT_EQ(HandleCommand(1, argv), 1); +} + +/** + * @tc.name: BatteryManagerCliTest_002 + * @tc.desc: Test unknown command returns error + */ +HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_002, TestSize.Level1) +{ + char prog[] = "ohos-battery-manager"; + char cmd[] = "unknown-cmd"; + char* argv[] = { prog, cmd }; + EXPECT_EQ(HandleCommand(2, argv), 1); +} + +/** + * @tc.name: BatteryManagerCliTest_003 + * @tc.desc: Test help command returns success + */ +HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_003, TestSize.Level1) +{ + char prog[] = "ohos-battery-manager"; + char cmd[] = "help"; + char* argv[] = { prog, cmd }; + EXPECT_EQ(HandleCommand(2, argv), 0); +} + +/** + * @tc.name: BatteryManagerCliTest_004 + * @tc.desc: Test capacity command returns success with valid value + */ +HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_004, TestSize.Level1) +{ + char prog[] = "ohos-battery-manager"; + char cmd[] = "capacity"; + char* argv[] = { prog, cmd }; + EXPECT_EQ(HandleCommand(2, argv), 0); +} + +/** + * @tc.name: BatteryManagerCliTest_005 + * @tc.desc: Test capacity command with extra arguments returns error + */ +HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_005, TestSize.Level1) +{ + char prog[] = "ohos-battery-manager"; + char cmd[] = "capacity"; + char extra[] = "extra_arg"; + char* argv[] = { prog, cmd, extra }; + EXPECT_EQ(HandleCommand(3, argv), 1); +} + +/** + * @tc.name: BatteryManagerCliTest_006 + * @tc.desc: Test total-energy command returns success with valid value + */ +HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_006, TestSize.Level1) +{ + char prog[] = "ohos-battery-manager"; + char cmd[] = "total-energy"; + char* argv[] = { prog, cmd }; + EXPECT_EQ(HandleCommand(2, argv), 0); +} + +/** + * @tc.name: BatteryManagerCliTest_007 + * @tc.desc: Test total-energy command with extra arguments returns error + */ +HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_007, TestSize.Level1) +{ + char prog[] = "ohos-battery-manager"; + char cmd[] = "total-energy"; + char extra[] = "extra_arg"; + char* argv[] = { prog, cmd, extra }; + EXPECT_EQ(HandleCommand(3, argv), 1); +} + +/** + * @tc.name: BatteryManagerCliTest_008 + * @tc.desc: Test remain-energy command returns success with valid value + */ +HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_008, TestSize.Level1) +{ + char prog[] = "ohos-battery-manager"; + char cmd[] = "remain-energy"; + char* argv[] = { prog, cmd }; + EXPECT_EQ(HandleCommand(2, argv), 0); +} + +/** + * @tc.name: BatteryManagerCliTest_009 + * @tc.desc: Test remain-energy command with extra arguments returns error + */ +HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_009, TestSize.Level1) +{ + char prog[] = "ohos-battery-manager"; + char cmd[] = "remain-energy"; + char extra[] = "extra_arg"; + char* argv[] = { prog, cmd, extra }; + EXPECT_EQ(HandleCommand(3, argv), 1); +} + +/** + * @tc.name: BatteryManagerCliTest_010 + * @tc.desc: Test capacity command fails when service returns invalid value + */ +HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_010, TestSize.Level1) +{ + g_capacityRet = OHOS::PowerMgr::INVALID_BATT_INT_VALUE; + char prog[] = "ohos-battery-manager"; + char cmd[] = "capacity"; + char* argv[] = { prog, cmd }; + EXPECT_EQ(HandleCommand(2, argv), 1); +} + +/** + * @tc.name: BatteryManagerCliTest_011 + * @tc.desc: Test total-energy command fails when service returns invalid value + */ +HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_011, TestSize.Level1) +{ + g_totalEnergyRet = OHOS::PowerMgr::INVALID_BATT_INT_VALUE; + char prog[] = "ohos-battery-manager"; + char cmd[] = "total-energy"; + char* argv[] = { prog, cmd }; + EXPECT_EQ(HandleCommand(2, argv), 1); +} + +/** + * @tc.name: BatteryManagerCliTest_012 + * @tc.desc: Test remain-energy command fails when service returns invalid value + */ +HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_012, TestSize.Level1) +{ + g_remainEnergyRet = OHOS::PowerMgr::INVALID_BATT_INT_VALUE; + char prog[] = "ohos-battery-manager"; + char cmd[] = "remain-energy"; + char* argv[] = { prog, cmd }; + EXPECT_EQ(HandleCommand(2, argv), 1); +}