merge master

Signed-off-by: xinxin13 <xinxin13@huawei.com>
This commit is contained in:
xinxin13
2022-11-23 17:18:19 +08:00
89 changed files with 7345 additions and 916 deletions
@@ -44,7 +44,7 @@ static napi_module _module = {
.nm_filename = nullptr,
.nm_register_func = Init,
.nm_modname = "napi_app_mgr",
.nm_priv = ((void *)0),
.nm_priv = (static_cast<void *>(0)),
.reserved = {0},
};
/*
@@ -51,7 +51,7 @@ static napi_module _module = {
.nm_filename = nullptr,
.nm_register_func = Init,
.nm_modname = "ability.featureAbility",
.nm_priv = ((void *)0),
.nm_priv = (static_cast<void *>(0)),
.reserved = {0}
};
@@ -47,7 +47,7 @@ static napi_module _module = {
.nm_filename = nullptr,
.nm_register_func = ParticleInit,
.nm_modname = "ability.particleAbility",
.nm_priv = ((void *)0),
.nm_priv = (static_cast<void *>(0)),
.reserved = {0}
};
@@ -41,7 +41,7 @@ static napi_module _module = {
#else
.nm_modname = "ability.wantConstant",
#endif
.nm_priv = ((void *)0),
.nm_priv = (static_cast<void *>(0)),
.reserved = {0}
};
+1 -1
View File
@@ -953,7 +953,7 @@ void Ability::DispatchLifecycleOnForeground(const Want &want)
HILOG_ERROR("Ability::OnForeground error. abilityLifecycleExecutor_ == nullptr.");
return;
}
if (abilityInfo_->isStageBasedModel) {
if (abilityInfo_ != nullptr && abilityInfo_->isStageBasedModel) {
abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::FOREGROUND_NEW);
} else {
abilityLifecycleExecutor_->DispatchLifecycleState(AbilityLifecycleExecutor::LifecycleState::INACTIVE);
+15 -5
View File
@@ -73,6 +73,7 @@ namespace AppExecFwk {
using namespace OHOS::AbilityRuntime::Constants;
std::weak_ptr<OHOSApplication> MainThread::applicationForDump_;
std::shared_ptr<EventHandler> MainThread::signalHandler_ = nullptr;
std::shared_ptr<MainThread::MainHandler> MainThread::mainHandler_ = nullptr;
static std::shared_ptr<MixStackDumper> mixStackDumper_ = nullptr;
namespace {
constexpr int32_t DELIVERY_TIME = 200;
@@ -1023,7 +1024,7 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con
ApplicationDataManager::GetInstance().NotifyUnhandledException(summary);
time_t timet;
time(&timet);
OHOS::HiviewDFX::HiSysEvent::Write(OHOS::HiviewDFX::HiSysEvent::Domain::AAFWK, "JS_ERROR",
HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::AAFWK, "JS_ERROR",
OHOS::HiviewDFX::HiSysEvent::EventType::FAULT,
EVENT_KEY_PACKAGE_NAME, bundleName,
EVENT_KEY_VERSION, std::to_string(versionCode),
@@ -1697,11 +1698,20 @@ void MainThread::HandleSignal(int signal)
void MainThread::HandleDumpHeap(bool isPrivate)
{
HILOG_DEBUG("Dump heap start.");
auto app = applicationForDump_.lock();
if (app != nullptr && app->GetRuntime() != nullptr) {
HILOG_DEBUG("Send dump heap to ark start.");
app->GetRuntime()->DumpHeapSnapshot(isPrivate);
if (mainHandler_ == nullptr) {
HILOG_ERROR("HandleDumpHeap failed, mainHandler is nullptr");
return;
}
auto task = [isPrivate] {
auto app = applicationForDump_.lock();
if (app == nullptr || app->GetRuntime() == nullptr) {
HILOG_ERROR("runtime is nullptr.");
return;
}
app->GetRuntime()->DumpHeapSnapshot(isPrivate);
};
mainHandler_->PostTask(task);
}
void MainThread::Start()
+1 -1
View File
@@ -172,7 +172,7 @@ void Watchdog::ReportEvent()
appMainHandler_->Dump(handlerDumper);
msgContent += handlerDumper.GetDumpInfo();
OHOS::HiviewDFX::HiSysEvent::Write(OHOS::HiviewDFX::HiSysEvent::Domain::AAFWK, eventType,
HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::AAFWK, eventType,
OHOS::HiviewDFX::HiSysEvent::EventType::FAULT, EVENT_KEY_UID, applicationInfo_->uid,
EVENT_KEY_PID, static_cast<int32_t>(getpid()), EVENT_KEY_PACKAGE_NAME, applicationInfo_->bundleName,
EVENT_KEY_PROCESS_NAME, applicationInfo_->process, EVENT_KEY_MESSAGE, msgContent);
+2 -2
View File
@@ -282,7 +282,7 @@ private:
void FinishPreload() override
{
panda::JSNApi::preFork(vm_);
panda::JSNApi::PreFork(vm_);
}
bool Initialize(const Runtime::Options& options) override
@@ -294,7 +294,7 @@ private:
std::string sandBoxAnFilePath = SANDBOX_ARK_CACHE_PATH + options.arkNativeFilePath;
postOption.SetAnDir(sandBoxAnFilePath);
}
panda::JSNApi::postFork(vm_, postOption);
panda::JSNApi::PostFork(vm_, postOption);
nativeEngine_->ReinitUVLoop();
panda::JSNApi::SetLoop(vm_, nativeEngine_->GetUVLoop());
} else {
@@ -237,6 +237,40 @@ void AsyncTask::RejectWithCustomize(NativeEngine& engine, NativeValue* error, Na
HILOG_DEBUG("AsyncTask::RejectWithCustomize is called end.");
}
void AsyncTask::ResolveWithCustomize(NativeEngine& engine, NativeValue* error, NativeValue* value)
{
HILOG_DEBUG("AsyncTask::Resolve is called");
if (deferred_) {
deferred_->Resolve(value);
deferred_.reset();
}
if (callbackRef_) {
NativeValue* argv[] = {
error,
value,
};
engine.CallFunction(engine.CreateUndefined(), callbackRef_->Get(), argv, ArraySize(argv));
callbackRef_.reset();
}
HILOG_DEBUG("AsyncTask::Resolve is called end.");
}
void AsyncTask::RejectWithCustomize(NativeEngine& engine, NativeValue* error, NativeValue* value)
{
if (deferred_) {
deferred_->Reject(error);
deferred_.reset();
}
if (callbackRef_) {
NativeValue* argv[] = {
error,
value,
};
engine.CallFunction(engine.CreateUndefined(), callbackRef_->Get(), argv, ArraySize(argv));
callbackRef_.reset();
}
}
void AsyncTask::Execute(NativeEngine* engine, void* data)
{
if (engine == nullptr || data == nullptr) {
+18 -11
View File
@@ -40,6 +40,13 @@ const std::string REALPATH_FLAG = "/temprary/";
const std::string ABILITYPATH_FLAG = "/entry/ets/";
const std::string NOT_FOUNDMAP = "Cannot get SourceMap info, dump raw stack:\n";
constexpr int64_t ASSET_FILE_MAX_SIZE = 20 * (1 << 20);
constexpr int32_t INDEX_TWO = 2;
constexpr int32_t INDEX_THREE = 3;
constexpr int32_t INDEX_FOUR = 4;
constexpr int32_t ANS_MAP_SIZE = 5;
constexpr int32_t NUM_TWENTY = 20;
constexpr int32_t NUM_TWENTYSIX = 26;
constexpr int32_t DIGIT_NUM = 64;
bool ModSourceMap::ReadSourceMapData(const std::string& filePath, std::string& content)
{
@@ -123,7 +130,7 @@ void ModSourceMap::ExtractKeyInfo(const std::string& sourceMap, std::vector<std:
if (sourceMap[i] == '"') {
cnt++;
}
if (cnt == 2) {
if (cnt == INDEX_TWO) {
sourceKeyInfo.push_back(tempStr);
tempStr = "";
cnt = 0;
@@ -247,10 +254,10 @@ void ModSourceMap::Init(const std::string& sourceMap, SourceMapData& curMapData)
// after decode, assgin each value to the position
curMapData.nowPos_.afterColumn += ans[0];
curMapData.nowPos_.sourcesVal += ans[1];
curMapData.nowPos_.beforeRow += ans[2];
curMapData.nowPos_.beforeColumn += ans[3];
if (ans.size() == 5) {
curMapData.nowPos_.namesVal += ans[4];
curMapData.nowPos_.beforeRow += ans[INDEX_TWO];
curMapData.nowPos_.beforeColumn += ans[INDEX_THREE];
if (ans.size() == ANS_MAP_SIZE) {
curMapData.nowPos_.namesVal += ans[INDEX_FOUR];
}
curMapData.afterPos_.push_back({
curMapData.nowPos_.beforeRow,
@@ -309,7 +316,7 @@ uint32_t ModSourceMap::Base64CharToInt(char charCode)
// 63: /
return 63;
}
return 64;
return DIGIT_NUM;
};
bool ModSourceMap::VlqRevCode(const std::string& vStr, std::vector<int32_t>& ans)
@@ -326,7 +333,7 @@ bool ModSourceMap::VlqRevCode(const std::string& vStr, std::vector<int32_t>& ans
bool continuation = 0;
for (uint32_t i = 0; i < vStr.size(); i++) {
uint32_t digit = Base64CharToInt(vStr[i]);
if (digit == 64) {
if (digit == DIGIT_NUM) {
return false;
}
continuation = digit & VLQ_CONTINUATION_BIT;
@@ -429,10 +436,10 @@ std::string ModSourceMap::TranslateBySourceMap(const std::string& stackStr, ModS
j = curSourceMap.find("},", s);
uint32_t q = s;
uint32_t jj = j;
value = curSourceMap.substr(q + 1, jj - q+2);
value = curSourceMap.substr(q + 1, jj - q + INDEX_TWO);
uint32_t sources = value.find("\"sources\": [");
uint32_t names = value.find("],");
key = value.substr(sources + 20, names - sources - 26);
key = value.substr(sources + NUM_TWENTY, names - sources - NUM_TWENTYSIX);
MapData.insert(std::pair<std::string, std::string>(key, value));
}
@@ -519,14 +526,14 @@ std::string ModSourceMap::GetOriginalNames(std::shared_ptr<SourceMapData> target
return sourceCode;
}
std::vector<std::string> names = targetMapData->names_;
if (names.size() % 2 != 0) {
if (names.size() % INDEX_TWO != 0) {
HILOG_ERROR("Names in sourcemap is wrong.");
return sourceCode;
}
std::string jsCode = sourceCode;
int32_t posDiff = 0;
for (uint32_t i = 0; i < names.size(); i += 2) {
for (uint32_t i = 0; i < names.size(); i += INDEX_TWO) {
auto found = jsCode.find(names[i]);
while (found != std::string::npos) {
// names_[i + 1] is the original name of names_[i]
@@ -467,7 +467,7 @@ private:
std::shared_ptr<ProcessInfo> processInfo_ = nullptr;
std::shared_ptr<OHOSApplication> application_ = nullptr;
std::shared_ptr<ApplicationImpl> applicationImpl_ = nullptr;
std::shared_ptr<MainHandler> mainHandler_ = nullptr;
static std::shared_ptr<MainHandler> mainHandler_;
std::shared_ptr<AbilityRecordMgr> abilityRecordMgr_ = nullptr;
std::shared_ptr<Watchdog> watchdog_ = nullptr;
MainThreadState mainThreadState_ = MainThreadState::INIT;
@@ -102,14 +102,6 @@ public:
*/
bool FindReusedMissionInfo(const std::string &missionName, const std::string &flag, InnerMissionInfo &info);
/**
* @brief Update mission timestamp.
*
* @param missionId indicates this mission id.
* @param timestamp indicates this mission timestamp.
*/
void UpdateMissionTimeStamp(int32_t missionId, const std::string& timestamp);
/**
* @brief Delete all the mission info.
*
@@ -420,7 +420,6 @@ private:
std::shared_ptr<AbilityRecord> GetAbilityRecordByCaller(
const std::shared_ptr<AbilityRecord> &caller, int requestCode);
std::shared_ptr<MissionList> GetTargetMissionList(int missionId, std::shared_ptr<Mission> &mission);
void UpdateMissionTimeStamp(const std::shared_ptr<AbilityRecord> &abilityRecord);
void PostStartWaitingAbility();
void HandleAbilityDied(std::shared_ptr<AbilityRecord> abilityRecord);
void HandleLauncherDied(std::shared_ptr<AbilityRecord> ability);
@@ -4166,7 +4166,7 @@ void AbilityManagerService::ScheduleRecoverAbility(const sptr<IRemoteObject>& to
want = record->GetWant();
want.SetParam(AAFwk::Want::PARAM_ABILITY_RECOVERY_RESTART, true);
HiSysEvent::Write(HiSysEvent::Domain::AAFWK, "APP_RECOVERY", HiSysEvent::EventType::BEHAVIOR,
HiSysEventWrite(HiSysEvent::Domain::AAFWK, "APP_RECOVERY", HiSysEvent::EventType::BEHAVIOR,
"APP_UID", record->GetUid(),
"VERSION_CODE", std::to_string(appInfo.versionCode),
"VERSION_NAME", appInfo.versionName,
@@ -29,6 +29,7 @@
namespace OHOS {
namespace AAFwk {
constexpr int CYCLE_LIMIT = 2000;
AbilitySchedulerStub::AbilitySchedulerStub()
{
requestFuncMap_[SCHEDULE_ABILITY_TRANSACTION] = &AbilitySchedulerStub::AbilityTransactionInner;
@@ -418,6 +419,10 @@ int AbilitySchedulerStub::BatchInsertInner(MessageParcel &data, MessageParcel &r
return ERR_INVALID_VALUE;
}
if (count > CYCLE_LIMIT) {
HILOG_ERROR("count is too large");
return ERR_INVALID_VALUE;
}
std::vector<NativeRdb::ValuesBucket> values;
for (int i = 0; i < count; i++) {
std::unique_ptr<NativeRdb::ValuesBucket> value(data.ReadParcelable<NativeRdb::ValuesBucket>());
@@ -537,6 +542,10 @@ int AbilitySchedulerStub::ExecuteBatchInner(MessageParcel &data, MessageParcel &
return ERR_INVALID_VALUE;
}
HILOG_INFO("AbilitySchedulerStub::ExecuteBatchInner count:%{public}d", count);
if (count > CYCLE_LIMIT) {
HILOG_ERROR("count is too large");
return ERR_INVALID_VALUE;
}
std::vector<std::shared_ptr<AppExecFwk::DataAbilityOperation>> operations;
for (int i = 0; i < count; i++) {
AppExecFwk::DataAbilityOperation *operation = data.ReadParcelable<AppExecFwk::DataAbilityOperation>();
@@ -320,28 +320,6 @@ bool MissionInfoMgr::FindReusedMissionInfo(const std::string &missionName,
return true;
}
void MissionInfoMgr::UpdateMissionTimeStamp(int32_t missionId, const std::string& timestamp)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
auto it = find_if(missionInfoList_.begin(), missionInfoList_.end(), [missionId](const InnerMissionInfo &info) {
return missionId == info.missionInfo.id;
});
if (it == missionInfoList_.end()) {
HILOG_ERROR("UpdateMissionTimeStamp failed, missionId %{public}d not exists", missionId);
return;
}
if (timestamp == it->missionInfo.time) {
return;
}
InnerMissionInfo updateInfo = *it;
updateInfo.missionInfo.time = timestamp;
missionInfoList_.erase(it);
missionIdMap_.erase(missionId);
(void)AddMissionInfo(updateInfo);
}
int MissionInfoMgr::UpdateMissionLabel(int32_t missionId, const std::string& label)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
@@ -726,9 +726,6 @@ int MissionListManager::MinimizeAbilityLocked(const std::shared_ptr<AbilityRecor
abilityRecord->SetMinimizeReason(fromUser);
MoveToBackgroundTask(abilityRecord);
if (abilityRecord->lifeCycleStateInfo_.sceneFlag != SCENE_FLAG_KEYGUARD) {
UpdateMissionTimeStamp(abilityRecord);
}
return ERR_OK;
}
@@ -1063,9 +1060,6 @@ void MissionListManager::CompleteForegroundSuccess(const std::shared_ptr<Ability
if (abilityRecord->GetPendingState() == AbilityState::BACKGROUND) {
abilityRecord->SetMinimizeReason(true);
MoveToBackgroundTask(abilityRecord);
if (abilityRecord->lifeCycleStateInfo_.sceneFlag != SCENE_FLAG_KEYGUARD) {
UpdateMissionTimeStamp(abilityRecord);
}
} else if (abilityRecord->GetPendingState() == AbilityState::FOREGROUND) {
HILOG_DEBUG("not continuous startup.");
abilityRecord->SetPendingState(AbilityState::INITIAL);
@@ -1656,7 +1650,7 @@ void MissionListManager::PrintTimeOutLog(const std::shared_ptr<AbilityRecord> &a
return;
}
std::string eventType = "LIFECYCLE_TIMEOUT";
OHOS::HiviewDFX::HiSysEvent::Write(OHOS::HiviewDFX::HiSysEvent::Domain::AAFWK, eventType,
HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::AAFWK, eventType,
OHOS::HiviewDFX::HiSysEvent::EventType::FAULT,
EVENT_KEY_UID, processInfo.uid_,
EVENT_KEY_PID, processInfo.pid_,
@@ -2062,16 +2056,6 @@ sptr<IRemoteObject> MissionListManager::GetAbilityTokenByMissionId(int32_t missi
return defaultStandardList_->GetAbilityTokenByMissionId((missionId));
}
void MissionListManager::UpdateMissionTimeStamp(const std::shared_ptr<AbilityRecord> &abilityRecord)
{
auto mission = abilityRecord->GetMission();
if (!mission) {
return;
}
std::string curTime = GetCurrentTime();
DelayedSingleton<MissionInfoMgr>::GetInstance()->UpdateMissionTimeStamp(mission->GetMissionId(), curTime);
}
void MissionListManager::PostStartWaitingAbility()
{
auto self(shared_from_this());
@@ -845,6 +845,10 @@ int64_t AppMgrServiceInner::SystemTimeMillisecond()
std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetAppRunningRecordByPid(const pid_t pid) const
{
if (!appRunningManager_) {
HILOG_ERROR("appRunningManager nullptr!");
return nullptr;
}
return appRunningManager_->GetAppRunningRecordByPid(pid);
}
@@ -2407,7 +2411,7 @@ void AppMgrServiceInner::SendHiSysEvent(const int32_t innerEventId, const int64_
packageName = %{public}s, processName = %{public}s, msg = %{public}s",
eventName.c_str(), uid, pid, packageName.c_str(), processName.c_str(), msg.c_str());
OHOS::HiviewDFX::HiSysEvent::Write(
HiSysEventWrite(
OHOS::HiviewDFX::HiSysEvent::Domain::AAFWK,
eventName,
OHOS::HiviewDFX::HiSysEvent::EventType::FAULT,
+14 -14
View File
@@ -36,7 +36,7 @@ const std::string EVENT_KEY_EXTENSION_TYPE = "EXTENSION_TYPE";
void EventReport::SendAppEvent(const std::string &eventName, HiSysEventType type,
const EventInfo& eventInfo)
{
HiSysEvent::Write(
HiSysEventWrite(
HiSysEvent::Domain::AAFWK,
eventName,
type,
@@ -51,7 +51,7 @@ void EventReport::SendAbilityEvent(const std::string &eventName, HiSysEventType
const EventInfo& eventInfo)
{
if (eventName == START_ABILITY_ERROR || eventName == TERMINATE_ABILITY_ERROR) {
HiSysEvent::Write(
HiSysEventWrite(
HiSysEvent::Domain::AAFWK,
eventName,
type,
@@ -61,7 +61,7 @@ void EventReport::SendAbilityEvent(const std::string &eventName, HiSysEventType
EVENT_KEY_ABILITY_NAME, eventInfo.abilityName,
EVENT_KEY_ERROR_CODE, eventInfo.errCode);
} else if (eventName == START_ABILITY) {
HiSysEvent::Write(
HiSysEventWrite(
HiSysEvent::Domain::AAFWK,
eventName,
type,
@@ -70,14 +70,14 @@ void EventReport::SendAbilityEvent(const std::string &eventName, HiSysEventType
EVENT_KEY_MODULE_NAME, eventInfo.moduleName,
EVENT_KEY_ABILITY_NAME, eventInfo.abilityName);
} else if (eventName == TERMINATE_ABILITY || eventName == CLOSE_ABILITY) {
HiSysEvent::Write(
HiSysEventWrite(
HiSysEvent::Domain::AAFWK,
eventName,
type,
EVENT_KEY_BUNDLE_NAME, eventInfo.bundleName,
EVENT_KEY_ABILITY_NAME, eventInfo.abilityName);
} else if (eventName == ABILITY_ONFOREGROUND || eventName == ABILITY_ONBACKGROUND) {
HiSysEvent::Write(
HiSysEventWrite(
HiSysEvent::Domain::AAFWK,
eventName,
type,
@@ -91,12 +91,12 @@ void EventReport::SendExtensionEvent(const std::string &eventName, HiSysEventTyp
const EventInfo& eventInfo)
{
if (eventName == DISCONNECT_SERVICE) {
HiSysEvent::Write(
HiSysEventWrite(
HiSysEvent::Domain::AAFWK,
eventName,
type);
} else if (eventName == CONNECT_SERVICE) {
HiSysEvent::Write(
HiSysEventWrite(
HiSysEvent::Domain::AAFWK,
eventName,
type,
@@ -105,7 +105,7 @@ void EventReport::SendExtensionEvent(const std::string &eventName, HiSysEventTyp
EVENT_KEY_MODULE_NAME, eventInfo.moduleName,
EVENT_KEY_ABILITY_NAME, eventInfo.abilityName);
} else if (eventName == START_SERVICE || eventName == STOP_SERVICE) {
HiSysEvent::Write(
HiSysEventWrite(
HiSysEvent::Domain::AAFWK,
eventName,
type,
@@ -116,7 +116,7 @@ void EventReport::SendExtensionEvent(const std::string &eventName, HiSysEventTyp
EVENT_KEY_EXTENSION_TYPE, eventInfo.extensionType);
} else if (eventName == START_EXTENSION_ERROR || eventName == STOP_EXTENSION_ERROR ||
eventName == CONNECT_SERVICE_ERROR) {
HiSysEvent::Write(
HiSysEventWrite(
HiSysEvent::Domain::AAFWK,
eventName,
type,
@@ -126,7 +126,7 @@ void EventReport::SendExtensionEvent(const std::string &eventName, HiSysEventTyp
EVENT_KEY_ABILITY_NAME, eventInfo.abilityName,
EVENT_KEY_ERROR_CODE, eventInfo.errCode);
} else if (eventName == DISCONNECT_SERVICE_ERROR) {
HiSysEvent::Write(
HiSysEventWrite(
HiSysEvent::Domain::AAFWK,
eventName,
type,
@@ -138,12 +138,12 @@ void EventReport::SendFormEvent(const std::string &eventName, HiSysEventType typ
const EventInfo& eventInfo)
{
if (eventName == DELETE_INVALID_FORM) {
HiSysEvent::Write(
HiSysEventWrite(
HiSysEvent::Domain::AAFWK,
eventName,
type);
} else if (eventName == ACQUIREFORMSTATE_FORM || eventName == MESSAGE_EVENT_FORM) {
HiSysEvent::Write(
HiSysEventWrite(
HiSysEvent::Domain::AAFWK,
eventName,
type,
@@ -151,7 +151,7 @@ void EventReport::SendFormEvent(const std::string &eventName, HiSysEventType typ
EVENT_KEY_MODULE_NAME, eventInfo.moduleName,
EVENT_KEY_ABILITY_NAME, eventInfo.abilityName);
} else if (eventName == ADD_FORM || eventName == REQUEST_FORM || eventName == ROUTE_EVENT_FORM) {
HiSysEvent::Write(
HiSysEventWrite(
HiSysEvent::Domain::AAFWK,
eventName,
type,
@@ -161,7 +161,7 @@ void EventReport::SendFormEvent(const std::string &eventName, HiSysEventType typ
EVENT_KEY_ABILITY_NAME, eventInfo.abilityName);
} else if (eventName == DELETE_FORM || eventName == CASTTEMP_FORM || eventName == RELEASE_FORM ||
eventName == SET_NEXT_REFRESH_TIME_FORM) {
HiSysEvent::Write(
HiSysEventWrite(
HiSysEvent::Domain::AAFWK,
eventName,
type,
@@ -0,0 +1,13 @@
{
"app": {
"bundleName": "com.ohos.amsdialog",
"vendor": "example",
"versionCode": 1000000,
"versionName": "1.0.0",
"icon": "$media:app_icon",
"label": "$string:app_name",
"distributedNotificationEnabled": true,
"minAPIVersion": 9,
"targetAPIVersion": 9
}
}
@@ -0,0 +1,8 @@
{
"string": [
{
"name": "app_name",
"value": "AmsSystemDialog"
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

@@ -0,0 +1,50 @@
# Copyright (c) 2021-2022 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")
ohos_hap("ams_system_dialog_hap") {
hap_profile = "entry/src/main/module.json"
deps = [
":ams_system_dialog_js_assets",
":ams_system_dialog_resources",
]
certificate_profile = "signature/openharmony_sx.p7b"
hap_name = "ams_system_dialog"
subsystem_name = "application"
part_name = "prebuilt_hap"
module_install_dir = "app/com.ohos.amsdialog"
}
ohos_js_assets("ams_system_dialog_js_assets") {
hap_profile = "entry/src/main/module.json"
ets2abc = true
source_dir = "entry/src/main/ets"
}
ohos_app_scope("ams_system_dialog_app_profile") {
app_profile = "AppScope/app.json"
sources = [ "AppScope/resources" ]
}
ohos_resources("ams_system_dialog_resources") {
sources = [ "entry/src/main/resources" ]
deps = [ ":ams_system_dialog_app_profile" ]
hap_profile = "entry/src/main/module.json"
}
group("dialog_hap") {
deps = [ ":ams_system_dialog_hap" ]
}
@@ -0,0 +1,22 @@
/*
* Copyright (c) 2022 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 AbilityStage from "@ohos.application.AbilityStage"
export default class DialogAbilityStage extends AbilityStage {
onCreate() {
console.log("DialogAbilityStage onCreate");
}
}
@@ -0,0 +1,80 @@
/*
* Copyright (c) 2022 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 extension from '@ohos.application.ServiceExtensionAbility';
import window from '@ohos.window';
import display from '@ohos.display';
const TAG = "notificationDialog_Service";
export default class NotificationDialogServiceExtensionAbility extends extension {
onCreate(want) {
console.debug(TAG, "onCreate, want: " + JSON.stringify(want));
globalThis.notificationExtensionContext = this.context;
globalThis.callbackImp = want.parameters.callbackStubImpl_;
globalThis.closeDialog = () => {
console.info(TAG, 'click waiting for a response');
globalThis.notificationExtensionContext.terminateSelf();
}
}
onRequest(want, startId) {
globalThis.abilityWant = want;
globalThis.resolution = display.getDefaultDisplaySync().densityDPI;
console.log(TAG, "globalThis.resolution" + JSON.stringify(globalThis.resolution));
display.getDefaultDisplay().then(dis => {
let thisWidth;
let thisHeight;
if (dis.width < dis.height) {
let widthRatio = 0.75;
let heightRatio = 5;
thisWidth = widthRatio * dis.width;
thisHeight = dis.height / heightRatio;
} else {
let widthRatio = 3;
let heightRatio = 4;
thisWidth = dis.width / widthRatio;
thisHeight = dis.height / heightRatio;
}
let navigationBarRect = {
left: (dis.width - thisWidth) / 2,
top: (dis.height - thisHeight) / 2,
width: thisWidth,
height: thisHeight
}
globalThis.popWidth = navigationBarRect.width;
globalThis.popHeight = navigationBarRect.height;
this.createWindow("NotificationDialog" + startId, window.WindowType.TYPE_SYSTEM_ALERT, navigationBarRect);
})
}
onDestroy() {
console.info(TAG, "onDestroy.");
}
private async createWindow(name: string, windowType: number, rect) {
console.info(TAG, "create window");
try {
const win = await window.create(globalThis.notificationExtensionContext, name, windowType);
await win.moveTo(rect.left, rect.top);
await win.resetSize(rect.width, rect.height - 22);
await win.loadContent('pages/notificationDialog');
await win.setBackgroundColor("#00000000");
await win.show();
} catch {
console.error(TAG, "window create failed!");
}
}
};
@@ -0,0 +1,131 @@
/*
* Copyright (c) 2022 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 extension from '@ohos.application.ServiceExtensionAbility';
import window from '@ohos.window';
import display from '@ohos.display';
const TAG = "SelectorDialog_Service";
var winNum = 1;
var win;
export default class SelectorServiceExtensionAbility extends extension {
onCreate(want) {
console.debug(TAG, "onCreate, want: " + JSON.stringify(want));
globalThis.selectExtensionContext = this.context;
}
async getPhoneShowHapList() {
const lineNums = 8;
let showHapList = [];
let phoneShowHapList = [];
for (let i = 1; i <= globalThis.params.hapList.length; i++) {
await this.getHapResource(globalThis.params.hapList[i - 1], showHapList);
if (i % lineNums == 0) {
phoneShowHapList.push(showHapList);
showHapList = [];
}
if (i >= globalThis.params.hapList.length && showHapList.length > 0) {
phoneShowHapList.push(showHapList);
}
}
globalThis.phoneShowHapList = phoneShowHapList;
console.debug(TAG, "phoneShowHapList: " + JSON.stringify(phoneShowHapList));
}
async getPcShowHapList() {
let pcShowHapList = [];
for (let i = 0; i < globalThis.params.hapList.length; i++) {
await this.getHapResource(globalThis.params.hapList[i], pcShowHapList);
}
globalThis.pcShowHapList = pcShowHapList;
console.debug(TAG, "pcShowHapList: " + JSON.stringify(pcShowHapList));
}
async getHapResource(hap, showHapList) {
let bundleName = hap.bundle;
let moduleName = hap.module;
let abilityName = hap.ability;
let appName = "";
let appIcon = "";
let lableId = Number(hap.label);
let moduleContext = globalThis.selectExtensionContext.createModuleContext(bundleName, moduleName);
await moduleContext.resourceManager.getString(lableId).then(value => {
appName = value;
}).catch(error => {
console.error(TAG, "getString error:" + JSON.stringify(error));
});
let iconId = Number(hap.icon);
await moduleContext.resourceManager.getMediaBase64(iconId).then(value => {
appIcon = value;
}).catch(error => {
console.error(TAG, "getMediaBase64 error:" + JSON.stringify(error));
});
showHapList.push(bundleName + "-" + abilityName + "-" + appName + "-" + appIcon);
}
async onRequest(want, startId) {
globalThis.abilityWant = want;
globalThis.params = JSON.parse(want["parameters"]["params"]);
globalThis.position = JSON.parse(want["parameters"]["position"]);
console.debug(TAG, "onRequest, params: " + JSON.stringify(globalThis.params));
console.debug(TAG, "onRequest, position: " + JSON.stringify(globalThis.position));
if (globalThis.params.deviceType == "phone") {
await this.getPhoneShowHapList();
} else {
await this.getPcShowHapList();
}
display.getDefaultDisplay().then(dis => {
let navigationBarRect = {
left: globalThis.position.offsetX,
top: globalThis.position.offsetY,
width: globalThis.position.width,
height: globalThis.position.height
}
if (winNum > 1) {
win.destroy();
winNum--;
}
this.createWindow("SelectorDialog" + startId, window.WindowType.TYPE_SYSTEM_ALERT, navigationBarRect);
winNum++;
})
}
onDestroy() {
console.info(TAG, "onDestroy.");
}
private async createWindow(name: string, windowType: number, rect) {
console.info(TAG, "create window");
try {
win = await window.create(globalThis.selectExtensionContext, name, windowType);
await win.moveTo(rect.left, rect.top);
await win.resetSize(rect.width, rect.height);
if (globalThis.params.deviceType == "phone") {
await win.loadContent('pages/selectorPhoneDialog');
} else {
await win.loadContent('pages/selectorPcDialog');
}
await win.setBackgroundColor("#00000000");
await win.show();
} catch {
console.error(TAG, "window create failed!");
}
}
};
@@ -0,0 +1,69 @@
/*
* Copyright (c) 2022 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 extension from '@ohos.application.ServiceExtensionAbility';
import window from '@ohos.window';
import display from '@ohos.display';
const TAG = "TipsDialog_Service";
var winNum = 1;
var win;
export default class TipsServiceExtensionAbility extends extension {
onCreate(want) {
console.debug(TAG, "onCreate, want: " + JSON.stringify(want));
globalThis.tipsExtensionContext = this.context;
}
onRequest(want, startId) {
globalThis.abilityWant = want;
globalThis.params = JSON.parse(want["parameters"]["params"]);
globalThis.position = JSON.parse(want["parameters"]["position"]);
display.getDefaultDisplay().then(dis => {
let navigationBarRect = {
left: globalThis.position.offsetX,
top: globalThis.position.offsetY,
width: globalThis.position.width,
height: globalThis.position.height
}
if (winNum > 1) {
win.destroy();
winNum--;
}
this.createWindow("TipsDialog" + startId, window.WindowType.TYPE_SYSTEM_ALERT, navigationBarRect);
winNum++;
})
}
onDestroy() {
console.info(TAG, "onDestroy.");
}
private async createWindow(name: string, windowType: number, rect) {
console.info(TAG, "create window");
try {
win = await window.create(globalThis.tipsExtensionContext, name, windowType);
await win.moveTo(rect.left, rect.top);
await win.resetSize(rect.width, rect.height);
await win.loadContent('pages/tipsDialog');
await win.setBackgroundColor("#00000000");
await win.show();
} catch {
console.error(TAG, "window create failed!");
}
}
};
@@ -0,0 +1,146 @@
/*
* Copyright (c) 2022 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 notification from '@ohos.notification'
import rpc from '@ohos.rpc';
class Proxy extends rpc.RemoteProxy {
}
@Entry
@Component
struct NotificationDialog {
@State private want: any = undefined
@State private uid: any = undefined
@State private style: any = {}
@State callBackImp_: any = {}
@State token_: any = undefined
@State popWidth: any = undefined
@State popHeight: any = undefined
@State bundleName: any = undefined
controller: CustomDialogController
private TAG = "[DialogService]"
build() {
Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text($r("app.string.if_allow_to_publish_notification"))
.width("350vp")
.height("22vp")
.margin({ top: 32 })
.fontSize(21)
.fontColor("#182431")
.fontWeight(400)
.opacity(1)
.textAlign(TextAlign.Center)
}
Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.Center }) {
Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.Center }) {
Button() {
Row() {
Text($r("app.string.allow"))
.textAlign(TextAlign.Center)
.fontSize("22fp")
.fontWeight(500)
.fontColor("#0D81F2")
}
}
.onClick(() => {
let popFlag = true
this.privacyChose(popFlag)
console.info("after privacyChose")
})
.width("116vp")
.height("40vp")
.margin({ top: "9vp", right: "8vp", bottom: "9vp", left: "8vp" })
.backgroundColor("#FFFFFF")
}
.margin({ top: 15, right: 5, bottom: 8, left: 8 })
Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.Center }) {
Button() {
Row() {
Text($r("app.string.ban"))
.textAlign(TextAlign.Center)
.lineHeight("22vp")
.fontSize("22fp")
.fontWeight(500)
.fontColor("#0D81F2")
}
}
.onClick(() => {
let popFlag = false
this.privacyChose(popFlag)
console.info("after privacyChose")
})
.width("116vp")
.height("40vp")
.margin({ top: "9vp", right: "8vp", bottom: "9vp", left: "8vp" })
.backgroundColor("#FFFFFF")
}
.margin({ top: 15, right: 8, bottom: 8, left: 5 })
}
}
.borderRadius(32)
.backgroundColor("#FFFFFF")
}
async privacyChose(flag) {
let enable = flag;
let bundleOption = {
bundle: globalThis.bundleName
}
console.info("before enableNotification")
await notification.enableNotification(bundleOption, enable, (err) => {
if (err.code) {
console.error('Start enableNotification failed. ErrCode: ' + JSON.stringify(err.code));
return
}
let option = new rpc.MessageOption()
let data = rpc.MessageParcel.create()
let reply = rpc.MessageParcel.create()
data.writeInterfaceToken("OHOS.Notification.AnsCallbackInterface")
data.writeBoolean(flag)
console.info("before send request")
this.callBackImp_.sendRequest(0, data, reply, option)
.then(function (result) {
console.info("start to send request")
if (result.errCode != 0) {
console.error("send request failed, errCode: " + result.errCode)
return
}
})
.catch(function (err) {
console.error(this.TAG + "send request got exception: " + err)
})
.finally(() => {
data.reclaim()
reply.reclaim()
globalThis.closeDialog()
})
})
console.info("after send request")
}
aboutToAppear() {
console.log(this.TAG, "dialog page appears")
this.want = globalThis.abilityWant
this.style = globalThis.style
this.callBackImp_ = globalThis.abilityWant.parameters['callbackStubImpl_'].value
this.token_ = globalThis.abilityWant.parameters['tokenId'].value
globalThis.bundleName = globalThis.abilityWant.parameters['from']
}
}
@@ -0,0 +1,154 @@
/*
* Copyright (c) 2022 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.
*/
@Entry
@Component
struct SelectorPcDialog {
@State private pcSelectorlist: any = {};
@State private hapList: any = [];
private TAG = "SelectorDialog_Pc_Page";
aboutToAppear(): void {
console.log(this.TAG, "dialog page appears");
this.hapList = globalThis.params.hapList;
this.getHapListStyle();
}
onSelectApp(item) {
globalThis.abilityWant.bundleName = item.split("-")[0];
globalThis.abilityWant.abilityName = item.split("-")[1];
globalThis.selectExtensionContext.startAbility(globalThis.abilityWant, (data, error) => {
if (error) {
console.error(this.TAG + " startAbility finish, error: " + JSON.stringify(error));
return;
}
console.log(this.TAG + " startAbility finish, data: " + JSON.stringify(data));
});
globalThis.selectExtensionContext.terminateSelf();
}
getHapListStyle() {
let heightTotalVp = 1;
let heightVal = 120;
if (this.hapList.length == 2) {
heightTotalVp = this.hapList.length * heightVal;
} else if (this.hapList.length == 3) {
heightTotalVp = this.hapList.length * heightVal;
} else if (this.hapList.length == 4) {
heightTotalVp = this.hapList.length * heightVal;
} else if (this.hapList.length > 4) {
heightTotalVp = 4 * heightVal + 20;
} else {
;
}
this.pcSelectorlist = {
width: "100%",
height: heightTotalVp + "vp",
};
}
build() {
Flex({ direction: FlexDirection.Column }) {
Flex({ direction: FlexDirection.Column }) {
Text($r("app.string.message_title_selector"))
.fontSize(22)
.fontWeight(FontWeight.Medium)
.textAlign(TextAlign.Start)
.margin({ top: 25, left: 20 })
}
.height(120)
Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
List() {
ForEach(globalThis.pcShowHapList, (item: any) => {
ListItem() {
Flex({ direction: FlexDirection.Row }) {
if (item.split("-")[3] != "") {
Image(item.split("-")[3])
.height(70)
.width(70)
.alignSelf(ItemAlign.Center)
.margin({ left: 16 })
} else {
Image($r("app.media.app_icon"))
.height(70)
.width(70)
.alignSelf(ItemAlign.Center)
.margin({ left: 16 })
}
if (item.split("-")[2] != "") {
Text(item.split("-")[2])
.fontSize(16)
.width("80%")
.height(60)
.alignSelf(ItemAlign.Center)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.margin({ left: 16 })
} else {
Text(item.split("-")[0])
.fontSize(16)
.width("80%")
.height(60)
.alignSelf(ItemAlign.Center)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.margin({ left: 16 })
}
}.onClick(() => {
this.onSelectApp(item)
})
}.margin({ top: 4, bottom: 4 }).backgroundColor("#ffffff")
}, item => item)
}
.margin({ left: 1, right: 1 })
.backgroundColor("#ffffff")
.scrollBar(globalThis.pcShowHapList.length > 4 ? BarState.Auto : BarState.Off)
.divider({ strokeWidth: 1 })
}
.backgroundColor("#ffffff")
.width("90%")
.height(this.pcSelectorlist.height)
.margin({ bottom: 10 })
Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
Text($r("app.string.message_cancel_selector"))
.fontSize("21fp")
.fontColor("#0A59F7")
.fontWeight(FontWeight.Regular)
.textAlign(TextAlign.Center)
}
.width("90%")
.height(50)
.margin({ top: 10 })
.borderRadius(28)
.backgroundColor("#F2F2F2")
}
.width("90%")
.margin({ left: 15, bottom: 20 })
.backgroundColor("#ffffff")
.borderRadius(20)
.onClick(() => {
globalThis.selectExtensionContext.terminateSelf();
})
}
.borderRadius(24)
.borderWidth(1)
.borderColor("#e9e9e9")
.backgroundColor("#ffffff")
.width("100%")
.height("100%")
}
}
@@ -0,0 +1,192 @@
/*
* Copyright (c) 2022 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.
*/
class SelectorDataSource implements IDataSource {
private list: string[] = []
private listener: DataChangeListener
constructor(list: string[]) {
this.list = list
}
totalCount(): number {
return this.list.length
}
getData(index: number): any {
return this.list[index]
}
registerDataChangeListener(listener: DataChangeListener): void {
this.listener = listener
}
unregisterDataChangeListener() {
}
}
@Entry
@Component
struct SelectorPhoneDialog {
private phoneShowData: SelectorDataSource = new SelectorDataSource([])
@State private selector: any = {
swiper: {
height: "100vp",
indicator: false,
contentHeight: "100vp",
gridColumns: "1fr 1fr",
gridRows: "1fr",
},
btn: {
marginTop: "20vp",
}
}
@State private hapList: any = [];
private TAG = "SelectorDialog_Phone_Page";
aboutToAppear(): void {
console.log(this.TAG, "dialog page appears");
this.hapList = globalThis.params.hapList;
this.getHapListStyle();
this.phoneShowData = new SelectorDataSource(globalThis.phoneShowHapList);
}
onSelectApp(item) {
globalThis.abilityWant.bundleName = item.split("-")[0];
globalThis.abilityWant.abilityName = item.split("-")[1];
globalThis.selectExtensionContext.startAbility(globalThis.abilityWant, (data, error) => {
if (error) {
console.error(this.TAG + " startAbility finish, error: " + JSON.stringify(error));
return;
}
console.log(this.TAG + " startAbility finish, data: " + JSON.stringify(data));
});
globalThis.selectExtensionContext.terminateSelf();
}
getHapListStyle() {
if (this.hapList.length > 8) {
this.selector.swiper.height = "220vp";
this.selector.swiper.indicator = true;
this.selector.swiper.contentHeight = "200vp";
this.selector.swiper.gridColumns = "1fr 1fr 1fr 1fr";
this.selector.swiper.gridRows = "1fr 1fr";
this.selector.btn.marginTop = "10vp";
} else if (this.hapList.length > 3) {
this.selector.swiper.height = "200vp";
this.selector.swiper.contentHeight = "200vp";
this.selector.swiper.gridColumns = "1fr 1fr 1fr 1fr";
this.selector.swiper.gridRows = "1fr 1fr";
} else if (this.hapList.length > 2) {
this.selector.swiper.gridColumns = "1fr 1fr 1fr";
} else {
;
}
}
build() {
Flex({ direction: FlexDirection.Column }) {
Flex({ direction: FlexDirection.Column }) {
Text($r("app.string.message_title_selector"))
.fontSize(22)
.fontWeight(FontWeight.Medium)
.textAlign(TextAlign.Start)
.margin({ top: 25, left: 20 })
}
.height(120)
Column(){
Swiper() {
LazyForEach(this.phoneShowData, (item: any) => {
Grid() {
ForEach(item, (item: any) => {
GridItem() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
if (item.split("-")[3] != "") {
Image(item.split("-")[3])
.height(70)
.width(70)
.alignSelf(ItemAlign.Center);
} else {
Image($r("app.media.app_icon"))
.height(70)
.width(70)
.alignSelf(ItemAlign.Center);
}
if (item.split("-")[2] != "") {
Text(item.split("-")[2])
.fontSize(16)
.width(68)
.height(33)
.textAlign(TextAlign.Center)
.alignSelf(ItemAlign.Center)
.textOverflow({ overflow: TextOverflow.Ellipsis })
} else {
Text(item.split("-")[0])
.fontSize(16)
.width(68)
.height(32)
.textAlign(TextAlign.Center)
.alignSelf(ItemAlign.Center)
.textOverflow({ overflow: TextOverflow.Ellipsis })
}
}
.height(200)
.onClick(() => {
this.onSelectApp(item)
})
}
}, item => item)
}
.columnsTemplate(this.selector.swiper.gridColumns)
.rowsTemplate(this.selector.swiper.gridRows)
.columnsGap(12)
.rowsGap(12)
.margin({ bottom: 10 })
.height(200)
}, item => item)
}
.indicatorStyle({ color: "#bebdc0", selectedColor: "#ff326Ce9", size: 4 })
.align(Alignment.Center)
.width("90%")
.indicator(this.phoneShowData.totalCount() > 1)
.margin({ bottom: 35, top: 20, left: 20 })
}
Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text(($r("app.string.message_cancel_selector")))
.fontSize(20)
.fontColor("#0A59F7")
.fontWeight(FontWeight.Regular)
}
.width("90%")
.height(150)
.backgroundColor("#ffffff")
.borderRadius(20)
.margin({ bottom: 20, top: 10 })
.onClick(() => {
globalThis.selectExtensionContext.terminateSelf();
})
}
.borderRadius(24)
.borderWidth(1)
.borderColor("#e9e9e9")
.backgroundColor("#ffffff")
.width("100%")
.height("100%")
}
}
@@ -0,0 +1,68 @@
/*
* Copyright (c) 2022 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.
*/
@Entry
@Component
struct TipsDialog {
@State private deviceType: string = "phone";
@State private btn: any = { color: "#FFFFFF" }
private TAG = "TipsDialog_Page"
aboutToAppear() {
console.log(this.TAG, "dialog page appears");
this.deviceType = globalThis.params.deviceType
if (this.deviceType == "pc") {
this.btn.color = "#F2F2F2";
}
}
onCloseApp() {
console.info(this.TAG, 'click close app');
globalThis.tipsExtensionContext.terminateSelf();
}
build() {
Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
Text($r('app.string.message_title_tips'))
.fontSize(22)
.fontWeight(FontWeight.Medium)
.height("29%")
.textOverflow({overflow: TextOverflow.Ellipsis})
.textAlign(TextAlign.Center)
}
Flex({ justifyContent: FlexAlign.Center }) {
Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
Text($r('app.string.message_close_tips'))
.fontSize("21fp")
.fontColor("#0A59F7")
.fontWeight(FontWeight.Regular)
.textAlign(TextAlign.Center)
}
.width(175)
.height(50)
.borderRadius(28)
.backgroundColor(this.btn.color)
.onClick(() => {
this.onCloseApp();
})
}.margin({ top: 10})
}
.borderRadius(20)
.borderWidth(1)
.borderColor("#e9e9e9")
.backgroundColor("#FFFFFF")
}
}
@@ -0,0 +1,58 @@
{
"module": {
"name": "entry",
"type": "entry",
"srcEntrance": "./ets/Application/AbilityStage.ts",
"description": "$string:entry_desc",
"mainElement": "MainAbility",
"deviceTypes": [
"default",
"tablet"
],
"deliveryWithInstall": true,
"installationFree": false,
"pages": "$profile:main_pages",
"uiSyntax": "ets",
"abilities": [],
"extensionAbilities": [
{
"name": "SelectorDialog",
"srcEntrance": "./ets/ServiceExtAbility/SelectorServiceExtAbility.ts",
"description": "$string:SelectorServiceExtAbility_desc",
"icon": "$media:icon",
"label": "$string:SelectorServiceExtAbility_label",
"visible": true,
"type": "service"
},
{
"name": "TipsDialog",
"srcEntrance": "./ets/ServiceExtAbility/TipsServiceExtAbility.ts",
"description": "$string:TipsServiceExtAbility_desc",
"icon": "$media:icon",
"label":"$string:TipsServiceExtAbility_label",
"visible": true,
"type": "service"
},
{
"name": "EnableNotificationDialog",
"srcEntrance": "./ets/ServiceExtAbility/NotificationServiceExtAbility.ts",
"description": "$string:NotificationServiceExtAbility_desc",
"icon": "$media:icon",
"label": "$string:NotificationServiceExtAbility_label",
"visible": true,
"type": "service"
}
],
"requestPermissions": [
{
"name": "ohos.permission.GET_BUNDLE_INFO_PRIVILEGED"
},
{
"name": "ohos.permission.START_ABILITIES_FROM_BACKGROUND"
},
{
"name": "ohos.permission.NOTIFICATION_CONTROLLER"
}
]
}
}
@@ -0,0 +1,20 @@
{
"color": [
{
"name": "white",
"value": "#FFFFFF"
},
{
"name": "default_background_color",
"value": "#ffffff"
},
{
"name": "divider_color",
"value": "#f3f4f6"
},
{
"name": "button_color",
"value": "#007DFF"
}
]
}
@@ -0,0 +1,60 @@
{
"string": [
{
"name": "entry_desc",
"value": "description"
},
{
"name": "SelectorServiceExtAbility_desc",
"value": "SelectorDialog"
},
{
"name": "SelectorServiceExtAbility_label",
"value": "SelectorDialog"
},
{
"name": "TipsServiceExtAbility_desc",
"value": "TipsDialog"
},
{
"name": "TipsServiceExtAbility_label",
"value": "TipsDialog"
},
{
"name": "NotificationServiceExtAbility_desc",
"value": "NotificationDialog"
},
{
"name": "NotificationServiceExtAbility_label",
"value": "NotificationDialog"
},
{
"name": "message_title_selector",
"value": "Open with the following options"
},
{
"name": "message_cancel_selector",
"value": "Cancel"
},
{
"name": "message_title_tips",
"value": "Cannot open this file"
},
{
"name": "message_close_tips",
"value": "Got it"
},
{
"name": "if_allow_to_publish_notification",
"value": "Do you allow the app to publish notification?"
},
{
"name": "allow",
"value": "allow"
},
{
"name": "ban",
"value": "ban"
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

@@ -0,0 +1,8 @@
{
"src": [
"pages/selectorPhoneDialog",
"pages/selectorPcDialog",
"pages/tipsDialog",
"pages/notificationDialog"
]
}
@@ -0,0 +1,60 @@
{
"string": [
{
"name": "entry_desc",
"value": "description"
},
{
"name": "SelectorServiceExtAbility_desc",
"value": "SelectorDialog"
},
{
"name": "SelectorServiceExtAbility_label",
"value": "SelectorDialog"
},
{
"name": "TipsServiceExtAbility_desc",
"value": "TipsDialog"
},
{
"name": "TipsServiceExtAbility_label",
"value": "TipsDialog"
},
{
"name": "NotificationServiceExtAbility_desc",
"value": "NotificationDialog"
},
{
"name": "NotificationServiceExtAbility_label",
"value": "NotificationDialog"
},
{
"name": "message_title_selector",
"value": "使用以下方式打开"
},
{
"name": "message_cancel_selector",
"value": "取消"
},
{
"name": "message_title_tips",
"value": "无法打开此文件"
},
{
"name": "message_close_tips",
"value": "知道了"
},
{
"name": "allow",
"value": "允许"
},
{
"name": "ban",
"value": "取消"
},
{
"name": "if_allow_to_publish_notification",
"value": "是否允许发送通知?"
}
]
}
@@ -1,80 +1,80 @@
/*
* Copyright (c) 2022 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 "cleanallmissions_fuzzer.h"
#include <cstddef>
#include <cstdint>
#include "ability_manager_client.h"
#include "securec.h"
using namespace OHOS::AAFwk;
using namespace OHOS::AppExecFwk;
namespace OHOS {
namespace {
constexpr size_t FOO_MAX_LEN = 1024;
constexpr size_t U32_AT_SIZE = 4;
}
bool DoSomethingInterestingWithMyAPI(const char* data, size_t size)
{
auto abilitymgr = AbilityManagerClient::GetInstance();
if (!abilitymgr) {
return false;
}
if (abilitymgr->CleanAllMissions() != 0) {
return false;
}
return true;
}
}
/* Fuzzer entry point */
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
/* Run your code on data */
if (data == nullptr) {
std::cout << "invalid data" << std::endl;
return 0;
}
/* Validate the length of size */
if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) {
return 0;
}
char* ch = (char *)malloc(size + 1);
if (ch == nullptr) {
std::cout << "malloc failed." << std::endl;
return 0;
}
(void)memset_s(ch, size + 1, 0x00, size + 1);
if (memcpy_s(ch, size, data, size) != EOK) {
std::cout << "copy failed." << std::endl;
free(ch);
ch = nullptr;
return 0;
}
OHOS::DoSomethingInterestingWithMyAPI(ch, size);
free(ch);
ch = nullptr;
return 0;
}
/*
* Copyright (c) 2022 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 "cleanallmissions_fuzzer.h"
#include <cstddef>
#include <cstdint>
#include "ability_manager_client.h"
#include "securec.h"
using namespace OHOS::AAFwk;
using namespace OHOS::AppExecFwk;
namespace OHOS {
namespace {
constexpr size_t FOO_MAX_LEN = 1024;
constexpr size_t U32_AT_SIZE = 4;
}
bool DoSomethingInterestingWithMyAPI(const char* data, size_t size)
{
auto abilitymgr = AbilityManagerClient::GetInstance();
if (!abilitymgr) {
return false;
}
if (abilitymgr->CleanAllMissions() != 0) {
return false;
}
return true;
}
}
/* Fuzzer entry point */
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
/* Run your code on data */
if (data == nullptr) {
std::cout << "invalid data" << std::endl;
return 0;
}
/* Validate the length of size */
if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) {
return 0;
}
char* ch = (char *)malloc(size + 1);
if (ch == nullptr) {
std::cout << "malloc failed." << std::endl;
return 0;
}
(void)memset_s(ch, size + 1, 0x00, size + 1);
if (memcpy_s(ch, size, data, size) != EOK) {
std::cout << "copy failed." << std::endl;
free(ch);
ch = nullptr;
return 0;
}
OHOS::DoSomethingInterestingWithMyAPI(ch, size);
free(ch);
ch = nullptr;
return 0;
}
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2022 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 FUZZTEST_OHOS_ABILITY_RUNTIME_CLEANALLMISSIONS_FUZZER_H
#define FUZZTEST_OHOS_ABILITY_RUNTIME_CLEANALLMISSIONS_FUZZER_H
#define FUZZ_PROJECT_NAME "cleanallmissions_fuzzer"
#endif
/*
* Copyright (c) 2022 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 FUZZTEST_OHOS_ABILITY_RUNTIME_CLEANALLMISSIONS_FUZZER_H
#define FUZZTEST_OHOS_ABILITY_RUNTIME_CLEANALLMISSIONS_FUZZER_H
#define FUZZ_PROJECT_NAME "cleanallmissions_fuzzer"
#endif
@@ -1,16 +1,16 @@
/*
* Copyright (c) 2022 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.
*/
/*
* Copyright (c) 2022 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.
*/
FUZZ
@@ -1,25 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) 2022 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.
-->
<fuzz_config>
<fuzztest>
<!-- maximum length of a test input -->
<max_len>1000</max_len>
<!-- maximum total time in seconds to run the fuzzer -->
<max_total_time>300</max_total_time>
<!-- memory usage limit in Mb -->
<rss_limit_mb>4096</rss_limit_mb>
</fuzztest>
</fuzz_config>
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) 2022 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.
-->
<fuzz_config>
<fuzztest>
<!-- maximum length of a test input -->
<max_len>1000</max_len>
<!-- maximum total time in seconds to run the fuzzer -->
<max_total_time>300</max_total_time>
<!-- memory usage limit in Mb -->
<rss_limit_mb>4096</rss_limit_mb>
</fuzztest>
</fuzz_config>
@@ -1,99 +1,99 @@
/*
* Copyright (c) 2022 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 "continuemission_fuzzer.h"
#include <cstddef>
#include <cstdint>
#include "ability_manager_client.h"
#include "securec.h"
using namespace OHOS::AAFwk;
using namespace OHOS::AppExecFwk;
namespace OHOS {
namespace {
constexpr size_t FOO_MAX_LEN = 1024;
constexpr size_t U32_AT_SIZE = 4;
}
uint32_t GetU32Data(const char* ptr)
{
// convert fuzz input data to an integer
return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3];
}
bool DoSomethingInterestingWithMyAPI(const char* data, size_t size)
{
auto abilitymgr = AbilityManagerClient::GetInstance();
if (!abilitymgr) {
return false;
}
std::string srcDeviceId(data, size);
std::string dstDeviceId(data, size);
int32_t missionId = static_cast<int32_t>(GetU32Data(data));
sptr<IRemoteObject> callback;
// get want agentInfo
Parcel paramsParcel;
WantParams *wantParams = nullptr;
if (paramsParcel.WriteBuffer(data, size)) {
WantParams *wantParams = WantParams::Unmarshalling(paramsParcel);
if (wantParams) {
abilitymgr->ContinueMission(srcDeviceId, dstDeviceId, missionId, callback, *wantParams);
}
}
if (wantParams) {
delete wantParams;
wantParams = nullptr;
}
return true;
}
}
/* Fuzzer entry point */
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
/* Run your code on data */
if (data == nullptr) {
std::cout << "invalid data" << std::endl;
return 0;
}
/* Validate the length of size */
if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) {
return 0;
}
char* ch = (char *)malloc(size + 1);
if (ch == nullptr) {
std::cout << "malloc failed." << std::endl;
return 0;
}
(void)memset_s(ch, size + 1, 0x00, size + 1);
if (memcpy_s(ch, size, data, size) != EOK) {
std::cout << "copy failed." << std::endl;
free(ch);
ch = nullptr;
return 0;
}
OHOS::DoSomethingInterestingWithMyAPI(ch, size);
free(ch);
ch = nullptr;
return 0;
}
/*
* Copyright (c) 2022 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 "continuemission_fuzzer.h"
#include <cstddef>
#include <cstdint>
#include "ability_manager_client.h"
#include "securec.h"
using namespace OHOS::AAFwk;
using namespace OHOS::AppExecFwk;
namespace OHOS {
namespace {
constexpr size_t FOO_MAX_LEN = 1024;
constexpr size_t U32_AT_SIZE = 4;
}
uint32_t GetU32Data(const char* ptr)
{
// convert fuzz input data to an integer
return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3];
}
bool DoSomethingInterestingWithMyAPI(const char* data, size_t size)
{
auto abilitymgr = AbilityManagerClient::GetInstance();
if (!abilitymgr) {
return false;
}
std::string srcDeviceId(data, size);
std::string dstDeviceId(data, size);
int32_t missionId = static_cast<int32_t>(GetU32Data(data));
sptr<IRemoteObject> callback;
// get want agentInfo
Parcel paramsParcel;
WantParams *wantParams = nullptr;
if (paramsParcel.WriteBuffer(data, size)) {
WantParams *wantParams = WantParams::Unmarshalling(paramsParcel);
if (wantParams) {
abilitymgr->ContinueMission(srcDeviceId, dstDeviceId, missionId, callback, *wantParams);
}
}
if (wantParams) {
delete wantParams;
wantParams = nullptr;
}
return true;
}
}
/* Fuzzer entry point */
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
/* Run your code on data */
if (data == nullptr) {
std::cout << "invalid data" << std::endl;
return 0;
}
/* Validate the length of size */
if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) {
return 0;
}
char* ch = (char *)malloc(size + 1);
if (ch == nullptr) {
std::cout << "malloc failed." << std::endl;
return 0;
}
(void)memset_s(ch, size + 1, 0x00, size + 1);
if (memcpy_s(ch, size, data, size) != EOK) {
std::cout << "copy failed." << std::endl;
free(ch);
ch = nullptr;
return 0;
}
OHOS::DoSomethingInterestingWithMyAPI(ch, size);
free(ch);
ch = nullptr;
return 0;
}
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2022 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 FUZZTEST_OHOS_ABILITY_RUNTIME_CONTINUEMISSION_FUZZER_H
#define FUZZTEST_OHOS_ABILITY_RUNTIME_CONTINUEMISSION_FUZZER_H
#define FUZZ_PROJECT_NAME "continuemission_fuzzer"
#endif
/*
* Copyright (c) 2022 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 FUZZTEST_OHOS_ABILITY_RUNTIME_CONTINUEMISSION_FUZZER_H
#define FUZZTEST_OHOS_ABILITY_RUNTIME_CONTINUEMISSION_FUZZER_H
#define FUZZ_PROJECT_NAME "continuemission_fuzzer"
#endif
@@ -1,16 +1,16 @@
/*
* Copyright (c) 2022 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.
*/
/*
* Copyright (c) 2022 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.
*/
FUZZ
@@ -1,25 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) 2022 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.
-->
<fuzz_config>
<fuzztest>
<!-- maximum length of a test input -->
<max_len>1000</max_len>
<!-- maximum total time in seconds to run the fuzzer -->
<max_total_time>300</max_total_time>
<!-- memory usage limit in Mb -->
<rss_limit_mb>4096</rss_limit_mb>
</fuzztest>
</fuzz_config>
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) 2022 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.
-->
<fuzz_config>
<fuzztest>
<!-- maximum length of a test input -->
<max_len>1000</max_len>
<!-- maximum total time in seconds to run the fuzzer -->
<max_total_time>300</max_total_time>
<!-- memory usage limit in Mb -->
<rss_limit_mb>4096</rss_limit_mb>
</fuzztest>
</fuzz_config>
@@ -53,7 +53,6 @@ bool DoSomethingInterestingWithMyAPI(const char* data, size_t size)
missionInfoMgr->GetMissionInfoById(int32Param, missionInfo);
missionInfoMgr->GetInnerMissionInfoById(int32Param, innerMissionInfo);
missionInfoMgr->FindReusedMissionInfo(stringParam, stringParam, innerMissionInfo);
missionInfoMgr->UpdateMissionTimeStamp(int32Param, stringParam);
return true;
}
@@ -119,7 +119,6 @@ bool DoSomethingInterestingWithMyAPI(const char* data, size_t size)
missionListManager->GetTargetMissionList(intParam, mission);
missionListManager->GetMissionIdByAbilityToken(token);
missionListManager->GetAbilityTokenByMissionId(int32Param);
missionListManager->UpdateMissionTimeStamp(abilityRecord);
missionListManager->PostStartWaitingAbility();
missionListManager->HandleAbilityDied(abilityRecord);
missionListManager->HandleLauncherDied(abilityRecord);
@@ -1,16 +1,16 @@
/*
* Copyright (c) 2022 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.
*/
/*
* Copyright (c) 2022 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.
*/
FUZZ
@@ -1,25 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) 2022 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.
-->
<fuzz_config>
<fuzztest>
<!-- maximum length of a test input -->
<max_len>1000</max_len>
<!-- maximum total time in seconds to run the fuzzer -->
<max_total_time>300</max_total_time>
<!-- memory usage limit in Mb -->
<rss_limit_mb>4096</rss_limit_mb>
</fuzztest>
</fuzz_config>
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) 2022 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.
-->
<fuzz_config>
<fuzztest>
<!-- maximum length of a test input -->
<max_len>1000</max_len>
<!-- maximum total time in seconds to run the fuzzer -->
<max_total_time>300</max_total_time>
<!-- memory usage limit in Mb -->
<rss_limit_mb>4096</rss_limit_mb>
</fuzztest>
</fuzz_config>
@@ -1,111 +1,111 @@
/*
* Copyright (c) 2022 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 "registermissionlistener_fuzzer.h"
#include <cstddef>
#include <cstdint>
#include "ability_manager_client.h"
#include "mission_listener_interface.h"
#include "remote_mission_listener_interface.h"
#include "securec.h"
using namespace OHOS::AAFwk;
using namespace OHOS::AppExecFwk;
namespace OHOS {
namespace {
constexpr size_t FOO_MAX_LEN = 1024;
constexpr size_t U32_AT_SIZE = 4;
}
class MissionListenerFuzz : public IMissionListener {
public:
explicit MissionListenerFuzz() {};
virtual ~MissionListenerFuzz() {};
void OnMissionCreated(int32_t missionId) override {};
void OnMissionDestroyed(int32_t missionId) override {};
void OnMissionSnapshotChanged(int32_t missionId) override {};
void OnMissionMovedToFront(int32_t missionId) override {};
void OnMissionClosed(int32_t missionId) override {};
void OnMissionLabelUpdated(int32_t missionId) override {};
#ifdef SUPPORT_GRAPHICS
void OnMissionIconUpdated(int32_t missionId, const std::shared_ptr<Media::PixelMap> &icon) override;
#endif
};
class RemoteMissionListenerFuzz : public IRemoteMissionListener {
public:
explicit RemoteMissionListenerFuzz() {};
virtual ~RemoteMissionListenerFuzz() {};
void NotifyMissionsChanged(const std::string& deviceId) override {};
void NotifySnapshot(const std::string& deviceId, int32_t missionId) override {};
void NotifyNetDisconnect(const std::string& deviceId, int32_t state) override {};
};
bool DoSomethingInterestingWithMyAPI(const char* data, size_t size)
{
auto abilitymgr = AbilityManagerClient::GetInstance();
if (!abilitymgr) {
return false;
}
sptr<MissionListenerFuzz> listener;
if (listener) {
abilitymgr->RegisterMissionListener(listener);
}
std::string deviceId(data, size);
sptr<RemoteMissionListenerFuzz> remoteListener;
if (!deviceId.empty() && remoteListener) {
abilitymgr->RegisterMissionListener(deviceId, remoteListener);
}
return true;
}
}
/* Fuzzer entry point */
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
/* Run your code on data */
if (data == nullptr) {
std::cout << "invalid data" << std::endl;
return 0;
}
/* Validate the length of size */
if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) {
return 0;
}
char* ch = (char *)malloc(size + 1);
if (ch == nullptr) {
std::cout << "malloc failed." << std::endl;
return 0;
}
(void)memset_s(ch, size + 1, 0x00, size + 1);
if (memcpy_s(ch, size, data, size) != EOK) {
std::cout << "copy failed." << std::endl;
free(ch);
ch = nullptr;
return 0;
}
OHOS::DoSomethingInterestingWithMyAPI(ch, size);
free(ch);
ch = nullptr;
return 0;
}
/*
* Copyright (c) 2022 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 "registermissionlistener_fuzzer.h"
#include <cstddef>
#include <cstdint>
#include "ability_manager_client.h"
#include "mission_listener_interface.h"
#include "remote_mission_listener_interface.h"
#include "securec.h"
using namespace OHOS::AAFwk;
using namespace OHOS::AppExecFwk;
namespace OHOS {
namespace {
constexpr size_t FOO_MAX_LEN = 1024;
constexpr size_t U32_AT_SIZE = 4;
}
class MissionListenerFuzz : public IMissionListener {
public:
explicit MissionListenerFuzz() {};
virtual ~MissionListenerFuzz() {};
void OnMissionCreated(int32_t missionId) override {};
void OnMissionDestroyed(int32_t missionId) override {};
void OnMissionSnapshotChanged(int32_t missionId) override {};
void OnMissionMovedToFront(int32_t missionId) override {};
void OnMissionClosed(int32_t missionId) override {};
void OnMissionLabelUpdated(int32_t missionId) override {};
#ifdef SUPPORT_GRAPHICS
void OnMissionIconUpdated(int32_t missionId, const std::shared_ptr<Media::PixelMap> &icon) override;
#endif
};
class RemoteMissionListenerFuzz : public IRemoteMissionListener {
public:
explicit RemoteMissionListenerFuzz() {};
virtual ~RemoteMissionListenerFuzz() {};
void NotifyMissionsChanged(const std::string& deviceId) override {};
void NotifySnapshot(const std::string& deviceId, int32_t missionId) override {};
void NotifyNetDisconnect(const std::string& deviceId, int32_t state) override {};
};
bool DoSomethingInterestingWithMyAPI(const char* data, size_t size)
{
auto abilitymgr = AbilityManagerClient::GetInstance();
if (!abilitymgr) {
return false;
}
sptr<MissionListenerFuzz> listener;
if (listener) {
abilitymgr->RegisterMissionListener(listener);
}
std::string deviceId(data, size);
sptr<RemoteMissionListenerFuzz> remoteListener;
if (!deviceId.empty() && remoteListener) {
abilitymgr->RegisterMissionListener(deviceId, remoteListener);
}
return true;
}
}
/* Fuzzer entry point */
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
/* Run your code on data */
if (data == nullptr) {
std::cout << "invalid data" << std::endl;
return 0;
}
/* Validate the length of size */
if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) {
return 0;
}
char* ch = (char *)malloc(size + 1);
if (ch == nullptr) {
std::cout << "malloc failed." << std::endl;
return 0;
}
(void)memset_s(ch, size + 1, 0x00, size + 1);
if (memcpy_s(ch, size, data, size) != EOK) {
std::cout << "copy failed." << std::endl;
free(ch);
ch = nullptr;
return 0;
}
OHOS::DoSomethingInterestingWithMyAPI(ch, size);
free(ch);
ch = nullptr;
return 0;
}
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2022 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 FUZZTEST_OHOS_ABILITY_RUNTIME_REGISTERMISSIONLISTENER_FUZZER_H
#define FUZZTEST_OHOS_ABILITY_RUNTIME_REGISTERMISSIONLISTENER_FUZZER_H
#define FUZZ_PROJECT_NAME "registermissionlistener_fuzzer"
#endif
/*
* Copyright (c) 2022 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 FUZZTEST_OHOS_ABILITY_RUNTIME_REGISTERMISSIONLISTENER_FUZZER_H
#define FUZZTEST_OHOS_ABILITY_RUNTIME_REGISTERMISSIONLISTENER_FUZZER_H
#define FUZZ_PROJECT_NAME "registermissionlistener_fuzzer"
#endif
+15 -15
View File
@@ -1,16 +1,16 @@
/*
* Copyright (c) 2022 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.
*/
/*
* Copyright (c) 2022 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.
*/
FUZZ
+25 -25
View File
@@ -1,25 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) 2022 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.
-->
<fuzz_config>
<fuzztest>
<!-- maximum length of a test input -->
<max_len>1000</max_len>
<!-- maximum total time in seconds to run the fuzzer -->
<max_total_time>300</max_total_time>
<!-- memory usage limit in Mb -->
<rss_limit_mb>4096</rss_limit_mb>
</fuzztest>
</fuzz_config>
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) 2022 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.
-->
<fuzz_config>
<fuzztest>
<!-- maximum length of a test input -->
<max_len>1000</max_len>
<!-- maximum total time in seconds to run the fuzzer -->
<max_total_time>300</max_total_time>
<!-- memory usage limit in Mb -->
<rss_limit_mb>4096</rss_limit_mb>
</fuzztest>
</fuzz_config>
@@ -1,92 +1,92 @@
/*
* Copyright (c) 2022 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 "releasecall_fuzzer.h"
#include <cstddef>
#include <cstdint>
#include "ability_manager_client.h"
#include "ability_connect_callback_interface.h"
#include "securec.h"
using namespace OHOS::AAFwk;
using namespace OHOS::AppExecFwk;
namespace OHOS {
namespace {
constexpr size_t FOO_MAX_LEN = 1024;
constexpr size_t U32_AT_SIZE = 4;
}
class AbilityConnectionFuzz : public IAbilityConnection {
public:
explicit AbilityConnectionFuzz() {};
virtual ~AbilityConnectionFuzz() {};
void OnAbilityConnectDone(
const AppExecFwk::ElementName &element, const sptr<IRemoteObject> &remoteObject, int resultCode) override {};
void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override {};
};
bool DoSomethingInterestingWithMyAPI(const char* data, size_t size)
{
auto abilitymgr = AbilityManagerClient::GetInstance();
if (!abilitymgr) {
return false;
}
// get token and connectCallback
sptr<AbilityConnectionFuzz> connect;
ElementName element;
if (connect) {
abilitymgr->ReleaseCall(connect, element);
}
return true;
}
}
/* Fuzzer entry point */
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
/* Run your code on data */
if (data == nullptr) {
std::cout << "invalid data" << std::endl;
return 0;
}
/* Validate the length of size */
if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) {
return 0;
}
char* ch = (char *)malloc(size + 1);
if (ch == nullptr) {
std::cout << "malloc failed." << std::endl;
return 0;
}
(void)memset_s(ch, size + 1, 0x00, size + 1);
if (memcpy_s(ch, size, data, size) != EOK) {
std::cout << "copy failed." << std::endl;
free(ch);
ch = nullptr;
return 0;
}
OHOS::DoSomethingInterestingWithMyAPI(ch, size);
free(ch);
ch = nullptr;
return 0;
}
/*
* Copyright (c) 2022 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 "releasecall_fuzzer.h"
#include <cstddef>
#include <cstdint>
#include "ability_manager_client.h"
#include "ability_connect_callback_interface.h"
#include "securec.h"
using namespace OHOS::AAFwk;
using namespace OHOS::AppExecFwk;
namespace OHOS {
namespace {
constexpr size_t FOO_MAX_LEN = 1024;
constexpr size_t U32_AT_SIZE = 4;
}
class AbilityConnectionFuzz : public IAbilityConnection {
public:
explicit AbilityConnectionFuzz() {};
virtual ~AbilityConnectionFuzz() {};
void OnAbilityConnectDone(
const AppExecFwk::ElementName &element, const sptr<IRemoteObject> &remoteObject, int resultCode) override {};
void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override {};
};
bool DoSomethingInterestingWithMyAPI(const char* data, size_t size)
{
auto abilitymgr = AbilityManagerClient::GetInstance();
if (!abilitymgr) {
return false;
}
// get token and connectCallback
sptr<AbilityConnectionFuzz> connect;
ElementName element;
if (connect) {
abilitymgr->ReleaseCall(connect, element);
}
return true;
}
}
/* Fuzzer entry point */
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
/* Run your code on data */
if (data == nullptr) {
std::cout << "invalid data" << std::endl;
return 0;
}
/* Validate the length of size */
if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) {
return 0;
}
char* ch = (char *)malloc(size + 1);
if (ch == nullptr) {
std::cout << "malloc failed." << std::endl;
return 0;
}
(void)memset_s(ch, size + 1, 0x00, size + 1);
if (memcpy_s(ch, size, data, size) != EOK) {
std::cout << "copy failed." << std::endl;
free(ch);
ch = nullptr;
return 0;
}
OHOS::DoSomethingInterestingWithMyAPI(ch, size);
free(ch);
ch = nullptr;
return 0;
}
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2022 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 FUZZTEST_OHOS_ABILITY_RUNTIME_RELEASECALL_FUZZER_H
#define FUZZTEST_OHOS_ABILITY_RUNTIME_RELEASECALL_FUZZER_H
#define FUZZ_PROJECT_NAME "releasecall_fuzzer"
#endif
/*
* Copyright (c) 2022 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 FUZZTEST_OHOS_ABILITY_RUNTIME_RELEASECALL_FUZZER_H
#define FUZZTEST_OHOS_ABILITY_RUNTIME_RELEASECALL_FUZZER_H
#define FUZZ_PROJECT_NAME "releasecall_fuzzer"
#endif
@@ -9,7 +9,7 @@
# 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.
# limitations under the License.
#####################hydra-fuzz###################
import("//build/config/features.gni")
@@ -1,16 +1,16 @@
/*
* Copyright (c) 2022 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.
*/
/*
* Copyright (c) 2022 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.
*/
FUZZ
@@ -1,25 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) 2022 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.
-->
<fuzz_config>
<fuzztest>
<!-- maximum length of a test input -->
<max_len>1000</max_len>
<!-- maximum total time in seconds to run the fuzzer -->
<max_total_time>300</max_total_time>
<!-- memory usage limit in Mb -->
<rss_limit_mb>4096</rss_limit_mb>
</fuzztest>
</fuzz_config>
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) 2022 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.
-->
<fuzz_config>
<fuzztest>
<!-- maximum length of a test input -->
<max_len>1000</max_len>
<!-- maximum total time in seconds to run the fuzzer -->
<max_total_time>300</max_total_time>
<!-- memory usage limit in Mb -->
<rss_limit_mb>4096</rss_limit_mb>
</fuzztest>
</fuzz_config>
@@ -1,103 +1,103 @@
/*
* Copyright (c) 2022 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 "releasedataability_fuzzer.h"
#include <cstddef>
#include <cstdint>
#include "ability_manager_client.h"
#include "ability_record.h"
using namespace OHOS::AAFwk;
using namespace OHOS::AppExecFwk;
namespace OHOS {
namespace {
constexpr size_t FOO_MAX_LEN = 1024;
constexpr size_t U32_AT_SIZE = 4;
}
sptr<Token> GetFuzzAbilityToken()
{
sptr<Token> token = nullptr;
AbilityRequest abilityRequest;
abilityRequest.appInfo.bundleName = "com.example.fuzzTest";
abilityRequest.abilityInfo.name = "MainAbility";
abilityRequest.abilityInfo.type = AbilityType::DATA;
std::shared_ptr<AbilityRecord> abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest);
if (abilityRecord) {
token = abilityRecord->GetToken();
}
return token;
}
bool DoSomethingInterestingWithMyAPI(const char* data, size_t size)
{
auto abilitymgr = AbilityManagerClient::GetInstance();
sptr<IAbilityScheduler> scheduler;
if (!abilitymgr) {
return false;
}
// get token
sptr<IRemoteObject> token = GetFuzzAbilityToken();
if (!token) {
std::cout << "Get ability token failed." << std::endl;
return false;
}
if (abilitymgr->ReleaseDataAbility(scheduler, token) != 0) {
return false;
}
return true;
}
}
/* Fuzzer entry point */
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
/* Run your code on data */
if (data == nullptr) {
std::cout << "invalid data" << std::endl;
return 0;
}
/* Validate the length of size */
if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) {
return 0;
}
char* ch = (char *)malloc(size + 1);
if (ch == nullptr) {
std::cout << "malloc failed." << std::endl;
return 0;
}
(void)memset_s(ch, size + 1, 0x00, size + 1);
if (memcpy_s(ch, size, data, size) != EOK) {
std::cout << "copy failed." << std::endl;
free(ch);
ch = nullptr;
return 0;
}
OHOS::DoSomethingInterestingWithMyAPI(ch, size);
free(ch);
ch = nullptr;
return 0;
}
/*
* Copyright (c) 2022 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 "releasedataability_fuzzer.h"
#include <cstddef>
#include <cstdint>
#include "ability_manager_client.h"
#include "ability_record.h"
using namespace OHOS::AAFwk;
using namespace OHOS::AppExecFwk;
namespace OHOS {
namespace {
constexpr size_t FOO_MAX_LEN = 1024;
constexpr size_t U32_AT_SIZE = 4;
}
sptr<Token> GetFuzzAbilityToken()
{
sptr<Token> token = nullptr;
AbilityRequest abilityRequest;
abilityRequest.appInfo.bundleName = "com.example.fuzzTest";
abilityRequest.abilityInfo.name = "MainAbility";
abilityRequest.abilityInfo.type = AbilityType::DATA;
std::shared_ptr<AbilityRecord> abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest);
if (abilityRecord) {
token = abilityRecord->GetToken();
}
return token;
}
bool DoSomethingInterestingWithMyAPI(const char* data, size_t size)
{
auto abilitymgr = AbilityManagerClient::GetInstance();
sptr<IAbilityScheduler> scheduler;
if (!abilitymgr) {
return false;
}
// get token
sptr<IRemoteObject> token = GetFuzzAbilityToken();
if (!token) {
std::cout << "Get ability token failed." << std::endl;
return false;
}
if (abilitymgr->ReleaseDataAbility(scheduler, token) != 0) {
return false;
}
return true;
}
}
/* Fuzzer entry point */
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
/* Run your code on data */
if (data == nullptr) {
std::cout << "invalid data" << std::endl;
return 0;
}
/* Validate the length of size */
if (size > OHOS::FOO_MAX_LEN || size < OHOS::U32_AT_SIZE) {
return 0;
}
char* ch = (char *)malloc(size + 1);
if (ch == nullptr) {
std::cout << "malloc failed." << std::endl;
return 0;
}
(void)memset_s(ch, size + 1, 0x00, size + 1);
if (memcpy_s(ch, size, data, size) != EOK) {
std::cout << "copy failed." << std::endl;
free(ch);
ch = nullptr;
return 0;
}
OHOS::DoSomethingInterestingWithMyAPI(ch, size);
free(ch);
ch = nullptr;
return 0;
}
@@ -1,21 +1,21 @@
/*
* Copyright (c) 2022 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 FUZZTEST_OHOS_ABILITY_RUNTIME_RELEASEDATAABILITY_FUZZER_H
#define FUZZTEST_OHOS_ABILITY_RUNTIME_RELEASEDATAABILITY_FUZZER_H
#define FUZZ_PROJECT_NAME "releasedataability_fuzzer"
#endif
/*
* Copyright (c) 2022 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 FUZZTEST_OHOS_ABILITY_RUNTIME_RELEASEDATAABILITY_FUZZER_H
#define FUZZTEST_OHOS_ABILITY_RUNTIME_RELEASEDATAABILITY_FUZZER_H
#define FUZZ_PROJECT_NAME "releasedataability_fuzzer"
#endif
@@ -70,6 +70,13 @@ public:
bool GetBundleInfo(const std::string &bundleName,
const BundleFlag flag, BundleInfo &bundleInfo, int32_t userId) override
{
if (bundleName == "test_contextImpl") {
bundleInfo.name = "test_contextImpl";
bundleInfo.applicationInfo.name = "test_contextImpl";
HapModuleInfo moduleInfo1;
moduleInfo1.moduleName = "test_moduleName";
bundleInfo.hapModuleInfos.push_back(moduleInfo1);
}
return true;
}
std::string GetAppType(const std::string &bundleName) override;
+1
View File
@@ -199,6 +199,7 @@ ohos_moduletest("data_ability_operation_moduletest") {
"ability_base:configuration",
"ability_base:want",
"ability_base:zuri",
"bundle_framework:appexecfwk_base",
"bundle_framework:appexecfwk_core",
"c_utils:utils",
"hiviewdfx_hilog_native:libhilog",
+6
View File
@@ -341,6 +341,9 @@ group("unittest") {
"frameworks_kits_appkit_native_test:unittest",
"lifecycle_deal_test:unittest",
"lifecycle_test:unittest",
"mission_data_storage_test:unittest",
"mission_info_mgr_test:unittest",
"mission_listener_stub_test:unittest",
"mission_listener_test:unittest",
"os_account_manager_wrapper_test:unittest",
"pending_want_key_test:unittest",
@@ -350,11 +353,13 @@ group("unittest") {
"pending_want_test:unittest",
"permission_verification_test:unittest",
"quick_fix:unittest",
"remote_mission_listener_stub_test:unittest",
"running_infos_test:unittest",
"runtime_extractor_test:unittest",
"runtime_test:unittest",
"sender_info_test:unittest",
"system_ability_token_callback_stub_test:unittest",
"task_data_persistence_mgr_test:unittest",
"trigger_Info_test:unittest",
"user_controller_test:unittest",
"want_agent_helper_test:unittest",
@@ -376,6 +381,7 @@ group("unittest") {
"mission_list_manager_test:unittest",
"mission_list_manager_ut_test:unittest",
"mission_list_test:unittest",
"mission_test:unittest",
"specified_mission_list_test:unittest",
"start_option_display_id_test:unittest",
]
@@ -118,5 +118,37 @@ HWTEST_F(AbilityMgrServiceDialogTest, AbilityMgrServiceDialog_0300, TestSize.Lev
EXPECT_EQ(want.GetElement().GetAbilityName(), "SelectorDialog");
HILOG_INFO("AbilityMgrServiceDialog_0300 end");
}
/*
* @tc.number : AbilityMgrServiceDialog_0400
* @tc.name : AbilityMgrServiceDialog
* @tc.desc : 1.Test GetSelectorParams
*/
HWTEST_F(AbilityMgrServiceDialogTest, AbilityMgrServiceDialog_0400, TestSize.Level1)
{
HILOG_INFO("AbilityMgrServiceDialog_0400 start");
std::vector<DialogAppInfo> dialogAppInfos;
auto params = systemDialogScheduler_->GetSelectorParams(dialogAppInfos);
EXPECT_EQ(params.size(), 0);
HILOG_INFO("AbilityMgrServiceDialog_0400 end");
}
/*
* @tc.number : AbilityMgrServiceDialog_0500
* @tc.name : AbilityMgrServiceDialog
* @tc.desc : 1.Test GetSelectorParams
*/
HWTEST_F(AbilityMgrServiceDialogTest, AbilityMgrServiceDialog_0500, TestSize.Level1)
{
HILOG_INFO("AbilityMgrServiceDialog_0500 start");
DialogAppInfo dialogAppInfo = {
0, 0, "com.example.test", "MainAbility", "entry"
};
std::vector<DialogAppInfo> dialogAppInfos = {dialogAppInfo};
auto params = systemDialogScheduler_->GetSelectorParams(dialogAppInfos);
nlohmann::json jsonObj = nlohmann::json::parse(params);
EXPECT_EQ(jsonObj["hapList"].size(), 1);
HILOG_INFO("AbilityMgrServiceDialog_0500 end");
}
} // namespace AAFwk
} // namespace OHOS
File diff suppressed because it is too large Load Diff
@@ -86,6 +86,7 @@ ohos_unittest("ability_test") {
"${ability_runtime_native_path}/appkit:app_context",
"${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"${global_path}/resource_management/frameworks/resmgr:global_resmgr",
"${multimodalinput_path}/frameworks/proxy:libmmi-common",
"//third_party/googletest:gmock_main",
"//third_party/googletest:gtest_main",
]
@@ -34,6 +34,7 @@
#include "data_ability_predicates.h"
#include "data_ability_result.h"
#include "hilog_wrapper.h"
#include "key_event.h"
#include "mock_page_ability.h"
#include "ohos_application.h"
#include "runtime.h"
@@ -181,6 +182,50 @@ HWTEST_F(AbilityBaseTest, AaFwk_Ability_Dump_0100, Function | MediumTest | Level
GTEST_LOG_(INFO) << "AaFwk_Ability_Dump_0100 end";
}
/**
* @tc.name: AaFwk_Ability_Dump_0200
* @tc.desc: Ability Dump basic test.
* @tc.type: FUNC
* @tc.require: issueI60B7N
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_Dump_0200, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
// ability info, lifecycle and lifecycle executor is nullptr
std::string extra = "";
ability->Dump(extra);
auto abilityInfo = std::make_shared<AbilityInfo>();
EXPECT_NE(abilityInfo, nullptr);
abilityInfo->package = "test_Dump";
abilityInfo->name = "test_Dump";
abilityInfo->label = "label";
abilityInfo->description = "test dump";
abilityInfo->iconPath = "/index/icon";
abilityInfo->visible = true;
abilityInfo->kind = "kind";
abilityInfo->type = AbilityType::SERVICE;
abilityInfo->orientation = DisplayOrientation::LANDSCAPE;
abilityInfo->launchMode = LaunchMode::SINGLETON;
abilityInfo->permissions.push_back("ohos.Permission.TestPermission1");
abilityInfo->permissions.push_back("ohos.Permission.TestPermission2");
abilityInfo->bundleName = "bundleName";
abilityInfo->applicationName = "applicationName";
auto application = std::make_shared<OHOSApplication>();
EXPECT_NE(application, nullptr);
auto eventRunner = EventRunner::Create(abilityInfo->name);
auto handler = std::make_shared<AbilityHandler>(eventRunner);
sptr<IRemoteObject> token = nullptr;
ability->Init(abilityInfo, application, handler, token);
ability->Dump(extra);
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.number: AaFwk_Ability_OnNewWant_0100
* @tc.name: OnNewWant
@@ -478,6 +523,68 @@ HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnStart_0200, Function | MediumTest | Le
GTEST_LOG_(INFO) << "AaFwk_Ability_OnStart_0200 end";
}
/**
* @tc.name: AaFwk_Ability_OnStart_0300
* @tc.desc: Ability OnStart test when configuration is not nullptr.
* @tc.type: FUNC
* @tc.require: issueI60B7N
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnStart_0300, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
auto abilityInfo = std::make_shared<AbilityInfo>();
EXPECT_NE(abilityInfo, nullptr);
abilityInfo->name = "test_OnStart";
abilityInfo->type = AbilityType::PAGE;
abilityInfo->isStageBasedModel = true;
auto application = std::make_shared<OHOSApplication>();
EXPECT_NE(application, nullptr);
Configuration config;
application->SetConfiguration(config);
auto eventRunner = EventRunner::Create(abilityInfo->name);
auto handler = std::make_shared<AbilityHandler>(eventRunner);
sptr<IRemoteObject> token = nullptr;
ability->Init(abilityInfo, application, handler, token);
Want want;
ability->OnStart(want);
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: AaFwk_Ability_OnStart_0400
* @tc.desc: Ability OnStart test when ability lifecycle executor or lifecycle is nullptr.
* @tc.type: FUNC
* @tc.require: issueI60B7N
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnStart_0400, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
auto abilityInfo = std::make_shared<AbilityInfo>();
EXPECT_NE(abilityInfo, nullptr);
abilityInfo->name = "test_OnStart";
abilityInfo->type = AbilityType::PAGE;
ability->abilityInfo_ = abilityInfo;
Want want;
// branch when lifecycle executor is nullptr
ability->OnStart(want);
// branch when lifecycle is nullptr
auto lifecycleExecutor = std::make_shared<AbilityLifecycleExecutor>();
ability->abilityLifecycleExecutor_ = lifecycleExecutor;
ability->OnStart(want);
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.number: AaFwk_Ability_OnStop_0100
* @tc.name: OnStop
@@ -527,6 +634,66 @@ HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnStop_0200, Function | MediumTest | Lev
GTEST_LOG_(INFO) << "AaFwk_Ability_OnStop_0200 end";
}
/**
* @tc.name: AaFwk_Ability_OnStop_0300
* @tc.desc: Ability OnStop test when ability recovery, window is not nullptr.
* @tc.type: FUNC
* @tc.require: issueI60B7N
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnStop_0300, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
// ability recovery is not nullptr
auto abilityRecovery = std::make_shared<AbilityRecovery>();
EXPECT_NE(abilityRecovery, nullptr);
ability->EnableAbilityRecovery(abilityRecovery);
ability->OnStop();
// window is not nullptr
int32_t displayId = 0;
sptr<Rosen::WindowOption> option = new Rosen::WindowOption();
ability->InitWindow(displayId, option);
ability->OnStop();
// lifecycle is nullptr and lifecycle executor is not nullptr
auto lifecycleExecutor = std::make_shared<AbilityLifecycleExecutor>();
ability->abilityLifecycleExecutor_ = lifecycleExecutor;
ability->OnStop();
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: DestroyInstance_0100
* @tc.desc: Ability DestroyInstance test.
* @tc.type: FUNC
* @tc.require: issueI60B7N
*/
HWTEST_F(AbilityBaseTest, DestroyInstance_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
auto abilityInfo = std::make_shared<AbilityInfo>();
EXPECT_NE(abilityInfo, nullptr);
abilityInfo->name = "test_DestroyInstance";
abilityInfo->type = AbilityType::PAGE;
abilityInfo->isStageBasedModel = false;
auto application = std::make_shared<OHOSApplication>();
EXPECT_NE(application, nullptr);
auto eventRunner = EventRunner::Create(abilityInfo->name);
auto handler = std::make_shared<AbilityHandler>(eventRunner);
sptr<IRemoteObject> token = nullptr;
ability->Init(abilityInfo, application, handler, token);
ability->DestroyInstance();
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.number: AaFwk_Ability_OnActive_0100
* @tc.name: OnActive
@@ -576,6 +743,25 @@ HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnActive_0200, Function | MediumTest | L
GTEST_LOG_(INFO) << "AaFwk_Ability_OnActive_0200 end";
}
/**
* @tc.name: AaFwk_Ability_OnActive_0300
* @tc.desc: Ability OnActive test when lifecycle is nullptr.
* @tc.type: FUNC
* @tc.require: issueI60B7N
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnActive_0300, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
// lifecycle is nullptr and lifecycle executor is not nullptr
auto lifecycleExecutor = std::make_shared<AbilityLifecycleExecutor>();
ability->abilityLifecycleExecutor_ = lifecycleExecutor;
ability->OnActive();
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.number: AaFwk_Ability_OnInactive_0100
* @tc.name: OnInactive
@@ -625,6 +811,25 @@ HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnInactive_0200, Function | MediumTest |
GTEST_LOG_(INFO) << "AaFwk_Ability_OnInactive_0200 end";
}
/**
* @tc.name: AaFwk_Ability_OnInactive_0300
* @tc.desc: Ability OnActive test when lifecycle is nullptr.
* @tc.type: FUNC
* @tc.require: issueI60B7N
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnInactive_0300, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
// lifecycle is nullptr and lifecycle executor is not nullptr
auto lifecycleExecutor = std::make_shared<AbilityLifecycleExecutor>();
ability->abilityLifecycleExecutor_ = lifecycleExecutor;
ability->OnInactive();
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.number: AaFwk_Ability_OnForeground_0100
* @tc.name: OnForeground
@@ -790,6 +995,43 @@ HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnBackground_0300, Function | MediumTest
GTEST_LOG_(INFO) << "AaFwk_Ability_OBackground_0300 end";
}
/**
* @tc.name: AaFwk_Ability_OnBackground_0400
* @tc.desc: Ability OnBackground basic test.
* @tc.type: FUNC
* @tc.require: issueI60B7N
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnBackground_0400, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
// ability info is nullptr
ability->OnBackground();
// stage mode, scene is not nullptr
auto abilityInfo = std::make_shared<AbilityInfo>();
EXPECT_NE(abilityInfo, nullptr);
abilityInfo->name = "test_OnStart";
abilityInfo->type = AbilityType::PAGE;
abilityInfo->isStageBasedModel = true;
auto application = std::make_shared<OHOSApplication>();
EXPECT_NE(application, nullptr);
auto eventRunner = EventRunner::Create(abilityInfo->name);
auto handler = std::make_shared<AbilityHandler>(eventRunner);
sptr<IRemoteObject> token = nullptr;
ability->Init(abilityInfo, application, handler, token);
int32_t displayId = 0;
sptr<Rosen::WindowOption> option = new Rosen::WindowOption();
ability->InitWindow(displayId, option);
ability->OnBackground();
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.number: AaFwk_Ability_OnConnect_0100
* @tc.name: OnConnect
@@ -817,6 +1059,29 @@ HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnConnect_0100, Function | MediumTest |
GTEST_LOG_(INFO) << "AaFwk_Ability_OnConnect_0100 end";
}
/**
* @tc.name: AaFwk_Ability_OnConnect_0200
* @tc.desc: Ability OnConnect test when lifecycle is nullptr.
* @tc.type: FUNC
* @tc.require: issueI60B7N
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnConnect_0200, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
// lifecycle executor is nullptr
Want want;
ability->OnConnect(want);
// lifecycle is nullptr and lifecycle executor is not nullptr
auto lifecycleExecutor = std::make_shared<AbilityLifecycleExecutor>();
ability->abilityLifecycleExecutor_ = lifecycleExecutor;
ability->OnConnect(want);
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.number: AaFwk_Ability_OnCommond_0100
* @tc.name: OnCommand
@@ -844,6 +1109,32 @@ HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnCommond_0100, Function | MediumTest |
GTEST_LOG_(INFO) << "AaFwk_Ability_OnCommond_0100 end";
}
/**
* @tc.name: AaFwk_Ability_OnCommand_0200
* @tc.desc: Ability OnCommand test when lifecycle is nullptr.
* @tc.type: FUNC
* @tc.require: issueI60B7N
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnCommand_0200, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
Want want;
bool restart = false;
int startId = 0;
// lifecycle executor is nullptr
ability->OnCommand(want, restart, startId);
// lifecycle is nullptr and lifecycle executor is not nullptr
auto lifecycleExecutor = std::make_shared<AbilityLifecycleExecutor>();
ability->abilityLifecycleExecutor_ = lifecycleExecutor;
ability->OnCommand(want, restart, startId);
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.number: AaFwk_Ability_OnDisconnect_0100
* @tc.name: OnDisconnect
@@ -962,6 +1253,50 @@ HWTEST_F(AbilityBaseTest, AaFwk_Ability_ExecuteBatch_0100, Function | MediumTest
GTEST_LOG_(INFO) << "AaFwk_Ability_ExecuteBatch_0100 end";
}
/**
* @tc.name: AaFwk_Ability_ExecuteBatch_0200
* @tc.desc: Ability ExecuteBatch basic test.
* @tc.type: FUNC
* @tc.require: issueI60B7N
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_ExecuteBatch_0200, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
std::shared_ptr<Uri> uri = std::make_shared<Uri>("dataability:///com.ohos.test");
std::shared_ptr<DataAbilityOperation> operation = DataAbilityOperation::NewUpdateBuilder(uri)->Build();;
std::vector<std::shared_ptr<DataAbilityOperation>> executeBatchOperations;
executeBatchOperations.push_back(operation);
// ability info is nullptr
auto result = ability->ExecuteBatch(executeBatchOperations);
auto abilityInfo = std::make_shared<AbilityInfo>();
EXPECT_NE(abilityInfo, nullptr);
abilityInfo->name = "test_ExecuteOperation";
abilityInfo->type = AbilityType::PAGE; // not DATA
auto application = std::make_shared<OHOSApplication>();
EXPECT_NE(application, nullptr);
auto eventRunner = EventRunner::Create(abilityInfo->name);
auto handler = std::make_shared<AbilityHandler>(eventRunner);
sptr<IRemoteObject> token = nullptr;
ability->Init(abilityInfo, application, handler, token);
// type is not DATA
result = ability->ExecuteBatch(executeBatchOperations);
ability->ExecuteOperation(operation, result, -1);
abilityInfo->type = AbilityType::DATA;
ability->Init(abilityInfo, application, handler, token);
ability->ExecuteOperation(operation, result, 0);
std::shared_ptr<DataAbilityOperation> nullOperation = nullptr;
ability->ExecuteOperation(nullOperation, result, 0);
HILOG_INFO("%{public}s end.", __func__);
}
class AbilityTest final : public Ability {
public:
AbilityTest() {}
@@ -995,6 +1330,23 @@ HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnBackPressed_0100, Function | MediumTes
GTEST_LOG_(INFO) << "AaFwk_Ability_OnBackPressed_0100 end";
}
/**
* @tc.name: AaFwk_Ability_OnBackPressed_0200
* @tc.desc: Ability OnBackPressed test when ability info is nullptr.
* @tc.type: FUNC
* @tc.require: issueI60B7N
*/
HWTEST_F(AbilityBaseTest, AaFwk_Ability_OnBackPressed_0200, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
ability->OnBackPressed();
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: AbilityCreate_0100
* @tc.desc: Ability create test.
@@ -1059,6 +1411,7 @@ HWTEST_F(AbilityBaseTest, AbilityContinuation_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
// branch when abilityContext_ is nullptr
auto ret = ability->IsRestoredInContinuation();
@@ -1094,6 +1447,7 @@ HWTEST_F(AbilityBaseTest, AbilityContinuation_0200, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
// branch when abilityRecovery_ is nullptr
Want want;
@@ -1140,6 +1494,7 @@ HWTEST_F(AbilityBaseTest, AbilityContinuation_0300, TestSize.Level1)
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
std::shared_ptr<AbilityInfo> pageAbilityInfo = std::make_shared<AbilityInfo>();
pageAbilityInfo->type = AppExecFwk::AbilityType::PAGE;
auto eventRunner = EventRunner::Create(pageAbilityInfo->name);
@@ -1164,6 +1519,7 @@ HWTEST_F(AbilityBaseTest, AbilityContinuation_0400, TestSize.Level1)
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
auto state = ability->GetContinuationState();
EXPECT_EQ(state, ContinuationState::LOCAL_RUNNING);
@@ -1192,6 +1548,7 @@ HWTEST_F(AbilityBaseTest, AbilityContinuation_0500, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
// branch when abilityInfo_ is nullptr
auto regMgr = ability->GetContinuationRegisterManager();
@@ -1242,6 +1599,7 @@ HWTEST_F(AbilityBaseTest, AbilityContinuation_0600, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
Want want;
want.SetFlags(Want::FLAG_ABILITY_CONTINUATION);
@@ -1282,20 +1640,53 @@ HWTEST_F(AbilityBaseTest, AbilityStartAbilityForResult_0100, TestSize.Level1)
// branch when abilityInfo_ is nullptr
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ability->StartAbilityForResult(want, requestCode, abilityStartSetting);
ASSERT_NE(ability, nullptr);
auto ret = ability->StartAbilityForResult(want, requestCode, abilityStartSetting);
EXPECT_EQ(ret, ERR_NULL_OBJECT);
// branch when type is not PAGE
std::shared_ptr<AbilityHandler> handler = nullptr;
std::shared_ptr<AbilityInfo> serviceAbilityInfo = std::make_shared<AbilityInfo>();
serviceAbilityInfo->type = AppExecFwk::AbilityType::SERVICE;
ability->Init(serviceAbilityInfo, nullptr, handler, nullptr);
ability->StartAbilityForResult(want, requestCode, abilityStartSetting);
ret = ability->StartAbilityForResult(want, requestCode, abilityStartSetting);
EXPECT_EQ(ret, ERR_INVALID_VALUE);
// branch when type is PAGE
std::shared_ptr<AbilityInfo> pageAbilityInfo = std::make_shared<AbilityInfo>();
pageAbilityInfo->type = AppExecFwk::AbilityType::PAGE;
ability->Init(pageAbilityInfo, nullptr, handler, nullptr);
ability->StartAbilityForResult(want, requestCode, abilityStartSetting);
ret = ability->StartAbilityForResult(want, requestCode, abilityStartSetting);
EXPECT_EQ(ret, ERR_INVALID_VALUE);
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: AbilityStartAbility_0100
* @tc.desc: Ability StartAbility test when type is not PAGE ans SERVICE.
* @tc.type: FUNC
* @tc.require: issueI60B7N
*/
HWTEST_F(AbilityBaseTest, AbilityStartAbility_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
Want want;
std::string bundleName = "bundleName";
std::string abilityName = "abilityName";
want.SetElementName(bundleName, abilityName);
AbilityStartSetting abilityStartSetting;
// branch when type is not PAGE
std::shared_ptr<AbilityHandler> handler = nullptr;
std::shared_ptr<AbilityInfo> abilityInfo = std::make_shared<AbilityInfo>();
abilityInfo->type = AppExecFwk::AbilityType::DATA;
ability->Init(abilityInfo, nullptr, handler, nullptr);
auto ret = ability->StartAbility(want, abilityStartSetting);
EXPECT_EQ(ret, ERR_INVALID_VALUE);
HILOG_INFO("%{public}s end.", __func__);
}
@@ -1310,6 +1701,7 @@ HWTEST_F(AbilityBaseTest, AbilityGetType_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
Uri uri("test_get_type");
auto type = ability->GetType(uri);
@@ -1333,6 +1725,7 @@ HWTEST_F(AbilityBaseTest, AbilityInsert_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
Uri uri("test_insert");
NativeRdb::ValuesBucket value;
@@ -1365,6 +1758,7 @@ HWTEST_F(AbilityBaseTest, AbilityCall_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
Uri uri("test_call");
std::string method;
@@ -1379,6 +1773,58 @@ HWTEST_F(AbilityBaseTest, AbilityCall_0100, TestSize.Level1)
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: InitConfigurationProperties_0100
* @tc.desc: Ability InitConfigurationProperties test.
* @tc.type: FUNC
* @tc.require: issueI60B7N
*/
HWTEST_F(AbilityBaseTest, InitConfigurationProperties_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
Configuration config;
config.AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE, "en");
config.AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE, "dark");
config.AddItem(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, "true");
std::string language;
std::string colormode;
std::string hasPointerDevice;
ability->InitConfigurationProperties(config, language, colormode, hasPointerDevice);
EXPECT_EQ(language, "en");
EXPECT_EQ(colormode, "dark");
EXPECT_EQ(hasPointerDevice, "true");
// branch when setting is not nullptr
auto setting = std::make_shared<AbilityStartSetting>();
ability->SetStartAbilitySetting(setting);
ability->InitConfigurationProperties(config, language, colormode, hasPointerDevice);
EXPECT_EQ(language, "en");
EXPECT_EQ(colormode, "dark");
EXPECT_EQ(hasPointerDevice, "true");
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: OnKeyUp_0100
* @tc.desc: Ability OnKeyUp test.
* @tc.type: FUNC
* @tc.require: issueI60B7N
*/
HWTEST_F(AbilityBaseTest, OnKeyUp_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
auto keyEvent = std::make_shared<MMI::KeyEvent>(MMI::KeyEvent::KEYCODE_BACK);
ability->OnKeyUp(keyEvent);
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: AbilityOnMemoryLevel_0100
* @tc.desc: Ability OnMemoryLevel test.
@@ -1389,6 +1835,7 @@ HWTEST_F(AbilityBaseTest, AbilityOnMemoryLevel_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
int level = 0;
ability->OnMemoryLevel(level);
@@ -1396,6 +1843,9 @@ HWTEST_F(AbilityBaseTest, AbilityOnMemoryLevel_0100, TestSize.Level1)
ability->scene_ = std::make_shared<Rosen::WindowScene>();
ability->OnMemoryLevel(level);
auto contentInfo = ability->GetContentInfo();
EXPECT_EQ(contentInfo, "");
HILOG_INFO("%{public}s end.", __func__);
}
@@ -1409,6 +1859,7 @@ HWTEST_F(AbilityBaseTest, AbilityOpenRawFile_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
Uri uri("test_open_file");
std::string mode;
@@ -1431,6 +1882,7 @@ HWTEST_F(AbilityBaseTest, AbilityVirtualFunc_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
Configuration configuration;
ability->OnConfigurationUpdated(configuration);
@@ -1466,6 +1918,7 @@ HWTEST_F(AbilityBaseTest, AbilityVirtualFunc_0200, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
bool ret = ability->OnStartContinuation();
EXPECT_EQ(ret, false);
@@ -1497,6 +1950,30 @@ HWTEST_F(AbilityBaseTest, AbilityVirtualFunc_0200, TestSize.Level1)
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: DispatchLifecycleOnForeground_0200
* @tc.desc: Ability DispatchLifecycleOnForeground test.
* @tc.type: FUNC
* @tc.require: issueI60B7N
*/
HWTEST_F(AbilityBaseTest, DispatchLifecycleOnForeground_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
// lifecycle executor is nullptr
Want want;
ability->DispatchLifecycleOnForeground(want);
// lifecycle is nullptr and lifecycle executor is not nullptr
auto lifecycleExecutor = std::make_shared<AbilityLifecycleExecutor>();
ability->abilityLifecycleExecutor_ = lifecycleExecutor;
ability->DispatchLifecycleOnForeground(want);
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: AbilityBackgroundRunning_0100
* @tc.desc: Ability function test, including StopBackgroundRunning and StartBackgroundRunning
@@ -1507,6 +1984,11 @@ HWTEST_F(AbilityBaseTest, AbilityBackgroundRunning_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
// branch when ability info is nullptr
AbilityRuntime::WantAgent::WantAgent wantAgent;
ability->StartBackgroundRunning(wantAgent);
std::shared_ptr<AbilityInfo> pageAbilityInfo = std::make_shared<AbilityInfo>();
pageAbilityInfo->type = AppExecFwk::AbilityType::PAGE;
@@ -1516,8 +1998,6 @@ HWTEST_F(AbilityBaseTest, AbilityBackgroundRunning_0100, TestSize.Level1)
auto bundleMgr = ability->GetBundleMgr();
ability->SetBundleManager(bundleMgr);
AbilityRuntime::WantAgent::WantAgent wantAgent;
ability->StartBackgroundRunning(wantAgent);
int id = 0;
@@ -1541,6 +2021,7 @@ HWTEST_F(AbilityBaseTest, AbilityParseValuesBucketReference_0100, TestSize.Level
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
std::vector<std::shared_ptr<DataAbilityResult>> results;
std::shared_ptr<DataAbilityOperation> operation = nullptr;
@@ -1565,6 +2046,7 @@ HWTEST_F(AbilityBaseTest, AbilityChangeRef2Value_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
// index larger than or equal to numRefs
std::vector<std::shared_ptr<DataAbilityResult>> results;
@@ -1609,6 +2091,7 @@ HWTEST_F(AbilityBaseTest, AbilityCheckAssertQueryResult_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
// queryResult is nullptr
std::shared_ptr<NativeRdb::AbsSharedResultSet> queryResult = nullptr;
@@ -1638,6 +2121,7 @@ HWTEST_F(AbilityBaseTest, AbilityStartFeatureAbilityForResult_0100, TestSize.Lev
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
Want want;
int requestCode = 0;
@@ -1647,6 +2131,9 @@ HWTEST_F(AbilityBaseTest, AbilityStartFeatureAbilityForResult_0100, TestSize.Lev
auto ret = ability->StartFeatureAbilityForResult(want, requestCode, std::move(task));
EXPECT_EQ(ret, ERR_NULL_OBJECT);
int resultCode = 0;
ability->OnFeatureAbilityResult(requestCode, resultCode, want);
HILOG_INFO("%{public}s end.", __func__);
}
@@ -1660,6 +2147,7 @@ HWTEST_F(AbilityBaseTest, AbilityFuncList_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
auto object = ability->CallRequest();
EXPECT_EQ(object, nullptr);
@@ -1692,6 +2180,7 @@ HWTEST_F(AbilityBaseTest, AbilityFuncList_0200, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
ability->OnLeaveForeground();
@@ -1716,6 +2205,7 @@ HWTEST_F(AbilityBaseTest, AbilitySetShowOnLockScreen_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
ability->SetShowOnLockScreen(true);
ability->SetShowOnLockScreen(false);
@@ -1746,6 +2236,7 @@ HWTEST_F(AbilityBaseTest, AbilityScene_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
ability->OnSceneCreated();
ability->OnSceneRestored();
@@ -1767,6 +2258,7 @@ HWTEST_F(AbilityBaseTest, AbilitySetUIContent_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
ComponentContainer componentContainer;
ability->SetUIContent(componentContainer);
@@ -1786,6 +2278,7 @@ HWTEST_F(AbilityBaseTest, AbilityFormFunction_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
int64_t formId = 0;
ability->OnUpdate(formId);
@@ -1810,6 +2303,7 @@ HWTEST_F(AbilityBaseTest, AbilityGetCurrentWindowMode_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
// scene_ is nullptr
int windowMode = ability->GetCurrentWindowMode();
@@ -1819,6 +2313,12 @@ HWTEST_F(AbilityBaseTest, AbilityGetCurrentWindowMode_0100, TestSize.Level1)
windowMode = ability->GetCurrentWindowMode();
EXPECT_EQ(windowMode, static_cast<int>(Rosen::WindowMode::WINDOW_MODE_UNDEFINED));
int32_t displayId = 0;
sptr<Rosen::WindowOption> option = new Rosen::WindowOption();
ability->InitWindow(displayId, option);
windowMode = ability->GetCurrentWindowMode();
EXPECT_EQ(windowMode, static_cast<int>(Rosen::WindowMode::WINDOW_MODE_UNDEFINED));
HILOG_INFO("%{public}s end.", __func__);
}
@@ -1832,6 +2332,7 @@ HWTEST_F(AbilityBaseTest, AbilitySetMissionLabel_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
std::string label = "test_label";
auto ret = ability->SetMissionLabel(label);
@@ -1856,6 +2357,12 @@ HWTEST_F(AbilityBaseTest, AbilitySetMissionLabel_0100, TestSize.Level1)
ret = ability->SetMissionLabel(label);
EXPECT_EQ(ret, -1);
int32_t displayId = 0;
sptr<Rosen::WindowOption> option = new Rosen::WindowOption();
ability->InitWindow(displayId, option);
ret = ability->SetMissionLabel(label);
EXPECT_EQ(ret, -1);
// fa mode
pageAbilityInfo->isStageBasedModel = false;
ability->Init(pageAbilityInfo, nullptr, handler, nullptr);
@@ -1875,6 +2382,7 @@ HWTEST_F(AbilityBaseTest, AbilitySetMissionIcon_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
auto icon = std::make_shared<Media::PixelMap>();
auto ret = ability->SetMissionIcon(icon);
@@ -1899,6 +2407,12 @@ HWTEST_F(AbilityBaseTest, AbilitySetMissionIcon_0100, TestSize.Level1)
ret = ability->SetMissionIcon(icon);
EXPECT_EQ(ret, -1);
int32_t displayId = 0;
sptr<Rosen::WindowOption> option = new Rosen::WindowOption();
ability->InitWindow(displayId, option);
ret = ability->SetMissionIcon(icon);
EXPECT_EQ(ret, -1);
// fa mode
pageAbilityInfo->isStageBasedModel = false;
ability->Init(pageAbilityInfo, nullptr, handler, nullptr);
@@ -1918,6 +2432,7 @@ HWTEST_F(AbilityBaseTest, AbilityOnChange_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
std::shared_ptr<AbilityInfo> pageAbilityInfo = std::make_shared<AbilityInfo>();
pageAbilityInfo->type = AppExecFwk::AbilityType::PAGE;
@@ -1931,7 +2446,11 @@ HWTEST_F(AbilityBaseTest, AbilityOnChange_0100, TestSize.Level1)
ability->OnDestroy(displayId);
ability->OnChange(displayId);
auto application = std::shared_ptr<OHOSApplication>(ApplicationLoader::GetInstance().GetApplicationByName());
auto application = std::make_shared<OHOSApplication>();
EXPECT_NE(application, nullptr);
Configuration config;
config.AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE, "dark");
application->SetConfiguration(config);
ability->Init(pageAbilityInfo, application, handler, nullptr);
ability->OnChange(displayId);
@@ -1948,6 +2467,7 @@ HWTEST_F(AbilityBaseTest, AbilityOnDisplayMove_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
std::shared_ptr<AbilityInfo> pageAbilityInfo = std::make_shared<AbilityInfo>();
pageAbilityInfo->type = AppExecFwk::AbilityType::PAGE;
@@ -1960,7 +2480,11 @@ HWTEST_F(AbilityBaseTest, AbilityOnDisplayMove_0100, TestSize.Level1)
Rosen::DisplayId toDisplayId = 0;
ability->OnDisplayMove(fromDisplayId, toDisplayId);
auto application = std::shared_ptr<OHOSApplication>(ApplicationLoader::GetInstance().GetApplicationByName());
auto application = std::make_shared<OHOSApplication>();
EXPECT_NE(application, nullptr);
Configuration config;
config.AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE, "dark");
application->SetConfiguration(config);
ability->Init(pageAbilityInfo, application, handler, nullptr);
ability->OnDisplayMove(fromDisplayId, toDisplayId);
@@ -1977,6 +2501,7 @@ HWTEST_F(AbilityBaseTest, AbilityRequestFocus_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
// ability window is nullptr
Want want;
@@ -2010,6 +2535,7 @@ HWTEST_F(AbilityBaseTest, AbilitySetWakeUpScreen_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
// ability window is nullptr
bool wakeUp = false;
@@ -2043,6 +2569,7 @@ HWTEST_F(AbilityBaseTest, AbilitySetDisplayOrientation_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
std::shared_ptr<Ability> ability = std::make_shared<Ability>();
ASSERT_NE(ability, nullptr);
// ability window is nullptr
int orientation = static_cast<int>(DisplayOrientation::FOLLOWRECENT);
@@ -90,6 +90,8 @@ ohos_unittest("application_test") {
"${ability_runtime_native_path}/appkit/app/app_context.cpp",
"${ability_runtime_native_path}/appkit/app/app_loader.cpp",
"${ability_runtime_native_path}/appkit/app/ohos_application.cpp",
"${ability_runtime_test_path}/mock/frameworks_kits_ability_native_test/include/mock_bundle_manager.cpp",
"${ability_runtime_test_path}/mock/frameworks_kits_ability_native_test/include/sys_mgr_client_mock.cpp",
"ability_stage_test.cpp",
"application_data_manager_test.cpp",
"application_test.cpp",
@@ -20,10 +20,17 @@
#include "context_impl.h"
#undef private
#include "ability_constants.h"
#include "ability_local_record.h"
#include "application_context.h"
#include "context.h"
#include "hap_module_info.h"
#include "hilog_wrapper.h"
#include "iremote_object.h"
#include "mock_ability_token.h"
#include "mock_bundle_manager.h"
#include "system_ability_definition.h"
#include "sys_mgr_client.h"
namespace OHOS {
namespace AppExecFwk {
@@ -31,6 +38,10 @@ using namespace testing::ext;
using namespace OHOS;
using namespace OHOS::AppExecFwk;
namespace {
const int64_t CONTEXT_CREATE_BY_SYSTEM_APP(0x00000001);
} // namespace
class ContextImplTest : public testing::Test {
public:
ContextImplTest() : contextImpl_(nullptr)
@@ -53,6 +64,9 @@ void ContextImplTest::TearDownTestCase(void)
void ContextImplTest::SetUp(void)
{
contextImpl_ = std::make_shared<AbilityRuntime::ContextImpl>();
sptr<IRemoteObject> bundleObject = new (std::nothrow) BundleMgrService();
DelayedSingleton<SysMrgClient>::GetInstance()->RegisterSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID,
bundleObject);
}
void ContextImplTest::TearDown(void)
@@ -91,6 +105,373 @@ HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetBundleName_002, Function | M
GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetBundleName_002 end";
}
/**
* @tc.name: AppExecFwk_ContextImpl_GetBundleName_003
* @tc.desc: Get bundle name when parent context is not nullptr.
* @tc.type: FUNC
* @tc.require: issueI61P7Y
*/
HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetBundleName_003, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
auto contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(contextImpl, nullptr);
auto parentContext = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(parentContext, nullptr);
auto applicationInfo = std::make_shared<AppExecFwk::ApplicationInfo>();
EXPECT_NE(applicationInfo, nullptr);
applicationInfo->bundleName = "com.test.parentcontext";
parentContext->SetApplicationInfo(applicationInfo);
contextImpl->SetParentContext(parentContext);
std::string bundleName = contextImpl->GetBundleName();
EXPECT_EQ(bundleName, "com.test.parentcontext");
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: GetBundleCodeDir_0100
* @tc.desc: Get bundle code directory.
* @tc.type: FUNC
* @tc.require: issueI61P7Y
*/
HWTEST_F(ContextImplTest, GetBundleCodeDir_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
auto contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(contextImpl, nullptr);
// branch when application info is nullptr
auto codeDir = contextImpl->GetBundleCodeDir();
EXPECT_EQ(codeDir, "");
// construct application info
auto applicationInfo = std::make_shared<AppExecFwk::ApplicationInfo>();
EXPECT_NE(applicationInfo, nullptr);
applicationInfo->codePath = "/data/app/el1/bundle/public/testCodeDir";
contextImpl->SetApplicationInfo(applicationInfo);
// not create by system app
codeDir = contextImpl->GetBundleCodeDir();
EXPECT_EQ(codeDir, AbilityRuntime::Constants::LOCAL_CODE_PATH);
// create by system app(flag is ContextImpl::CONTEXT_CREATE_BY_SYSTEM_APP)
contextImpl->SetFlags(CONTEXT_CREATE_BY_SYSTEM_APP);
codeDir = contextImpl->GetBundleCodeDir();
EXPECT_EQ(codeDir, "/data/bundles/testCodeDir");
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: IsUpdatingConfigurations_0100
* @tc.desc: IsUpdatingConfigurations basic test.
* @tc.type: FUNC
* @tc.require: issueI61P7Y
*/
HWTEST_F(ContextImplTest, IsUpdatingConfigurations_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
auto contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(contextImpl, nullptr);
auto isUpdating = contextImpl->IsUpdatingConfigurations();
EXPECT_EQ(isUpdating, false);
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: PrintDrawnCompleted_0100
* @tc.desc: PrintDrawnCompleted basic test.
* @tc.type: FUNC
* @tc.require: issueI61P7Y
*/
HWTEST_F(ContextImplTest, PrintDrawnCompleted_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
auto contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(contextImpl, nullptr);
auto isComplete = contextImpl->PrintDrawnCompleted();
EXPECT_EQ(isComplete, false);
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: GetDatabaseDir_0100
* @tc.desc: Get base directory basic test.
* @tc.type: FUNC
* @tc.require: issueI61P7Y
*/
HWTEST_F(ContextImplTest, GetDatabaseDir_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
auto contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(contextImpl, nullptr);
// not create by system app and parent context is nullptr
auto databaseDir = contextImpl->GetDatabaseDir();
EXPECT_EQ(databaseDir, "/data/storage/el2/database");
// create by system app and parent context is not nullptr
contextImpl->SetFlags(CONTEXT_CREATE_BY_SYSTEM_APP);
auto parentContext = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(parentContext, nullptr);
auto applicationInfo = std::make_shared<AppExecFwk::ApplicationInfo>();
EXPECT_NE(applicationInfo, nullptr);
applicationInfo->bundleName = "com.test.database";
parentContext->SetApplicationInfo(applicationInfo);
contextImpl->SetParentContext(parentContext);
databaseDir = contextImpl->GetDatabaseDir();
EXPECT_EQ(databaseDir, "/data/app/el2/0/database/com.test.database/");
// create by system app and hap module info of parent context is not nullptr
AppExecFwk::HapModuleInfo hapModuleInfo;
hapModuleInfo.moduleName = "test_moduleName";
contextImpl->InitHapModuleInfo(hapModuleInfo);
databaseDir = contextImpl->GetDatabaseDir();
EXPECT_EQ(databaseDir, "/data/app/el2/0/database/com.test.database/test_moduleName");
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: GetPreferencesDir_0100
* @tc.desc: Get preference directory basic test.
* @tc.type: FUNC
* @tc.require: issueI61P7Y
*/
HWTEST_F(ContextImplTest, GetPreferencesDir_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
auto contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(contextImpl, nullptr);
auto preferenceDir = contextImpl->GetPreferencesDir();
EXPECT_EQ(preferenceDir, "/data/storage/el2/base/preferences");
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: GetTempDir_0100
* @tc.desc: Get temp directory basic test.
* @tc.type: FUNC
* @tc.require: issueI61P7Y
*/
HWTEST_F(ContextImplTest, GetTempDir_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
auto contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(contextImpl, nullptr);
auto tempDir = contextImpl->GetTempDir();
EXPECT_EQ(tempDir, "/data/storage/el2/base/temp");
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: GetFilesDir_0100
* @tc.desc: Get files directory basic test.
* @tc.type: FUNC
* @tc.require: issueI61P7Y
*/
HWTEST_F(ContextImplTest, GetFilesDir_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
auto contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(contextImpl, nullptr);
auto filesDir = contextImpl->GetFilesDir();
EXPECT_EQ(filesDir, "/data/storage/el2/base/files");
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: GetDistributedFilesDir_0100
* @tc.desc: Get distributed directory basic test.
* @tc.type: FUNC
* @tc.require: issueI61P7Y
*/
HWTEST_F(ContextImplTest, GetDistributedFilesDir_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
auto contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(contextImpl, nullptr);
// not create by system app
auto distributedDir = contextImpl->GetDistributedFilesDir();
EXPECT_EQ(distributedDir, "/data/storage/el2/distributedfiles");
// create by system app and bundleName is empty
contextImpl->SetFlags(CONTEXT_CREATE_BY_SYSTEM_APP);
distributedDir = contextImpl->GetDistributedFilesDir();
EXPECT_EQ(distributedDir, "/mnt/hmdfs/0/device_view/local/data/");
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: GetBaseDir_0100
* @tc.desc: Get base directory basic test.
* @tc.type: FUNC
* @tc.require: issueI61P7Y
*/
HWTEST_F(ContextImplTest, GetBaseDir_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
auto contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(contextImpl, nullptr);
// not create by system app and parent context is nullptr
auto baseDir = contextImpl->GetBaseDir();
EXPECT_EQ(baseDir, "/data/storage/el2/base");
// create by system app and parent context is not nullptr
contextImpl->SetFlags(CONTEXT_CREATE_BY_SYSTEM_APP);
auto parentContext = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(parentContext, nullptr);
auto applicationInfo = std::make_shared<AppExecFwk::ApplicationInfo>();
EXPECT_NE(applicationInfo, nullptr);
applicationInfo->bundleName = "com.test.base";
parentContext->SetApplicationInfo(applicationInfo);
contextImpl->SetParentContext(parentContext);
baseDir = contextImpl->GetBaseDir();
EXPECT_EQ(baseDir, "/data/app/el2/0/base/com.test.base/haps/");
// create by system app and hap module info of parent context is not nullptr
AppExecFwk::HapModuleInfo hapModuleInfo;
hapModuleInfo.moduleName = "test_moduleName";
contextImpl->InitHapModuleInfo(hapModuleInfo);
baseDir = contextImpl->GetBaseDir();
EXPECT_EQ(baseDir, "/data/app/el2/0/base/com.test.base/haps/test_moduleName");
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: SwitchArea_0100
* @tc.desc: Switch area basic test.
* @tc.type: FUNC
* @tc.require: issueI61P7Y
*/
HWTEST_F(ContextImplTest, SwitchArea_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
auto contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(contextImpl, nullptr);
// invalid mode
contextImpl->SwitchArea(-1);
contextImpl->SwitchArea(2);
// valid mode
contextImpl->SwitchArea(0);
contextImpl->SwitchArea(1);
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: GetAreaArea_0100
* @tc.desc: Get area basic test.
* @tc.type: FUNC
* @tc.require: issueI61P7Y
*/
HWTEST_F(ContextImplTest, GetAreaArea_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
auto contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(contextImpl, nullptr);
contextImpl->SwitchArea(0);
auto mode = contextImpl->GetArea();
EXPECT_EQ(mode, 0);
contextImpl->SwitchArea(1);
mode = contextImpl->GetArea();
EXPECT_EQ(mode, 1);
// invalid area_
contextImpl->currArea_ = "invalid";
mode = contextImpl->GetArea();
EXPECT_EQ(mode, 1); // default is AbilityRuntime::ContextImpl::EL_DEFAULT
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: GetCurrentAccountId_0100
* @tc.desc: Get current account id test.
* @tc.type: FUNC
* @tc.require: issueI61P7Y
*/
HWTEST_F(ContextImplTest, GetCurrentAccountId_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
auto contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(contextImpl, nullptr);
auto accountId = contextImpl->GetCurrentAccountId();
EXPECT_EQ(accountId, 0); // default account id
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: GetCurrentActiveAccountId_0100
* @tc.desc: Get current active account id test.
* @tc.type: FUNC
* @tc.require: issueI61P7Y
*/
HWTEST_F(ContextImplTest, GetCurrentActiveAccountId_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
auto contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(contextImpl, nullptr);
auto accountId = contextImpl->GetCurrentActiveAccountId();
EXPECT_EQ(accountId, 100); // default active account id is 100
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: CreateBundleContext_0100
* @tc.desc: Create bundle context test.
* @tc.type: FUNC
* @tc.require: issueI61P7Y
*/
HWTEST_F(ContextImplTest, CreateBundleContext_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
auto contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(contextImpl, nullptr);
// bundle name is empty
auto context = contextImpl->CreateBundleContext("");
EXPECT_EQ(context, nullptr);
// bundle name is invalid
context = contextImpl->CreateBundleContext("invalid_bundleName");
EXPECT_EQ(context, nullptr);
context = contextImpl->CreateBundleContext("test_contextImpl");
EXPECT_NE(context, nullptr);
// parent context is not nullptr
auto parentContext = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(parentContext, nullptr);
contextImpl->SetParentContext(parentContext);
context = contextImpl->CreateBundleContext("");
EXPECT_EQ(context, nullptr);
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.number: AppExecFwk_ContextImpl_SetApplicationInfo_001
* @tc.name: SetApplicationInfo
@@ -101,6 +482,8 @@ HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetBundleName_002, Function | M
HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_SetApplicationInfo_001, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_SetApplicationInfo_001 start";
contextImpl_->SetApplicationInfo(nullptr);
EXPECT_EQ(contextImpl_->GetApplicationInfo(), nullptr);
std::shared_ptr<AppExecFwk::ApplicationInfo> applicationInfo = std::make_shared<AppExecFwk::ApplicationInfo>();
contextImpl_->SetApplicationInfo(applicationInfo);
EXPECT_NE(contextImpl_->GetApplicationInfo(), nullptr);
@@ -132,6 +515,15 @@ HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetApplicationContext_001, Func
{
GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetApplicationContext_001 start";
EXPECT_TRUE(contextImpl_->GetApplicationContext() == nullptr);
auto contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(contextImpl, nullptr);
auto parentContext = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(parentContext, nullptr);
contextImpl->SetParentContext(parentContext);
EXPECT_EQ(contextImpl->GetApplicationInfo(), nullptr);
GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_GetApplicationContext_001 end";
}
@@ -166,19 +558,49 @@ HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_GetHapModuleInfo_001, Function
}
/**
* @tc.number: AppExecFwk_ContextImpl_CreateModuleContext_001
* @tc.number: CreateModuleContext_001
* @tc.name: CreateModuleContext
* @tc.desc: Test whether CreateModuleContext is called normally.
* @tc.type: FUNC
* @tc.require: SR000H6I25
*/
HWTEST_F(ContextImplTest, AppExecFwk_ContextImpl_CreateModuleContext_001, Function | MediumTest | Level1)
HWTEST_F(ContextImplTest, CreateModuleContext_001, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_CreateModuleContext_001 start";
EXPECT_EQ(contextImpl_->CreateModuleContext("module_name"), nullptr);
GTEST_LOG_(INFO) << "AppExecFwk_ContextImpl_CreateModuleContext_001 end";
}
/**
* @tc.name: CreateModuleContext_002
* @tc.desc: Create module context test.
* @tc.type: FUNC
* @tc.require: issueI61P7Y
*/
HWTEST_F(ContextImplTest, CreateModuleContext_002, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
auto contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(contextImpl, nullptr);
// bundleName is valid, but module name is empty
auto moduleContext = contextImpl->CreateModuleContext("test_contextImpl", "");
EXPECT_EQ(moduleContext, nullptr);
// bundle name is invalid
moduleContext = contextImpl->CreateModuleContext("invalid_bundleName", "invalid_moduleName");
EXPECT_EQ(moduleContext, nullptr);
// module didn't exist
moduleContext = contextImpl->CreateModuleContext("test_contextImpl", "invalid_moduleName");
EXPECT_EQ(moduleContext, nullptr);
moduleContext = contextImpl->CreateModuleContext("test_contextImpl", "test_moduleName");
EXPECT_NE(moduleContext, nullptr);
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.number: AppExecFwk_AppContext_RegisterAbilityLifecycleCallback_001
* @tc.name: RegisterAbilityLifecycleCallback
@@ -317,7 +739,7 @@ HWTEST_F(ContextImplTest, AppExecFwk_AppContext_InitResourceManager_003, Functio
bundleInfo.hapModuleInfos.push_back(info);
contextImpl_->InitResourceManager(bundleInfo, appContext, true, "entry");
EXPECT_TRUE(appContext->GetResourceManager() != nullptr);
contextImpl_->InitResourceManager(bundleInfo, appContext, true, "");
EXPECT_TRUE(appContext->GetResourceManager() != nullptr);
@@ -326,7 +748,7 @@ HWTEST_F(ContextImplTest, AppExecFwk_AppContext_InitResourceManager_003, Functio
bundleInfo.hapModuleInfos.push_back(info);
contextImpl_->InitResourceManager(bundleInfo, appContext, true, "entry");
EXPECT_TRUE(appContext->GetResourceManager() != nullptr);
contextImpl_->InitResourceManager(bundleInfo, appContext, true, "");
EXPECT_TRUE(appContext->GetResourceManager() != nullptr);
@@ -360,7 +782,7 @@ HWTEST_F(ContextImplTest, AppExecFwk_AppContext_InitResourceManager_004, Functio
bundleInfo.hapModuleInfos.push_back(info);
contextImpl_->InitResourceManager(bundleInfo, appContext, true, "entry");
EXPECT_TRUE(appContext->GetResourceManager() != nullptr);
contextImpl_->InitResourceManager(bundleInfo, appContext, false, "entry");
EXPECT_TRUE(appContext->GetResourceManager() != nullptr);
@@ -372,5 +794,156 @@ HWTEST_F(ContextImplTest, AppExecFwk_AppContext_InitResourceManager_004, Functio
GTEST_LOG_(INFO) << "AppExecFwk_AppContext_InitResourceManager_004 end";
}
/**
* @tc.name: AppExecFwk_AppContext_InitResourceManager_005
* @tc.desc: abnornal branch test for InitResourceManager.
* @tc.type: FUNC
* @tc.require: issueI61P7Y
*/
HWTEST_F(ContextImplTest, AppExecFwk_AppContext_InitResourceManager_005, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
auto contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(contextImpl, nullptr);
// branch when appContext is nullptr
AppExecFwk::BundleInfo bundleInfo;
contextImpl->InitResourceManager(bundleInfo, nullptr, true, "");
// parent context is not nullptr
auto parentContext = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(parentContext, nullptr);
contextImpl->SetParentContext(parentContext);
EXPECT_EQ(contextImpl->GetResourceManager(), nullptr);
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: GetBundleCodePath_0100
* @tc.desc: Get bundle code path test.
* @tc.type: FUNC
* @tc.require: issueI61P7Y
*/
HWTEST_F(ContextImplTest, GetBundleCodePath_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
auto contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(contextImpl, nullptr);
auto codePath = contextImpl->GetBundleCodePath();
EXPECT_EQ(codePath, "");
// construt application info
auto applicationInfo = std::make_shared<AppExecFwk::ApplicationInfo>();
EXPECT_NE(applicationInfo, nullptr);
applicationInfo->codePath = "/data/app/el1";
contextImpl->SetApplicationInfo(applicationInfo);
EXPECT_EQ(contextImpl->GetBundleCodePath(), "/data/app/el1");
// parent context is not nullptr
auto parentContext = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(parentContext, nullptr);
contextImpl->SetParentContext(parentContext);
EXPECT_EQ(contextImpl->GetBundleCodePath(), "");
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: InitHapModuleInfo_0100
* @tc.desc: Init hap module info test.
* @tc.type: FUNC
* @tc.require: issueI61P7Y
*/
HWTEST_F(ContextImplTest, InitHapModuleInfo_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
auto contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(contextImpl, nullptr);
AppExecFwk::HapModuleInfo hapModuleInfo;
contextImpl->InitHapModuleInfo(hapModuleInfo);
EXPECT_NE(contextImpl->GetHapModuleInfo(), nullptr);
// branch when hap module info has been assigned
auto abilityInfo = std::make_shared<AppExecFwk::AbilityInfo>();
contextImpl->InitHapModuleInfo(abilityInfo);
EXPECT_NE(contextImpl->GetHapModuleInfo(), nullptr);
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: InitHapModuleInfo_0200
* @tc.desc: Init hap module info test.
* @tc.type: FUNC
* @tc.require: issueI61P7Y
*/
HWTEST_F(ContextImplTest, InitHapModuleInfo_0200, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
auto contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(contextImpl, nullptr);
auto abilityInfo = std::make_shared<AppExecFwk::AbilityInfo>();
contextImpl->InitHapModuleInfo(nullptr);
contextImpl->InitHapModuleInfo(abilityInfo);
EXPECT_NE(contextImpl->GetHapModuleInfo(), nullptr);
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: SetToken_0100
* @tc.desc: set token and get token test.
* @tc.type: FUNC
* @tc.require: issueI61P7Y
*/
HWTEST_F(ContextImplTest, SetToken_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
auto contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(contextImpl, nullptr);
contextImpl->SetToken(nullptr);
sptr<IRemoteObject> token = new (std::nothrow) MockAbilityToken();
contextImpl->SetToken(token);
auto after = contextImpl->GetToken();
EXPECT_EQ(token, after);
HILOG_INFO("%{public}s end.", __func__);
}
/**
* @tc.name: GetDeviceType_0100
* @tc.desc: Get device type test.
* @tc.type: FUNC
* @tc.require: issueI61P7Y
*/
HWTEST_F(ContextImplTest, GetDeviceType_0100, TestSize.Level1)
{
HILOG_INFO("%{public}s start.", __func__);
auto contextImpl = std::make_shared<AbilityRuntime::ContextImpl>();
EXPECT_NE(contextImpl, nullptr);
// branch when config is nullptr
auto deviceType = contextImpl->GetDeviceType();
EXPECT_EQ(deviceType, Global::Resource::DeviceType::DEVICE_PHONE);
// get device type again
deviceType = contextImpl->GetDeviceType();
EXPECT_EQ(deviceType, Global::Resource::DeviceType::DEVICE_PHONE);
// construct configuration
auto config = std::make_shared<AppExecFwk::Configuration>();
EXPECT_NE(config, nullptr);
config->AddItem(AAFwk::GlobalConfigurationKey::DEVICE_TYPE, "phone");
contextImpl->SetConfiguration(config);
deviceType = contextImpl->GetDeviceType();
EXPECT_EQ(deviceType, Global::Resource::DeviceType::DEVICE_PHONE);
HILOG_INFO("%{public}s end.", __func__);
}
} // namespace AppExecFwk
}
+71
View File
@@ -0,0 +1,71 @@
# Copyright (c) 2022 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("//foundation/ability/ability_runtime/ability_runtime.gni")
module_output_path = "ability_runtime/abilitymgr"
ohos_unittest("mission_data_storage_test") {
module_out_path = module_output_path
include_dirs = [
"${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/system_ability_mock",
"${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include",
]
sources = [
"${ability_runtime_services_path}/common/src/permission_verification.cpp",
"${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp",
"mission_data_storage_test.cpp", # add mock file
]
configs = [
"${ability_runtime_services_path}/abilitymgr:abilityms_config",
"${ability_runtime_test_path}/mock/services_abilitymgr_test:aafwk_mock_config",
]
cflags = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
deps = [
"${ability_runtime_native_path}/ability/native:abilitykit_native",
"${ability_runtime_services_path}/abilitymgr:abilityms",
"${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/aakit:aakit_mock",
"${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/appexecfwk_core:appexecfwk_appmgr_mock",
"${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/appexecfwk_core:appexecfwk_bundlemgr_mock",
"${ability_runtime_test_path}/unittest:abilityms_test_source",
"//third_party/googletest:gtest_main",
]
external_deps = [
"ability_base:want",
"ability_base:zuri",
"access_token:libaccesstoken_sdk",
"c_utils:utils",
"common_event_service:cesfwk_innerkits",
"eventhandler:libeventhandler",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
if (background_task_mgr_continuous_task_enable) {
external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ]
}
}
group("unittest") {
testonly = true
deps = [ ":mission_data_storage_test" ]
}
@@ -0,0 +1,723 @@
/*
* Copyright (c) 2022 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>
#define private public
#define protected public
#include "mission_data_storage.h"
#undef private
#undef protected
using namespace testing::ext;
using namespace OHOS::AppExecFwk;
namespace OHOS {
namespace AAFwk {
class MissionDataStorageTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void MissionDataStorageTest::SetUpTestCase(void)
{}
void MissionDataStorageTest::TearDownTestCase(void)
{}
void MissionDataStorageTest::SetUp(void)
{}
void MissionDataStorageTest::TearDown(void)
{}
/*
* Feature: MissionListManager
* Function: SetEventHandler
* SubFunction: NA
* FunctionPoints: MissionDataStorage SetEventHandler
* EnvConditions: NA
* CaseDescription: Verify SetEventHandler
*/
HWTEST_F(MissionDataStorageTest, SetEventHandler_001, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
auto handler = std::make_shared<EventHandler>(EventRunner::Create());
missionDataStorage->SetEventHandler(handler);
}
/*
* Feature: MissionListManager
* Function: SaveMissionInfo
* SubFunction: NA
* FunctionPoints: MissionDataStorage SaveMissionInfo
* EnvConditions: NA
* CaseDescription: Verify SaveMissionInfo
*/
HWTEST_F(MissionDataStorageTest, SaveMissionInfo_001, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
InnerMissionInfo missionInfo;
missionInfo.missionInfo.id = 0;
missionDataStorage->SaveMissionInfo(missionInfo);
}
/*
* Feature: MissionListManager
* Function: SaveMissionInfo
* SubFunction: NA
* FunctionPoints: MissionDataStorage SaveMissionInfo
* EnvConditions: NA
* CaseDescription: Verify SaveMissionInfo
*/
HWTEST_F(MissionDataStorageTest, SaveMissionInfo_002, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
missionDataStorage->userId_ = 10;
InnerMissionInfo missionInfo;
missionInfo.missionInfo.id = 1;
missionDataStorage->SaveMissionInfo(missionInfo);
}
/*
* Feature: MissionListManager
* Function: DeleteMissionInfo
* SubFunction: NA
* FunctionPoints: MissionDataStorage DeleteMissionInfo
* EnvConditions: NA
* CaseDescription: Verify DeleteMissionInfo
*/
HWTEST_F(MissionDataStorageTest, DeleteMissionInfo_001, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int missionId = 0;
missionDataStorage->DeleteMissionInfo(missionId);
missionId = 1;
missionDataStorage->DeleteMissionInfo(missionId);
}
/*
* Feature: MissionListManager
* Function: SaveMissionSnapshot
* SubFunction: NA
* FunctionPoints: MissionDataStorage SaveMissionSnapshot
* EnvConditions: NA
* CaseDescription: Verify SaveMissionSnapshot
*/
HWTEST_F(MissionDataStorageTest, SaveMissionSnapshot_001, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int missionId = 0;
MissionSnapshot missionSnapshot;
missionDataStorage->SaveMissionSnapshot(missionId, missionSnapshot);
}
/*
* Feature: MissionListManager
* Function: DeleteMissionSnapshot
* SubFunction: NA
* FunctionPoints: MissionDataStorage DeleteMissionSnapshot
* EnvConditions: NA
* CaseDescription: Verify DeleteMissionSnapshot
*/
HWTEST_F(MissionDataStorageTest, DeleteMissionSnapshot_001, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int missionId = 0;
missionDataStorage->DeleteMissionSnapshot(missionId);
}
/*
* Feature: MissionListManager
* Function: DeleteMissionSnapshot
* SubFunction: NA
* FunctionPoints: MissionDataStorage DeleteMissionSnapshot
* EnvConditions: NA
* CaseDescription: Verify DeleteMissionSnapshot
*/
HWTEST_F(MissionDataStorageTest, DeleteMissionSnapshot_002, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int32_t missionId = 0;
MissionSnapshot missionSnapshot;
missionDataStorage->SaveMissionSnapshot(missionId, missionSnapshot);
missionDataStorage->DeleteMissionSnapshot(missionId);
}
/*
* Feature: MissionListManager
* Function: GetMissionSnapshot
* SubFunction: NA
* FunctionPoints: MissionDataStorage GetMissionSnapshot
* EnvConditions: NA
* CaseDescription: Verify GetMissionSnapshot
*/
HWTEST_F(MissionDataStorageTest, GetMissionSnapshot_001, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int missionId = 0;
MissionSnapshot missionSnapshot;
bool isLowResolution = true;
missionDataStorage->SaveCachedSnapshot(missionId, missionSnapshot);
bool res = missionDataStorage->GetMissionSnapshot(missionId, missionSnapshot, isLowResolution);
EXPECT_TRUE(res);
}
/*
* Feature: MissionListManager
* Function: GetMissionSnapshot
* SubFunction: NA
* FunctionPoints: MissionDataStorage GetMissionSnapshot
* EnvConditions: NA
* CaseDescription: Verify GetMissionSnapshot
*/
HWTEST_F(MissionDataStorageTest, GetMissionSnapshot_002, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int missionId = 0;
MissionSnapshot missionSnapshot;
bool isLowResolution = false;
missionDataStorage->SaveCachedSnapshot(missionId, missionSnapshot);
bool res = missionDataStorage->GetMissionSnapshot(missionId, missionSnapshot, isLowResolution);
EXPECT_TRUE(res);
}
/*
* Feature: MissionListManager
* Function: GetMissionSnapshot
* SubFunction: NA
* FunctionPoints: MissionDataStorage GetMissionSnapshot
* EnvConditions: NA
* CaseDescription: Verify GetMissionSnapshot
*/
HWTEST_F(MissionDataStorageTest, GetMissionSnapshot_003, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int missionId = 0;
MissionSnapshot missionSnapshot;
bool isLowResolution = true;
bool res = missionDataStorage->GetMissionSnapshot(missionId, missionSnapshot, isLowResolution);
EXPECT_FALSE(res);
}
/*
* Feature: MissionListManager
* Function: GetMissionDataFilePath
* SubFunction: NA
* FunctionPoints: MissionDataStorage GetMissionDataFilePath
* EnvConditions: NA
* CaseDescription: Verify GetMissionDataFilePath
*/
HWTEST_F(MissionDataStorageTest, GetMissionDataFilePath_001, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int missionId = 0;
std::string res = missionDataStorage->GetMissionDataFilePath(missionId);
EXPECT_EQ(res, "/data/service/el1/public/AbilityManagerService/0/MissionInfo/mission_0.json");
}
/*
* Feature: MissionListManager
* Function: GetMissionSnapshotPath
* SubFunction: NA
* FunctionPoints: MissionDataStorage GetMissionSnapshotPath
* EnvConditions: NA
* CaseDescription: Verify GetMissionSnapshotPath
*/
HWTEST_F(MissionDataStorageTest, GetMissionSnapshotPath_001, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int missionId = 0;
bool isLowResolution = true;
std::string res = missionDataStorage->GetMissionSnapshotPath(missionId, isLowResolution);
EXPECT_EQ(res, "/data/service/el1/public/AbilityManagerService/0/MissionInfo/mission_0_little.jpg");
}
/*
* Feature: MissionListManager
* Function: GetMissionSnapshotPath
* SubFunction: NA
* FunctionPoints: MissionDataStorage GetMissionSnapshotPath
* EnvConditions: NA
* CaseDescription: Verify GetMissionSnapshotPath
*/
HWTEST_F(MissionDataStorageTest, GetMissionSnapshotPath_002, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int missionId = 0;
bool isLowResolution = false;
std::string res = missionDataStorage->GetMissionSnapshotPath(missionId, isLowResolution);
EXPECT_EQ(res, "/data/service/el1/public/AbilityManagerService/0/MissionInfo/mission_0.jpg");
}
/*
* Feature: MissionListManager
* Function: SaveSnapshotFile
* SubFunction: NA
* FunctionPoints: MissionDataStorage SaveSnapshotFile
* EnvConditions: NA
* CaseDescription: Verify SaveSnapshotFile
*/
HWTEST_F(MissionDataStorageTest, SaveSnapshotFile_001, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int32_t missionId = 0;
MissionSnapshot missionSnapshot;
missionDataStorage->SaveSnapshotFile(missionId, missionSnapshot);
}
/*
* Feature: MissionListManager
* Function: SaveSnapshotFile
* SubFunction: NA
* FunctionPoints: MissionDataStorage SaveSnapshotFile
* EnvConditions: NA
* CaseDescription: Verify SaveSnapshotFile
*/
HWTEST_F(MissionDataStorageTest, SaveSnapshotFile_002, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int32_t missionId = 1;
MissionSnapshot missionSnapshot;
missionSnapshot.snapshot = std::make_shared<Media::PixelMap>();
missionDataStorage->SaveSnapshotFile(missionId, missionSnapshot);
}
/*
* Feature: MissionListManager
* Function: SaveSnapshotFile
* SubFunction: NA
* FunctionPoints: MissionDataStorage SaveSnapshotFile
* EnvConditions: NA
* CaseDescription: Verify SaveSnapshotFile
*/
HWTEST_F(MissionDataStorageTest, SaveSnapshotFile_003, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int32_t missionId = 0;
MissionSnapshot missionSnapshot;
missionSnapshot.isPrivate = true;
missionSnapshot.snapshot = std::make_shared<Media::PixelMap>();
missionDataStorage->SaveSnapshotFile(missionId, missionSnapshot);
}
/*
* Feature: MissionListManager
* Function: SaveSnapshotFile
* SubFunction: NA
* FunctionPoints: MissionDataStorage SaveSnapshotFile
* EnvConditions: NA
* CaseDescription: Verify SaveSnapshotFile
*/
HWTEST_F(MissionDataStorageTest, SaveSnapshotFile_004, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int32_t missionId = 0;
MissionSnapshot missionSnapshot;
missionSnapshot.snapshot = std::make_shared<Media::PixelMap>();
missionSnapshot.snapshot->imageInfo_.pixelFormat = Media::PixelFormat::RGB_565;
missionDataStorage->SaveSnapshotFile(missionId, missionSnapshot);
}
/*
* Feature: MissionListManager
* Function: SaveSnapshotFile
* SubFunction: NA
* FunctionPoints: MissionDataStorage SaveSnapshotFile
* EnvConditions: NA
* CaseDescription: Verify SaveSnapshotFile
*/
HWTEST_F(MissionDataStorageTest, SaveSnapshotFile_005, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int32_t missionId = 0;
MissionSnapshot missionSnapshot;
missionSnapshot.snapshot = std::make_shared<Media::PixelMap>();
missionSnapshot.snapshot->imageInfo_.pixelFormat = Media::PixelFormat::RGBA_8888;
missionDataStorage->SaveSnapshotFile(missionId, missionSnapshot);
}
/*
* Feature: MissionListManager
* Function: SaveSnapshotFile
* SubFunction: NA
* FunctionPoints: MissionDataStorage SaveSnapshotFile
* EnvConditions: NA
* CaseDescription: Verify SaveSnapshotFile
*/
HWTEST_F(MissionDataStorageTest, SaveSnapshotFile_006, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int32_t missionId = 0;
MissionSnapshot missionSnapshot;
missionSnapshot.snapshot = std::make_shared<Media::PixelMap>();
missionSnapshot.snapshot->imageInfo_.pixelFormat = Media::PixelFormat::RGB_888;
missionDataStorage->SaveSnapshotFile(missionId, missionSnapshot);
}
/*
* Feature: MissionListManager
* Function: SaveSnapshotFile
* SubFunction: NA
* FunctionPoints: MissionDataStorage SaveSnapshotFile
* EnvConditions: NA
* CaseDescription: Verify SaveSnapshotFile
*/
HWTEST_F(MissionDataStorageTest, SaveSnapshotFile_007, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int32_t missionId = 0;
MissionSnapshot missionSnapshot;
missionSnapshot.snapshot = std::make_shared<Media::PixelMap>();
missionDataStorage->SaveSnapshotFile(missionId, missionSnapshot);
}
/*
* Feature: MissionListManager
* Function: GetReducedPixelMap
* SubFunction: NA
* FunctionPoints: MissionDataStorage GetReducedPixelMap
* EnvConditions: NA
* CaseDescription: Verify GetReducedPixelMap
*/
HWTEST_F(MissionDataStorageTest, GetReducedPixelMap_001, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
std::shared_ptr<OHOS::Media::PixelMap> snapshot = nullptr;
auto res = missionDataStorage->GetReducedPixelMap(snapshot);
EXPECT_EQ(res, nullptr);
}
/*
* Feature: MissionListManager
* Function: GetReducedPixelMap
* SubFunction: NA
* FunctionPoints: MissionDataStorage GetReducedPixelMap
* EnvConditions: NA
* CaseDescription: Verify GetReducedPixelMap
*/
HWTEST_F(MissionDataStorageTest, GetReducedPixelMap_002, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
std::shared_ptr<OHOS::Media::PixelMap> snapshot = std::make_shared<Media::PixelMap>();
auto res = missionDataStorage->GetReducedPixelMap(snapshot);
EXPECT_EQ(res, nullptr);
}
/*
* Feature: MissionListManager
* Function: GetCachedSnapshot
* SubFunction: NA
* FunctionPoints: MissionDataStorage GetCachedSnapshot
* EnvConditions: NA
* CaseDescription: Verify GetCachedSnapshot
*/
HWTEST_F(MissionDataStorageTest, GetCachedSnapshot_001, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int32_t missionId = 0;
MissionSnapshot missionSnapshot;
bool res = missionDataStorage->GetCachedSnapshot(missionId, missionSnapshot);
EXPECT_FALSE(res);
}
/*
* Feature: MissionListManager
* Function: GetCachedSnapshot
* SubFunction: NA
* FunctionPoints: MissionDataStorage GetCachedSnapshot
* EnvConditions: NA
* CaseDescription: Verify GetCachedSnapshot
*/
HWTEST_F(MissionDataStorageTest, GetCachedSnapshot_002, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
missionDataStorage->cachedPixelMap_.insert({0, nullptr});
int32_t missionId = 0;
MissionSnapshot missionSnapshot;
bool res = missionDataStorage->GetCachedSnapshot(missionId, missionSnapshot);
EXPECT_TRUE(res);
}
/*
* Feature: MissionListManager
* Function: SaveCachedSnapshot
* SubFunction: NA
* FunctionPoints: MissionDataStorage SaveCachedSnapshot
* EnvConditions: NA
* CaseDescription: Verify SaveCachedSnapshot
*/
HWTEST_F(MissionDataStorageTest, SaveCachedSnapshot_001, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int32_t missionId = 0;
MissionSnapshot missionSnapshot;
missionSnapshot.snapshot = std::make_shared<Media::PixelMap>();
bool res = missionDataStorage->SaveCachedSnapshot(missionId, missionSnapshot);
EXPECT_TRUE(res);
}
/*
* Feature: MissionListManager
* Function: SaveCachedSnapshot
* SubFunction: NA
* FunctionPoints: MissionDataStorage SaveCachedSnapshot
* EnvConditions: NA
* CaseDescription: Verify SaveCachedSnapshot
*/
HWTEST_F(MissionDataStorageTest, SaveCachedSnapshot_002, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int32_t missionId = 0;
MissionSnapshot missionSnapshot;
missionDataStorage->SaveCachedSnapshot(missionId, missionSnapshot);
bool res = missionDataStorage->SaveCachedSnapshot(missionId, missionSnapshot);
EXPECT_FALSE(res);
}
/*
* Feature: MissionListManager
* Function: DeleteCachedSnapshot
* SubFunction: NA
* FunctionPoints: MissionDataStorage DeleteCachedSnapshot
* EnvConditions: NA
* CaseDescription: Verify DeleteCachedSnapshot
*/
HWTEST_F(MissionDataStorageTest, DeleteCachedSnapshot_001, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int32_t missionId = 0;
bool res = missionDataStorage->DeleteCachedSnapshot(missionId);
EXPECT_FALSE(res);
}
/*
* Feature: MissionListManager
* Function: DeleteCachedSnapshot
* SubFunction: NA
* FunctionPoints: MissionDataStorage DeleteCachedSnapshot
* EnvConditions: NA
* CaseDescription: Verify DeleteCachedSnapshot
*/
HWTEST_F(MissionDataStorageTest, DeleteCachedSnapshot_002, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
missionDataStorage->cachedPixelMap_.insert({0, nullptr});
int32_t missionId = 0;
bool res = missionDataStorage->DeleteCachedSnapshot(missionId);
EXPECT_TRUE(res);
}
/*
* Feature: MissionListManager
* Function: GetSnapshot
* SubFunction: NA
* FunctionPoints: MissionDataStorage GetSnapshot
* EnvConditions: NA
* CaseDescription: Verify GetSnapshot
*/
HWTEST_F(MissionDataStorageTest, GetSnapshot_001, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int32_t missionId = 0;
bool isLowResolution = true;
std::shared_ptr<Media::PixelMap> res = missionDataStorage->GetSnapshot(missionId, isLowResolution);
EXPECT_EQ(res, nullptr);
}
/*
* Feature: MissionListManager
* Function: GetPixelMap
* SubFunction: NA
* FunctionPoints: MissionDataStorage GetPixelMap
* EnvConditions: NA
* CaseDescription: Verify GetPixelMap
*/
HWTEST_F(MissionDataStorageTest, GetPixelMap_001, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int32_t missionId = 0;
bool isLowResolution = true;
std::unique_ptr<Media::PixelMap> res = missionDataStorage->GetPixelMap(missionId, isLowResolution);
EXPECT_EQ(res, nullptr);
}
/*
* Feature: MissionListManager
* Function: GetPixelMap
* SubFunction: NA
* FunctionPoints: MissionDataStorage GetPixelMap
* EnvConditions: NA
* CaseDescription: Verify GetPixelMap
*/
HWTEST_F(MissionDataStorageTest, GetPixelMap_002, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int32_t missionId = 100;
bool isLowResolution = false;
std::unique_ptr<Media::PixelMap> res = missionDataStorage->GetPixelMap(missionId, isLowResolution);
EXPECT_EQ(res, nullptr);
}
/*
* Feature: MissionListManager
* Function: WriteRgb888ToJpeg
* SubFunction: NA
* FunctionPoints: MissionDataStorage WriteRgb888ToJpeg
* EnvConditions: NA
* CaseDescription: Verify WriteRgb888ToJpeg
*/
HWTEST_F(MissionDataStorageTest, WriteRgb888ToJpeg_001, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
char* fileName;
uint32_t width = 0;
uint32_t height = 0;
uint8_t* data;
missionDataStorage->WriteRgb888ToJpeg(fileName, width, height, data);
}
/*
* Feature: MissionListManager
* Function: WriteRgb888ToJpeg
* SubFunction: NA
* FunctionPoints: MissionDataStorage WriteRgb888ToJpeg
* EnvConditions: NA
* CaseDescription: Verify WriteRgb888ToJpeg
*/
HWTEST_F(MissionDataStorageTest, WriteRgb888ToJpeg_002, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
char* fileName;
uint32_t width = 0;
uint32_t height = 1;
uint8_t* data = new uint8_t[height];
missionDataStorage->WriteRgb888ToJpeg(fileName, width, height, data);
}
/*
* Feature: MissionListManager
* Function: RGB565ToRGB888
* SubFunction: NA
* FunctionPoints: MissionDataStorage RGB565ToRGB888
* EnvConditions: NA
* CaseDescription: Verify RGB565ToRGB888
*/
HWTEST_F(MissionDataStorageTest, RGB565ToRGB888_001, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
uint16_t* rgb565Buf = nullptr;
int32_t rgb565Size = 0;
uint8_t* rgb888Buf = nullptr;
int32_t rgb888Size = 0;
bool res = missionDataStorage->RGB565ToRGB888(rgb565Buf, rgb565Size, rgb888Buf, rgb888Size);
EXPECT_FALSE(res);
}
/*
* Feature: MissionListManager
* Function: RGB565ToRGB888
* SubFunction: NA
* FunctionPoints: MissionDataStorage RGB565ToRGB888
* EnvConditions: NA
* CaseDescription: Verify RGB565ToRGB888
*/
HWTEST_F(MissionDataStorageTest, RGB565ToRGB888_002, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int32_t rgb565Size = 1;
uint16_t* rgb565Buf = new uint16_t[rgb565Size];
int32_t rgb888Size = 1;
uint8_t* rgb888Buf = new uint8_t[rgb888Size];
bool res = missionDataStorage->RGB565ToRGB888(rgb565Buf, rgb565Size, rgb888Buf, rgb888Size);
EXPECT_FALSE(res);
}
/*
* Feature: MissionListManager
* Function: RGB565ToRGB888
* SubFunction: NA
* FunctionPoints: MissionDataStorage RGB565ToRGB888
* EnvConditions: NA
* CaseDescription: Verify RGB565ToRGB888
*/
HWTEST_F(MissionDataStorageTest, RGB565ToRGB888_003, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int32_t rgb565Size = 1;
uint16_t* rgb565Buf = new uint16_t[rgb565Size];
int32_t rgb888Size = 10;
uint8_t* rgb888Buf = new uint8_t[rgb888Size];
bool res = missionDataStorage->RGB565ToRGB888(rgb565Buf, rgb565Size, rgb888Buf, rgb888Size);
EXPECT_TRUE(res);
}
/*
* Feature: MissionListManager
* Function: RGBA8888ToRGB888
* SubFunction: NA
* FunctionPoints: MissionDataStorage RGBA8888ToRGB888
* EnvConditions: NA
* CaseDescription: Verify RGBA8888ToRGB888
*/
HWTEST_F(MissionDataStorageTest, RGBA8888ToRGB888_001, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
uint32_t* rgba8888Buf = nullptr;
int32_t rgba8888Size = 0;
uint8_t* rgb888Buf = nullptr;
int32_t rgb888Size = 0;
bool res = missionDataStorage->RGBA8888ToRGB888(rgba8888Buf, rgba8888Size, rgb888Buf, rgb888Size);
EXPECT_FALSE(res);
}
/*
* Feature: MissionListManager
* Function: RGBA8888ToRGB888
* SubFunction: NA
* FunctionPoints: MissionDataStorage RGBA8888ToRGB888
* EnvConditions: NA
* CaseDescription: Verify RGBA8888ToRGB888
*/
HWTEST_F(MissionDataStorageTest, RGBA8888ToRGB888_002, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int32_t rgba8888Size = 1;
uint32_t* rgba8888Buf = new uint32_t[rgba8888Size];
int32_t rgb888Size = 1;
uint8_t* rgb888Buf = new uint8_t[rgb888Size];
bool res = missionDataStorage->RGBA8888ToRGB888(rgba8888Buf, rgba8888Size, rgb888Buf, rgb888Size);
EXPECT_FALSE(res);
}
/*
* Feature: MissionListManager
* Function: RGBA8888ToRGB888
* SubFunction: NA
* FunctionPoints: MissionDataStorage RGBA8888ToRGB888
* EnvConditions: NA
* CaseDescription: Verify RGBA8888ToRGB888
*/
HWTEST_F(MissionDataStorageTest, RGBA8888ToRGB888_003, TestSize.Level1)
{
auto missionDataStorage = std::make_shared<MissionDataStorage>();
int32_t rgba8888Size = 1;
uint32_t* rgba8888Buf = new uint32_t[rgba8888Size];
int32_t rgb888Size = 10;
uint8_t* rgb888Buf = new uint8_t[rgb888Size];
bool res = missionDataStorage->RGBA8888ToRGB888(rgba8888Buf, rgba8888Size, rgb888Buf, rgb888Size);
EXPECT_TRUE(res);
}
} // namespace AAFwk
} // namespace OHOS
+71
View File
@@ -0,0 +1,71 @@
# Copyright (c) 2022 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("//foundation/ability/ability_runtime/ability_runtime.gni")
module_output_path = "ability_runtime/abilitymgr"
ohos_unittest("mission_info_mgr_test") {
module_out_path = module_output_path
include_dirs = [
"${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/system_ability_mock",
"${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include",
]
sources = [
"${ability_runtime_services_path}/common/src/permission_verification.cpp",
"${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp",
"mission_info_mgr_test.cpp", # add mock file
]
configs = [
"${ability_runtime_services_path}/abilitymgr:abilityms_config",
"${ability_runtime_test_path}/mock/services_abilitymgr_test:aafwk_mock_config",
]
cflags = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
deps = [
"${ability_runtime_native_path}/ability/native:abilitykit_native",
"${ability_runtime_services_path}/abilitymgr:abilityms",
"${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/aakit:aakit_mock",
"${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/appexecfwk_core:appexecfwk_appmgr_mock",
"${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/appexecfwk_core:appexecfwk_bundlemgr_mock",
"${ability_runtime_test_path}/unittest:abilityms_test_source",
"//third_party/googletest:gtest_main",
]
external_deps = [
"ability_base:want",
"ability_base:zuri",
"access_token:libaccesstoken_sdk",
"c_utils:utils",
"common_event_service:cesfwk_innerkits",
"eventhandler:libeventhandler",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
if (background_task_mgr_continuous_task_enable) {
external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ]
}
}
group("unittest") {
testonly = true
deps = [ ":mission_info_mgr_test" ]
}
@@ -0,0 +1,200 @@
/*
* Copyright (c) 2022 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>
#define private public
#include "mission_info_mgr.h"
#undef private
using namespace testing::ext;
using namespace OHOS::AppExecFwk;
namespace OHOS {
namespace AAFwk {
class MissionInfoMgrTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void MissionInfoMgrTest::SetUpTestCase(void)
{}
void MissionInfoMgrTest::TearDownTestCase(void)
{}
void MissionInfoMgrTest::SetUp(void)
{}
void MissionInfoMgrTest::TearDown(void)
{}
/*
* Feature: MissionInfoMgr
* Function: GenerateMissionId
* SubFunction: NA
* FunctionPoints: MissionDataStorage GenerateMissionId
* EnvConditions: NA
* CaseDescription: Verify GenerateMissionId
*/
HWTEST_F(MissionInfoMgrTest, GenerateMissionId_001, TestSize.Level1)
{
auto missionInfoMgr = std::make_shared<MissionInfoMgr>();
missionInfoMgr->currentMissionId_ = MAX_MISSION_ID;
int32_t missionId = 1;
bool res = missionInfoMgr->GenerateMissionId(missionId);
EXPECT_TRUE(res);
}
/*
* Feature: MissionInfoMgr
* Function: GenerateMissionId
* SubFunction: NA
* FunctionPoints: MissionDataStorage GenerateMissionId
* EnvConditions: NA
* CaseDescription: Verify GenerateMissionId
*/
HWTEST_F(MissionInfoMgrTest, GenerateMissionId_002, TestSize.Level1)
{
auto missionInfoMgr = std::make_shared<MissionInfoMgr>();
missionInfoMgr->missionIdMap_[missionInfoMgr->currentMissionId_] = true;
int32_t missionId = 1;
bool res = missionInfoMgr->GenerateMissionId(missionId);
EXPECT_TRUE(res);
}
/*
* Feature: MissionInfoMgr
* Function: AddMissionInfo
* SubFunction: NA
* FunctionPoints: MissionDataStorage AddMissionInfo
* EnvConditions: NA
* CaseDescription: Verify AddMissionInfo
*/
HWTEST_F(MissionInfoMgrTest, AddMissionInfo_001, TestSize.Level1)
{
auto missionInfoMgr = std::make_shared<MissionInfoMgr>();
missionInfoMgr->missionIdMap_[1] = true;
InnerMissionInfo missionInfo;
missionInfo.missionInfo.id = 1;
bool res = missionInfoMgr->AddMissionInfo(missionInfo);
EXPECT_FALSE(res);
}
/*
* Feature: MissionListManager
* Function: AddMissionInfo
* SubFunction: NA
* FunctionPoints: MissionDataStorage AddMissionInfo
* EnvConditions: NA
* CaseDescription: Verify AddMissionInfo
*/
HWTEST_F(MissionInfoMgrTest, AddMissionInfo_002, TestSize.Level1)
{
auto missionInfoMgr = std::make_shared<MissionInfoMgr>();
int userId = 0;
missionInfoMgr->Init(userId);
InnerMissionInfo missionInfo;
missionInfo.missionInfo.time = 'a';
auto listIter = missionInfoMgr->missionInfoList_.begin();
missionInfoMgr->missionInfoList_.insert(listIter, missionInfo);
missionInfo.missionInfo.time = 'b';
missionInfo.missionInfo.id = 1;
bool res = missionInfoMgr->AddMissionInfo(missionInfo);
EXPECT_FALSE(res);
}
/*
* Feature: MissionInfoMgr
* Function: AddMissionInfo
* SubFunction: NA
* FunctionPoints: MissionDataStorage AddMissionInfo
* EnvConditions: NA
* CaseDescription: Verify AddMissionInfo
*/
HWTEST_F(MissionInfoMgrTest, AddMissionInfo_003, TestSize.Level1)
{
auto missionInfoMgr = std::make_shared<MissionInfoMgr>();
int userId = 0;
missionInfoMgr->Init(userId);
InnerMissionInfo missionInfo;
InnerMissionInfo missionInfo2;
missionInfo.missionInfo.time = 'a';
missionInfo2.missionInfo.time = 'b';
auto listIter = missionInfoMgr->missionInfoList_.begin();
missionInfoMgr->missionInfoList_.insert(listIter, missionInfo2);
missionInfo.missionInfo.id = 1;
bool res = missionInfoMgr->AddMissionInfo(missionInfo);
EXPECT_FALSE(res);
}
/*
* Feature: MissionInfoMgr
* Function: UpdateMissionInfo
* SubFunction: NA
* FunctionPoints: MissionDataStorage UpdateMissionInfo
* EnvConditions: NA
* CaseDescription: Verify UpdateMissionInfo
*/
HWTEST_F(MissionInfoMgrTest, UpdateMissionInfo_001, TestSize.Level1)
{
auto missionInfoMgr = std::make_shared<MissionInfoMgr>();
InnerMissionInfo missionInfo;
missionInfo.missionInfo.id = 1;
bool res = missionInfoMgr->UpdateMissionInfo(missionInfo);
EXPECT_FALSE(res);
}
/*
* Feature: MissionInfoMgr
* Function: UpdateMissionInfo
* SubFunction: NA
* FunctionPoints: MissionDataStorage UpdateMissionInfo
* EnvConditions: NA
* CaseDescription: Verify UpdateMissionInfo
*/
HWTEST_F(MissionInfoMgrTest, UpdateMissionInfo_002, TestSize.Level1)
{
auto missionInfoMgr = std::make_shared<MissionInfoMgr>();
missionInfoMgr->missionIdMap_[1] = false;
InnerMissionInfo missionInfo;
missionInfo.missionInfo.id = 1;
bool res = missionInfoMgr->UpdateMissionInfo(missionInfo);
EXPECT_FALSE(res);
}
/*
* Feature: MissionInfoMgr
* Function: UpdateMissionInfo
* SubFunction: NA
* FunctionPoints: MissionDataStorage UpdateMissionInfo
* EnvConditions: NA
* CaseDescription: Verify UpdateMissionInfo
*/
HWTEST_F(MissionInfoMgrTest, UpdateMissionInfo_003, TestSize.Level1)
{
auto missionInfoMgr = std::make_shared<MissionInfoMgr>();
int userId = 0;
missionInfoMgr->Init(userId);
missionInfoMgr->missionIdMap_[1] = true;
InnerMissionInfo missionInfo;
missionInfo.missionInfo.id = 1;
auto listIter = missionInfoMgr->missionInfoList_.begin();
missionInfoMgr->missionInfoList_.insert(listIter, missionInfo);
bool res = missionInfoMgr->UpdateMissionInfo(missionInfo);
EXPECT_TRUE(res);
}
} // namespace AAFwk
} // namespace OHOS
+56
View File
@@ -0,0 +1,56 @@
# Copyright (c) 2021-2022 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("//foundation/ability/ability_runtime/ability_runtime.gni")
module_output_path = "ability_runtime/abilitymgr"
ohos_unittest("mission_listener_stub_test") {
module_out_path = module_output_path
include_dirs = []
sources = [ "mission_listener_stub_test.cpp" ]
configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ]
cflags = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
deps = [
"${ability_runtime_services_path}/abilitymgr:abilityms",
"//third_party/googletest:gmock_main",
"//third_party/googletest:gtest_main",
]
external_deps = [
"ability_base:want",
"ability_base:zuri",
"access_token:libaccesstoken_sdk",
"c_utils:utils",
"eventhandler:libeventhandler",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
if (background_task_mgr_continuous_task_enable) {
external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ]
}
}
group("unittest") {
testonly = true
deps = [ ":mission_listener_stub_test" ]
}
@@ -0,0 +1,223 @@
/*
* Copyright (c) 2021 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 "mock_mission_listener_stub.h"
using namespace testing::ext;
using namespace testing;
namespace OHOS {
namespace AAFwk {
class MissionListenerStubTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
void WriteInterfaceToken(MessageParcel &data);
sptr<MockMissionListenerStub> stub_ {nullptr};
};
void MissionListenerStubTest::SetUpTestCase(void)
{}
void MissionListenerStubTest::TearDownTestCase(void)
{}
void MissionListenerStubTest::SetUp()
{
stub_ = new MockMissionListenerStub();
}
void MissionListenerStubTest::TearDown()
{}
void MissionListenerStubTest::WriteInterfaceToken(MessageParcel &data)
{
data.WriteInterfaceToken(MockMissionListenerStub::GetDescriptor());
}
/*
* Feature: MissionListenerStub
* Function: OnRemoteRequest
* SubFunction: NA
* FunctionPoints: MissionListenerStub OnRemoteRequest
* EnvConditions: The code which not exist
* CaseDescription: Verify that on remote request is abnormal
*/
HWTEST_F(MissionListenerStubTest, MissionListenerStubTest_OnRemoteRequest_001, TestSize.Level1)
{
MessageParcel data;
MessageParcel reply;
MessageOption option;
WriteInterfaceToken(data);
int res = stub_->OnRemoteRequest(10000, data, reply, option);
EXPECT_EQ(res, IPC_STUB_UNKNOW_TRANS_ERR);
}
/*
* Feature: MissionListenerStub
* Function: OnRemoteRequest
* SubFunction: NA
* FunctionPoints: MissionListenerStub OnRemoteRequest
* EnvConditions: Description abnormal
* CaseDescription: Verify that on remote request is abnormal
*/
HWTEST_F(MissionListenerStubTest, MissionListenerStubTest_OnRemoteRequest_002, TestSize.Level1)
{
MessageParcel data;
MessageParcel reply;
MessageOption option;
int res = stub_->OnRemoteRequest(IMissionListener::ON_MISSION_CREATED, data, reply, option);
EXPECT_EQ(res, ERR_INVALID_STATE);
}
/*
* Feature: MissionListenerStub
* Function: OnRemoteRequest
* SubFunction: NA
* FunctionPoints: MissionListenerStub OnRemoteRequest
* EnvConditions: Code is ON_MISSION_CREATED
* CaseDescription: Verify that on remote request is normal
*/
HWTEST_F(MissionListenerStubTest, MissionListenerStubTest_OnRemoteRequest_003, TestSize.Level1)
{
MessageParcel data;
MessageParcel reply;
MessageOption option;
WriteInterfaceToken(data);
EXPECT_CALL(*stub_, OnMissionCreated(_)).Times(1).WillOnce(Return());
int res = stub_->OnRemoteRequest(IMissionListener::ON_MISSION_CREATED, data, reply, option);
EXPECT_EQ(res, NO_ERROR);
}
/*
* Feature: MissionListenerStub
* Function: OnMissionCreatedInner
* SubFunction: NA
* FunctionPoints: MissionListenerStub OnMissionCreatedInner
* EnvConditions: Description normal
* CaseDescription: Verify that on mission created inner is normal
*/
HWTEST_F(MissionListenerStubTest, MissionListenerStubTest_OnMissionCreatedInner_001, TestSize.Level1)
{
MessageParcel data;
MessageParcel reply;
EXPECT_CALL(*stub_, OnMissionCreated(_)).Times(1).WillOnce(Return());
int res = stub_->OnMissionCreatedInner(data, reply);
EXPECT_EQ(res, NO_ERROR);
}
/*
* Feature: MissionListenerStub
* Function: OnMissionDestroyedInner
* SubFunction: NA
* FunctionPoints: MissionListenerStub OnMissionDestroyedInner
* EnvConditions: Description normal
* CaseDescription: Verify that on mission destroyed inner is normal
*/
HWTEST_F(MissionListenerStubTest, MissionListenerStubTest_OnMissionDestroyedInner_001, TestSize.Level1)
{
MessageParcel data;
MessageParcel reply;
EXPECT_CALL(*stub_, OnMissionDestroyed(_)).Times(1).WillOnce(Return());
int res = stub_->OnMissionDestroyedInner(data, reply);
EXPECT_EQ(res, NO_ERROR);
}
/*
* Feature: MissionListenerStub
* Function: OnMissionSnapshotChangedInner
* SubFunction: NA
* FunctionPoints: MissionListenerStub OnMissionSnapshotChangedInner
* EnvConditions: Description normal
* CaseDescription: Verify that on mission snapshot changed inner is normal
*/
HWTEST_F(MissionListenerStubTest, MissionListenerStubTest_OnMissionSnapshotChangedInner_001, TestSize.Level1)
{
MessageParcel data;
MessageParcel reply;
EXPECT_CALL(*stub_, OnMissionSnapshotChanged(_)).Times(1).WillOnce(Return());
int res = stub_->OnMissionSnapshotChangedInner(data, reply);
EXPECT_EQ(res, NO_ERROR);
}
/*
* Feature: MissionListenerStub
* Function: OnMissionMovedToFrontInner
* SubFunction: NA
* FunctionPoints: MissionListenerStub OnMissionMovedToFrontInner
* EnvConditions: Description normal
* CaseDescription: Verify that on mission moved to front inner is normal
*/
HWTEST_F(MissionListenerStubTest, MissionListenerStubTest_OnMissionMovedToFrontInner_001, TestSize.Level1)
{
MessageParcel data;
MessageParcel reply;
EXPECT_CALL(*stub_, OnMissionMovedToFront(_)).Times(1).WillOnce(Return());
int res = stub_->OnMissionMovedToFrontInner(data, reply);
EXPECT_EQ(res, NO_ERROR);
}
/*
* Feature: MissionListenerStub
* Function: OnMissionIconUpdatedInner
* SubFunction: NA
* FunctionPoints: MissionListenerStub OnMissionIconUpdatedInner
* EnvConditions: Description normal
* CaseDescription: Verify that on mission icon updated inner is normal
*/
HWTEST_F(MissionListenerStubTest, MissionListenerStubTest_OnMissionIconUpdatedInner_001, TestSize.Level1)
{
MessageParcel data;
MessageParcel reply;
EXPECT_CALL(*stub_, OnMissionIconUpdated(_, _)).Times(1).WillOnce(Return());
int res = stub_->OnMissionIconUpdatedInner(data, reply);
EXPECT_EQ(res, NO_ERROR);
}
/*
* Feature: MissionListenerStub
* Function: OnMissionClosedInner
* SubFunction: NA
* FunctionPoints: MissionListenerStub OnMissionClosedInner
* EnvConditions: Description normal
* CaseDescription: Verify that on mission closed inner is normal
*/
HWTEST_F(MissionListenerStubTest, MissionListenerStubTest_OnMissionClosedInner_001, TestSize.Level1)
{
MessageParcel data;
MessageParcel reply;
EXPECT_CALL(*stub_, OnMissionClosed(_)).Times(1).WillOnce(Return());
int res = stub_->OnMissionClosedInner(data, reply);
EXPECT_EQ(res, NO_ERROR);
}
/*
* Feature: MissionListenerStub
* Function: OnMissionLabelUpdatedInner
* SubFunction: NA
* FunctionPoints: MissionListenerStub OnMissionLabelUpdatedInner
* EnvConditions: Description normal
* CaseDescription: Verify that on mission label updated inner is normal
*/
HWTEST_F(MissionListenerStubTest, MissionListenerStubTest_OnMissionLabelUpdatedInner_001, TestSize.Level1)
{
MessageParcel data;
MessageParcel reply;
EXPECT_CALL(*stub_, OnMissionLabelUpdated(_)).Times(1).WillOnce(Return());
int res = stub_->OnMissionLabelUpdatedInner(data, reply);
EXPECT_EQ(res, NO_ERROR);
}
} // namespace AAFwk
} // namespace OHOS
@@ -0,0 +1,43 @@
/*
* Copyright (c) 2021 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 UNITTEST_OHOS_ABILITY_RUNTIME_MOCK_MISSION_LISTENER_STUB_H
#define UNITTEST_OHOS_ABILITY_RUNTIME_MOCK_MISSION_LISTENER_STUB_H
#include <gmock/gmock.h>
#define private public
#include "mission_listener_stub.h"
#undef private
namespace OHOS {
namespace AAFwk {
class MockMissionListenerStub : public MissionListenerStub {
public:
MockMissionListenerStub() = default;
virtual ~MockMissionListenerStub() = default;
MOCK_METHOD1(OnMissionCreated, void(int32_t missionId));
MOCK_METHOD1(OnMissionDestroyed, void(int32_t missionId));
MOCK_METHOD1(OnMissionSnapshotChanged, void(int32_t missionId));
MOCK_METHOD1(OnMissionMovedToFront, void(int32_t missionId));
MOCK_METHOD2(OnMissionIconUpdated, void(int32_t missionId, const std::shared_ptr<OHOS::Media::PixelMap> &icon));
MOCK_METHOD1(OnMissionClosed, void(int32_t missionId));
MOCK_METHOD1(OnMissionLabelUpdated, void(int32_t missionId));
};
} // namespace AAFwk
} // namespace OHOS
#endif // UNITTEST_OHOS_ABILITY_RUNTIME_MOCK_MISSION_LISTENER_STUB_H
+252 -14
View File
@@ -84,7 +84,7 @@ AbilityRequest MissionTest::GenerateAbilityRequest(const std::string &deviceName
*/
HWTEST_F(MissionTest, mission_set_mission_list_001, TestSize.Level1)
{
auto mission = std::make_shared<Mission>(nullptr, "");
auto mission = std::make_shared<Mission>(1, nullptr);
EXPECT_EQ(nullptr, mission->GetMissionList());
}
@@ -98,7 +98,7 @@ HWTEST_F(MissionTest, mission_set_mission_list_001, TestSize.Level1)
*/
HWTEST_F(MissionTest, mission_set_mission_list_002, TestSize.Level1)
{
auto mission = std::make_shared<Mission>(nullptr, "");
auto mission = std::make_shared<Mission>(1, nullptr);
mission->SetMissionList(nullptr);
EXPECT_EQ(nullptr, mission->GetMissionList());
}
@@ -113,7 +113,7 @@ HWTEST_F(MissionTest, mission_set_mission_list_002, TestSize.Level1)
*/
HWTEST_F(MissionTest, mission_set_mission_list_003, TestSize.Level1)
{
auto mission = std::make_shared<Mission>(nullptr, "");
auto mission = std::make_shared<Mission>(1, nullptr);
auto missionList = std::make_shared<MissionList>();
mission->SetMissionList(missionList);
EXPECT_EQ(missionList, mission->GetMissionList());
@@ -129,7 +129,7 @@ HWTEST_F(MissionTest, mission_set_mission_list_003, TestSize.Level1)
*/
HWTEST_F(MissionTest, mission_set_mission_list_004, TestSize.Level1)
{
auto mission = std::make_shared<Mission>(nullptr, "");
auto mission = std::make_shared<Mission>(1, nullptr);
auto missionList = std::make_shared<MissionList>();
mission->SetMissionList(missionList);
auto missionList1 = std::make_shared<MissionList>();
@@ -147,7 +147,7 @@ HWTEST_F(MissionTest, mission_set_mission_list_004, TestSize.Level1)
*/
HWTEST_F(MissionTest, mission_is_singleton_001, TestSize.Level1)
{
auto mission = std::make_shared<Mission>(nullptr, "");
auto mission = std::make_shared<Mission>(1, nullptr);
EXPECT_FALSE(mission->IsSingletonAbility());
}
@@ -166,7 +166,7 @@ HWTEST_F(MissionTest, mission_is_singleton_002, TestSize.Level1)
Want want;
AppExecFwk::ApplicationInfo applicationInfo;
std::shared_ptr<AbilityRecord> abilityRecord = std::make_shared<AbilityRecord>(want, abilityInfo, applicationInfo);
auto mission = std::make_shared<Mission>(abilityRecord);
auto mission = std::make_shared<Mission>(0, abilityRecord);
EXPECT_FALSE(mission->IsSingletonAbility());
}
@@ -185,7 +185,7 @@ HWTEST_F(MissionTest, mission_is_singleton_003, TestSize.Level1)
Want want;
AppExecFwk::ApplicationInfo applicationInfo;
std::shared_ptr<AbilityRecord> abilityRecord = std::make_shared<AbilityRecord>(want, abilityInfo, applicationInfo);
auto mission = std::make_shared<Mission>(abilityRecord);
auto mission = std::make_shared<Mission>(0, abilityRecord);
EXPECT_TRUE(mission->IsSingletonAbility());
}
@@ -204,7 +204,7 @@ HWTEST_F(MissionTest, mission_get_mission_name_001, TestSize.Level1)
Want want;
AppExecFwk::ApplicationInfo applicationInfo;
std::shared_ptr<AbilityRecord> abilityRecord = std::make_shared<AbilityRecord>(want, abilityInfo, applicationInfo);
auto mission = std::make_shared<Mission>(abilityRecord);
auto mission = std::make_shared<Mission>(0, abilityRecord);
EXPECT_TRUE("" == mission->GetMissionName());
}
@@ -223,7 +223,7 @@ HWTEST_F(MissionTest, mission_get_mission_name_002, TestSize.Level1)
Want want;
AppExecFwk::ApplicationInfo applicationInfo;
std::shared_ptr<AbilityRecord> abilityRecord = std::make_shared<AbilityRecord>(want, abilityInfo, applicationInfo);
auto mission = std::make_shared<Mission>(abilityRecord, "");
auto mission = std::make_shared<Mission>(0, abilityRecord, "");
EXPECT_TRUE("" == mission->GetMissionName());
}
@@ -242,7 +242,7 @@ HWTEST_F(MissionTest, mission_get_mission_name_003, TestSize.Level1)
Want want;
AppExecFwk::ApplicationInfo applicationInfo;
std::shared_ptr<AbilityRecord> abilityRecord = std::make_shared<AbilityRecord>(want, abilityInfo, applicationInfo);
auto mission = std::make_shared<Mission>(abilityRecord, "name1");
auto mission = std::make_shared<Mission>(0, abilityRecord, "name1");
EXPECT_TRUE("name1" == mission->GetMissionName());
}
@@ -261,7 +261,7 @@ HWTEST_F(MissionTest, mission_locked_state_001, TestSize.Level1)
Want want;
AppExecFwk::ApplicationInfo applicationInfo;
std::shared_ptr<AbilityRecord> abilityRecord = std::make_shared<AbilityRecord>(want, abilityInfo, applicationInfo);
auto mission = std::make_shared<Mission>(abilityRecord, "name1");
auto mission = std::make_shared<Mission>(0, abilityRecord, "name1");
EXPECT_FALSE(mission->IsLockedState());
}
@@ -280,7 +280,7 @@ HWTEST_F(MissionTest, mission_locked_state_002, TestSize.Level1)
Want want;
AppExecFwk::ApplicationInfo applicationInfo;
std::shared_ptr<AbilityRecord> abilityRecord = std::make_shared<AbilityRecord>(want, abilityInfo, applicationInfo);
auto mission = std::make_shared<Mission>(abilityRecord, "name1");
auto mission = std::make_shared<Mission>(0, abilityRecord, "name1");
mission->SetLockedState(true);
EXPECT_TRUE(mission->IsLockedState());
}
@@ -300,11 +300,249 @@ HWTEST_F(MissionTest, mission_locked_state_003, TestSize.Level1)
Want want;
AppExecFwk::ApplicationInfo applicationInfo;
std::shared_ptr<AbilityRecord> abilityRecord = std::make_shared<AbilityRecord>(want, abilityInfo, applicationInfo);
auto mission = std::make_shared<Mission>(abilityRecord, "name1");
auto mission = std::make_shared<Mission>(0, abilityRecord, "name1");
mission->SetLockedState(true);
EXPECT_TRUE(mission->IsLockedState());
mission->SetLockedState(false);
EXPECT_FALSE(mission->IsLockedState());
}
/*
* Feature: Mission
* Function: copy constructor
* SubFunction: NA
* FunctionPoints: Mission copy constructor
* EnvConditions: NA
* CaseDescription: deep copy a object, with same content but different pointer address
*/
HWTEST_F(MissionTest, mission_copy_constructor_001, TestSize.Level1)
{
AppExecFwk::AbilityInfo abilityInfo;
abilityInfo.launchMode = AppExecFwk::LaunchMode::SINGLETON;
Want want;
AppExecFwk::ApplicationInfo applicationInfo;
std::shared_ptr<AbilityRecord> abilityRecord = std::make_shared<AbilityRecord>(want, abilityInfo, applicationInfo);
auto mission1 = std::make_shared<Mission>(0, abilityRecord, "name1");
auto mission2= std::make_shared<Mission>(mission1);
EXPECT_NE(mission1, mission2);
EXPECT_NE(&(mission1->missionId_), &(mission2->missionId_));
EXPECT_NE(&(mission1->startMethod_), &(mission2->startMethod_));
EXPECT_NE(&(mission1->abilityRecord_), &(mission2->abilityRecord_));
EXPECT_NE(&(mission1->missionName_), &(mission2->missionName_));
EXPECT_EQ(mission1->missionId_, mission2->missionId_);
EXPECT_EQ(mission1->startMethod_, mission2->startMethod_);
EXPECT_EQ(mission1->abilityRecord_, mission2->abilityRecord_);
EXPECT_EQ(mission1->missionName_, mission2->missionName_);
}
/*
* Feature: Mission
* Function: IsSpecifiedAbility
* SubFunction: NA
* FunctionPoints: Mission IsSpecifiedAbility
* EnvConditions: NA
* CaseDescription: Verify IsSpecifiedAbility
*/
HWTEST_F(MissionTest, mission_is_specified_001, TestSize.Level1)
{
auto mission = std::make_shared<Mission>(1, nullptr);
EXPECT_FALSE(mission->IsSpecifiedAbility());
}
/*
* Feature: Mission
* Function: IsSpecifiedAbility
* SubFunction: NA
* FunctionPoints: Mission IsSpecifiedAbility
* EnvConditions: NA
* CaseDescription: Verify IsSpecifiedAbility
*/
HWTEST_F(MissionTest, mission_is_specified_002, TestSize.Level1)
{
AppExecFwk::AbilityInfo abilityInfo;
abilityInfo.launchMode = AppExecFwk::LaunchMode::STANDARD;
Want want;
AppExecFwk::ApplicationInfo applicationInfo;
std::shared_ptr<AbilityRecord> abilityRecord = std::make_shared<AbilityRecord>(want, abilityInfo, applicationInfo);
auto mission = std::make_shared<Mission>(0, abilityRecord);
EXPECT_FALSE(mission->IsSpecifiedAbility());
}
/*
* Feature: Mission
* Function: IsSpecifiedAbility
* SubFunction: NA
* FunctionPoints: Mission IsSpecifiedAbility
* EnvConditions: NA
* CaseDescription: Verify IsSpecifiedAbility
*/
HWTEST_F(MissionTest, mission_is_specified_003, TestSize.Level1)
{
AppExecFwk::AbilityInfo abilityInfo;
abilityInfo.launchMode = AppExecFwk::LaunchMode::SPECIFIED;
Want want;
AppExecFwk::ApplicationInfo applicationInfo;
std::shared_ptr<AbilityRecord> abilityRecord = std::make_shared<AbilityRecord>(want, abilityInfo, applicationInfo);
auto mission = std::make_shared<Mission>(0, abilityRecord);
EXPECT_TRUE(mission->IsSpecifiedAbility());
}
/*
* Feature: Mission
* Function: SetSpecifiedFlag and GetSpecifiedFlag
* SubFunction: NA
* FunctionPoints: Mission SetSpecifiedFlag
* EnvConditions: NA
* CaseDescription: Verify SetSpecifiedFlag
*/
HWTEST_F(MissionTest, mission_set_specified_flag_001, TestSize.Level1)
{
auto mission = std::make_shared<Mission>(1, nullptr);
EXPECT_EQ("", mission->GetSpecifiedFlag());
}
/*
* Feature: Mission
* Function: SetSpecifiedFlag and GetSpecifiedFlag
* SubFunction: NA
* FunctionPoints: Mission SetSpecifiedFlag
* EnvConditions: NA
* CaseDescription: Verify SetSpecifiedFlag
*/
HWTEST_F(MissionTest, mission_set_specified_flag_002, TestSize.Level1)
{
auto mission = std::make_shared<Mission>(1, nullptr);
mission->SetSpecifiedFlag("");
EXPECT_EQ("", mission->GetSpecifiedFlag());
}
/*
* Feature: Mission
* Function: SetSpecifiedFlag and GetSpecifiedFlag
* SubFunction: NA
* FunctionPoints: Mission SetSpecifiedFlag
* EnvConditions: NA
* CaseDescription: Verify SetSpecifiedFlag
*/
HWTEST_F(MissionTest, mission_set_specified_flag_003, TestSize.Level1)
{
auto mission = std::make_shared<Mission>(1, nullptr);
mission->SetSpecifiedFlag("test_string");
EXPECT_EQ("test_string", mission->GetSpecifiedFlag());
}
/*
* Feature: Mission
* Function: SetSpecifiedFlag and GetSpecifiedFlag
* SubFunction: NA
* FunctionPoints: Mission SetSpecifiedFlag
* EnvConditions: NA
* CaseDescription: Verify SetSpecifiedFlag
*/
HWTEST_F(MissionTest, mission_set_specified_flag_004, TestSize.Level1)
{
auto mission = std::make_shared<Mission>(1, nullptr);
mission->SetSpecifiedFlag("test_string");
mission->SetSpecifiedFlag("test_string2");
EXPECT_EQ("test_string2", mission->GetSpecifiedFlag());
}
/*
* Feature: Mission
* Function: SetMovingState and IsMovingState
* SubFunction: NA
* FunctionPoints: Mission SetMovingState
* EnvConditions: NA
* CaseDescription: Verify SetMovingState
*/
HWTEST_F(MissionTest, mission_set_moving_state_001, TestSize.Level1)
{
auto mission = std::make_shared<Mission>(1, nullptr);
EXPECT_EQ(false, mission->IsMovingState());
}
/*
* Feature: Mission
* Function: SetMovingState and IsMovingState
* SubFunction: NA
* FunctionPoints: Mission SetMovingState
* EnvConditions: NA
* CaseDescription: Verify SetMovingState
*/
HWTEST_F(MissionTest, mission_set_moving_state_002, TestSize.Level1)
{
auto mission = std::make_shared<Mission>(1, nullptr);
mission->SetMovingState(true);
EXPECT_EQ(true, mission->IsMovingState());
}
/*
* Feature: Mission
* Function: SetANRState and IsANRState
* SubFunction: NA
* FunctionPoints: Mission SetANRState
* EnvConditions: NA
* CaseDescription: Verify SetANRState
*/
HWTEST_F(MissionTest, mission_set_anr_state_001, TestSize.Level1)
{
auto mission = std::make_shared<Mission>(1, nullptr);
EXPECT_EQ(false, mission->IsANRState());
}
/*
* Feature: Mission
* Function: SetANRState and IsANRState
* SubFunction: NA
* FunctionPoints: Mission SetANRState
* EnvConditions: NA
* CaseDescription: Verify SetANRState
*/
HWTEST_F(MissionTest, mission_set_anr_state_002, TestSize.Level1)
{
auto mission = std::make_shared<Mission>(1, nullptr);
mission->SetANRState(true);
EXPECT_EQ(true, mission->IsANRState());
}
/*
* Feature: Mission
* Function: Dump
* SubFunction: NA
* FunctionPoints: Mission Dump
* EnvConditions: NA
* CaseDescription: Test Dump
*/
HWTEST_F(MissionTest, mission_dump, TestSize.Level1)
{
AppExecFwk::AbilityInfo abilityInfo;
abilityInfo.launchMode = AppExecFwk::LaunchMode::SINGLETON;
Want want;
AppExecFwk::ApplicationInfo applicationInfo;
std::shared_ptr<AbilityRecord> abilityRecord = std::make_shared<AbilityRecord>(want, abilityInfo, applicationInfo);
auto mission = std::make_shared<Mission>(0, abilityRecord, "name1");
std::vector<std::string> info;
mission->Dump(info);
}
/*
* Feature: Mission
* Function: UpdateMissionId
* SubFunction: NA
* FunctionPoints: Mission UpdateMissionId
* EnvConditions: NA
* CaseDescription: Verify UpdateMissionId
*/
HWTEST_F(MissionTest, mission_update_mission_id, TestSize.Level1)
{
auto mission = std::make_shared<Mission>(1, nullptr, "name1", 0);
EXPECT_EQ(1,mission->GetMissionId());
EXPECT_EQ(false, mission->UpdateMissionId(2, 0));
EXPECT_EQ(1,mission->GetMissionId());
EXPECT_EQ(true, mission->UpdateMissionId(2, 1));
EXPECT_EQ(2,mission->GetMissionId());
}
} // namespace AAFwk
} // namespace OHOS
} // namespace OHOS
@@ -728,4 +728,222 @@ HWTEST_F(PendingWantTest, PendingWant_4100, Function | MediumTest | Level1)
EXPECT_EQ(pendingWant.GetWant(target, want), ERR_ABILITY_RUNTIME_EXTERNAL_INVALID_WANTAGENT);
EXPECT_EQ(want, nullptr);
}
/*
* @tc.number : PendingWant_4200
* @tc.name : PendingWant GetBundleName
* @tc.desc : 1.GetBundleName
*/
HWTEST_F(PendingWantTest, PendingWant_4200, Function | MediumTest | Level1)
{
PendingWant pendingWant(nullptr);
auto BundleName = pendingWant.GetBundleName(nullptr);
EXPECT_EQ(BundleName, "");
}
/*
* @tc.number : PendingWant_4300
* @tc.name : PendingWant GetUid
* @tc.desc : 1.GetUid
*/
HWTEST_F(PendingWantTest, PendingWant_4300, Function | MediumTest | Level1)
{
PendingWant pendingWant(nullptr);
auto uid = pendingWant.GetUid(nullptr);
EXPECT_EQ(uid, -1);
}
/*
* @tc.number : PendingWant_4400
* @tc.name : PendingWant Send
* @tc.desc : Send
*/
HWTEST_F(PendingWantTest, PendingWant_4400, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "PendingWant_4400 start";
PendingWant pendingWant(nullptr);
sptr<AAFwk::IWantSender> target;
pendingWant.Send(target);
EXPECT_TRUE(true);
GTEST_LOG_(INFO) << "PendingWant_4400 end";
}
/*
* @tc.number : PendingWant_4500
* @tc.name : PendingWant Send
* @tc.desc : Send
*/
HWTEST_F(PendingWantTest, PendingWant_4500, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "PendingWant_4500 start";
PendingWant pendingWant(nullptr);
int requestCode = 10;
sptr<AAFwk::IWantSender> target;
pendingWant.Send(requestCode, target);
EXPECT_TRUE(true);
GTEST_LOG_(INFO) << "PendingWant_4500 end";
}
/*
* @tc.number : PendingWant_4600
* @tc.name : PendingWant Send
* @tc.desc : Send
*/
HWTEST_F(PendingWantTest, PendingWant_4600, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "PendingWant_4600 start";
PendingWant pendingWant(nullptr);
int requestCode = 10;
std::shared_ptr<Want> want = std::make_shared<Want>();
ElementName element("device", "bundleName", "abilityName");
want->SetElement(element);
sptr<AAFwk::IWantSender> target;
pendingWant.Send(requestCode, want, target);
EXPECT_TRUE(true);
GTEST_LOG_(INFO) << "PendingWant_4600 end";
}
/*
* @tc.number : PendingWant_4700
* @tc.name : PendingWant Send
* @tc.desc : Send
*/
HWTEST_F(PendingWantTest, PendingWant_4700, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "PendingWant_4700 start";
PendingWant pendingWant(nullptr);
int requestCode = 10;
sptr<CompletedDispatcher> onCompleted;
sptr<AAFwk::IWantSender> target;
pendingWant.Send(requestCode, onCompleted, target);
EXPECT_TRUE(true);
GTEST_LOG_(INFO) << "PendingWant_4700 end";
}
/*
* @tc.number : PendingWant_4800
* @tc.name : PendingWant Send
* @tc.desc : Send
*/
HWTEST_F(PendingWantTest, PendingWant_4800, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "PendingWant_4800 start";
PendingWant pendingWant(nullptr);
int requestCode = 10;
std::shared_ptr<Want> want = std::make_shared<Want>();
ElementName element("device", "bundleName", "abilityName");
want->SetElement(element);
sptr<CompletedDispatcher> onCompleted;
sptr<AAFwk::IWantSender> target;
pendingWant.Send(requestCode, want, onCompleted, target);
EXPECT_TRUE(true);
GTEST_LOG_(INFO) << "PendingWant_4800 end";
}
/*
* @tc.number : PendingWant_4900
* @tc.name : PendingWant Send
* @tc.desc : Send
*/
HWTEST_F(PendingWantTest, PendingWant_4900, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "PendingWant_4900 start";
PendingWant pendingWant(nullptr);
int requestCode = 10;
std::shared_ptr<Want> want = std::make_shared<Want>();
ElementName element("device", "bundleName", "abilityName");
want->SetElement(element);
sptr<CompletedDispatcher> onCompleted = nullptr;
std::string requiredPermission = "Permission";
sptr<AAFwk::IWantSender> target;
pendingWant.Send(requestCode, want, onCompleted, requiredPermission, target);
EXPECT_TRUE(true);
GTEST_LOG_(INFO) << "PendingWant_4900 end";
}
/*
* @tc.number : PendingWant_5000
* @tc.name : PendingWant Send
* @tc.desc : Send
*/
HWTEST_F(PendingWantTest, PendingWant_5000, Function | MediumTest | Level1)
{
GTEST_LOG_(INFO) << "PendingWant_5000 start";
PendingWant pendingWant(nullptr);
int requestCode = 10;
std::shared_ptr<Want> want = std::make_shared<Want>();
ElementName element("device", "bundleName", "abilityName");
want->SetElement(element);
sptr<CompletedDispatcher> onCompleted;
std::string requiredPermission = "Permission";
std::shared_ptr<WantParams> options;
sptr<AAFwk::IWantSender> target;
pendingWant.Send(requestCode, want, onCompleted, requiredPermission, options, target);
EXPECT_TRUE(true);
GTEST_LOG_(INFO) << "PendingWant_5000 end";
}
/*
* @tc.number : PendingWant_5100
* @tc.name : PendingWant SetTarget
* @tc.desc : SetTarget
*/
HWTEST_F(PendingWantTest, PendingWant_5100, Function | MediumTest | Level1)
{
sptr<AAFwk::IWantSender> target(new (std::nothrow) PendingWantRecord());
PendingWant pendingWant(nullptr);
auto target1 = pendingWant.GetTarget();
pendingWant.SetTarget(target);
auto target2 = pendingWant.GetTarget();
EXPECT_EQ(target1, nullptr);
EXPECT_EQ(target2, target);
}
/*
* @tc.number : PendingWant_5200
* @tc.name : Unmarshalling_01
* @tc.desc : Test Unmarshalling function when target is null
*/
HWTEST_F(PendingWantTest, PendingWant_5200, Function | MediumTest | Level1)
{
sptr<AAFwk::IWantSender> target(new (std::nothrow) PendingWantRecord());
PendingWant pendingWant(target);
MessageParcel parcel;
pendingWant.Unmarshalling(parcel);
auto target1 = pendingWant.GetTarget();
EXPECT_EQ(target1, target);
}
/*
* @tc.number : PendingWant_5300
* @tc.name : PendingWant GetWantSenderInfo
* @tc.desc : GetWantSenderInfo
*/
HWTEST_F(PendingWantTest, PendingWant_5300, Function | MediumTest | Level1)
{
PendingWant pendingWant(nullptr);
auto wantsenderinfo = pendingWant.GetWantSenderInfo(nullptr);
EXPECT_EQ(wantsenderinfo, nullptr);
}
/*
* @tc.number : PendingWant_5400
* @tc.name : PendingWant NotifyCancelListeners
* @tc.desc : NotifyCancelListeners
*/
HWTEST_F(PendingWantTest, PendingWant_5400, Function | MediumTest | Level1)
{
std::shared_ptr<PendingWant> pendingWant = std::make_shared<PendingWant>(nullptr);
std::shared_ptr<CancelListener> cancelListener1 = std::make_shared<CancelListenerSon>();
std::shared_ptr<CancelListener> cancelListener2 = std::make_shared<CancelListenerSon>();
pendingWant->RegisterCancelListener(cancelListener1, nullptr);
pendingWant->RegisterCancelListener(cancelListener2, nullptr);
std::weak_ptr<PendingWant> outerInstance(pendingWant);
PendingWant::CancelReceiver cancelreceiver(outerInstance);
cancelreceiver.Send(0);
EXPECT_EQ(callBackCancelListenerConnt, 2);
callBackCancelListenerConnt = 0;
}
} // namespace OHOS::AbilityRuntime::WantAgent
+48
View File
@@ -0,0 +1,48 @@
# Copyright (c) 2021-2022 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("//foundation/ability/ability_runtime/ability_runtime.gni")
module_output_path = "ability_runtime/abilitymgr"
ohos_unittest("remote_mission_listener_stub_test") {
module_out_path = module_output_path
include_dirs = []
sources = [ "remote_mission_listener_stub_test.cpp" ]
configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ]
cflags = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
deps = [
"${ability_runtime_services_path}/abilitymgr:abilityms",
"//third_party/googletest:gmock_main",
"//third_party/googletest:gtest_main",
]
external_deps = [
"c_utils:utils",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
}
group("unittest") {
testonly = true
deps = [ ":remote_mission_listener_stub_test" ]
}
@@ -0,0 +1,39 @@
/*
* Copyright (c) 2021 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 UNITTEST_OHOS_ABILITY_RUNTIME_MOCK_REMOTE_MISSION_LISTENER_STUB_H
#define UNITTEST_OHOS_ABILITY_RUNTIME_MOCK_REMOTE_MISSION_LISTENER_STUB_H
#include <gmock/gmock.h>
#define private public
#include "remote_mission_listener_stub.h"
#undef private
namespace OHOS {
namespace AAFwk {
class MockRemoteMissionListenerStub : public RemoteMissionListenerStub {
public:
MockRemoteMissionListenerStub() = default;
virtual ~MockRemoteMissionListenerStub() = default;
MOCK_METHOD1(NotifyMissionsChanged, void(const std::string& deviceId));
MOCK_METHOD2(NotifySnapshot, void(const std::string& deviceId, int32_t missionId));
MOCK_METHOD2(NotifyNetDisconnect, void(const std::string& deviceId, int32_t state));
};
} // namespace AAFwk
} // namespace OHOS
#endif // UNITTEST_OHOS_ABILITY_RUNTIME_MOCK_REMOTE_MISSION_LISTENER_STUB_H
@@ -0,0 +1,193 @@
/*
* Copyright (c) 2021 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 "mock_remote_mission_listener_stub.h"
using namespace testing::ext;
using namespace testing;
namespace OHOS {
namespace AAFwk {
class RemoteMissionListenerStubTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
void WriteInterfaceToken(MessageParcel &data);
sptr<MockRemoteMissionListenerStub> stub_ {nullptr};
};
void RemoteMissionListenerStubTest::SetUpTestCase(void)
{}
void RemoteMissionListenerStubTest::TearDownTestCase(void)
{}
void RemoteMissionListenerStubTest::SetUp()
{
stub_ = new MockRemoteMissionListenerStub();
}
void RemoteMissionListenerStubTest::TearDown()
{}
void RemoteMissionListenerStubTest::WriteInterfaceToken(MessageParcel &data)
{
data.WriteInterfaceToken(MockRemoteMissionListenerStub::GetDescriptor());
}
/*
* Feature: RemoteMissionListenerStub
* Function: OnRemoteRequest
* SubFunction: NA
* FunctionPoints: RemoteMissionListenerStub OnRemoteRequest
* EnvConditions: The code which not exist
* CaseDescription: Verify that on remote request is abnormal
*/
HWTEST_F(RemoteMissionListenerStubTest, RemoteMissionListenerStubTest_OnRemoteRequest_001, TestSize.Level1)
{
MessageParcel data;
MessageParcel reply;
MessageOption option;
WriteInterfaceToken(data);
int res = stub_->OnRemoteRequest(10000, data, reply, option);
EXPECT_EQ(res, IPC_STUB_UNKNOW_TRANS_ERR);
}
/*
* Feature: RemoteMissionListenerStub
* Function: OnRemoteRequest
* SubFunction: NA
* FunctionPoints: RemoteMissionListenerStub OnRemoteRequest
* EnvConditions: Description abnormal
* CaseDescription: Verify that on remote request is abnormal
*/
HWTEST_F(RemoteMissionListenerStubTest, RemoteMissionListenerStubTest_OnRemoteRequest_002, TestSize.Level1)
{
MessageParcel data;
MessageParcel reply;
MessageOption option;
int res = stub_->OnRemoteRequest(IRemoteMissionListener::NOTIFY_MISSION_CHANGED, data, reply, option);
EXPECT_EQ(res, ERR_INVALID_STATE);
}
/*
* Feature: RemoteMissionListenerStub
* Function: OnRemoteRequest
* SubFunction: NA
* FunctionPoints: RemoteMissionListenerStub OnRemoteRequest
* EnvConditions: Code is NOTIFY_MISSION_CHANGED
* CaseDescription: Verify that on remote request is normal
*/
HWTEST_F(RemoteMissionListenerStubTest, RemoteMissionListenerStubTest_OnRemoteRequest_003, TestSize.Level1)
{
MessageParcel data;
MessageParcel reply;
MessageOption option;
WriteInterfaceToken(data);
EXPECT_CALL(*stub_, NotifyMissionsChanged(_)).Times(1).WillOnce(Return());
int res = stub_->OnRemoteRequest(IRemoteMissionListener::NOTIFY_MISSION_CHANGED, data, reply, option);
EXPECT_EQ(res, NO_ERROR);
}
/*
* Feature: RemoteMissionListenerStub
* Function: OnRemoteRequest
* SubFunction: NA
* FunctionPoints: RemoteMissionListenerStub OnRemoteRequest
* EnvConditions: Code is NOTIFY_SNAPSHOT
* CaseDescription: Verify that on remote request is normal
*/
HWTEST_F(RemoteMissionListenerStubTest, RemoteMissionListenerStubTest_OnRemoteRequest_004, TestSize.Level1)
{
MessageParcel data;
MessageParcel reply;
MessageOption option;
WriteInterfaceToken(data);
EXPECT_CALL(*stub_, NotifySnapshot(_, _)).Times(1).WillOnce(Return());
int res = stub_->OnRemoteRequest(IRemoteMissionListener::NOTIFY_SNAPSHOT, data, reply, option);
EXPECT_EQ(res, NO_ERROR);
}
/*
* Feature: RemoteMissionListenerStub
* Function: OnRemoteRequest
* SubFunction: NA
* FunctionPoints: RemoteMissionListenerStub OnRemoteRequest
* EnvConditions: Code is NOTIFY_NET_DISCONNECT
* CaseDescription: Verify that on remote request is normal
*/
HWTEST_F(RemoteMissionListenerStubTest, RemoteMissionListenerStubTest_OnRemoteRequest_005, TestSize.Level1)
{
MessageParcel data;
MessageParcel reply;
MessageOption option;
WriteInterfaceToken(data);
EXPECT_CALL(*stub_, NotifyNetDisconnect(_, _)).Times(1).WillOnce(Return());
int res = stub_->OnRemoteRequest(IRemoteMissionListener::NOTIFY_NET_DISCONNECT, data, reply, option);
EXPECT_EQ(res, NO_ERROR);
}
/*
* Feature: RemoteMissionListenerStub
* Function: NotifyMissionsChangedInner
* SubFunction: NA
* FunctionPoints: RemoteMissionListenerStub NotifyMissionsChangedInner
* EnvConditions: Description normal
* CaseDescription: Verify that notify missions changed inner is normal
*/
HWTEST_F(RemoteMissionListenerStubTest, RemoteMissionListenerStubTest_NotifyMissionsChangedInner_001, TestSize.Level1)
{
MessageParcel data;
MessageParcel reply;
EXPECT_CALL(*stub_, NotifyMissionsChanged(_)).Times(1).WillOnce(Return());
int res = stub_->NotifyMissionsChangedInner(data, reply);
EXPECT_EQ(res, NO_ERROR);
}
/*
* Feature: RemoteMissionListenerStub
* Function: NotifySnapshotInner
* SubFunction: NA
* FunctionPoints: RemoteMissionListenerStub NotifySnapshotInner
* EnvConditions: Description normal
* CaseDescription: Verify that notify snapshot inner is normal
*/
HWTEST_F(RemoteMissionListenerStubTest, RemoteMissionListenerStubTest_NotifySnapshotInner_001, TestSize.Level1)
{
MessageParcel data;
MessageParcel reply;
EXPECT_CALL(*stub_, NotifySnapshot(_, _)).Times(1).WillOnce(Return());
int res = stub_->NotifySnapshotInner(data, reply);
EXPECT_EQ(res, NO_ERROR);
}
/*
* Feature: RemoteMissionListenerStub
* Function: NotifyNetDisconnectInner
* SubFunction: NA
* FunctionPoints: RemoteMissionListenerStub NotifyNetDisconnectInner
* EnvConditions: Description normal
* CaseDescription: Verify that notify net disconnect inner is normal
*/
HWTEST_F(RemoteMissionListenerStubTest, RemoteMissionListenerStubTest_NotifyNetDisconnectInner_001, TestSize.Level1)
{
MessageParcel data;
MessageParcel reply;
EXPECT_CALL(*stub_, NotifyNetDisconnect(_, _)).Times(1).WillOnce(Return());
int res = stub_->NotifyNetDisconnectInner(data, reply);
EXPECT_EQ(res, NO_ERROR);
}
} // namespace AAFwk
} // namespace OHOS
+71
View File
@@ -0,0 +1,71 @@
# Copyright (c) 2022 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("//foundation/ability/ability_runtime/ability_runtime.gni")
module_output_path = "ability_runtime/abilitymgr"
ohos_unittest("task_data_persistence_mgr_test") {
module_out_path = module_output_path
include_dirs = [
"${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/system_ability_mock",
"${distributedschedule_path}/samgr/interfaces/innerkits/samgr_proxy/include",
]
sources = [
"${ability_runtime_services_path}/common/src/permission_verification.cpp",
"${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp",
"task_data_persistence_mgr_test.cpp", # add mock file
]
configs = [
"${ability_runtime_services_path}/abilitymgr:abilityms_config",
"${ability_runtime_test_path}/mock/services_abilitymgr_test:aafwk_mock_config",
]
cflags = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
deps = [
"${ability_runtime_native_path}/ability/native:abilitykit_native",
"${ability_runtime_services_path}/abilitymgr:abilityms",
"${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/aakit:aakit_mock",
"${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/appexecfwk_core:appexecfwk_appmgr_mock",
"${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/appexecfwk_core:appexecfwk_bundlemgr_mock",
"${ability_runtime_test_path}/unittest:abilityms_test_source",
"//third_party/googletest:gtest_main",
]
external_deps = [
"ability_base:want",
"ability_base:zuri",
"access_token:libaccesstoken_sdk",
"c_utils:utils",
"common_event_service:cesfwk_innerkits",
"eventhandler:libeventhandler",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
if (background_task_mgr_continuous_task_enable) {
external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ]
}
}
group("unittest") {
testonly = true
deps = [ ":task_data_persistence_mgr_test" ]
}
@@ -0,0 +1,268 @@
/*
* Copyright (c) 2022 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>
#define private public
#include "task_data_persistence_mgr.h"
#undef private
using namespace testing::ext;
using namespace OHOS::AppExecFwk;
namespace OHOS {
namespace AAFwk {
class TaskDataPersistenceMgrTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void TaskDataPersistenceMgrTest::SetUpTestCase(void)
{}
void TaskDataPersistenceMgrTest::TearDownTestCase(void)
{}
void TaskDataPersistenceMgrTest::SetUp(void)
{}
void TaskDataPersistenceMgrTest::TearDown(void)
{}
/*
* Feature: TaskDataPersistenceMgr
* Function: LoadAllMissionInfo
* SubFunction: NA
* FunctionPoints: MissionDataStorage LoadAllMissionInfo
* EnvConditions: NA
* CaseDescription: Verify LoadAllMissionInfo
*/
HWTEST_F(TaskDataPersistenceMgrTest, LoadAllMissionInfo_001, TestSize.Level1)
{
auto taskDataPersistenceMgr = std::make_shared<TaskDataPersistenceMgr>();
std::list<InnerMissionInfo> missionInfoList;
bool res = taskDataPersistenceMgr->LoadAllMissionInfo(missionInfoList);
EXPECT_FALSE(res);
}
/*
* Feature: TaskDataPersistenceMgr
* Function: SaveMissionInfo
* SubFunction: NA
* FunctionPoints: MissionDataStorage SaveMissionInfo
* EnvConditions: NA
* CaseDescription: Verify SaveMissionInfo
*/
HWTEST_F(TaskDataPersistenceMgrTest, SaveMissionInfo_001, TestSize.Level1)
{
auto taskDataPersistenceMgr = std::make_shared<TaskDataPersistenceMgr>();
InnerMissionInfo missionInfo;
bool res = taskDataPersistenceMgr->SaveMissionInfo(missionInfo);
EXPECT_FALSE(res);
}
/*
* Feature: TaskDataPersistenceMgr
* Function: SaveMissionInfo
* SubFunction: NA
* FunctionPoints: MissionDataStorage SaveMissionInfo
* EnvConditions: NA
* CaseDescription: Verify SaveMissionInfo
*/
HWTEST_F(TaskDataPersistenceMgrTest, SaveMissionInfo_002, TestSize.Level1)
{
auto taskDataPersistenceMgr = std::make_shared<TaskDataPersistenceMgr>();
int userId = 0;
taskDataPersistenceMgr->Init(userId);
InnerMissionInfo missionInfo;
bool res = taskDataPersistenceMgr->SaveMissionInfo(missionInfo);
EXPECT_TRUE(res);
}
/*
* Feature: TaskDataPersistenceMgr
* Function: DeleteMissionInfo
* SubFunction: NA
* FunctionPoints: MissionDataStorage DeleteMissionInfo
* EnvConditions: NA
* CaseDescription: Verify DeleteMissionInfo
*/
HWTEST_F(TaskDataPersistenceMgrTest, DeleteMissionInfo_001, TestSize.Level1)
{
auto taskDataPersistenceMgr = std::make_shared<TaskDataPersistenceMgr>();
int missionId = 0;
bool res = taskDataPersistenceMgr->DeleteMissionInfo(missionId);
EXPECT_FALSE(res);
}
/*
* Feature: TaskDataPersistenceMgr
* Function: DeleteMissionInfo
* SubFunction: NA
* FunctionPoints: MissionDataStorage DeleteMissionInfo
* EnvConditions: NA
* CaseDescription: Verify DeleteMissionInfo
*/
HWTEST_F(TaskDataPersistenceMgrTest, DeleteMissionInfo_002, TestSize.Level1)
{
auto taskDataPersistenceMgr = std::make_shared<TaskDataPersistenceMgr>();
int userId = 0;
taskDataPersistenceMgr->Init(userId);
int missionId = 0;
bool res = taskDataPersistenceMgr->DeleteMissionInfo(missionId);
EXPECT_TRUE(res);
}
/*
* Feature: TaskDataPersistenceMgr
* Function: RemoveUserDir
* SubFunction: NA
* FunctionPoints: MissionDataStorage RemoveUserDir
* EnvConditions: NA
* CaseDescription: Verify RemoveUserDir
*/
HWTEST_F(TaskDataPersistenceMgrTest, RemoveUserDir_001, TestSize.Level1)
{
auto taskDataPersistenceMgr = std::make_shared<TaskDataPersistenceMgr>();
int32_t userId = 0;
bool res = taskDataPersistenceMgr->RemoveUserDir(userId);
EXPECT_FALSE(res);
}
/*
* Feature: TaskDataPersistenceMgr
* Function: RemoveUserDir
* SubFunction: NA
* FunctionPoints: MissionDataStorage RemoveUserDir
* EnvConditions: NA
* CaseDescription: Verify RemoveUserDir
*/
HWTEST_F(TaskDataPersistenceMgrTest, RemoveUserDir_002, TestSize.Level1)
{
auto taskDataPersistenceMgr = std::make_shared<TaskDataPersistenceMgr>();
int32_t userId = -1;
bool res = taskDataPersistenceMgr->RemoveUserDir(userId);
EXPECT_FALSE(res);
}
/*
* Feature: TaskDataPersistenceMgr
* Function: SaveMissionSnapshot
* SubFunction: NA
* FunctionPoints: MissionDataStorage SaveMissionSnapshot
* EnvConditions: NA
* CaseDescription: Verify SaveMissionSnapshot
*/
HWTEST_F(TaskDataPersistenceMgrTest, SaveMissionSnapshot_001, TestSize.Level1)
{
auto taskDataPersistenceMgr = std::make_shared<TaskDataPersistenceMgr>();
int missionId = 0;
MissionSnapshot snapshot;
bool res = taskDataPersistenceMgr->SaveMissionSnapshot(missionId, snapshot);
EXPECT_FALSE(res);
}
/*
* Feature: TaskDataPersistenceMgr
* Function: SaveMissionSnapshot
* SubFunction: NA
* FunctionPoints: MissionDataStorage SaveMissionSnapshot
* EnvConditions: NA
* CaseDescription: Verify SaveMissionSnapshot
*/
HWTEST_F(TaskDataPersistenceMgrTest, SaveMissionSnapshot_002, TestSize.Level1)
{
auto taskDataPersistenceMgr = std::make_shared<TaskDataPersistenceMgr>();
int userId = 0;
taskDataPersistenceMgr->Init(userId);
int missionId = 0;
MissionSnapshot snapshot;
bool res = taskDataPersistenceMgr->SaveMissionSnapshot(missionId, snapshot);
EXPECT_TRUE(res);
}
/*
* Feature: TaskDataPersistenceMgr
* Function: GetSnapshot
* SubFunction: NA
* FunctionPoints: MissionDataStorage GetSnapshot
* EnvConditions: NA
* CaseDescription: Verify GetSnapshot
*/
HWTEST_F(TaskDataPersistenceMgrTest, GetSnapshot_001, TestSize.Level1)
{
auto taskDataPersistenceMgr = std::make_shared<TaskDataPersistenceMgr>();
int missionId = 0;
std::shared_ptr<Media::PixelMap> res = taskDataPersistenceMgr->GetSnapshot(missionId);
EXPECT_EQ(res, nullptr);
}
/*
* Feature: TaskDataPersistenceMgr
* Function: GetSnapshot
* SubFunction: NA
* FunctionPoints: MissionDataStorage GetSnapshot
* EnvConditions: NA
* CaseDescription: Verify GetSnapshot
*/
HWTEST_F(TaskDataPersistenceMgrTest, GetSnapshot_002, TestSize.Level1)
{
auto taskDataPersistenceMgr = std::make_shared<TaskDataPersistenceMgr>();
int userId = 0;
taskDataPersistenceMgr->Init(userId);
int missionId = 0;
std::shared_ptr<Media::PixelMap> res = taskDataPersistenceMgr->GetSnapshot(missionId);
EXPECT_EQ(res, nullptr);
}
/*
* Feature: TaskDataPersistenceMgr
* Function: GetMissionSnapshot
* SubFunction: NA
* FunctionPoints: MissionDataStorage GetMissionSnapshot
* EnvConditions: NA
* CaseDescription: Verify GetMissionSnapshot
*/
HWTEST_F(TaskDataPersistenceMgrTest, GetMissionSnapshot_001, TestSize.Level1)
{
auto taskDataPersistenceMgr = std::make_shared<TaskDataPersistenceMgr>();
int missionId = 0;
MissionSnapshot snapshot;
bool isLowResolution = true;
bool res = taskDataPersistenceMgr->GetMissionSnapshot(missionId, snapshot, isLowResolution);
EXPECT_FALSE(res);
}
/*
* Feature: TaskDataPersistenceMgr
* Function: GetMissionSnapshot
* SubFunction: NA
* FunctionPoints: MissionDataStorage GetMissionSnapshot
* EnvConditions: NA
* CaseDescription: Verify GetMissionSnapshot
*/
HWTEST_F(TaskDataPersistenceMgrTest, GetMissionSnapshot_002, TestSize.Level1)
{
auto taskDataPersistenceMgr = std::make_shared<TaskDataPersistenceMgr>();
int userId = 0;
taskDataPersistenceMgr->Init(userId);
int missionId = 0;
MissionSnapshot snapshot;
bool isLowResolution = true;
bool res = taskDataPersistenceMgr->GetMissionSnapshot(missionId, snapshot, isLowResolution);
EXPECT_FALSE(res);
}
} // namespace AAFwk
} // namespace OHOS
+2 -8
View File
@@ -198,10 +198,7 @@ public:
const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int UserID) override
{}
int StartUserTest(const Want &want, const sptr<IRemoteObject> &observer) override
{
return 0;
}
MOCK_METHOD2(StartUserTest, int(const Want &want, const sptr<IRemoteObject> &observer));
int FinishUserTest(
const std::string &msg, const int64_t &resultCode, const std::string &bundleName) override
@@ -225,10 +222,7 @@ public:
}
#ifdef ABILITY_COMMAND_FOR_TEST
int ForceTimeoutForTest(const std::string &abilityName, const std::string &state) override
{
return 0;
}
MOCK_METHOD2(ForceTimeoutForTest, int(const std::string &abilityName, const std::string &state));
virtual int BlockAmsService()
{
+87
View File
@@ -188,15 +188,102 @@ ohos_unittest("aa_command_screen_test") {
]
}
ohos_unittest("aa_command_force_stop_test") {
module_out_path = module_output_path
sources = [ "aa_command_force_stop_test.cpp" ]
sources += tools_aa_mock_sources
configs = [ ":tools_aa_config_mock" ]
cflags = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
deps = [
"${ability_runtime_path}/tools/aa:tools_aa_source_set",
"//third_party/googletest:gmock_main",
"//third_party/googletest:gtest_main",
]
external_deps = [
"ability_base:configuration",
"bundle_framework:appexecfwk_base",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
}
ohos_unittest("aa_command_force_timeout_test") {
module_out_path = module_output_path
sources = [ "aa_command_force_timeout_test.cpp" ]
sources += tools_aa_mock_sources
configs = [ ":tools_aa_config_mock" ]
cflags = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
deps = [
"${ability_runtime_path}/tools/aa:tools_aa_source_set",
"//third_party/googletest:gmock_main",
"//third_party/googletest:gtest_main",
]
external_deps = [
"ability_base:configuration",
"bundle_framework:appexecfwk_base",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
}
ohos_unittest("aa_command_test_test") {
module_out_path = module_output_path
sources = [ "aa_command_test_test.cpp" ]
sources += tools_aa_mock_sources
configs = [ ":tools_aa_config_mock" ]
cflags = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
deps = [
"${ability_runtime_path}/tools/aa:tools_aa_source_set",
"//third_party/googletest:gmock_main",
"//third_party/googletest:gtest_main",
]
external_deps = [
"ability_base:configuration",
"bundle_framework:appexecfwk_base",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
}
group("unittest") {
testonly = true
deps = [
":aa_command_dump_test",
":aa_command_dumpsys_test",
":aa_command_force_stop_test",
":aa_command_screen_test",
":aa_command_start_test",
":aa_command_stop_service_test",
":aa_command_test",
":aa_command_test_test",
]
if (ability_command_for_test) {
deps += [ ":aa_command_force_timeout_test" ]
}
}
@@ -0,0 +1,151 @@
/*
* Copyright (c) 2022 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 <gmock/gmock.h>
#define protected public
#include "ability_command.h"
#undef protected
#include "mock_ability_manager_stub.h"
#define private public
#include "ability_manager_client.h"
#undef private
#include "ability_manager_interface.h"
using namespace testing::ext;
using namespace OHOS;
using namespace OHOS::AAFwk;
using testing::_;
using testing::Invoke;
using testing::Return;
namespace {
const std::string STRING_BUNDLE_NAME = "bundle";
} // namespace
class AaCommandForceStopTest : public ::testing::Test {
public:
static void SetUpTestCase();
static void TearDownTestCase();
void SetUp() override;
void TearDown() override;
void MakeMockObjects() const;
std::string cmd_ = "force-stop";
};
void AaCommandForceStopTest::SetUpTestCase()
{}
void AaCommandForceStopTest::TearDownTestCase()
{}
void AaCommandForceStopTest::SetUp()
{
// reset optind to 0
optind = 0;
// make mock objects
MakeMockObjects();
}
void AaCommandForceStopTest::TearDown()
{}
void AaCommandForceStopTest::MakeMockObjects() const
{
// mock a stub
auto managerStubPtr = sptr<IAbilityManager>(new MockAbilityManagerStub());
// set the mock stub
auto managerClientPtr = AbilityManagerClient::GetInstance();
managerClientPtr->proxy_ = managerStubPtr;
}
/**
* @tc.number: Aa_Command_Force_Stop_0100
* @tc.name: ExecCommand
* @tc.desc: Verify the "aa force-stop" command.
*/
HWTEST_F(AaCommandForceStopTest, Aa_Command_Force_Stop_0100, Function | MediumTest | Level1)
{
char *argv[] = {
(char *)TOOL_NAME.c_str(),
(char *)cmd_.c_str(),
(char *)"",
};
int argc = sizeof(argv) / sizeof(argv[0]) - 1;
AbilityManagerShellCommand cmd(argc, argv);
EXPECT_EQ(cmd.ExecCommand(), HELP_MSG_FORCE_STOP + "\n");
}
/**
* @tc.number: Aa_Command_Force_Stop_0200
* @tc.name: ExecCommand
* @tc.desc: Verify the "aa force-stop xxx" command.
*/
HWTEST_F(AaCommandForceStopTest, Aa_Command_Force_Stop_0200, Function | MediumTest | Level1)
{
char *argv[] = {
(char *)TOOL_NAME.c_str(),
(char *)cmd_.c_str(),
(char *)"xxx",
(char *)"",
};
int argc = sizeof(argv) / sizeof(argv[0]) - 1;
AbilityManagerShellCommand cmd(argc, argv);
auto managerClientPtr = AbilityManagerClient::GetInstance();
auto mockAbilityManagerStub = sptr<MockAbilityManagerStub>(new MockAbilityManagerStub());
ASSERT_NE(mockAbilityManagerStub, nullptr);
EXPECT_CALL(*mockAbilityManagerStub, KillProcess(_))
.Times(1)
.WillOnce(Return(-1));
managerClientPtr->proxy_ = static_cast<IAbilityManager *>(mockAbilityManagerStub);
EXPECT_EQ(cmd.ExecCommand(), STRING_FORCE_STOP_NG + "\n");
testing::Mock::AllowLeak(mockAbilityManagerStub);
}
/**
* @tc.number: Aa_Command_Force_Stop_0300
* @tc.name: ExecCommand
* @tc.desc: Verify the "aa force-stop bundle" command.
*/
HWTEST_F(AaCommandForceStopTest, Aa_Command_Force_Stop_0300, Function | MediumTest | Level1)
{
char *argv[] = {
(char *)TOOL_NAME.c_str(),
(char *)cmd_.c_str(),
(char *)"STRING_BUNDLE_NAME",
(char *)"",
};
int argc = sizeof(argv) / sizeof(argv[0]) - 1;
AbilityManagerShellCommand cmd(argc, argv);
auto managerClientPtr = AbilityManagerClient::GetInstance();
auto mockAbilityManagerStub = sptr<MockAbilityManagerStub>(new MockAbilityManagerStub());
ASSERT_NE(mockAbilityManagerStub, nullptr);
EXPECT_CALL(*mockAbilityManagerStub, KillProcess(_))
.Times(1)
.WillOnce(Return(0));
managerClientPtr->proxy_ = static_cast<IAbilityManager *>(mockAbilityManagerStub);
EXPECT_EQ(cmd.ExecCommand(), STRING_FORCE_STOP_OK + "\n");
testing::Mock::AllowLeak(mockAbilityManagerStub);
}
@@ -0,0 +1,185 @@
/*
* Copyright (c) 2022 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 <gmock/gmock.h>
#define protected public
#include "ability_command.h"
#undef protected
#include "mock_ability_manager_stub.h"
#define private public
#include "ability_manager_client.h"
#undef private
#include "ability_manager_interface.h"
using namespace testing::ext;
using namespace OHOS;
using namespace OHOS::AAFwk;
using testing::_;
using testing::Invoke;
using testing::Return;
class AaCommandForceTimeOut : public ::testing::Test {
public:
static void SetUpTestCase();
static void TearDownTestCase();
void SetUp() override;
void TearDown() override;
void MakeMockObjects() const;
std::string cmd_ = "force-timeout";
};
void AaCommandForceTimeOut::SetUpTestCase()
{}
void AaCommandForceTimeOut::TearDownTestCase()
{}
void AaCommandForceTimeOut::SetUp()
{
// reset optind to 0
optind = 0;
// make mock objects
MakeMockObjects();
}
void AaCommandForceTimeOut::TearDown()
{}
void AaCommandForceTimeOut::MakeMockObjects() const
{
// mock a stub
auto managerStubPtr = sptr<IAbilityManager>(new MockAbilityManagerStub());
// set the mock stub
auto managerClientPtr = AbilityManagerClient::GetInstance();
managerClientPtr->proxy_ = managerStubPtr;
}
/**
* @tc.number: Aa_Command_Force_Timeout_0100
* @tc.name: ExecCommand
* @tc.desc: Verify the "aa force-timeout" command.
*/
HWTEST_F(AaCommandForceTimeOut, Aa_Command_Force_Timeout_0100, Function | MediumTest | Level1)
{
char *argv[] = {
(char *)TOOL_NAME.c_str(),
(char *)cmd_.c_str(),
(char *)"",
};
int argc = sizeof(argv) / sizeof(argv[0]) - 1;
AbilityManagerShellCommand cmd(argc, argv);
EXPECT_EQ(cmd.ExecCommand(), HELP_MSG_FORCE_TIMEOUT + "\n");
}
/**
* @tc.number: Aa_Command_Force_Timeout_0200
* @tc.name: ExecCommand
* @tc.desc: Verify the "aa force-timeout xxx" command.
*/
HWTEST_F(AaCommandForceTimeOut, Aa_Command_Force_Timeout_0200, Function | MediumTest | Level1)
{
char *argv[] = {
(char *)TOOL_NAME.c_str(),
(char *)cmd_.c_str(),
(char *)"xxx",
(char *)"",
};
int argc = sizeof(argv) / sizeof(argv[0]) - 1;
AbilityManagerShellCommand cmd(argc, argv);
EXPECT_EQ(cmd.ExecCommand(), HELP_MSG_FORCE_TIMEOUT + "\n");
}
/**
* @tc.number: Aa_Command_Force_Timeout_0300
* @tc.name: ExecCommand
* @tc.desc: Verify the "aa force-timeout clean" command.
*/
HWTEST_F(AaCommandForceTimeOut, Aa_Command_Force_Timeout_0300, Function | MediumTest | Level1)
{
char *argv[] = {
(char *)TOOL_NAME.c_str(),
(char *)cmd_.c_str(),
(char *)"clean",
(char *)"",
};
int argc = sizeof(argv) / sizeof(argv[0]) - 1;
AbilityManagerShellCommand cmd(argc, argv);
EXPECT_EQ(cmd.ExecCommand(), STRING_FORCE_TIMEOUT_OK + "\n");
}
/**
* @tc.number: Aa_Command_Force_Timeout_0400
* @tc.name: ExecCommand
* @tc.desc: Verify the "aa force-timeout xxx INITIAL" command.
*/
HWTEST_F(AaCommandForceTimeOut, Aa_Command_Force_Timeout_0400, Function | MediumTest | Level1)
{
char *argv[] = {
(char *)TOOL_NAME.c_str(),
(char *)cmd_.c_str(),
(char *)"clean",
(char *)"",
};
int argc = sizeof(argv) / sizeof(argv[0]) - 1;
AbilityManagerShellCommand cmd(argc, argv);
auto managerClientPtr = AbilityManagerClient::GetInstance();
auto mockAbilityManagerStub = sptr<MockAbilityManagerStub>(new MockAbilityManagerStub());
ASSERT_NE(mockAbilityManagerStub, nullptr);
EXPECT_CALL(*mockAbilityManagerStub, ForceTimeoutForTest(_, _))
.Times(1)
.WillOnce(Return(-1));
managerClientPtr->proxy_ = static_cast<IAbilityManager *>(mockAbilityManagerStub);
EXPECT_EQ(cmd.ExecCommand(), STRING_FORCE_TIMEOUT_NG + "\n");
testing::Mock::AllowLeak(mockAbilityManagerStub);
}
/**
* @tc.number: Aa_Command_Force_Timeout_0500
* @tc.name: ExecCommand
* @tc.desc: Verify the "aa force-timeout ability INITIAL" command.
*/
HWTEST_F(AaCommandForceTimeOut, Aa_Command_Force_Timeout_0500, Function | MediumTest | Level1)
{
char *argv[] = {
(char *)TOOL_NAME.c_str(),
(char *)cmd_.c_str(),
(char *)"clean",
(char *)"",
};
int argc = sizeof(argv) / sizeof(argv[0]) - 1;
AbilityManagerShellCommand cmd(argc, argv);
auto managerClientPtr = AbilityManagerClient::GetInstance();
auto mockAbilityManagerStub = sptr<MockAbilityManagerStub>(new MockAbilityManagerStub());
ASSERT_NE(mockAbilityManagerStub, nullptr);
EXPECT_CALL(*mockAbilityManagerStub, ForceTimeoutForTest(_, _))
.Times(1)
.WillOnce(Return(0));
managerClientPtr->proxy_ = static_cast<IAbilityManager *>(mockAbilityManagerStub);
EXPECT_EQ(cmd.ExecCommand(), STRING_FORCE_TIMEOUT_OK + "\n");
testing::Mock::AllowLeak(mockAbilityManagerStub);
}
@@ -0,0 +1,218 @@
/*
* Copyright (c) 2022 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 <gmock/gmock.h>
#define protected public
#include "ability_command.h"
#undef protected
#include "mock_ability_manager_stub.h"
#define private public
#include "ability_manager_client.h"
#undef private
#include "ability_manager_interface.h"
#include "itest_observer.h"
using namespace testing::ext;
using namespace OHOS;
using namespace OHOS::AAFwk;
using testing::_;
using testing::Invoke;
using testing::Return;
namespace {
const std::string STRING_BUNDLE_NAME = "bundle";
} // namespace
class AaCommandTestTest : public ::testing::Test {
public:
static void SetUpTestCase();
static void TearDownTestCase();
void SetUp() override;
void TearDown() override;
void MakeMockObjects() const;
std::string cmd_ = "test";
};
void AaCommandTestTest::SetUpTestCase()
{}
void AaCommandTestTest::TearDownTestCase()
{}
void AaCommandTestTest::SetUp()
{
// reset optind to 0
optind = 0;
// make mock objects
MakeMockObjects();
}
void AaCommandTestTest::TearDown()
{}
void AaCommandTestTest::MakeMockObjects() const
{
// mock a stub
auto managerStubPtr = sptr<IAbilityManager>(new MockAbilityManagerStub());
// set the mock stub
auto managerClientPtr = AbilityManagerClient::GetInstance();
managerClientPtr->proxy_ = managerStubPtr;
}
/**
* @tc.number: Aa_Command_Test_0100
* @tc.name: ExecCommand
* @tc.desc: Verify the "aa test -b xxx -s unittest 1" command.
*/
HWTEST_F(AaCommandTestTest, Aa_Command_Test_0100, Function | MediumTest | Level1)
{
char *argv[] = {
(char *)TOOL_NAME.c_str(),
(char *)cmd_.c_str(),
(char *)"-b",
(char *)"xxx",
(char *)"-s",
(char *)"unittest",
(char *)"1",
(char *)"",
};
int argc = sizeof(argv) / sizeof(argv[0]) - 1;
AbilityManagerShellCommand cmd(argc, argv);
auto managerClientPtr = AbilityManagerClient::GetInstance();
auto mockAbilityManagerStub = sptr<MockAbilityManagerStub>(new MockAbilityManagerStub());
ASSERT_NE(mockAbilityManagerStub, nullptr);
EXPECT_CALL(*mockAbilityManagerStub, StartUserTest(_, _))
.Times(1)
.WillOnce(Return(-1));
managerClientPtr->proxy_ = static_cast<IAbilityManager *>(mockAbilityManagerStub);
EXPECT_EQ(cmd.ExecCommand(), STRING_START_USER_TEST_NG + "\n");
}
/**
* @tc.number: Aa_Command_Test_0200
* @tc.name: ExecCommand
* @tc.desc: Verify the "aa test -b xxx -s unittest 1 -D" command.
*/
HWTEST_F(AaCommandTestTest, Aa_Command_Test_0200, Function | MediumTest | Level1)
{
char *argv[] = {
(char *)TOOL_NAME.c_str(),
(char *)cmd_.c_str(),
(char *)"-b",
(char *)"xxx",
(char *)"-s",
(char *)"unittest",
(char *)"1",
(char *)"-D",
(char *)"",
};
int argc = sizeof(argv) / sizeof(argv[0]) - 1;
AbilityManagerShellCommand cmd(argc, argv);
auto managerClientPtr = AbilityManagerClient::GetInstance();
auto mockAbilityManagerStub = sptr<MockAbilityManagerStub>(new MockAbilityManagerStub());
ASSERT_NE(mockAbilityManagerStub, nullptr);
EXPECT_CALL(*mockAbilityManagerStub, StartUserTest(_, _))
.Times(1)
.WillOnce(Return(-1));
managerClientPtr->proxy_ = static_cast<IAbilityManager *>(mockAbilityManagerStub);
EXPECT_EQ(cmd.ExecCommand(), STRING_START_USER_TEST_NG + "\n");
testing::Mock::AllowLeak(mockAbilityManagerStub);
}
/**
* @tc.number: Aa_Command_Test_0300
* @tc.name: ExecCommand
* @tc.desc: Verify the "aa test -b bundle -s unittest 1 -w 1" command.
*/
HWTEST_F(AaCommandTestTest, Aa_Command_Test_0300, Function | MediumTest | Level1)
{
char *argv[] = {
(char *)TOOL_NAME.c_str(),
(char *)cmd_.c_str(),
(char *)"-b",
(char *)STRING_BUNDLE_NAME.c_str(),
(char *)"-s",
(char *)"unittest",
(char *)"1",
(char *)"-w",
(char *)"1",
(char *)"",
};
int argc = sizeof(argv) / sizeof(argv[0]) - 1;
AbilityManagerShellCommand cmd(argc, argv);
auto managerClientPtr = AbilityManagerClient::GetInstance();
auto mockAbilityManagerStub = sptr<MockAbilityManagerStub>(new MockAbilityManagerStub());
ASSERT_NE(mockAbilityManagerStub, nullptr);
EXPECT_CALL(*mockAbilityManagerStub, StartUserTest(_, _))
.Times(1)
.WillOnce(Return(0));
managerClientPtr->proxy_ = static_cast<IAbilityManager *>(mockAbilityManagerStub);
EXPECT_EQ(cmd.ExecCommand(), "Timeout: user test is not completed within the specified time.\n");
testing::Mock::AllowLeak(mockAbilityManagerStub);
}
/**
* @tc.number: Aa_Command_Test_0400
* @tc.name: ExecCommand
* @tc.desc: Verify the "aa test -b bundle -s unittest 1 -w 0" command.
*/
HWTEST_F(AaCommandTestTest, Aa_Command_Test_0400, Function | MediumTest | Level1)
{
char *argv[] = {
(char *)TOOL_NAME.c_str(),
(char *)cmd_.c_str(),
(char *)"-b",
(char *)STRING_BUNDLE_NAME.c_str(),
(char *)"-s",
(char *)"unittest",
(char *)"1",
(char *)"-w",
(char *)"0",
(char *)"",
};
int argc = sizeof(argv) / sizeof(argv[0]) - 1;
AbilityManagerShellCommand cmd(argc, argv);
auto mockHandler = [](const Want &want, const sptr<IRemoteObject> &observer) -> int {
sptr<ITestObserver> testObserver = iface_cast<ITestObserver>(observer);
if (!testObserver) {
return -1;
}
testObserver->TestFinished("success", 0);
return 0;
};
auto managerClientPtr = AbilityManagerClient::GetInstance();
auto mockAbilityManagerStub = sptr<MockAbilityManagerStub>(new MockAbilityManagerStub());
ASSERT_NE(mockAbilityManagerStub, nullptr);
EXPECT_CALL(*mockAbilityManagerStub, StartUserTest(_, _))
.Times(1)
.WillOnce(Invoke(mockHandler));
managerClientPtr->proxy_ = static_cast<IAbilityManager *>(mockAbilityManagerStub);
EXPECT_EQ(cmd.ExecCommand(), STRING_USER_TEST_FINISHED + "\n");
testing::Mock::AllowLeak(mockAbilityManagerStub);
}