diff --git a/frameworks/js/napi/app/appMgr/native_module.cpp b/frameworks/js/napi/app/appMgr/native_module.cpp index 1d270e9fe6..cd03b9b3a0 100644 --- a/frameworks/js/napi/app/appMgr/native_module.cpp +++ b/frameworks/js/napi/app/appMgr/native_module.cpp @@ -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(0)), .reserved = {0}, }; /* diff --git a/frameworks/js/napi/featureAbility/native_module.cpp b/frameworks/js/napi/featureAbility/native_module.cpp index 8618068649..755ef46b8e 100644 --- a/frameworks/js/napi/featureAbility/native_module.cpp +++ b/frameworks/js/napi/featureAbility/native_module.cpp @@ -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(0)), .reserved = {0} }; diff --git a/frameworks/js/napi/particleAbility/native_module.cpp b/frameworks/js/napi/particleAbility/native_module.cpp index fcbdfce736..507483520b 100644 --- a/frameworks/js/napi/particleAbility/native_module.cpp +++ b/frameworks/js/napi/particleAbility/native_module.cpp @@ -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(0)), .reserved = {0} }; diff --git a/frameworks/js/napi/wantConstant/native_module.cpp b/frameworks/js/napi/wantConstant/native_module.cpp index cb04fef691..89f668de26 100644 --- a/frameworks/js/napi/wantConstant/native_module.cpp +++ b/frameworks/js/napi/wantConstant/native_module.cpp @@ -41,7 +41,7 @@ static napi_module _module = { #else .nm_modname = "ability.wantConstant", #endif - .nm_priv = ((void *)0), + .nm_priv = (static_cast(0)), .reserved = {0} }; diff --git a/frameworks/native/ability/native/ability.cpp b/frameworks/native/ability/native/ability.cpp index bee1475c9c..0ce7d7db01 100644 --- a/frameworks/native/ability/native/ability.cpp +++ b/frameworks/native/ability/native/ability.cpp @@ -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); diff --git a/frameworks/native/appkit/app/main_thread.cpp b/frameworks/native/appkit/app/main_thread.cpp index 69f50e5b12..1758de166d 100644 --- a/frameworks/native/appkit/app/main_thread.cpp +++ b/frameworks/native/appkit/app/main_thread.cpp @@ -73,6 +73,7 @@ namespace AppExecFwk { using namespace OHOS::AbilityRuntime::Constants; std::weak_ptr MainThread::applicationForDump_; std::shared_ptr MainThread::signalHandler_ = nullptr; +std::shared_ptr MainThread::mainHandler_ = nullptr; static std::shared_ptr 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() diff --git a/frameworks/native/appkit/app/watchdog.cpp b/frameworks/native/appkit/app/watchdog.cpp index 4360be0a5c..eb3b713ae3 100644 --- a/frameworks/native/appkit/app/watchdog.cpp +++ b/frameworks/native/appkit/app/watchdog.cpp @@ -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(getpid()), EVENT_KEY_PACKAGE_NAME, applicationInfo_->bundleName, EVENT_KEY_PROCESS_NAME, applicationInfo_->process, EVENT_KEY_MESSAGE, msgContent); diff --git a/frameworks/native/runtime/js_runtime.cpp b/frameworks/native/runtime/js_runtime.cpp index b36e4984e8..1cb1f569f1 100644 --- a/frameworks/native/runtime/js_runtime.cpp +++ b/frameworks/native/runtime/js_runtime.cpp @@ -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 { diff --git a/frameworks/native/runtime/js_runtime_utils.cpp b/frameworks/native/runtime/js_runtime_utils.cpp index dce4384f39..f4263f1f97 100644 --- a/frameworks/native/runtime/js_runtime_utils.cpp +++ b/frameworks/native/runtime/js_runtime_utils.cpp @@ -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) { diff --git a/frameworks/native/runtime/source_map.cpp b/frameworks/native/runtime/source_map.cpp index b15cec50f9..289859f4b7 100644 --- a/frameworks/native/runtime/source_map.cpp +++ b/frameworks/native/runtime/source_map.cpp @@ -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& ans) @@ -326,7 +333,7 @@ bool ModSourceMap::VlqRevCode(const std::string& vStr, std::vector& 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(key, value)); } @@ -519,14 +526,14 @@ std::string ModSourceMap::GetOriginalNames(std::shared_ptr target return sourceCode; } std::vector 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] diff --git a/interfaces/kits/native/appkit/app/main_thread.h b/interfaces/kits/native/appkit/app/main_thread.h index 87e69b46cb..1c47bc81ea 100644 --- a/interfaces/kits/native/appkit/app/main_thread.h +++ b/interfaces/kits/native/appkit/app/main_thread.h @@ -467,7 +467,7 @@ private: std::shared_ptr processInfo_ = nullptr; std::shared_ptr application_ = nullptr; std::shared_ptr applicationImpl_ = nullptr; - std::shared_ptr mainHandler_ = nullptr; + static std::shared_ptr mainHandler_; std::shared_ptr abilityRecordMgr_ = nullptr; std::shared_ptr watchdog_ = nullptr; MainThreadState mainThreadState_ = MainThreadState::INIT; diff --git a/services/abilitymgr/include/mission_info_mgr.h b/services/abilitymgr/include/mission_info_mgr.h index 240a454bc2..1d5ed841fd 100644 --- a/services/abilitymgr/include/mission_info_mgr.h +++ b/services/abilitymgr/include/mission_info_mgr.h @@ -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. * diff --git a/services/abilitymgr/include/mission_list_manager.h b/services/abilitymgr/include/mission_list_manager.h index 6c9f2e0e01..745b60af42 100644 --- a/services/abilitymgr/include/mission_list_manager.h +++ b/services/abilitymgr/include/mission_list_manager.h @@ -420,7 +420,6 @@ private: std::shared_ptr GetAbilityRecordByCaller( const std::shared_ptr &caller, int requestCode); std::shared_ptr GetTargetMissionList(int missionId, std::shared_ptr &mission); - void UpdateMissionTimeStamp(const std::shared_ptr &abilityRecord); void PostStartWaitingAbility(); void HandleAbilityDied(std::shared_ptr abilityRecord); void HandleLauncherDied(std::shared_ptr ability); diff --git a/services/abilitymgr/src/ability_manager_service.cpp b/services/abilitymgr/src/ability_manager_service.cpp index 45cca01f34..8add598150 100644 --- a/services/abilitymgr/src/ability_manager_service.cpp +++ b/services/abilitymgr/src/ability_manager_service.cpp @@ -4166,7 +4166,7 @@ void AbilityManagerService::ScheduleRecoverAbility(const sptr& 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, diff --git a/services/abilitymgr/src/ability_scheduler_stub.cpp b/services/abilitymgr/src/ability_scheduler_stub.cpp index ef925c30c7..a82a397d1a 100644 --- a/services/abilitymgr/src/ability_scheduler_stub.cpp +++ b/services/abilitymgr/src/ability_scheduler_stub.cpp @@ -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 values; for (int i = 0; i < count; i++) { std::unique_ptr value(data.ReadParcelable()); @@ -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> operations; for (int i = 0; i < count; i++) { AppExecFwk::DataAbilityOperation *operation = data.ReadParcelable(); diff --git a/services/abilitymgr/src/mission_info_mgr.cpp b/services/abilitymgr/src/mission_info_mgr.cpp index 7240f4ff7c..a84c2bad5d 100644 --- a/services/abilitymgr/src/mission_info_mgr.cpp +++ b/services/abilitymgr/src/mission_info_mgr.cpp @@ -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 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 lock(mutex_); diff --git a/services/abilitymgr/src/mission_list_manager.cpp b/services/abilitymgr/src/mission_list_manager.cpp index 508b0eaf7a..83369eb082 100644 --- a/services/abilitymgr/src/mission_list_manager.cpp +++ b/services/abilitymgr/src/mission_list_manager.cpp @@ -726,9 +726,6 @@ int MissionListManager::MinimizeAbilityLocked(const std::shared_ptrSetMinimizeReason(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_ptrGetPendingState() == 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 &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 MissionListManager::GetAbilityTokenByMissionId(int32_t missi return defaultStandardList_->GetAbilityTokenByMissionId((missionId)); } -void MissionListManager::UpdateMissionTimeStamp(const std::shared_ptr &abilityRecord) -{ - auto mission = abilityRecord->GetMission(); - if (!mission) { - return; - } - std::string curTime = GetCurrentTime(); - DelayedSingleton::GetInstance()->UpdateMissionTimeStamp(mission->GetMissionId(), curTime); -} - void MissionListManager::PostStartWaitingAbility() { auto self(shared_from_this()); diff --git a/services/appmgr/src/app_mgr_service_inner.cpp b/services/appmgr/src/app_mgr_service_inner.cpp index 024fcf4667..65c9bde349 100644 --- a/services/appmgr/src/app_mgr_service_inner.cpp +++ b/services/appmgr/src/app_mgr_service_inner.cpp @@ -845,6 +845,10 @@ int64_t AppMgrServiceInner::SystemTimeMillisecond() std::shared_ptr 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, diff --git a/services/common/src/event_report.cpp b/services/common/src/event_report.cpp index 15c379c19e..670f33c2e5 100644 --- a/services/common/src/event_report.cpp +++ b/services/common/src/event_report.cpp @@ -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, diff --git a/services/dialog_ui/ams_system_dialog/AppScope/app.json b/services/dialog_ui/ams_system_dialog/AppScope/app.json new file mode 100644 index 0000000000..a9577b0b41 --- /dev/null +++ b/services/dialog_ui/ams_system_dialog/AppScope/app.json @@ -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 + } +} diff --git a/services/dialog_ui/ams_system_dialog/AppScope/resources/base/element/string.json b/services/dialog_ui/ams_system_dialog/AppScope/resources/base/element/string.json new file mode 100644 index 0000000000..5fd43366da --- /dev/null +++ b/services/dialog_ui/ams_system_dialog/AppScope/resources/base/element/string.json @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "app_name", + "value": "AmsSystemDialog" + } + ] +} diff --git a/services/dialog_ui/ams_system_dialog/AppScope/resources/base/media/app_icon.png b/services/dialog_ui/ams_system_dialog/AppScope/resources/base/media/app_icon.png new file mode 100644 index 0000000000..ce307a8827 Binary files /dev/null and b/services/dialog_ui/ams_system_dialog/AppScope/resources/base/media/app_icon.png differ diff --git a/services/dialog_ui/ams_system_dialog/BUILD.gn b/services/dialog_ui/ams_system_dialog/BUILD.gn new file mode 100644 index 0000000000..583787287f --- /dev/null +++ b/services/dialog_ui/ams_system_dialog/BUILD.gn @@ -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" ] +} diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/ets/Application/AbilityStage.ts b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/Application/AbilityStage.ts new file mode 100644 index 0000000000..1821f62885 --- /dev/null +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/Application/AbilityStage.ts @@ -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"); + } +} \ No newline at end of file diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts new file mode 100644 index 0000000000..e02a8d678f --- /dev/null +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/ServiceExtAbility/NotificationServiceExtAbility.ts @@ -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!"); + } + } +}; diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/ets/ServiceExtAbility/SelectorServiceExtAbility.ts b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/ServiceExtAbility/SelectorServiceExtAbility.ts new file mode 100644 index 0000000000..d8ff0b001b --- /dev/null +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/ServiceExtAbility/SelectorServiceExtAbility.ts @@ -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!"); + } + } +}; diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/ets/ServiceExtAbility/TipsServiceExtAbility.ts b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/ServiceExtAbility/TipsServiceExtAbility.ts new file mode 100644 index 0000000000..3049177481 --- /dev/null +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/ServiceExtAbility/TipsServiceExtAbility.ts @@ -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!"); + } + } +}; diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/notificationDialog.ets b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/notificationDialog.ets new file mode 100644 index 0000000000..46617d006f --- /dev/null +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/notificationDialog.ets @@ -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'] + } +} \ No newline at end of file diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/selectorPcDialog.ets b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/selectorPcDialog.ets new file mode 100644 index 0000000000..2347e8317f --- /dev/null +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/selectorPcDialog.ets @@ -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%") + } +} \ No newline at end of file diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/selectorPhoneDialog.ets b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/selectorPhoneDialog.ets new file mode 100644 index 0000000000..f5df8864ae --- /dev/null +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/selectorPhoneDialog.ets @@ -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%") + } +} \ No newline at end of file diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/tipsDialog.ets b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/tipsDialog.ets new file mode 100644 index 0000000000..12f82fcd07 --- /dev/null +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/ets/pages/tipsDialog.ets @@ -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") + } +} \ No newline at end of file diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/module.json b/services/dialog_ui/ams_system_dialog/entry/src/main/module.json new file mode 100644 index 0000000000..4b5d1aca49 --- /dev/null +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/module.json @@ -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" + } + ] + } +} \ No newline at end of file diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/element/color.json b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/element/color.json new file mode 100644 index 0000000000..ea4b161648 --- /dev/null +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/element/color.json @@ -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" + } + ] +} \ No newline at end of file diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/element/string.json b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/element/string.json new file mode 100644 index 0000000000..f373431072 --- /dev/null +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/element/string.json @@ -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" + } + ] +} \ No newline at end of file diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/media/icon.png b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/media/icon.png new file mode 100644 index 0000000000..ce307a8827 Binary files /dev/null and b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/media/icon.png differ diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/profile/main_pages.json b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/profile/main_pages.json new file mode 100644 index 0000000000..660c467d40 --- /dev/null +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/base/profile/main_pages.json @@ -0,0 +1,8 @@ +{ + "src": [ + "pages/selectorPhoneDialog", + "pages/selectorPcDialog", + "pages/tipsDialog", + "pages/notificationDialog" + ] +} diff --git a/services/dialog_ui/ams_system_dialog/entry/src/main/resources/zh/element/string.json b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/zh/element/string.json new file mode 100644 index 0000000000..758d0ce52e --- /dev/null +++ b/services/dialog_ui/ams_system_dialog/entry/src/main/resources/zh/element/string.json @@ -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": "是否允许发送通知?" + } + ] +} \ No newline at end of file diff --git a/services/dialog_ui/ams_system_dialog/signature/openharmony_sx.p7b b/services/dialog_ui/ams_system_dialog/signature/openharmony_sx.p7b new file mode 100644 index 0000000000..c4a83be9a7 Binary files /dev/null and b/services/dialog_ui/ams_system_dialog/signature/openharmony_sx.p7b differ diff --git a/test/fuzztest/cleanallmissions_fuzzer/cleanallmissions_fuzzer.cpp b/test/fuzztest/cleanallmissions_fuzzer/cleanallmissions_fuzzer.cpp index 75dec9261d..bb12b245c0 100644 --- a/test/fuzztest/cleanallmissions_fuzzer/cleanallmissions_fuzzer.cpp +++ b/test/fuzztest/cleanallmissions_fuzzer/cleanallmissions_fuzzer.cpp @@ -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 -#include - -#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 +#include + +#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; +} + diff --git a/test/fuzztest/cleanallmissions_fuzzer/cleanallmissions_fuzzer.h b/test/fuzztest/cleanallmissions_fuzzer/cleanallmissions_fuzzer.h index b6cbcd625d..9dcf1089e1 100644 --- a/test/fuzztest/cleanallmissions_fuzzer/cleanallmissions_fuzzer.h +++ b/test/fuzztest/cleanallmissions_fuzzer/cleanallmissions_fuzzer.h @@ -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 diff --git a/test/fuzztest/cleanallmissions_fuzzer/corpus/init b/test/fuzztest/cleanallmissions_fuzzer/corpus/init index 6d6bd4a361..8eb5a7d6eb 100644 --- a/test/fuzztest/cleanallmissions_fuzzer/corpus/init +++ b/test/fuzztest/cleanallmissions_fuzzer/corpus/init @@ -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 \ No newline at end of file diff --git a/test/fuzztest/cleanallmissions_fuzzer/project.xml b/test/fuzztest/cleanallmissions_fuzzer/project.xml index 1020c7b430..6e8ad2cfde 100644 --- a/test/fuzztest/cleanallmissions_fuzzer/project.xml +++ b/test/fuzztest/cleanallmissions_fuzzer/project.xml @@ -1,25 +1,25 @@ - - - - - - 1000 - - 300 - - 4096 - - + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/continuemission_fuzzer/continuemission_fuzzer.cpp b/test/fuzztest/continuemission_fuzzer/continuemission_fuzzer.cpp index d8876804f2..2ce9e32938 100644 --- a/test/fuzztest/continuemission_fuzzer/continuemission_fuzzer.cpp +++ b/test/fuzztest/continuemission_fuzzer/continuemission_fuzzer.cpp @@ -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 -#include - -#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(GetU32Data(data)); - sptr 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 +#include + +#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(GetU32Data(data)); + sptr 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; +} + diff --git a/test/fuzztest/continuemission_fuzzer/continuemission_fuzzer.h b/test/fuzztest/continuemission_fuzzer/continuemission_fuzzer.h index fa9222f9b0..02f4ff4dd1 100644 --- a/test/fuzztest/continuemission_fuzzer/continuemission_fuzzer.h +++ b/test/fuzztest/continuemission_fuzzer/continuemission_fuzzer.h @@ -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 diff --git a/test/fuzztest/continuemission_fuzzer/corpus/init b/test/fuzztest/continuemission_fuzzer/corpus/init index 6d6bd4a361..8eb5a7d6eb 100644 --- a/test/fuzztest/continuemission_fuzzer/corpus/init +++ b/test/fuzztest/continuemission_fuzzer/corpus/init @@ -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 \ No newline at end of file diff --git a/test/fuzztest/continuemission_fuzzer/project.xml b/test/fuzztest/continuemission_fuzzer/project.xml index 1020c7b430..6e8ad2cfde 100644 --- a/test/fuzztest/continuemission_fuzzer/project.xml +++ b/test/fuzztest/continuemission_fuzzer/project.xml @@ -1,25 +1,25 @@ - - - - - - 1000 - - 300 - - 4096 - - + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/missioninfomgrb_fuzzer/missioninfomgrb_fuzzer.cpp b/test/fuzztest/missioninfomgrb_fuzzer/missioninfomgrb_fuzzer.cpp index 106690e8f6..dcaf94591d 100755 --- a/test/fuzztest/missioninfomgrb_fuzzer/missioninfomgrb_fuzzer.cpp +++ b/test/fuzztest/missioninfomgrb_fuzzer/missioninfomgrb_fuzzer.cpp @@ -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; } diff --git a/test/fuzztest/missionlistmanagersecond_fuzzer/missionlistmanagersecond_fuzzer.cpp b/test/fuzztest/missionlistmanagersecond_fuzzer/missionlistmanagersecond_fuzzer.cpp index a3e3fd8807..01a716d325 100755 --- a/test/fuzztest/missionlistmanagersecond_fuzzer/missionlistmanagersecond_fuzzer.cpp +++ b/test/fuzztest/missionlistmanagersecond_fuzzer/missionlistmanagersecond_fuzzer.cpp @@ -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); diff --git a/test/fuzztest/registermissionlistener_fuzzer/corpus/init b/test/fuzztest/registermissionlistener_fuzzer/corpus/init index 6d6bd4a361..8eb5a7d6eb 100644 --- a/test/fuzztest/registermissionlistener_fuzzer/corpus/init +++ b/test/fuzztest/registermissionlistener_fuzzer/corpus/init @@ -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 \ No newline at end of file diff --git a/test/fuzztest/registermissionlistener_fuzzer/project.xml b/test/fuzztest/registermissionlistener_fuzzer/project.xml index 1020c7b430..6e8ad2cfde 100644 --- a/test/fuzztest/registermissionlistener_fuzzer/project.xml +++ b/test/fuzztest/registermissionlistener_fuzzer/project.xml @@ -1,25 +1,25 @@ - - - - - - 1000 - - 300 - - 4096 - - + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/registermissionlistener_fuzzer/registermissionlistener_fuzzer.cpp b/test/fuzztest/registermissionlistener_fuzzer/registermissionlistener_fuzzer.cpp index 5d1a75f55e..33ae170d90 100644 --- a/test/fuzztest/registermissionlistener_fuzzer/registermissionlistener_fuzzer.cpp +++ b/test/fuzztest/registermissionlistener_fuzzer/registermissionlistener_fuzzer.cpp @@ -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 -#include - -#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 &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 listener; - if (listener) { - abilitymgr->RegisterMissionListener(listener); - } - - std::string deviceId(data, size); - sptr 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 +#include + +#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 &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 listener; + if (listener) { + abilitymgr->RegisterMissionListener(listener); + } + + std::string deviceId(data, size); + sptr 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; +} + diff --git a/test/fuzztest/registermissionlistener_fuzzer/registermissionlistener_fuzzer.h b/test/fuzztest/registermissionlistener_fuzzer/registermissionlistener_fuzzer.h index 653f346efb..3fd9d324b9 100644 --- a/test/fuzztest/registermissionlistener_fuzzer/registermissionlistener_fuzzer.h +++ b/test/fuzztest/registermissionlistener_fuzzer/registermissionlistener_fuzzer.h @@ -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 diff --git a/test/fuzztest/releasecall_fuzzer/corpus/init b/test/fuzztest/releasecall_fuzzer/corpus/init index 6d6bd4a361..8eb5a7d6eb 100644 --- a/test/fuzztest/releasecall_fuzzer/corpus/init +++ b/test/fuzztest/releasecall_fuzzer/corpus/init @@ -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 \ No newline at end of file diff --git a/test/fuzztest/releasecall_fuzzer/project.xml b/test/fuzztest/releasecall_fuzzer/project.xml index 1020c7b430..6e8ad2cfde 100644 --- a/test/fuzztest/releasecall_fuzzer/project.xml +++ b/test/fuzztest/releasecall_fuzzer/project.xml @@ -1,25 +1,25 @@ - - - - - - 1000 - - 300 - - 4096 - - + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/releasecall_fuzzer/releasecall_fuzzer.cpp b/test/fuzztest/releasecall_fuzzer/releasecall_fuzzer.cpp index e6f3672e63..8564e8bc30 100644 --- a/test/fuzztest/releasecall_fuzzer/releasecall_fuzzer.cpp +++ b/test/fuzztest/releasecall_fuzzer/releasecall_fuzzer.cpp @@ -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 -#include - -#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 &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 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 +#include + +#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 &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 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; +} + diff --git a/test/fuzztest/releasecall_fuzzer/releasecall_fuzzer.h b/test/fuzztest/releasecall_fuzzer/releasecall_fuzzer.h index 98dd0bfae1..c601c007c1 100644 --- a/test/fuzztest/releasecall_fuzzer/releasecall_fuzzer.h +++ b/test/fuzztest/releasecall_fuzzer/releasecall_fuzzer.h @@ -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 diff --git a/test/fuzztest/releasedataability_fuzzer/BUILD.gn b/test/fuzztest/releasedataability_fuzzer/BUILD.gn index c78bc57796..7efa184631 100644 --- a/test/fuzztest/releasedataability_fuzzer/BUILD.gn +++ b/test/fuzztest/releasedataability_fuzzer/BUILD.gn @@ -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") diff --git a/test/fuzztest/releasedataability_fuzzer/corpus/init b/test/fuzztest/releasedataability_fuzzer/corpus/init index 6d6bd4a361..8eb5a7d6eb 100644 --- a/test/fuzztest/releasedataability_fuzzer/corpus/init +++ b/test/fuzztest/releasedataability_fuzzer/corpus/init @@ -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 \ No newline at end of file diff --git a/test/fuzztest/releasedataability_fuzzer/project.xml b/test/fuzztest/releasedataability_fuzzer/project.xml index 1020c7b430..6e8ad2cfde 100644 --- a/test/fuzztest/releasedataability_fuzzer/project.xml +++ b/test/fuzztest/releasedataability_fuzzer/project.xml @@ -1,25 +1,25 @@ - - - - - - 1000 - - 300 - - 4096 - - + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/releasedataability_fuzzer/releasedataability_fuzzer.cpp b/test/fuzztest/releasedataability_fuzzer/releasedataability_fuzzer.cpp index 7d87a35aba..d35decf8c0 100644 --- a/test/fuzztest/releasedataability_fuzzer/releasedataability_fuzzer.cpp +++ b/test/fuzztest/releasedataability_fuzzer/releasedataability_fuzzer.cpp @@ -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 -#include - -#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 GetFuzzAbilityToken() -{ - sptr token = nullptr; - - AbilityRequest abilityRequest; - abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; - abilityRequest.abilityInfo.name = "MainAbility"; - abilityRequest.abilityInfo.type = AbilityType::DATA; - std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); - if (abilityRecord) { - token = abilityRecord->GetToken(); - } - - return token; -} -bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) -{ - auto abilitymgr = AbilityManagerClient::GetInstance(); - sptr scheduler; - if (!abilitymgr) { - return false; - } - - // get token - sptr 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 +#include + +#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 GetFuzzAbilityToken() +{ + sptr token = nullptr; + + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.fuzzTest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AbilityType::DATA; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + if (abilityRecord) { + token = abilityRecord->GetToken(); + } + + return token; +} +bool DoSomethingInterestingWithMyAPI(const char* data, size_t size) +{ + auto abilitymgr = AbilityManagerClient::GetInstance(); + sptr scheduler; + if (!abilitymgr) { + return false; + } + + // get token + sptr 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; +} + diff --git a/test/fuzztest/releasedataability_fuzzer/releasedataability_fuzzer.h b/test/fuzztest/releasedataability_fuzzer/releasedataability_fuzzer.h index 24f48fa44c..10d1b799f9 100644 --- a/test/fuzztest/releasedataability_fuzzer/releasedataability_fuzzer.h +++ b/test/fuzztest/releasedataability_fuzzer/releasedataability_fuzzer.h @@ -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 diff --git a/test/mock/frameworks_kits_ability_native_test/include/mock_bundle_manager.h b/test/mock/frameworks_kits_ability_native_test/include/mock_bundle_manager.h index 23a6f58a65..58a82376a5 100644 --- a/test/mock/frameworks_kits_ability_native_test/include/mock_bundle_manager.h +++ b/test/mock/frameworks_kits_ability_native_test/include/mock_bundle_manager.h @@ -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; diff --git a/test/moduletest/ability_test/BUILD.gn b/test/moduletest/ability_test/BUILD.gn index 5ad37da8bc..bd3a3afc71 100644 --- a/test/moduletest/ability_test/BUILD.gn +++ b/test/moduletest/ability_test/BUILD.gn @@ -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", diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 487cd2e335..2b1d5c0b2b 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -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", ] diff --git a/test/unittest/ability_manager_service_dialog_test/ability_manager_service_dialog_test.cpp b/test/unittest/ability_manager_service_dialog_test/ability_manager_service_dialog_test.cpp index 6a63821f45..3f65514111 100644 --- a/test/unittest/ability_manager_service_dialog_test/ability_manager_service_dialog_test.cpp +++ b/test/unittest/ability_manager_service_dialog_test/ability_manager_service_dialog_test.cpp @@ -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 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 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 \ No newline at end of file diff --git a/test/unittest/app_mgr_service_inner_test/app_mgr_service_inner_test.cpp b/test/unittest/app_mgr_service_inner_test/app_mgr_service_inner_test.cpp index f07fa072d9..f9bba1734e 100644 --- a/test/unittest/app_mgr_service_inner_test/app_mgr_service_inner_test.cpp +++ b/test/unittest/app_mgr_service_inner_test/app_mgr_service_inner_test.cpp @@ -17,10 +17,14 @@ #define private public #include "app_mgr_service_inner.h" +#include "app_running_record.h" #undef private +#include "event_handler.h" #include "hilog_wrapper.h" #include "mock_ability_token.h" #include "mock_app_scheduler.h" +#include "mock_bundle_manager.h" +#include "mock_iapp_state_callback.h" #include "mock_native_token.h" #include "parameters.h" @@ -1353,5 +1357,1030 @@ HWTEST_F(AppMgrServiceInnerTest, KillProcessesByUserId_001, TestSize.Level0) HILOG_INFO("KillProcessesByUserId_001 end"); } + +/** + * @tc.name: StartAbility_001 + * @tc.desc: start ability. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, StartAbility_001, TestSize.Level0) +{ + HILOG_INFO("StartAbility_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + HapModuleInfo hapModuleInfo; + std::shared_ptr want; + std::shared_ptr appRecord; + appMgrServiceInner->StartAbility(nullptr, nullptr, abilityInfo_, nullptr, hapModuleInfo, nullptr); + appMgrServiceInner->StartAbility(nullptr, nullptr, abilityInfo_, appRecord, hapModuleInfo, nullptr); + appMgrServiceInner->StartAbility(nullptr, nullptr, abilityInfo_, appRecord, hapModuleInfo, want); + + OHOS::sptr token = sptr(new (std::nothrow) MockAbilityToken()); + OHOS::sptr preToken = sptr(new (std::nothrow) MockAbilityToken()); + appMgrServiceInner->StartAbility(token, nullptr, abilityInfo_, appRecord, hapModuleInfo, want); + appMgrServiceInner->StartAbility(nullptr, preToken, abilityInfo_, appRecord, hapModuleInfo, want); + appMgrServiceInner->StartAbility(token, preToken, abilityInfo_, appRecord, hapModuleInfo, want); + + BundleInfo bundleInfo; + std::string processName = "test_processName"; + appRecord = appMgrServiceInner->CreateAppRunningRecord(token, nullptr, + applicationInfo_, abilityInfo_, processName, bundleInfo, hapModuleInfo, want); + EXPECT_NE(appRecord, nullptr); + appMgrServiceInner->StartAbility(token, nullptr, abilityInfo_, appRecord, hapModuleInfo, want); + appMgrServiceInner->StartAbility(token, preToken, abilityInfo_, appRecord, hapModuleInfo, want); + + abilityInfo_->applicationInfo.name = "hiservcie"; + abilityInfo_->applicationInfo.bundleName = "com.ix.hiservcie"; + appMgrServiceInner->StartAbility(token, preToken, abilityInfo_, appRecord, hapModuleInfo, want); + + HILOG_INFO("StartAbility_001 end"); +} + +/** + * @tc.name: GetAppRunningRecordByAbilityToken_001 + * @tc.desc: get app running record by ability token. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, GetAppRunningRecordByAbilityToken_001, TestSize.Level0) +{ + HILOG_INFO("GetAppRunningRecordByAbilityToken_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + OHOS::sptr token = sptr(new (std::nothrow) MockAbilityToken()); + appMgrServiceInner->GetAppRunningRecordByAbilityToken(token); + + appMgrServiceInner->appRunningManager_ = nullptr; + appMgrServiceInner->GetAppRunningRecordByAbilityToken(token); + + HILOG_INFO("GetAppRunningRecordByAbilityToken_001 end"); +} + +/** + * @tc.name: AbilityTerminated_001 + * @tc.desc: ability terminated. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, AbilityTerminated_001, TestSize.Level0) +{ + HILOG_INFO("AbilityTerminated_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + appMgrServiceInner->AbilityTerminated(nullptr); + + OHOS::sptr token = sptr(new (std::nothrow) MockAbilityToken()); + appMgrServiceInner->AbilityTerminated(token); + + BundleInfo bundleInfo; + HapModuleInfo hapModuleInfo; + std::shared_ptr want; + std::string processName = "test_processName"; + std::shared_ptr appRecord = appMgrServiceInner->CreateAppRunningRecord(token, nullptr, + applicationInfo_, abilityInfo_, processName, bundleInfo, hapModuleInfo, want); + EXPECT_NE(appRecord, nullptr); + appMgrServiceInner->AbilityTerminated(token); + + HILOG_INFO("AbilityTerminated_001 end"); +} + +/** + * @tc.name: GetAppRunningRecordByAppRecordId_001 + * @tc.desc: get app running record by app record id. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, GetAppRunningRecordByAppRecordId_001, TestSize.Level0) +{ + HILOG_INFO("GetAppRunningRecordByAppRecordId_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + appMgrServiceInner->GetAppRunningRecordByAppRecordId(0); + + appMgrServiceInner->appRunningManager_ = nullptr; + appMgrServiceInner->GetAppRunningRecordByAppRecordId(0); + + HILOG_INFO("GetAppRunningRecordByAppRecordId_001 end"); +} + +/** + * @tc.name: OnAppStateChanged_001 + * @tc.desc: on app state changed. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, OnAppStateChanged_001, TestSize.Level0) +{ + HILOG_INFO("OnAppStateChanged_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + appMgrServiceInner->OnAppStateChanged(nullptr, ApplicationState::APP_STATE_CREATE, true); + appMgrServiceInner->OnAppStateChanged(nullptr, ApplicationState::APP_STATE_CREATE, false); + + BundleInfo bundleInfo; + std::string processName = "test_processName"; + std::shared_ptr appRecord = + appMgrServiceInner->appRunningManager_->CreateAppRunningRecord(applicationInfo_, processName, bundleInfo); + EXPECT_NE(appRecord, nullptr); + appMgrServiceInner->OnAppStateChanged(appRecord, ApplicationState::APP_STATE_CREATE, true); + + sptr mockCallback(new MockAppStateCallback()); + EXPECT_CALL(*mockCallback, OnAppStateChanged(_)).Times(2); + sptr callback1 = iface_cast(mockCallback); + appMgrServiceInner->appStateCallbacks_.push_back(callback1); + appMgrServiceInner->OnAppStateChanged(appRecord, ApplicationState::APP_STATE_CREATE, true); + + sptr callback; + appMgrServiceInner->appStateCallbacks_.push_back(callback); + appMgrServiceInner->OnAppStateChanged(appRecord, ApplicationState::APP_STATE_CREATE, true); + + HILOG_INFO("OnAppStateChanged_001 end"); +} + +/** + * @tc.name: OnAbilityStateChanged_001 + * @tc.desc: on ability state changed. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, OnAbilityStateChanged_001, TestSize.Level0) +{ + HILOG_INFO("OnAbilityStateChanged_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + appMgrServiceInner->OnAbilityStateChanged(nullptr, AbilityState::ABILITY_STATE_CREATE); + + sptr token = new MockAbilityToken(); + std::shared_ptr abilityRunningRecord = + std::make_shared(abilityInfo_, token); + appMgrServiceInner->OnAbilityStateChanged(abilityRunningRecord, AbilityState::ABILITY_STATE_CREATE); + + sptr mockCallback(new MockAppStateCallback()); + EXPECT_CALL(*mockCallback, OnAbilityRequestDone(_, _)).Times(2); + sptr callback1 = iface_cast(mockCallback); + appMgrServiceInner->appStateCallbacks_.push_back(callback1); + appMgrServiceInner->OnAbilityStateChanged(abilityRunningRecord, AbilityState::ABILITY_STATE_CREATE); + + sptr callback; + appMgrServiceInner->appStateCallbacks_.push_back(callback); + appMgrServiceInner->OnAbilityStateChanged(abilityRunningRecord, AbilityState::ABILITY_STATE_CREATE); + + HILOG_INFO("OnAbilityStateChanged_001 end"); +} + +/** + * @tc.name: StartProcess_001 + * @tc.desc: start process. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, StartProcess_001, TestSize.Level0) +{ + HILOG_INFO("StartProcess_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + BundleInfo bundleInfo; + std::string appName = "test_appName"; + std::string processName = "test_processName"; + std::string bundleName = "test_bundleName"; + sptr token = new MockAbilityToken(); + std::shared_ptr appRecord = + appMgrServiceInner->appRunningManager_->CreateAppRunningRecord(applicationInfo_, processName, bundleInfo); + EXPECT_NE(appRecord, nullptr); + appMgrServiceInner->StartProcess(appName, processName, 0, nullptr, 0, bundleName, 0); + appMgrServiceInner->StartProcess(appName, processName, 0, appRecord, 0, bundleName, 0); + appMgrServiceInner->StartProcess(appName, processName, 0, appRecord, 0, bundleName, 1); + + appMgrServiceInner->SetBundleManager(nullptr); + appMgrServiceInner->StartProcess(appName, processName, 0, appRecord, 0, bundleName, 0); + + appMgrServiceInner->SetAppSpawnClient(nullptr); + appMgrServiceInner->StartProcess(appName, processName, 0, nullptr, 0, bundleName, 0); + appMgrServiceInner->StartProcess(appName, processName, 0, appRecord, 0, bundleName, 0); + + HILOG_INFO("StartProcess_001 end"); +} + +/** + * @tc.name: RemoveAppFromRecentList_001 + * @tc.desc: remove app from recent list. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, RemoveAppFromRecentList_001, TestSize.Level0) +{ + HILOG_INFO("RemoveAppFromRecentList_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + std::string appName = "test_appName"; + std::string processName = "test_processName"; + appMgrServiceInner->RemoveAppFromRecentList(appName, processName); + + appMgrServiceInner->AddAppToRecentList(appName, processName, 0, 0); + appMgrServiceInner->RemoveAppFromRecentList(appName, processName); + + appMgrServiceInner->ClearRecentAppList(); + BundleInfo bundleInfo; + std::string appName1 = "hiservcie"; + std::string processName1 = "hiservcie_processName"; + std::shared_ptr appRecord = + appMgrServiceInner->appRunningManager_->CreateAppRunningRecord(applicationInfo_, processName1, bundleInfo); + HILOG_INFO("RemoveAppFromRecentList_001 start 22"); + + pid_t pid = 123; + std::shared_ptr renderRecord = RenderRecord::CreateRenderRecord(pid, "", 0, 0, appRecord); + appRecord->SetRenderRecord(renderRecord); + appMgrServiceInner->AddAppToRecentList(appName1, processName1, pid, 0); + appRecord->SetKeepAliveAppState(true, true); + appMgrServiceInner->RemoveAppFromRecentList(appName1, processName1); + appRecord->SetKeepAliveAppState(false, false); + appMgrServiceInner->RemoveAppFromRecentList(appName1, processName1); + + HILOG_INFO("RemoveAppFromRecentList_001 end"); +} + +/** + * @tc.name: ClearRecentAppList_001 + * @tc.desc: clear recent list. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, ClearRecentAppList_001, TestSize.Level0) +{ + HILOG_INFO("ClearRecentAppList_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + appMgrServiceInner->ClearRecentAppList(); + std::list> list = appMgrServiceInner->GetRecentAppList(); + EXPECT_EQ(list.size(), 0); + + HILOG_INFO("ClearRecentAppList_001 end"); +} + +/** + * @tc.name: OnRemoteDied_001 + * @tc.desc: on remote died. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, OnRemoteDied_001, TestSize.Level0) +{ + HILOG_INFO("OnRemoteDied_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + sptr remoteObject; + appMgrServiceInner->OnRemoteDied(remoteObject, true); + appMgrServiceInner->OnRemoteDied(remoteObject, false); + + HILOG_INFO("OnRemoteDied_001 end"); +} + +/** + * @tc.name: ClearAppRunningData_001 + * @tc.desc: clear app running data. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, ClearAppRunningData_001, TestSize.Level0) +{ + HILOG_INFO("ClearAppRunningData_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + appMgrServiceInner->ClearAppRunningData(nullptr, true); + + BundleInfo info; + std::string processName = "test_processName"; + std::shared_ptr appRecord = + appMgrServiceInner->appRunningManager_->CreateAppRunningRecord(applicationInfo_, processName, info); + appMgrServiceInner->ClearAppRunningData(appRecord, true); + appMgrServiceInner->ClearAppRunningData(appRecord, false); + + std::shared_ptr renderRecord = RenderRecord::CreateRenderRecord(0, "", 0, 0, appRecord); + appRecord->SetRenderRecord(renderRecord); + appMgrServiceInner->ClearAppRunningData(appRecord, false); + + pid_t pid = 123; + std::shared_ptr renderRecord1 = RenderRecord::CreateRenderRecord(pid, "", 0, 0, appRecord); + appRecord->SetRenderRecord(renderRecord1); + appMgrServiceInner->ClearAppRunningData(appRecord, false); + + appRecord->SetKeepAliveAppState(true, true); + appMgrServiceInner->ClearAppRunningData(appRecord, false); + + appMgrServiceInner->eventHandler_ = nullptr; + appMgrServiceInner->ClearAppRunningData(appRecord, false); + + appRecord->restartResidentProcCount_ = 0; + appMgrServiceInner->ClearAppRunningData(appRecord, false); + + appRecord->appInfo_ = nullptr; + appMgrServiceInner->ClearAppRunningData(appRecord, false); + + HILOG_INFO("ClearAppRunningData_001 end"); +} + +/** + * @tc.name: AddAppDeathRecipient_001 + * @tc.desc: add app death recipient. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, AddAppDeathRecipient_001, TestSize.Level0) +{ + HILOG_INFO("AddAppDeathRecipient_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + BundleInfo bundleInfo; + std::string appName = "test_appName"; + std::string processName = "test_processName"; + std::string bundleName = "test_bundleName"; + sptr token = new MockAbilityToken(); + std::shared_ptr appRecord = + appMgrServiceInner->appRunningManager_->CreateAppRunningRecord(applicationInfo_, processName, bundleInfo); + EXPECT_NE(appRecord, nullptr); + sptr appDeathRecipient; + pid_t pid = 999; + appMgrServiceInner->AddAppDeathRecipient(pid, appDeathRecipient); + + pid_t pid1 = 123; + appMgrServiceInner->AddAppDeathRecipient(pid1, appDeathRecipient); + + HILOG_INFO("AddAppDeathRecipient_001 end"); +} + +/** + * @tc.name: HandleTimeOut_001 + * @tc.desc: handle time out. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, HandleTimeOut_001, TestSize.Level0) +{ + HILOG_INFO("HandleTimeOut_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + InnerEvent::Pointer innerEvent = InnerEvent::Pointer(nullptr, nullptr); + appMgrServiceInner->HandleTimeOut(innerEvent); + + appMgrServiceInner->appRunningManager_ = nullptr; + appMgrServiceInner->HandleTimeOut(innerEvent); + + HILOG_INFO("HandleTimeOut_001 end"); +} + +/** + * @tc.name: HandleAbilityAttachTimeOut_001 + * @tc.desc: handle ability attach time out. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, HandleAbilityAttachTimeOut_001, TestSize.Level0) +{ + HILOG_INFO("HandleAbilityAttachTimeOut_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + appMgrServiceInner->HandleAbilityAttachTimeOut(nullptr); + + appMgrServiceInner->appRunningManager_ = nullptr; + appMgrServiceInner->HandleAbilityAttachTimeOut(nullptr); + + HILOG_INFO("HandleAbilityAttachTimeOut_001 end"); +} + +/** + * @tc.name: PrepareTerminate_001 + * @tc.desc: prepare terminate. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, PrepareTerminate_001, TestSize.Level0) +{ + HILOG_INFO("PrepareTerminate_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + appMgrServiceInner->PrepareTerminate(nullptr); + + appMgrServiceInner->appRunningManager_ = nullptr; + appMgrServiceInner->PrepareTerminate(nullptr); + + HILOG_INFO("PrepareTerminate_001 end"); +} + +/** + * @tc.name: HandleTerminateApplicationTimeOut_001 + * @tc.desc: handle terminate application time out. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, HandleTerminateApplicationTimeOut_001, TestSize.Level0) +{ + HILOG_INFO("HandleTerminateApplicationTimeOut_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + appMgrServiceInner->HandleTerminateApplicationTimeOut(0); + + BundleInfo bundleInfo; + std::string appName = "test_appName"; + std::string processName = "test_processName"; + std::string bundleName = "test_bundleName"; + sptr token = new MockAbilityToken(); + std::shared_ptr appRecord = + appMgrServiceInner->appRunningManager_->CreateAppRunningRecord(applicationInfo_, processName, bundleInfo); + EXPECT_NE(appRecord, nullptr); + appRecord->eventId_ = 0; + appMgrServiceInner->HandleTerminateApplicationTimeOut(0); + + pid_t pid = 1; + appRecord->GetPriorityObject()->SetPid(pid); + appMgrServiceInner->HandleTerminateApplicationTimeOut(0); + + appMgrServiceInner->eventHandler_ = nullptr; + appMgrServiceInner->HandleTerminateApplicationTimeOut(0); + + appMgrServiceInner->appRunningManager_ = nullptr; + appMgrServiceInner->HandleTerminateApplicationTimeOut(0); + + HILOG_INFO("HandleTerminateApplicationTimeOut_001 end"); +} + +/** + * @tc.name: HandleAddAbilityStageTimeOut_001 + * @tc.desc: handle add ability stage time out. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, HandleAddAbilityStageTimeOut_001, TestSize.Level0) +{ + HILOG_INFO("HandleAddAbilityStageTimeOut_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + appMgrServiceInner->HandleAddAbilityStageTimeOut(0); + + BundleInfo bundleInfo; + std::string appName = "test_appName"; + std::string processName = "test_processName"; + std::string bundleName = "test_bundleName"; + sptr token = new MockAbilityToken(); + std::shared_ptr appRecord = + appMgrServiceInner->appRunningManager_->CreateAppRunningRecord(applicationInfo_, processName, bundleInfo); + EXPECT_NE(appRecord, nullptr); + appRecord->eventId_ = 0; + appMgrServiceInner->HandleAddAbilityStageTimeOut(0); + + appRecord->isSpecifiedAbility_ = true; + appMgrServiceInner->HandleAddAbilityStageTimeOut(0); + + sptr response; + appMgrServiceInner->startSpecifiedAbilityResponse_ = response; + appMgrServiceInner->HandleAddAbilityStageTimeOut(0); + + appMgrServiceInner->appRunningManager_ = nullptr; + appMgrServiceInner->HandleAddAbilityStageTimeOut(0); + + HILOG_INFO("HandleAddAbilityStageTimeOut_001 end"); +} + +/** + * @tc.name: GetRunningProcessInfoByToken_001 + * @tc.desc: get running process info by token. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, GetRunningProcessInfoByToken_001, TestSize.Level0) +{ + HILOG_INFO("GetRunningProcessInfoByToken_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + AppExecFwk::RunningProcessInfo info; + appMgrServiceInner->GetRunningProcessInfoByToken(nullptr, info); + + appMgrServiceInner->appRunningManager_ = nullptr; + appMgrServiceInner->GetRunningProcessInfoByToken(nullptr, info); + + HILOG_INFO("GetRunningProcessInfoByToken_001 end"); +} + +/** + * @tc.name: GetRunningProcessInfoByAccessTokenID_001 + * @tc.desc: get running process info by access token id. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, GetRunningProcessInfoByAccessTokenID_001, TestSize.Level0) +{ + HILOG_INFO("GetRunningProcessInfoByAccessTokenID_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + AppExecFwk::RunningProcessInfo info; + appMgrServiceInner->GetRunningProcessInfoByAccessTokenID(0, info); + + appMgrServiceInner->appRunningManager_ = nullptr; + appMgrServiceInner->GetRunningProcessInfoByAccessTokenID(0, info); + + HILOG_INFO("GetRunningProcessInfoByAccessTokenID_001 end"); +} + +/** + * @tc.name: CheckGetRunningInfoPermission_001 + * @tc.desc: check get running info permission. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, CheckGetRunningInfoPermission_001, TestSize.Level0) +{ + HILOG_INFO("CheckGetRunningInfoPermission_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + appMgrServiceInner->CheckGetRunningInfoPermission(); + + appMgrServiceInner->appRunningManager_ = nullptr; + appMgrServiceInner->CheckGetRunningInfoPermission(); + + HILOG_INFO("CheckGetRunningInfoPermission_001 end"); +} + +/** + * @tc.name: LoadResidentProcess_001 + * @tc.desc: load resident process. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, LoadResidentProcess_001, TestSize.Level0) +{ + HILOG_INFO("LoadResidentProcess_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + std::vector infos; + appMgrServiceInner->LoadResidentProcess(infos); + + HILOG_INFO("LoadResidentProcess_001 end"); +} + +/** + * @tc.name: StartResidentProcess_001 + * @tc.desc: start resident process. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, StartResidentProcess_001, TestSize.Level0) +{ + HILOG_INFO("StartResidentProcess_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + std::vector infos; + appMgrServiceInner->StartResidentProcess(infos, 0, true); + + BundleInfo info; + infos.push_back(info); + + BundleInfo info1; + info1.applicationInfo.process = ""; + infos.push_back(info1); + + BundleInfo info2; + info2.applicationInfo.process = "test_process"; + infos.push_back(info2); + appMgrServiceInner->StartResidentProcess(infos, 0, true); + + appMgrServiceInner->appRunningManager_ = nullptr; + appMgrServiceInner->StartResidentProcess(infos, 0, true); + + HILOG_INFO("StartResidentProcess_001 end"); +} + +/** + * @tc.name: StartEmptyResidentProcess_001 + * @tc.desc: start empty resident process. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, StartEmptyResidentProcess_001, TestSize.Level0) +{ + HILOG_INFO("StartEmptyResidentProcess_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + BundleInfo info; + info.applicationInfo = *applicationInfo_; + std::string processName = "test_process"; + appMgrServiceInner->StartEmptyResidentProcess(info, processName, 0, true); + + appMgrServiceInner->StartEmptyResidentProcess(info, processName, 1, true); + + appMgrServiceInner->StartEmptyResidentProcess(info, "", 0, true); + + appMgrServiceInner->appRunningManager_ = nullptr; + appMgrServiceInner->StartEmptyResidentProcess(info, processName, 0, true); + + appMgrServiceInner->remoteClientManager_ = nullptr; + appMgrServiceInner->StartEmptyResidentProcess(info, processName, 0, true); + + HILOG_INFO("StartEmptyResidentProcess_001 end"); +} + +/** + * @tc.name: CheckRemoteClient_001 + * @tc.desc: check remote client. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, CheckRemoteClient_001, TestSize.Level0) +{ + HILOG_INFO("CheckRemoteClient_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + appMgrServiceInner->CheckRemoteClient(); + + appMgrServiceInner->remoteClientManager_->SetSpawnClient(nullptr); + appMgrServiceInner->CheckRemoteClient(); + + appMgrServiceInner->remoteClientManager_->SetBundleManager(nullptr); + appMgrServiceInner->CheckRemoteClient(); + + appMgrServiceInner->remoteClientManager_ = nullptr; + appMgrServiceInner->CheckRemoteClient(); + + HILOG_INFO("CheckRemoteClient_001 end"); +} + +/** + * @tc.name: RestartResidentProcess_001 + * @tc.desc: restart resident process. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, RestartResidentProcess_001, TestSize.Level0) +{ + HILOG_INFO("RestartResidentProcess_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + appMgrServiceInner->RestartResidentProcess(nullptr); + + std::shared_ptr appRecord; + appMgrServiceInner->RestartResidentProcess(appRecord); + + BundleInfo bundleInfo; + std::string processName = "test_processName"; + appRecord = + appMgrServiceInner->appRunningManager_->CreateAppRunningRecord(applicationInfo_, processName, bundleInfo); + EXPECT_NE(appRecord, nullptr); + appRecord->mainBundleName_ = "com.ohos.settings"; + appMgrServiceInner->RestartResidentProcess(appRecord); + + appMgrServiceInner->appRunningManager_ = nullptr; + appMgrServiceInner->RestartResidentProcess(appRecord); + + appMgrServiceInner->remoteClientManager_ = nullptr; + appMgrServiceInner->RestartResidentProcess(appRecord); + + HILOG_INFO("RestartResidentProcess_001 end"); +} + +/** + * @tc.name: NotifyAppStatusByCallerUid_001 + * @tc.desc: notify app status by caller uid. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, NotifyAppStatusByCallerUid_001, TestSize.Level0) +{ + HILOG_INFO("NotifyAppStatusByCallerUid_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + std::string bundleName = "test_bundle_name"; + std::string eventData = "test_event_data"; + appMgrServiceInner->NotifyAppStatusByCallerUid(bundleName, 0, 0, eventData); + + HILOG_INFO("NotifyAppStatusByCallerUid_001 end"); +} + +/** + * @tc.name: RegisterApplicationStateObserver_001 + * @tc.desc: register application state observer. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, RegisterApplicationStateObserver_001, TestSize.Level0) +{ + HILOG_INFO("RegisterApplicationStateObserver_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + sptr observer; + std::vector bundleNameList; + appMgrServiceInner->RegisterApplicationStateObserver(observer, bundleNameList); + + HILOG_INFO("RegisterApplicationStateObserver_001 end"); +} + +/** + * @tc.name: UnregisterApplicationStateObserver_001 + * @tc.desc: unregister application state observer. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, UnregisterApplicationStateObserver_001, TestSize.Level0) +{ + HILOG_INFO("UnregisterApplicationStateObserver_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + sptr observer; + appMgrServiceInner->UnregisterApplicationStateObserver(observer); + + HILOG_INFO("UnregisterApplicationStateObserver_001 end"); +} + +/** + * @tc.name: GetForegroundApplications_001 + * @tc.desc: get foreground applications. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, GetForegroundApplications_001, TestSize.Level0) +{ + HILOG_INFO("GetForegroundApplications_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + std::vector list; + appMgrServiceInner->GetForegroundApplications(list); + + HILOG_INFO("GetForegroundApplications_001 end"); +} + +/** + * @tc.name: StartUserTestProcess_001 + * @tc.desc: start user test process. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, StartUserTestProcess_001, TestSize.Level0) +{ + HILOG_INFO("StartUserTestProcess_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + AAFwk::Want want; + sptr observer; + BundleInfo bundleInfo; + appMgrServiceInner->StartUserTestProcess(want, nullptr, bundleInfo, 0); + + appMgrServiceInner->StartUserTestProcess(want, observer, bundleInfo, 0); + + std::string bundle_name = "test_bundle_name"; + want.SetParam("-b", bundle_name); + appMgrServiceInner->StartUserTestProcess(want, observer, bundleInfo, 0); + + std::string moduleName = "test_module_name"; + want.SetParam("-m", moduleName); + HapModuleInfo hapModuleInfo; + hapModuleInfo.moduleName = moduleName; + bundleInfo.hapModuleInfos.push_back(hapModuleInfo); + appMgrServiceInner->StartUserTestProcess(want, observer, bundleInfo, 0); + + appMgrServiceInner->remoteClientManager_ = nullptr; + appMgrServiceInner->StartUserTestProcess(want, observer, bundleInfo, 0); + + appMgrServiceInner->appRunningManager_ = nullptr; + appMgrServiceInner->StartUserTestProcess(want, observer, bundleInfo, 0); + + HILOG_INFO("StartUserTestProcess_001 end"); +} + +/** + * @tc.name: GetHapModuleInfoForTestRunner_001 + * @tc.desc: get hap module info for test runner. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, GetHapModuleInfoForTestRunner_001, TestSize.Level0) +{ + HILOG_INFO("GetHapModuleInfoForTestRunner_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + AAFwk::Want want; + sptr observer; + BundleInfo bundleInfo; + HapModuleInfo hapModuleInfo; + appMgrServiceInner->GetHapModuleInfoForTestRunner(want, nullptr, bundleInfo, hapModuleInfo); + + appMgrServiceInner->GetHapModuleInfoForTestRunner(want, observer, bundleInfo, hapModuleInfo); + + hapModuleInfo.moduleName = "test_module_name"; + bundleInfo.hapModuleInfos.push_back(hapModuleInfo); + appMgrServiceInner->GetHapModuleInfoForTestRunner(want, observer, bundleInfo, hapModuleInfo); + + bundleInfo.hapModuleInfos.back().isModuleJson = true; + appMgrServiceInner->GetHapModuleInfoForTestRunner(want, observer, bundleInfo, hapModuleInfo); + + std::string testmoduleName = "test_XXX"; + want.SetParam("-m", testmoduleName); + appMgrServiceInner->GetHapModuleInfoForTestRunner(want, observer, bundleInfo, hapModuleInfo); + + std::string moduleName = "test_module_name"; + want.SetParam("-m", moduleName); + appMgrServiceInner->GetHapModuleInfoForTestRunner(want, observer, bundleInfo, hapModuleInfo); + + HILOG_INFO("GetHapModuleInfoForTestRunner_001 end"); +} + +/** + * @tc.name: UserTestAbnormalFinish_001 + * @tc.desc: user test abnormal finish. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, UserTestAbnormalFinish_001, TestSize.Level0) +{ + HILOG_INFO("UserTestAbnormalFinish_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + sptr observer; + std::string msg = "testmsg"; + appMgrServiceInner->UserTestAbnormalFinish(nullptr, ""); + appMgrServiceInner->UserTestAbnormalFinish(nullptr, msg); + appMgrServiceInner->UserTestAbnormalFinish(observer, ""); + appMgrServiceInner->UserTestAbnormalFinish(observer, msg); + + HILOG_INFO("UserTestAbnormalFinish_001 end"); +} + +/** + * @tc.name: StartEmptyProcess_001 + * @tc.desc: start empty process. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, StartEmptyProcess_001, TestSize.Level0) +{ + HILOG_INFO("StartEmptyProcess_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + AAFwk::Want want; + sptr observer; + BundleInfo info; + HapModuleInfo hapModuleInfo; + std::string processName = "test_processName"; + appMgrServiceInner->StartEmptyProcess(want, nullptr, info, "", 0); + appMgrServiceInner->StartEmptyProcess(want, observer, info, "", 0); + appMgrServiceInner->StartEmptyProcess(want, observer, info, processName, 0); + + info.applicationInfo = *applicationInfo_; + appMgrServiceInner->StartEmptyProcess(want, observer, info, processName, 0); + + want.SetParam("coldStart", true); + appMgrServiceInner->StartEmptyProcess(want, observer, info, processName, 0); + + appMgrServiceInner->remoteClientManager_ = nullptr; + appMgrServiceInner->StartEmptyProcess(want, observer, info, processName, 0); + + appMgrServiceInner->appRunningManager_ = nullptr; + appMgrServiceInner->StartEmptyProcess(want, observer, info, processName, 0); + + HILOG_INFO("StartEmptyProcess_001 end"); +} + +/** + * @tc.name: FinishUserTest_001 + * @tc.desc: finish user test. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, FinishUserTest_001, TestSize.Level0) +{ + HILOG_INFO("FinishUserTest_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + pid_t pid = 0; + appMgrServiceInner->FinishUserTest("", 0, "", pid); + + std::string msg = "testmsg"; + std::string bundleName = "test_bundle_name"; + appMgrServiceInner->FinishUserTest("", 0, bundleName, pid); + appMgrServiceInner->FinishUserTest(msg, 0, "", pid); + appMgrServiceInner->FinishUserTest(msg, 0, bundleName, pid); + + BundleInfo bundleInfo; + HapModuleInfo hapModuleInfo; + std::shared_ptr want; + sptr token = new MockAbilityToken(); + std::string processName = "test_processName"; + std::shared_ptr appRecord = appMgrServiceInner->CreateAppRunningRecord(token, nullptr, + applicationInfo_, abilityInfo_, processName, bundleInfo, hapModuleInfo, want); + EXPECT_NE(appRecord, nullptr); + pid = appRecord->GetPriorityObject()->GetPid(); + appMgrServiceInner->FinishUserTest(msg, 0, bundleName, pid); + + std::shared_ptr record = std::make_shared(); + appRecord->SetUserTestInfo(record); + appMgrServiceInner->FinishUserTest(msg, 0, bundleName, pid); + + appMgrServiceInner->appRunningManager_ = nullptr; + appMgrServiceInner->FinishUserTest(msg, 0, bundleName, pid); + + HILOG_INFO("FinishUserTest_001 end"); +} + +/** + * @tc.name: FinishUserTestLocked_001 + * @tc.desc: finish user test locked. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, FinishUserTestLocked_001, TestSize.Level0) +{ + HILOG_INFO("FinishUserTestLocked_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + appMgrServiceInner->FinishUserTestLocked("", 0, nullptr); + + std::shared_ptr appRecord; + appMgrServiceInner->FinishUserTestLocked("", 0, appRecord); + + std::string msg = "testmsg"; + appMgrServiceInner->FinishUserTestLocked(msg, 0, nullptr); + appMgrServiceInner->FinishUserTestLocked(msg, 0, appRecord); + + BundleInfo bundleInfo; + std::string processName = "test_processName"; + appRecord = + appMgrServiceInner->appRunningManager_->CreateAppRunningRecord(applicationInfo_, processName, bundleInfo); + EXPECT_NE(appRecord, nullptr); + std::shared_ptr record = std::make_shared(); + appRecord->SetUserTestInfo(record); + appMgrServiceInner->FinishUserTestLocked(msg, 0, appRecord); + + record->isFinished = true; + appRecord->SetUserTestInfo(record); + appMgrServiceInner->FinishUserTestLocked(msg, 0, appRecord); + + record->observer = nullptr; + appRecord->SetUserTestInfo(record); + appMgrServiceInner->FinishUserTestLocked(msg, 0, appRecord); + + HILOG_INFO("FinishUserTestLocked_001 end"); +} + +/** + * @tc.name: StartSpecifiedAbility_001 + * @tc.desc: start specified ability. + * @tc.type: FUNC + * @tc.require: issueI5W4S7 + */ +HWTEST_F(AppMgrServiceInnerTest, StartSpecifiedAbility_001, TestSize.Level0) +{ + HILOG_INFO("StartSpecifiedAbility_001 start"); + auto appMgrServiceInner = std::make_shared(); + EXPECT_NE(appMgrServiceInner, nullptr); + + AAFwk::Want want; + AbilityInfo abilityInfo; + appMgrServiceInner->StartSpecifiedAbility(want, abilityInfo); + + appMgrServiceInner->StartSpecifiedAbility(want, *abilityInfo_); + + abilityInfo_->applicationInfo = *applicationInfo_; + appMgrServiceInner->StartSpecifiedAbility(want, *abilityInfo_); + + appMgrServiceInner->remoteClientManager_->SetBundleManager(nullptr); + appMgrServiceInner->StartSpecifiedAbility(want, *abilityInfo_); + + appMgrServiceInner->remoteClientManager_ = nullptr; + appMgrServiceInner->StartSpecifiedAbility(want, *abilityInfo_); + + HILOG_INFO("StartSpecifiedAbility_001 end"); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/test/unittest/frameworks_kits_ability_native_test/BUILD.gn b/test/unittest/frameworks_kits_ability_native_test/BUILD.gn index f93dad9fff..a16f61d2f3 100644 --- a/test/unittest/frameworks_kits_ability_native_test/BUILD.gn +++ b/test/unittest/frameworks_kits_ability_native_test/BUILD.gn @@ -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", ] diff --git a/test/unittest/frameworks_kits_ability_native_test/ability_test.cpp b/test/unittest/frameworks_kits_ability_native_test/ability_test.cpp index 2d8f004778..bc15bf2b12 100644 --- a/test/unittest/frameworks_kits_ability_native_test/ability_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/ability_test.cpp @@ -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 = std::make_shared(); + ASSERT_NE(ability, nullptr); + + // ability info, lifecycle and lifecycle executor is nullptr + std::string extra = ""; + ability->Dump(extra); + + auto abilityInfo = std::make_shared(); + 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(); + EXPECT_NE(application, nullptr); + auto eventRunner = EventRunner::Create(abilityInfo->name); + auto handler = std::make_shared(eventRunner); + sptr 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 = std::make_shared(); + ASSERT_NE(ability, nullptr); + + auto abilityInfo = std::make_shared(); + EXPECT_NE(abilityInfo, nullptr); + abilityInfo->name = "test_OnStart"; + abilityInfo->type = AbilityType::PAGE; + abilityInfo->isStageBasedModel = true; + + auto application = std::make_shared(); + EXPECT_NE(application, nullptr); + Configuration config; + application->SetConfiguration(config); + + auto eventRunner = EventRunner::Create(abilityInfo->name); + auto handler = std::make_shared(eventRunner); + sptr 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 = std::make_shared(); + ASSERT_NE(ability, nullptr); + + auto abilityInfo = std::make_shared(); + 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(); + 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 = std::make_shared(); + ASSERT_NE(ability, nullptr); + + // ability recovery is not nullptr + auto abilityRecovery = std::make_shared(); + EXPECT_NE(abilityRecovery, nullptr); + ability->EnableAbilityRecovery(abilityRecovery); + ability->OnStop(); + + // window is not nullptr + int32_t displayId = 0; + sptr option = new Rosen::WindowOption(); + ability->InitWindow(displayId, option); + ability->OnStop(); + + // lifecycle is nullptr and lifecycle executor is not nullptr + auto lifecycleExecutor = std::make_shared(); + 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 = std::make_shared(); + ASSERT_NE(ability, nullptr); + + auto abilityInfo = std::make_shared(); + EXPECT_NE(abilityInfo, nullptr); + abilityInfo->name = "test_DestroyInstance"; + abilityInfo->type = AbilityType::PAGE; + abilityInfo->isStageBasedModel = false; + auto application = std::make_shared(); + EXPECT_NE(application, nullptr); + auto eventRunner = EventRunner::Create(abilityInfo->name); + auto handler = std::make_shared(eventRunner); + sptr 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 = std::make_shared(); + ASSERT_NE(ability, nullptr); + + // lifecycle is nullptr and lifecycle executor is not nullptr + auto lifecycleExecutor = std::make_shared(); + 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 = std::make_shared(); + ASSERT_NE(ability, nullptr); + + // lifecycle is nullptr and lifecycle executor is not nullptr + auto lifecycleExecutor = std::make_shared(); + 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 = std::make_shared(); + ASSERT_NE(ability, nullptr); + + // ability info is nullptr + ability->OnBackground(); + + // stage mode, scene is not nullptr + auto abilityInfo = std::make_shared(); + EXPECT_NE(abilityInfo, nullptr); + abilityInfo->name = "test_OnStart"; + abilityInfo->type = AbilityType::PAGE; + abilityInfo->isStageBasedModel = true; + + auto application = std::make_shared(); + EXPECT_NE(application, nullptr); + auto eventRunner = EventRunner::Create(abilityInfo->name); + auto handler = std::make_shared(eventRunner); + sptr token = nullptr; + ability->Init(abilityInfo, application, handler, token); + + int32_t displayId = 0; + sptr 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 = std::make_shared(); + 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(); + 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 = std::make_shared(); + 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(); + 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 = std::make_shared(); + ASSERT_NE(ability, nullptr); + + std::shared_ptr uri = std::make_shared("dataability:///com.ohos.test"); + std::shared_ptr operation = DataAbilityOperation::NewUpdateBuilder(uri)->Build();; + std::vector> executeBatchOperations; + executeBatchOperations.push_back(operation); + + // ability info is nullptr + auto result = ability->ExecuteBatch(executeBatchOperations); + + auto abilityInfo = std::make_shared(); + EXPECT_NE(abilityInfo, nullptr); + abilityInfo->name = "test_ExecuteOperation"; + abilityInfo->type = AbilityType::PAGE; // not DATA + auto application = std::make_shared(); + EXPECT_NE(application, nullptr); + auto eventRunner = EventRunner::Create(abilityInfo->name); + auto handler = std::make_shared(eventRunner); + sptr 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 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 = std::make_shared(); + 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 = std::make_shared(); + 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 = std::make_shared(); + 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 = std::make_shared(); + ASSERT_NE(ability, nullptr); std::shared_ptr pageAbilityInfo = std::make_shared(); 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 = std::make_shared(); + 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 = std::make_shared(); + 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 = std::make_shared(); + 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 = std::make_shared(); - 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 handler = nullptr; std::shared_ptr serviceAbilityInfo = std::make_shared(); 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 pageAbilityInfo = std::make_shared(); 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 = std::make_shared(); + 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 handler = nullptr; + std::shared_ptr abilityInfo = std::make_shared(); + 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 = std::make_shared(); + 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 = std::make_shared(); + 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 = std::make_shared(); + 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 = std::make_shared(); + 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(); + 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 = std::make_shared(); + ASSERT_NE(ability, nullptr); + + auto keyEvent = std::make_shared(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 = std::make_shared(); + 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(); 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 = std::make_shared(); + 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 = std::make_shared(); + 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 = std::make_shared(); + 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 = std::make_shared(); + 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(); + 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 = std::make_shared(); + ASSERT_NE(ability, nullptr); + + // branch when ability info is nullptr + AbilityRuntime::WantAgent::WantAgent wantAgent; + ability->StartBackgroundRunning(wantAgent); std::shared_ptr pageAbilityInfo = std::make_shared(); 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 = std::make_shared(); + ASSERT_NE(ability, nullptr); std::vector> results; std::shared_ptr operation = nullptr; @@ -1565,6 +2046,7 @@ HWTEST_F(AbilityBaseTest, AbilityChangeRef2Value_0100, TestSize.Level1) { HILOG_INFO("%{public}s start.", __func__); std::shared_ptr ability = std::make_shared(); + ASSERT_NE(ability, nullptr); // index larger than or equal to numRefs std::vector> results; @@ -1609,6 +2091,7 @@ HWTEST_F(AbilityBaseTest, AbilityCheckAssertQueryResult_0100, TestSize.Level1) { HILOG_INFO("%{public}s start.", __func__); std::shared_ptr ability = std::make_shared(); + ASSERT_NE(ability, nullptr); // queryResult is nullptr std::shared_ptr queryResult = nullptr; @@ -1638,6 +2121,7 @@ HWTEST_F(AbilityBaseTest, AbilityStartFeatureAbilityForResult_0100, TestSize.Lev { HILOG_INFO("%{public}s start.", __func__); std::shared_ptr ability = std::make_shared(); + 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 = std::make_shared(); + 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 = std::make_shared(); + 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 = std::make_shared(); + 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 = std::make_shared(); + 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 = std::make_shared(); + 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 = std::make_shared(); + 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 = std::make_shared(); + 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(Rosen::WindowMode::WINDOW_MODE_UNDEFINED)); + int32_t displayId = 0; + sptr option = new Rosen::WindowOption(); + ability->InitWindow(displayId, option); + windowMode = ability->GetCurrentWindowMode(); + EXPECT_EQ(windowMode, static_cast(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 = std::make_shared(); + 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 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 = std::make_shared(); + ASSERT_NE(ability, nullptr); auto icon = std::make_shared(); 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 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 = std::make_shared(); + ASSERT_NE(ability, nullptr); std::shared_ptr pageAbilityInfo = std::make_shared(); 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(ApplicationLoader::GetInstance().GetApplicationByName()); + auto application = std::make_shared(); + 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 = std::make_shared(); + ASSERT_NE(ability, nullptr); std::shared_ptr pageAbilityInfo = std::make_shared(); 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(ApplicationLoader::GetInstance().GetApplicationByName()); + auto application = std::make_shared(); + 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 = std::make_shared(); + 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 = std::make_shared(); + 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 = std::make_shared(); + ASSERT_NE(ability, nullptr); // ability window is nullptr int orientation = static_cast(DisplayOrientation::FOLLOWRECENT); diff --git a/test/unittest/frameworks_kits_appkit_native_test/BUILD.gn b/test/unittest/frameworks_kits_appkit_native_test/BUILD.gn index d04c84396a..71c13199ea 100644 --- a/test/unittest/frameworks_kits_appkit_native_test/BUILD.gn +++ b/test/unittest/frameworks_kits_appkit_native_test/BUILD.gn @@ -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", diff --git a/test/unittest/frameworks_kits_appkit_native_test/context_impl_test.cpp b/test/unittest/frameworks_kits_appkit_native_test/context_impl_test.cpp index 58c5726f74..1e222777e1 100644 --- a/test/unittest/frameworks_kits_appkit_native_test/context_impl_test.cpp +++ b/test/unittest/frameworks_kits_appkit_native_test/context_impl_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(); + sptr bundleObject = new (std::nothrow) BundleMgrService(); + DelayedSingleton::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(); + EXPECT_NE(contextImpl, nullptr); + + auto parentContext = std::make_shared(); + EXPECT_NE(parentContext, nullptr); + auto applicationInfo = std::make_shared(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + EXPECT_NE(parentContext, nullptr); + auto applicationInfo = std::make_shared(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + EXPECT_NE(parentContext, nullptr); + auto applicationInfo = std::make_shared(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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 applicationInfo = std::make_shared(); 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(); + EXPECT_NE(contextImpl, nullptr); + + auto parentContext = std::make_shared(); + 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(); + 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(); + 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(); + 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(); + EXPECT_NE(contextImpl, nullptr); + + auto codePath = contextImpl->GetBundleCodePath(); + EXPECT_EQ(codePath, ""); + + // construt application info + auto applicationInfo = std::make_shared(); + 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(); + 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(); + 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(); + 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(); + EXPECT_NE(contextImpl, nullptr); + + auto abilityInfo = std::make_shared(); + 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(); + EXPECT_NE(contextImpl, nullptr); + + contextImpl->SetToken(nullptr); + sptr 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(); + 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(); + 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 } diff --git a/test/unittest/mission_data_storage_test/BUILD.gn b/test/unittest/mission_data_storage_test/BUILD.gn new file mode 100755 index 0000000000..a7761ad97b --- /dev/null +++ b/test/unittest/mission_data_storage_test/BUILD.gn @@ -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" ] +} diff --git a/test/unittest/mission_data_storage_test/mission_data_storage_test.cpp b/test/unittest/mission_data_storage_test/mission_data_storage_test.cpp new file mode 100755 index 0000000000..bf9c03ed22 --- /dev/null +++ b/test/unittest/mission_data_storage_test/mission_data_storage_test.cpp @@ -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 +#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(); + auto handler = std::make_shared(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(); + 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->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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + int32_t missionId = 1; + MissionSnapshot missionSnapshot; + missionSnapshot.snapshot = std::make_shared(); + 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(); + int32_t missionId = 0; + MissionSnapshot missionSnapshot; + missionSnapshot.isPrivate = true; + missionSnapshot.snapshot = std::make_shared(); + 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(); + int32_t missionId = 0; + MissionSnapshot missionSnapshot; + missionSnapshot.snapshot = std::make_shared(); + 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(); + int32_t missionId = 0; + MissionSnapshot missionSnapshot; + missionSnapshot.snapshot = std::make_shared(); + 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(); + int32_t missionId = 0; + MissionSnapshot missionSnapshot; + missionSnapshot.snapshot = std::make_shared(); + 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(); + int32_t missionId = 0; + MissionSnapshot missionSnapshot; + missionSnapshot.snapshot = std::make_shared(); + 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(); + std::shared_ptr 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(); + std::shared_ptr snapshot = std::make_shared(); + 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(); + 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->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(); + int32_t missionId = 0; + MissionSnapshot missionSnapshot; + missionSnapshot.snapshot = std::make_shared(); + 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(); + 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(); + 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->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(); + int32_t missionId = 0; + bool isLowResolution = true; + std::shared_ptr 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(); + int32_t missionId = 0; + bool isLowResolution = true; + std::unique_ptr 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(); + int32_t missionId = 100; + bool isLowResolution = false; + std::unique_ptr 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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 diff --git a/test/unittest/mission_info_mgr_test/BUILD.gn b/test/unittest/mission_info_mgr_test/BUILD.gn new file mode 100755 index 0000000000..5510a209c4 --- /dev/null +++ b/test/unittest/mission_info_mgr_test/BUILD.gn @@ -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" ] +} diff --git a/test/unittest/mission_info_mgr_test/mission_info_mgr_test.cpp b/test/unittest/mission_info_mgr_test/mission_info_mgr_test.cpp new file mode 100755 index 0000000000..7f3f45fa0a --- /dev/null +++ b/test/unittest/mission_info_mgr_test/mission_info_mgr_test.cpp @@ -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 + +#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->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->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->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(); + 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(); + 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(); + 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->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(); + 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 diff --git a/test/unittest/mission_listener_stub_test/BUILD.gn b/test/unittest/mission_listener_stub_test/BUILD.gn new file mode 100755 index 0000000000..7a8ba6cbfd --- /dev/null +++ b/test/unittest/mission_listener_stub_test/BUILD.gn @@ -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" ] +} diff --git a/test/unittest/mission_listener_stub_test/mission_listener_stub_test.cpp b/test/unittest/mission_listener_stub_test/mission_listener_stub_test.cpp new file mode 100755 index 0000000000..3886812a29 --- /dev/null +++ b/test/unittest/mission_listener_stub_test/mission_listener_stub_test.cpp @@ -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 +#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 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 diff --git a/test/unittest/mission_listener_stub_test/mock_mission_listener_stub.h b/test/unittest/mission_listener_stub_test/mock_mission_listener_stub.h new file mode 100755 index 0000000000..03a167da0b --- /dev/null +++ b/test/unittest/mission_listener_stub_test/mock_mission_listener_stub.h @@ -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 + +#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 &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 diff --git a/test/unittest/mission_test/mission_test.cpp b/test/unittest/mission_test/mission_test.cpp index df732aafdc..4904ee82f6 100644 --- a/test/unittest/mission_test/mission_test.cpp +++ b/test/unittest/mission_test/mission_test.cpp @@ -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(nullptr, ""); + auto mission = std::make_shared(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(nullptr, ""); + auto mission = std::make_shared(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(nullptr, ""); + auto mission = std::make_shared(1, nullptr); auto missionList = std::make_shared(); 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(nullptr, ""); + auto mission = std::make_shared(1, nullptr); auto missionList = std::make_shared(); mission->SetMissionList(missionList); auto missionList1 = std::make_shared(); @@ -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(nullptr, ""); + auto mission = std::make_shared(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 = std::make_shared(want, abilityInfo, applicationInfo); - auto mission = std::make_shared(abilityRecord); + auto mission = std::make_shared(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 = std::make_shared(want, abilityInfo, applicationInfo); - auto mission = std::make_shared(abilityRecord); + auto mission = std::make_shared(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 = std::make_shared(want, abilityInfo, applicationInfo); - auto mission = std::make_shared(abilityRecord); + auto mission = std::make_shared(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 = std::make_shared(want, abilityInfo, applicationInfo); - auto mission = std::make_shared(abilityRecord, ""); + auto mission = std::make_shared(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 = std::make_shared(want, abilityInfo, applicationInfo); - auto mission = std::make_shared(abilityRecord, "name1"); + auto mission = std::make_shared(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 = std::make_shared(want, abilityInfo, applicationInfo); - auto mission = std::make_shared(abilityRecord, "name1"); + auto mission = std::make_shared(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 = std::make_shared(want, abilityInfo, applicationInfo); - auto mission = std::make_shared(abilityRecord, "name1"); + auto mission = std::make_shared(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 = std::make_shared(want, abilityInfo, applicationInfo); - auto mission = std::make_shared(abilityRecord, "name1"); + auto mission = std::make_shared(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 = std::make_shared(want, abilityInfo, applicationInfo); + auto mission1 = std::make_shared(0, abilityRecord, "name1"); + auto mission2= std::make_shared(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(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 = std::make_shared(want, abilityInfo, applicationInfo); + auto mission = std::make_shared(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 = std::make_shared(want, abilityInfo, applicationInfo); + auto mission = std::make_shared(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(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(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(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(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(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(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(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(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 = std::make_shared(want, abilityInfo, applicationInfo); + auto mission = std::make_shared(0, abilityRecord, "name1"); + std::vector 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(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 \ No newline at end of file diff --git a/test/unittest/pending_want_test/pending_want_test.cpp b/test/unittest/pending_want_test/pending_want_test.cpp index 042542e670..ad112f79ed 100644 --- a/test/unittest/pending_want_test/pending_want_test.cpp +++ b/test/unittest/pending_want_test/pending_want_test.cpp @@ -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 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 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 = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + sptr 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 onCompleted; + sptr 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 = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + sptr onCompleted; + sptr 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 = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + sptr onCompleted = nullptr; + std::string requiredPermission = "Permission"; + sptr 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 = std::make_shared(); + ElementName element("device", "bundleName", "abilityName"); + want->SetElement(element); + sptr onCompleted; + std::string requiredPermission = "Permission"; + std::shared_ptr options; + sptr 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 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 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 = std::make_shared(nullptr); + std::shared_ptr cancelListener1 = std::make_shared(); + std::shared_ptr cancelListener2 = std::make_shared(); + pendingWant->RegisterCancelListener(cancelListener1, nullptr); + pendingWant->RegisterCancelListener(cancelListener2, nullptr); + std::weak_ptr outerInstance(pendingWant); + PendingWant::CancelReceiver cancelreceiver(outerInstance); + cancelreceiver.Send(0); + + EXPECT_EQ(callBackCancelListenerConnt, 2); + callBackCancelListenerConnt = 0; +} + } // namespace OHOS::AbilityRuntime::WantAgent diff --git a/test/unittest/remote_mission_listener_stub_test/BUILD.gn b/test/unittest/remote_mission_listener_stub_test/BUILD.gn new file mode 100755 index 0000000000..9fb453c9b6 --- /dev/null +++ b/test/unittest/remote_mission_listener_stub_test/BUILD.gn @@ -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" ] +} diff --git a/test/unittest/remote_mission_listener_stub_test/mock_remote_mission_listener_stub.h b/test/unittest/remote_mission_listener_stub_test/mock_remote_mission_listener_stub.h new file mode 100755 index 0000000000..c726f434b8 --- /dev/null +++ b/test/unittest/remote_mission_listener_stub_test/mock_remote_mission_listener_stub.h @@ -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 + +#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 diff --git a/test/unittest/remote_mission_listener_stub_test/remote_mission_listener_stub_test.cpp b/test/unittest/remote_mission_listener_stub_test/remote_mission_listener_stub_test.cpp new file mode 100755 index 0000000000..c30f9ed4de --- /dev/null +++ b/test/unittest/remote_mission_listener_stub_test/remote_mission_listener_stub_test.cpp @@ -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 +#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 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 diff --git a/test/unittest/task_data_persistence_mgr_test/BUILD.gn b/test/unittest/task_data_persistence_mgr_test/BUILD.gn new file mode 100755 index 0000000000..daf42e3985 --- /dev/null +++ b/test/unittest/task_data_persistence_mgr_test/BUILD.gn @@ -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" ] +} diff --git a/test/unittest/task_data_persistence_mgr_test/task_data_persistence_mgr_test.cpp b/test/unittest/task_data_persistence_mgr_test/task_data_persistence_mgr_test.cpp new file mode 100755 index 0000000000..93722f196a --- /dev/null +++ b/test/unittest/task_data_persistence_mgr_test/task_data_persistence_mgr_test.cpp @@ -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 + +#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(); + std::list 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + int missionId = 0; + std::shared_ptr 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(); + int userId = 0; + taskDataPersistenceMgr->Init(userId); + int missionId = 0; + std::shared_ptr 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(); + 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(); + 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 diff --git a/tools/test/mock/mock_ability_manager_stub.h b/tools/test/mock/mock_ability_manager_stub.h index ff89b1e62c..9e09ccde34 100644 --- a/tools/test/mock/mock_ability_manager_stub.h +++ b/tools/test/mock/mock_ability_manager_stub.h @@ -198,10 +198,7 @@ public: const std::string& args, std::vector& info, bool isClient, bool isUserID, int UserID) override {} - int StartUserTest(const Want &want, const sptr &observer) override - { - return 0; - } + MOCK_METHOD2(StartUserTest, int(const Want &want, const sptr &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() { diff --git a/tools/test/unittest/aa/BUILD.gn b/tools/test/unittest/aa/BUILD.gn index 9dbdffbd80..6fea039777 100644 --- a/tools/test/unittest/aa/BUILD.gn +++ b/tools/test/unittest/aa/BUILD.gn @@ -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" ] + } } diff --git a/tools/test/unittest/aa/aa_command_force_stop_test.cpp b/tools/test/unittest/aa/aa_command_force_stop_test.cpp new file mode 100644 index 0000000000..23078cbc7e --- /dev/null +++ b/tools/test/unittest/aa/aa_command_force_stop_test.cpp @@ -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 +#include + +#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(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(new MockAbilityManagerStub()); + ASSERT_NE(mockAbilityManagerStub, nullptr); + EXPECT_CALL(*mockAbilityManagerStub, KillProcess(_)) + .Times(1) + .WillOnce(Return(-1)); + managerClientPtr->proxy_ = static_cast(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(new MockAbilityManagerStub()); + ASSERT_NE(mockAbilityManagerStub, nullptr); + EXPECT_CALL(*mockAbilityManagerStub, KillProcess(_)) + .Times(1) + .WillOnce(Return(0)); + managerClientPtr->proxy_ = static_cast(mockAbilityManagerStub); + + EXPECT_EQ(cmd.ExecCommand(), STRING_FORCE_STOP_OK + "\n"); + testing::Mock::AllowLeak(mockAbilityManagerStub); +} \ No newline at end of file diff --git a/tools/test/unittest/aa/aa_command_force_timeout_test.cpp b/tools/test/unittest/aa/aa_command_force_timeout_test.cpp new file mode 100644 index 0000000000..df31697206 --- /dev/null +++ b/tools/test/unittest/aa/aa_command_force_timeout_test.cpp @@ -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 +#include + +#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(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(new MockAbilityManagerStub()); + ASSERT_NE(mockAbilityManagerStub, nullptr); + EXPECT_CALL(*mockAbilityManagerStub, ForceTimeoutForTest(_, _)) + .Times(1) + .WillOnce(Return(-1)); + managerClientPtr->proxy_ = static_cast(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(new MockAbilityManagerStub()); + ASSERT_NE(mockAbilityManagerStub, nullptr); + EXPECT_CALL(*mockAbilityManagerStub, ForceTimeoutForTest(_, _)) + .Times(1) + .WillOnce(Return(0)); + managerClientPtr->proxy_ = static_cast(mockAbilityManagerStub); + + EXPECT_EQ(cmd.ExecCommand(), STRING_FORCE_TIMEOUT_OK + "\n"); + testing::Mock::AllowLeak(mockAbilityManagerStub); +} \ No newline at end of file diff --git a/tools/test/unittest/aa/aa_command_test_test.cpp b/tools/test/unittest/aa/aa_command_test_test.cpp new file mode 100644 index 0000000000..a16d8adfa4 --- /dev/null +++ b/tools/test/unittest/aa/aa_command_test_test.cpp @@ -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 +#include + +#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(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(new MockAbilityManagerStub()); + ASSERT_NE(mockAbilityManagerStub, nullptr); + EXPECT_CALL(*mockAbilityManagerStub, StartUserTest(_, _)) + .Times(1) + .WillOnce(Return(-1)); + managerClientPtr->proxy_ = static_cast(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(new MockAbilityManagerStub()); + ASSERT_NE(mockAbilityManagerStub, nullptr); + EXPECT_CALL(*mockAbilityManagerStub, StartUserTest(_, _)) + .Times(1) + .WillOnce(Return(-1)); + managerClientPtr->proxy_ = static_cast(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(new MockAbilityManagerStub()); + ASSERT_NE(mockAbilityManagerStub, nullptr); + EXPECT_CALL(*mockAbilityManagerStub, StartUserTest(_, _)) + .Times(1) + .WillOnce(Return(0)); + managerClientPtr->proxy_ = static_cast(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 &observer) -> int { + sptr testObserver = iface_cast(observer); + if (!testObserver) { + return -1; + } + testObserver->TestFinished("success", 0); + return 0; + }; + auto managerClientPtr = AbilityManagerClient::GetInstance(); + auto mockAbilityManagerStub = sptr(new MockAbilityManagerStub()); + ASSERT_NE(mockAbilityManagerStub, nullptr); + EXPECT_CALL(*mockAbilityManagerStub, StartUserTest(_, _)) + .Times(1) + .WillOnce(Invoke(mockHandler)); + managerClientPtr->proxy_ = static_cast(mockAbilityManagerStub); + + EXPECT_EQ(cmd.ExecCommand(), STRING_USER_TEST_FINISHED + "\n"); + testing::Mock::AllowLeak(mockAbilityManagerStub); +} \ No newline at end of file