mirror of
https://github.com/openharmony/powermgr_battery_manager.git
synced 2026-07-01 06:42:05 -04:00
!808 merge feat/add-battery-cli-tool into master
refactor: replace nlohmann_json with cJSON and refactor CLI handler Created-by: wangyantian0 Commit-by: wangyantian Merged-by: openharmony_ci Description: > 请检查PR是否满足[《代码合入流程指导和规范》](https://gitee.com/openharmony/powermgr_power_manager/wikis/issue-commit-pr-standard) , 否则将不会审查通过。 **【关联Issue】** https://gitcode.com/openharmony/powermgr_battery_manager/issues/651 **【修改描述】** **【验证结果】** See merge request: openharmony/powermgr_battery_manager!808
This commit is contained in:
+2
-2
@@ -16,13 +16,13 @@ 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" ]
|
||||
deps = [ "ohos-batteryManager:ohos-batteryManager" ]
|
||||
}
|
||||
}
|
||||
|
||||
group("cli_test_group") {
|
||||
testonly = true
|
||||
if (battery_manager_feature_support_battery_cli) {
|
||||
deps = [ "ohos-battery-manager/tests:test_ohos_battery_manager_cli" ]
|
||||
deps = [ "ohos-batteryManager/tests:test_ohos_battery_manager_cli" ]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
{
|
||||
"$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"]
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
# ohos-battery-manager
|
||||
|
||||
Battery information query CLI tool for OpenHarmony.
|
||||
|
||||
## Overview
|
||||
|
||||
Query battery capacity and energy status via system SA (System Ability 3302).
|
||||
|
||||
## Commands
|
||||
|
||||
| Command | Description | Parameters | Permissions |
|
||||
|---------|-------------|------------|-------------|
|
||||
| capacity | Query battery capacity (0-100%) | None | None |
|
||||
| total-energy | Query battery total energy (mAh) | None | System caller identity |
|
||||
| remain-energy | Query battery remaining energy (mAh) | None | System caller identity |
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
ohos-battery-manager <command>
|
||||
```
|
||||
|
||||
### 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 <command> [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."}
|
||||
```
|
||||
|
||||
## 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
|
||||
|
||||
```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
|
||||
```
|
||||
@@ -1,211 +0,0 @@
|
||||
/*
|
||||
* 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 <cstdlib>
|
||||
#include <cstring>
|
||||
#include <functional>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
#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<int(int, char**)>;
|
||||
struct Command {
|
||||
const char* name;
|
||||
const char* description;
|
||||
CommandHandler handler;
|
||||
};
|
||||
|
||||
static std::unordered_map<std::string, Command> 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 <command> [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 <command>' 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<OHOS::PowerMgr::BatterySrvClient>::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<OHOS::PowerMgr::BatterySrvClient>::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<OHOS::PowerMgr::BatterySrvClient>::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 <command> [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);
|
||||
}
|
||||
@@ -1,215 +0,0 @@
|
||||
/*
|
||||
* 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 <gtest/gtest.h>
|
||||
|
||||
#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);
|
||||
}
|
||||
@@ -12,9 +12,10 @@
|
||||
# limitations under the License.
|
||||
|
||||
import("//build/ohos.gni")
|
||||
import("//build/ohos/cli/ohos_cli_executable.gni")
|
||||
import("../../batterymgr.gni")
|
||||
|
||||
ohos_executable("ohos-battery-manager") {
|
||||
ohos_cli_executable("ohos-batteryManager") {
|
||||
sanitize = {
|
||||
cfi = true
|
||||
cfi_cross_dso = true
|
||||
@@ -23,6 +24,8 @@ ohos_executable("ohos-battery-manager") {
|
||||
|
||||
branch_protector_ret = "pac_ret"
|
||||
|
||||
cli_config_file = "ohos-batteryManager.json"
|
||||
|
||||
sources = [
|
||||
"src/cli_handler.cpp",
|
||||
"src/main.cpp",
|
||||
@@ -35,6 +38,7 @@ ohos_executable("ohos-battery-manager") {
|
||||
configs = [ "${battery_utils}:coverage_flags" ]
|
||||
|
||||
external_deps = [
|
||||
"cJSON:cjson",
|
||||
"c_utils:utils",
|
||||
"hilog:libhilog",
|
||||
"ipc:ipc_core",
|
||||
@@ -0,0 +1,105 @@
|
||||
# ohos-batteryManager
|
||||
|
||||
## 概述
|
||||
|
||||
Battery capacity and energy query CLI tool. Queries battery status via BatteryService (SA 3302).
|
||||
|
||||
## 功能列表
|
||||
|
||||
- Query battery capacity percentage (0-100%)
|
||||
- Query battery total energy (mAh)
|
||||
- Query battery remaining energy (mAh)
|
||||
- View command help information (--help)
|
||||
|
||||
## 依赖
|
||||
|
||||
- System Ability: BatteryService (SA 3302, process: powermgr)
|
||||
- Inner API: `batterysrv_client` (`BatterySrvClient`)
|
||||
- Permission: `total-energy` and `remain-energy` commands require system caller identity (`Permission::IsSystem()`)
|
||||
|
||||
## 基本用法
|
||||
|
||||
```bash
|
||||
ohos-batteryManager <command> [options]
|
||||
```
|
||||
|
||||
## 命令列表
|
||||
|
||||
| 命令 | 说明 | 参数 | 权限 | 前置依赖 |
|
||||
|------|------|------|------|----------|
|
||||
| capacity | Query battery capacity percentage (0-100%) | 无 | 无 | 无 |
|
||||
| total-energy | Query battery total energy (mAh) | 无 | System caller identity | 无 |
|
||||
| remain-energy | Query battery remaining energy (mAh) | 无 | System caller identity | 无 |
|
||||
|
||||
**前置依赖说明**:
|
||||
- **无**: The command can be executed directly without prerequisites
|
||||
|
||||
## 示例
|
||||
|
||||
```bash
|
||||
# View all command help
|
||||
ohos-batteryManager --help
|
||||
|
||||
# View subcommand help
|
||||
ohos-batteryManager capacity --help
|
||||
ohos-batteryManager total-energy --help
|
||||
ohos-batteryManager remain-energy --help
|
||||
|
||||
# Query battery capacity
|
||||
ohos-batteryManager capacity
|
||||
# Output: {"type":"result","status":"success","data":{"capacity":85}}
|
||||
|
||||
# Query battery total energy
|
||||
ohos-batteryManager total-energy
|
||||
# Output: {"type":"result","status":"success","data":{"totalEnergy":4000}}
|
||||
|
||||
# Query battery remaining energy
|
||||
ohos-batteryManager remain-energy
|
||||
# Output: {"type":"result","status":"success","data":{"remainEnergy":3200}}
|
||||
```
|
||||
|
||||
## 错误处理示例
|
||||
|
||||
```bash
|
||||
# Extra arguments rejected
|
||||
ohos-batteryManager capacity extra_arg
|
||||
# stderr: [ERROR] Unexpected argument for 'capacity' command
|
||||
# stdout: {"type":"result","status":"error","errCode":"ERR_ARG_INVALID","errMsg":"Unexpected argument for 'capacity' command. This command takes no arguments.","suggestion":"Usage: ohos-batteryManager capacity"}
|
||||
|
||||
# Unknown command
|
||||
ohos-batteryManager unknown
|
||||
# stderr: [ERROR] Unknown command: unknown
|
||||
# stderr: [ERROR] Usage: ohos-batteryManager <command> [options]
|
||||
```
|
||||
|
||||
## 输出格式
|
||||
|
||||
- **stdout**: JSON result
|
||||
- **stderr**: Logs and debug information
|
||||
|
||||
### 成功响应
|
||||
|
||||
```json
|
||||
{"type":"result","status":"success","data":{"capacity":85}}
|
||||
```
|
||||
|
||||
### 失败响应
|
||||
|
||||
```json
|
||||
{"type":"result","status":"error","errCode":"ERR_BATT_SERVICE_UNAVAILABLE","errMsg":"Failed to get battery capacity. BatterySrvClient returned invalid value.","suggestion":"Check if powermgr process is running: ps -ef | grep powermgr"}
|
||||
```
|
||||
|
||||
## 编译
|
||||
|
||||
```bash
|
||||
# Enable feature flag 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-batteryManager:ohos-batteryManager \
|
||||
--ccache
|
||||
|
||||
# Install path
|
||||
/system/bin/cli_tool/executable/ohos-batteryManager
|
||||
```
|
||||
@@ -0,0 +1,158 @@
|
||||
{
|
||||
"name": "ohos-batteryManager",
|
||||
"version": "1.0.0",
|
||||
"description": "Battery capacity and energy query tool. Used for system management, maintenance troubleshooting and battery status inspection. Not applicable for real-time battery monitoring or battery event subscription.",
|
||||
"executablePath": "/system/bin/cli_tool/executable/ohos-batteryManager",
|
||||
"requirePermissions": [],
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
},
|
||||
"outputSchema": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
},
|
||||
"hasSubCommand": true,
|
||||
"subcommands": {
|
||||
"capacity": {
|
||||
"description": "Query battery capacity percentage (0-100%). Used for battery status checking and system management scenarios. Not applicable for real-time monitoring or subscription-based battery events.",
|
||||
"requirePermissions": [],
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
},
|
||||
"outputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"enum": ["result"],
|
||||
"description": "Response type indicator"
|
||||
},
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": ["success", "error"],
|
||||
"description": "Execution status"
|
||||
},
|
||||
"data": {
|
||||
"type": "object",
|
||||
"description": "Battery capacity data",
|
||||
"properties": {
|
||||
"capacity": {
|
||||
"type": "integer",
|
||||
"description": "Battery capacity percentage (0-100)",
|
||||
"minimum": 0,
|
||||
"maximum": 100
|
||||
}
|
||||
}
|
||||
},
|
||||
"errCode": {
|
||||
"type": "string",
|
||||
"description": "Error code when execution fails"
|
||||
},
|
||||
"errMsg": {
|
||||
"type": "string",
|
||||
"description": "Error message when execution fails"
|
||||
},
|
||||
"suggestion": {
|
||||
"type": "string",
|
||||
"description": "Suggested resolution when execution fails"
|
||||
}
|
||||
},
|
||||
"required": ["type", "status", "data"]
|
||||
}
|
||||
},
|
||||
"total-energy": {
|
||||
"description": "Query battery total energy in mAh. Used for battery hardware diagnostics and system maintenance scenarios. Requires system caller identity, not available for third-party applications.",
|
||||
"requirePermissions": [],
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
},
|
||||
"outputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"enum": ["result"],
|
||||
"description": "Response type indicator"
|
||||
},
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": ["success", "error"],
|
||||
"description": "Execution status"
|
||||
},
|
||||
"data": {
|
||||
"type": "object",
|
||||
"description": "Battery total energy data",
|
||||
"properties": {
|
||||
"totalEnergy": {
|
||||
"type": "integer",
|
||||
"description": "Battery total energy (mAh)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"errCode": {
|
||||
"type": "string",
|
||||
"description": "Error code when execution fails"
|
||||
},
|
||||
"errMsg": {
|
||||
"type": "string",
|
||||
"description": "Error message when execution fails"
|
||||
},
|
||||
"suggestion": {
|
||||
"type": "string",
|
||||
"description": "Suggested resolution when execution fails"
|
||||
}
|
||||
},
|
||||
"required": ["type", "status", "data"]
|
||||
}
|
||||
},
|
||||
"remain-energy": {
|
||||
"description": "Query battery remaining energy in mAh. Used for battery health assessment and power management diagnostics. Requires system caller identity, not available for third-party applications.",
|
||||
"requirePermissions": [],
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
},
|
||||
"outputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"enum": ["result"],
|
||||
"description": "Response type indicator"
|
||||
},
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": ["success", "error"],
|
||||
"description": "Execution status"
|
||||
},
|
||||
"data": {
|
||||
"type": "object",
|
||||
"description": "Battery remaining energy data",
|
||||
"properties": {
|
||||
"remainEnergy": {
|
||||
"type": "integer",
|
||||
"description": "Battery remaining energy (mAh)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"errCode": {
|
||||
"type": "string",
|
||||
"description": "Error code when execution fails"
|
||||
},
|
||||
"errMsg": {
|
||||
"type": "string",
|
||||
"description": "Error message when execution fails"
|
||||
},
|
||||
"suggestion": {
|
||||
"type": "string",
|
||||
"description": "Suggested resolution when execution fails"
|
||||
}
|
||||
},
|
||||
"required": ["type", "status", "data"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
/*
|
||||
* 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 <functional>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <cstring>
|
||||
|
||||
#include "battery_info.h"
|
||||
#include "battery_srv_client.h"
|
||||
#include "battery_srv_errors.h"
|
||||
#include "cJSON.h"
|
||||
|
||||
namespace {
|
||||
using CommandHandler = std::function<int(int, char**)>;
|
||||
struct Command {
|
||||
const char* name;
|
||||
const char* description;
|
||||
const char* usage;
|
||||
const char* parameters;
|
||||
const char* examples;
|
||||
CommandHandler handler;
|
||||
};
|
||||
|
||||
struct cJSONDeleter {
|
||||
void operator()(cJSON* obj) const { cJSON_Delete(obj); }
|
||||
};
|
||||
using cJSONPtr = std::unique_ptr<cJSON, cJSONDeleter>;
|
||||
|
||||
static constexpr uint32_t CLI_SUCCESS = 0;
|
||||
static constexpr uint32_t CLI_FAILURE = 1;
|
||||
static constexpr uint32_t CLI_CMD_PARAM_INDEX_1 = 1;
|
||||
static constexpr uint32_t CLI_CMD_PARAM_INDEX_2 = 2;
|
||||
static const char* CLI_TOOL_NAME = nullptr;
|
||||
static constexpr const char* TOOL_DESCRIPTION =
|
||||
"Battery capacity and energy query tool. "
|
||||
"Used for system management, maintenance troubleshooting and battery status inspection. "
|
||||
"Not applicable for real-time battery monitoring or battery event subscription.";
|
||||
static std::unordered_map<std::string, Command> g_commands;
|
||||
static bool g_hasSubcommands = false;
|
||||
|
||||
#define CLI_LOG(fmt, ...) fprintf(stderr, fmt "\n", ##__VA_ARGS__)
|
||||
#define CLI_ERROR(fmt, ...) fprintf(stderr, "[ERROR] " fmt "\n", ##__VA_ARGS__)
|
||||
#define REGISTER_CMD(name, desc, usage, params, examples, handler) \
|
||||
g_commands[name] = { name, desc, usage, params, examples, handler }
|
||||
|
||||
bool HasHelpFlag(int argc, char** argv, int start)
|
||||
{
|
||||
for (int i = start; i < argc; i++) {
|
||||
if (strcmp(argv[i], "--help") == 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// Transfers ownership of data to internal JSON response. Caller must not use data after this call.
|
||||
static int OutputSuccess(cJSONPtr& data)
|
||||
{
|
||||
cJSONPtr root(cJSON_CreateObject());
|
||||
if (!root) {
|
||||
CLI_ERROR("Failed to create JSON response");
|
||||
return CLI_FAILURE;
|
||||
}
|
||||
cJSON_AddStringToObject(root.get(), "type", "result");
|
||||
cJSON_AddStringToObject(root.get(), "status", "success");
|
||||
cJSON_AddItemToObject(root.get(), "data", data.release());
|
||||
|
||||
char* output = cJSON_PrintUnformatted(root.get());
|
||||
if (output) {
|
||||
std::cout << output << std::endl;
|
||||
cJSON_free(output);
|
||||
}
|
||||
return CLI_SUCCESS;
|
||||
}
|
||||
|
||||
static int OutputError(const std::string& errCode, const std::string& errMsg,
|
||||
const std::string& suggestion)
|
||||
{
|
||||
cJSONPtr root(cJSON_CreateObject());
|
||||
if (!root) {
|
||||
CLI_ERROR("Failed to create JSON response");
|
||||
return CLI_FAILURE;
|
||||
}
|
||||
cJSON_AddStringToObject(root.get(), "type", "result");
|
||||
cJSON_AddStringToObject(root.get(), "status", "error");
|
||||
cJSON_AddStringToObject(root.get(), "errCode", errCode.c_str());
|
||||
cJSON_AddStringToObject(root.get(), "errMsg", errMsg.c_str());
|
||||
cJSON_AddStringToObject(root.get(), "suggestion", suggestion.c_str());
|
||||
|
||||
char* output = cJSON_PrintUnformatted(root.get());
|
||||
if (output) {
|
||||
std::cout << output << std::endl;
|
||||
cJSON_free(output);
|
||||
}
|
||||
return CLI_FAILURE;
|
||||
}
|
||||
|
||||
static void PrintFullHelp()
|
||||
{
|
||||
CLI_LOG("%s - %s", CLI_TOOL_NAME, TOOL_DESCRIPTION);
|
||||
CLI_LOG("");
|
||||
CLI_LOG("Usage:");
|
||||
CLI_LOG(" %s [options]", CLI_TOOL_NAME);
|
||||
if (g_hasSubcommands) {
|
||||
CLI_LOG(" %s <command> [options]", CLI_TOOL_NAME);
|
||||
}
|
||||
CLI_LOG("");
|
||||
CLI_LOG("Parameters:");
|
||||
CLI_LOG(" --help Display this help message");
|
||||
if (g_hasSubcommands) {
|
||||
CLI_LOG("");
|
||||
CLI_LOG("SubCommands:");
|
||||
for (const auto& pair : g_commands) {
|
||||
CLI_LOG(" %-18s %s", pair.first.c_str(),
|
||||
pair.second.description ? pair.second.description : "");
|
||||
}
|
||||
}
|
||||
CLI_LOG("");
|
||||
CLI_LOG("Examples:");
|
||||
if (g_hasSubcommands) {
|
||||
CLI_LOG(" %s --help", CLI_TOOL_NAME);
|
||||
for (const auto& pair : g_commands) {
|
||||
CLI_LOG(" %s %s --help", CLI_TOOL_NAME, pair.first.c_str());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static int PrintSubcommandHelp(const std::string& targetCmd)
|
||||
{
|
||||
auto it = g_commands.find(targetCmd);
|
||||
if (it == g_commands.end()) {
|
||||
CLI_ERROR("Unknown command: %s", targetCmd.c_str());
|
||||
return CLI_FAILURE;
|
||||
}
|
||||
const Command& cmd = it->second;
|
||||
CLI_LOG("%s %s - %s", CLI_TOOL_NAME, cmd.name, cmd.description ? cmd.description : "N/A");
|
||||
if (cmd.usage) {
|
||||
CLI_LOG("");
|
||||
CLI_LOG("Usage:");
|
||||
CLI_LOG(" %s", cmd.usage);
|
||||
}
|
||||
if (cmd.parameters) {
|
||||
CLI_LOG("");
|
||||
CLI_LOG("Parameters:");
|
||||
CLI_LOG("%s", cmd.parameters);
|
||||
}
|
||||
CLI_LOG(" %-18s %s", "--help", "Display this help message");
|
||||
if (cmd.examples) {
|
||||
CLI_LOG("");
|
||||
CLI_LOG("Examples:");
|
||||
CLI_LOG("%s", cmd.examples);
|
||||
}
|
||||
return CLI_SUCCESS;
|
||||
}
|
||||
|
||||
static void PrintUsage(const char* prog)
|
||||
{
|
||||
CLI_ERROR("Usage: %s <command> [options]", prog);
|
||||
CLI_ERROR("Run '%s --help' for more information.", prog);
|
||||
}
|
||||
|
||||
static int CmdCapacity([[maybe_unused]] int argc, [[maybe_unused]] char** argv)
|
||||
{
|
||||
if (argc > 0) {
|
||||
CLI_ERROR("Unexpected argument for 'capacity' command");
|
||||
return OutputError("ERR_ARG_INVALID",
|
||||
"Unexpected argument for 'capacity' command. This command takes no arguments.",
|
||||
"Usage: ohos-batteryManager capacity");
|
||||
}
|
||||
auto& client = OHOS::DelayedRefSingleton<OHOS::PowerMgr::BatterySrvClient>::GetInstance();
|
||||
int32_t capacity = client.GetCapacity();
|
||||
if (capacity == OHOS::PowerMgr::INVALID_BATT_INT_VALUE) {
|
||||
CLI_ERROR("Failed to get battery capacity, service may be unavailable");
|
||||
return OutputError("ERR_BATT_SERVICE_UNAVAILABLE",
|
||||
"Failed to get battery capacity. BatterySrvClient returned invalid value.",
|
||||
"Check if powermgr process is running: ps -ef | grep powermgr");
|
||||
}
|
||||
|
||||
cJSONPtr data(cJSON_CreateObject());
|
||||
cJSON_AddNumberToObject(data.get(), "capacity", capacity);
|
||||
return OutputSuccess(data);
|
||||
}
|
||||
|
||||
static int CmdTotalEnergy([[maybe_unused]] int argc, [[maybe_unused]] char** argv)
|
||||
{
|
||||
if (argc > 0) {
|
||||
CLI_ERROR("Unexpected argument for 'total-energy' command");
|
||||
return OutputError("ERR_ARG_INVALID",
|
||||
"Unexpected argument for 'total-energy' command. This command takes no arguments.",
|
||||
"Usage: ohos-batteryManager total-energy");
|
||||
}
|
||||
auto& client = OHOS::DelayedRefSingleton<OHOS::PowerMgr::BatterySrvClient>::GetInstance();
|
||||
int32_t totalEnergy = client.GetTotalEnergy();
|
||||
if (totalEnergy == OHOS::PowerMgr::INVALID_BATT_INT_VALUE) {
|
||||
CLI_ERROR("Failed to get total battery energy, service may be unavailable or permission denied");
|
||||
return OutputError("ERR_BATT_SERVICE_UNAVAILABLE",
|
||||
"Failed to get total battery energy. BatterySrvClient returned invalid value.",
|
||||
"Check if powermgr process is running and caller has system permission.");
|
||||
}
|
||||
|
||||
cJSONPtr data(cJSON_CreateObject());
|
||||
cJSON_AddNumberToObject(data.get(), "totalEnergy", totalEnergy);
|
||||
return OutputSuccess(data);
|
||||
}
|
||||
|
||||
static int CmdRemainEnergy([[maybe_unused]] int argc, [[maybe_unused]] char** argv)
|
||||
{
|
||||
if (argc > 0) {
|
||||
CLI_ERROR("Unexpected argument for 'remain-energy' command");
|
||||
return OutputError("ERR_ARG_INVALID",
|
||||
"Unexpected argument for 'remain-energy' command. This command takes no arguments.",
|
||||
"Usage: ohos-batteryManager remain-energy");
|
||||
}
|
||||
auto& client = OHOS::DelayedRefSingleton<OHOS::PowerMgr::BatterySrvClient>::GetInstance();
|
||||
int32_t remainEnergy = client.GetRemainEnergy();
|
||||
if (remainEnergy == OHOS::PowerMgr::INVALID_BATT_INT_VALUE) {
|
||||
CLI_ERROR("Failed to get remaining battery energy, service may be unavailable or permission denied");
|
||||
return OutputError("ERR_BATT_SERVICE_UNAVAILABLE",
|
||||
"Failed to get remaining battery energy. BatterySrvClient returned invalid value.",
|
||||
"Check if powermgr process is running and caller has system permission.");
|
||||
}
|
||||
|
||||
cJSONPtr data(cJSON_CreateObject());
|
||||
cJSON_AddNumberToObject(data.get(), "remainEnergy", remainEnergy);
|
||||
return OutputSuccess(data);
|
||||
}
|
||||
|
||||
static void InitCommands()
|
||||
{
|
||||
REGISTER_CMD("capacity", "Query battery capacity percentage (0-100%)",
|
||||
"ohos-batteryManager capacity",
|
||||
" (No parameters. This command takes no arguments.)",
|
||||
" # Query battery capacity\n"
|
||||
" ohos-batteryManager capacity",
|
||||
CmdCapacity);
|
||||
|
||||
REGISTER_CMD("total-energy", "Query battery total energy (mAh)",
|
||||
"ohos-batteryManager total-energy",
|
||||
" (No parameters. This command takes no arguments.)",
|
||||
" # Query total energy\n"
|
||||
" ohos-batteryManager total-energy",
|
||||
CmdTotalEnergy);
|
||||
|
||||
REGISTER_CMD("remain-energy", "Query battery remaining energy (mAh)",
|
||||
"ohos-batteryManager remain-energy",
|
||||
" (No parameters. This command takes no arguments.)",
|
||||
" # Query remaining energy\n"
|
||||
" ohos-batteryManager remain-energy",
|
||||
CmdRemainEnergy);
|
||||
|
||||
g_hasSubcommands = (!g_commands.empty());
|
||||
}
|
||||
|
||||
int HandleCommand(int argc, char** argv)
|
||||
{
|
||||
CLI_TOOL_NAME = argv[0];
|
||||
InitCommands();
|
||||
|
||||
if (argc < CLI_CMD_PARAM_INDEX_2) {
|
||||
PrintUsage(argv[0]);
|
||||
return CLI_FAILURE;
|
||||
}
|
||||
if (strcmp(argv[CLI_CMD_PARAM_INDEX_1], "--help") == 0) {
|
||||
PrintFullHelp();
|
||||
return CLI_SUCCESS;
|
||||
}
|
||||
|
||||
std::string cmdName = argv[CLI_CMD_PARAM_INDEX_1];
|
||||
auto it = g_commands.find(cmdName);
|
||||
if (it == g_commands.end()) {
|
||||
CLI_ERROR("Unknown command: %s", cmdName.c_str());
|
||||
PrintUsage(argv[0]);
|
||||
return CLI_FAILURE;
|
||||
}
|
||||
if (HasHelpFlag(argc, argv, CLI_CMD_PARAM_INDEX_2)) {
|
||||
return PrintSubcommandHelp(cmdName);
|
||||
}
|
||||
return it->second.handler(argc - CLI_CMD_PARAM_INDEX_2, argv + CLI_CMD_PARAM_INDEX_2);
|
||||
}
|
||||
@@ -34,6 +34,7 @@ ohos_unittest("test_ohos_battery_manager_cli") {
|
||||
deps = [ "${battery_inner_api}:batterysrv_client" ]
|
||||
|
||||
external_deps = [
|
||||
"cJSON:cjson",
|
||||
"c_utils:utils",
|
||||
"googletest:gtest_main",
|
||||
"hilog:libhilog",
|
||||
@@ -0,0 +1,491 @@
|
||||
/*
|
||||
* 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 <gtest/gtest.h>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
|
||||
#include "battery_info.h"
|
||||
#include "battery_srv_client.h"
|
||||
#include "battery_srv_errors.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 (argc < 2 path)
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_001, TestSize.Level1)
|
||||
{
|
||||
char prog[] = "ohos-batteryManager";
|
||||
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-batteryManager";
|
||||
char cmd[] = "unknown-cmd";
|
||||
char* argv[] = { prog, cmd };
|
||||
EXPECT_EQ(HandleCommand(2, argv), 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_003
|
||||
* @tc.desc: Test "help" is treated as unknown command (no help subcommand)
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_003, TestSize.Level1)
|
||||
{
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "help";
|
||||
char* argv[] = { prog, cmd };
|
||||
EXPECT_EQ(HandleCommand(2, argv), 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_004
|
||||
* @tc.desc: Test capacity command returns success with valid value
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_004, TestSize.Level1)
|
||||
{
|
||||
char prog[] = "ohos-batteryManager";
|
||||
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-batteryManager";
|
||||
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 capacity command fails when service returns INVALID_BATT_INT_VALUE
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_006, TestSize.Level1)
|
||||
{
|
||||
g_capacityRet = OHOS::PowerMgr::INVALID_BATT_INT_VALUE;
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "capacity";
|
||||
char* argv[] = { prog, cmd };
|
||||
EXPECT_EQ(HandleCommand(2, argv), 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_007
|
||||
* @tc.desc: Test total-energy command returns success with valid value
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_007, TestSize.Level1)
|
||||
{
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "total-energy";
|
||||
char* argv[] = { prog, cmd };
|
||||
EXPECT_EQ(HandleCommand(2, argv), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_008
|
||||
* @tc.desc: Test total-energy command with extra arguments returns error
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_008, TestSize.Level1)
|
||||
{
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "total-energy";
|
||||
char extra[] = "extra_arg";
|
||||
char* argv[] = { prog, cmd, extra };
|
||||
EXPECT_EQ(HandleCommand(3, argv), 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_009
|
||||
* @tc.desc: Test total-energy command fails when service returns INVALID_BATT_INT_VALUE
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_009, TestSize.Level1)
|
||||
{
|
||||
g_totalEnergyRet = OHOS::PowerMgr::INVALID_BATT_INT_VALUE;
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "total-energy";
|
||||
char* argv[] = { prog, cmd };
|
||||
EXPECT_EQ(HandleCommand(2, argv), 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_010
|
||||
* @tc.desc: Test remain-energy command returns success with valid value
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_010, TestSize.Level1)
|
||||
{
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "remain-energy";
|
||||
char* argv[] = { prog, cmd };
|
||||
EXPECT_EQ(HandleCommand(2, argv), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_011
|
||||
* @tc.desc: Test remain-energy command with extra arguments returns error
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_011, TestSize.Level1)
|
||||
{
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "remain-energy";
|
||||
char extra[] = "extra_arg";
|
||||
char* argv[] = { prog, cmd, extra };
|
||||
EXPECT_EQ(HandleCommand(3, argv), 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_012
|
||||
* @tc.desc: Test remain-energy command fails when service returns INVALID_BATT_INT_VALUE
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_012, TestSize.Level1)
|
||||
{
|
||||
g_remainEnergyRet = OHOS::PowerMgr::INVALID_BATT_INT_VALUE;
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "remain-energy";
|
||||
char* argv[] = { prog, cmd };
|
||||
EXPECT_EQ(HandleCommand(2, argv), 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_013
|
||||
* @tc.desc: Test capacity with boundary value 0
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_013, TestSize.Level1)
|
||||
{
|
||||
g_capacityRet = 0;
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "capacity";
|
||||
char* argv[] = { prog, cmd };
|
||||
EXPECT_EQ(HandleCommand(2, argv), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_014
|
||||
* @tc.desc: Test capacity with boundary value 100
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_014, TestSize.Level1)
|
||||
{
|
||||
g_capacityRet = 100;
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "capacity";
|
||||
char* argv[] = { prog, cmd };
|
||||
EXPECT_EQ(HandleCommand(2, argv), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_015
|
||||
* @tc.desc: Test capacity with non-INVALID negative value still succeeds
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_015, TestSize.Level1)
|
||||
{
|
||||
g_capacityRet = -2;
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "capacity";
|
||||
char* argv[] = { prog, cmd };
|
||||
EXPECT_EQ(HandleCommand(2, argv), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_016
|
||||
* @tc.desc: Test all three commands can be called sequentially
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_016, TestSize.Level1)
|
||||
{
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char capacityCmd[] = "capacity";
|
||||
char totalEnergyCmd[] = "total-energy";
|
||||
char remainEnergyCmd[] = "remain-energy";
|
||||
|
||||
char* argv1[] = { prog, capacityCmd };
|
||||
EXPECT_EQ(HandleCommand(2, argv1), 0);
|
||||
|
||||
char* argv2[] = { prog, totalEnergyCmd };
|
||||
EXPECT_EQ(HandleCommand(2, argv2), 0);
|
||||
|
||||
char* argv3[] = { prog, remainEnergyCmd };
|
||||
EXPECT_EQ(HandleCommand(2, argv3), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_017
|
||||
* @tc.desc: Test total-energy command with zero value
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_017, TestSize.Level1)
|
||||
{
|
||||
g_totalEnergyRet = 0;
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "total-energy";
|
||||
char* argv[] = { prog, cmd };
|
||||
EXPECT_EQ(HandleCommand(2, argv), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_018
|
||||
* @tc.desc: Test remain-energy command with zero value
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_018, TestSize.Level1)
|
||||
{
|
||||
g_remainEnergyRet = 0;
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "remain-energy";
|
||||
char* argv[] = { prog, cmd };
|
||||
EXPECT_EQ(HandleCommand(2, argv), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_019
|
||||
* @tc.desc: Test --help flag at top level shows full help and returns success
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_019, TestSize.Level1)
|
||||
{
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char helpFlag[] = "--help";
|
||||
char* argv[] = { prog, helpFlag };
|
||||
EXPECT_EQ(HandleCommand(2, argv), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_020
|
||||
* @tc.desc: Test capacity --help shows subcommand help
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_020, TestSize.Level1)
|
||||
{
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "capacity";
|
||||
char helpFlag[] = "--help";
|
||||
char* argv[] = { prog, cmd, helpFlag };
|
||||
EXPECT_EQ(HandleCommand(3, argv), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_021
|
||||
* @tc.desc: Test total-energy --help shows subcommand help
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_021, TestSize.Level1)
|
||||
{
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "total-energy";
|
||||
char helpFlag[] = "--help";
|
||||
char* argv[] = { prog, cmd, helpFlag };
|
||||
EXPECT_EQ(HandleCommand(3, argv), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_022
|
||||
* @tc.desc: Test remain-energy --help shows subcommand help
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_022, TestSize.Level1)
|
||||
{
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "remain-energy";
|
||||
char helpFlag[] = "--help";
|
||||
char* argv[] = { prog, cmd, helpFlag };
|
||||
EXPECT_EQ(HandleCommand(3, argv), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_023
|
||||
* @tc.desc: Test --help after extra args still triggers subcommand help
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_023, TestSize.Level1)
|
||||
{
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "capacity";
|
||||
char arg1[] = "some_arg";
|
||||
char helpFlag[] = "--help";
|
||||
char* argv[] = { prog, cmd, arg1, helpFlag };
|
||||
EXPECT_EQ(HandleCommand(4, argv), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_024
|
||||
* @tc.desc: Test total-energy with non-INVALID negative value still succeeds
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_024, TestSize.Level1)
|
||||
{
|
||||
g_totalEnergyRet = -2;
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "total-energy";
|
||||
char* argv[] = { prog, cmd };
|
||||
EXPECT_EQ(HandleCommand(2, argv), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_025
|
||||
* @tc.desc: Test remain-energy with non-INVALID negative value still succeeds
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_025, TestSize.Level1)
|
||||
{
|
||||
g_remainEnergyRet = -2;
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "remain-energy";
|
||||
char* argv[] = { prog, cmd };
|
||||
EXPECT_EQ(HandleCommand(2, argv), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_026
|
||||
* @tc.desc: Test capacity with multiple extra arguments returns error
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_026, TestSize.Level1)
|
||||
{
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "capacity";
|
||||
char extra1[] = "arg1";
|
||||
char extra2[] = "arg2";
|
||||
char* argv[] = { prog, cmd, extra1, extra2 };
|
||||
EXPECT_EQ(HandleCommand(4, argv), 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_027
|
||||
* @tc.desc: Test total-energy with multiple extra arguments returns error
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_027, TestSize.Level1)
|
||||
{
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "total-energy";
|
||||
char extra1[] = "arg1";
|
||||
char extra2[] = "arg2";
|
||||
char* argv[] = { prog, cmd, extra1, extra2 };
|
||||
EXPECT_EQ(HandleCommand(4, argv), 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_028
|
||||
* @tc.desc: Test remain-energy with multiple extra arguments returns error
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_028, TestSize.Level1)
|
||||
{
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "remain-energy";
|
||||
char extra1[] = "arg1";
|
||||
char extra2[] = "arg2";
|
||||
char* argv[] = { prog, cmd, extra1, extra2 };
|
||||
EXPECT_EQ(HandleCommand(4, argv), 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_029
|
||||
* @tc.desc: Test capacity with large positive value succeeds
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_029, TestSize.Level1)
|
||||
{
|
||||
g_capacityRet = 10000;
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "capacity";
|
||||
char* argv[] = { prog, cmd };
|
||||
EXPECT_EQ(HandleCommand(2, argv), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_030
|
||||
* @tc.desc: Test repeated execution of same command succeeds
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_030, TestSize.Level1)
|
||||
{
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "capacity";
|
||||
char* argv[] = { prog, cmd };
|
||||
EXPECT_EQ(HandleCommand(2, argv), 0);
|
||||
EXPECT_EQ(HandleCommand(2, argv), 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_031
|
||||
* @tc.desc: Test unknown-cmd --help returns error (PrintSubcommandHelp find failure)
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_031, TestSize.Level1)
|
||||
{
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char cmd[] = "nonexistent";
|
||||
char helpFlag[] = "--help";
|
||||
char* argv[] = { prog, cmd, helpFlag };
|
||||
EXPECT_EQ(HandleCommand(3, argv), 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @tc.name: BatteryManagerCliTest_032
|
||||
* @tc.desc: Test help --help triggers PrintFullHelp (argv[1]=="--help" path)
|
||||
*/
|
||||
HWTEST_F(BatteryManagerCliTest, BatteryManagerCliTest_032, TestSize.Level1)
|
||||
{
|
||||
char prog[] = "ohos-batteryManager";
|
||||
char helpFlag[] = "--help";
|
||||
char extra[] = "--help";
|
||||
char* argv[] = { prog, helpFlag, extra };
|
||||
EXPECT_EQ(HandleCommand(3, argv), 0);
|
||||
}
|
||||
Reference in New Issue
Block a user