From 4c8d87443e6d7e4848d7e382f27bae975c0b624b Mon Sep 17 00:00:00 2001 From: zhangzezhong Date: Tue, 3 Jun 2025 13:06:54 +0800 Subject: [PATCH 01/23] add AppRunningManager unittest cases for ability_runtime Signed-off-by: zhangzezhong --- .../app_running_manager_third_test.cpp | 105 ++++ .../app_running_record_test.cpp | 465 +++++++++++++++++- ...ght_intent_execute_manager_second_test.cpp | 297 +++++++++++ ...sight_intent_execute_param_second_test.cpp | 144 ++++++ 4 files changed, 1010 insertions(+), 1 deletion(-) diff --git a/test/unittest/app_running_manager_third_test/app_running_manager_third_test.cpp b/test/unittest/app_running_manager_third_test/app_running_manager_third_test.cpp index e73206e788..b79730d0f3 100644 --- a/test/unittest/app_running_manager_third_test/app_running_manager_third_test.cpp +++ b/test/unittest/app_running_manager_third_test/app_running_manager_third_test.cpp @@ -518,5 +518,110 @@ HWTEST_F(AppRunningManagerThirdTest, AppRunningManager_UpdateConfigurationByBund EXPECT_EQ(ret, ERR_INVALID_VALUE); TAG_LOGI(AAFwkTag::TEST, "AppRunningManager_UpdateConfigurationByBundleName_0200 end"); } + +/** + * @tc.name: AppRunningManager_GetAppRunningRecordByChildRecordPid_0100 + * @tc.desc: Test GetAppRunningRecordByChildRecordPid + * @tc.type: FUNC + */ +HWTEST_F(AppRunningManagerThirdTest, AppRunningManager_GetAppRunningRecordByChildRecordPid_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningManager_GetAppRunningRecordByChildRecordPid_0100 start"); + auto appRunningManager = std::make_shared(); + EXPECT_NE(appRunningManager, nullptr); + pid_t pid = PID; + auto result = appRunningManager->GetAppRunningRecordByChildRecordPid(pid); + EXPECT_EQ(result, nullptr); + TAG_LOGI(AAFwkTag::TEST, "AppRunningManager_GetAppRunningRecordByChildRecordPid_0100 end"); +} + +/** + * @tc.name: AppRunningManager_GetAppRunningRecordByChildRecordPid_0200 + * @tc.desc: Test GetAppRunningRecordByChildRecordPid + * @tc.type: FUNC + */ +HWTEST_F(AppRunningManagerThirdTest, AppRunningManager_GetAppRunningRecordByChildRecordPid_0200, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningManager_GetAppRunningRecordByChildRecordPid_0200 start"); + auto appRunningManager = std::make_shared(); + EXPECT_NE(appRunningManager, nullptr); + auto appRunningRecord = std::make_shared(appInfo_, USR_ID_100, PROCESS_NAME); + auto appRunningRecordChild = std::make_shared(appInfo_, USR_ID_100, PROCESS_NAME); + appRunningRecord->childAppRecordMap_[PID] = appRunningRecordChild; + EXPECT_NE(appRunningRecord, nullptr); + appRunningManager->appRunningRecordMap_.emplace(PID, appRunningRecord); + pid_t pid = PID; + auto ret = appRunningManager->GetAppRunningRecordByChildRecordPid(pid); + EXPECT_NE(ret, nullptr); + TAG_LOGI(AAFwkTag::TEST, "AppRunningManager_GetAppRunningRecordByChildRecordPid_0200 end"); +} + +/** + * @tc.name: AppRunningManager_AddUIExtensionBindItem_0100 + * @tc.desc: Test AddUIExtensionBindItem + * @tc.type: FUNC + */ +HWTEST_F(AppRunningManagerThirdTest, AppRunningManager_AddUIExtensionBindItem_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningManager_AddUIExtensionBindItem_0100 start"); + auto appRunningManager = std::make_shared(); + EXPECT_NE(appRunningManager, nullptr); + int32_t bindId = 0; + UIExtensionProcessBindInfo bindInfo; + auto ret = appRunningManager->AddUIExtensionBindItem(bindId, bindInfo); + EXPECT_EQ(ret, ERR_OK); + TAG_LOGI(AAFwkTag::TEST, "AppRunningManager_AddUIExtensionBindItem_0100 end"); +} + +/** + * @tc.name: AppRunningManager_RemoveUIExtensionBindItemById_0100 + * @tc.desc: Test RemoveUIExtensionBindItemById + * @tc.type: FUNC + */ +HWTEST_F(AppRunningManagerThirdTest, AppRunningManager_RemoveUIExtensionBindItemById_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningManager_RemoveUIExtensionBindItemById_0100 start"); + auto appRunningManager = std::make_shared(); + EXPECT_NE(appRunningManager, nullptr); + int32_t bindId = 0; + auto ret = appRunningManager->RemoveUIExtensionBindItemById(bindId); + EXPECT_EQ(ret, ERR_OK); + TAG_LOGI(AAFwkTag::TEST, "AppRunningManager_RemoveUIExtensionBindItemById_0100 end"); +} + +/** + * @tc.name: AppRunningManager_QueryUIExtensionBindItemById_0100 + * @tc.desc: Test QueryUIExtensionBindItemById + * @tc.type: FUNC + */ +HWTEST_F(AppRunningManagerThirdTest, AppRunningManager_QueryUIExtensionBindItemById_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningManager_QueryUIExtensionBindItemById_0100 start"); + auto appRunningManager = std::make_shared(); + EXPECT_NE(appRunningManager, nullptr); + int32_t bindId = 0; + UIExtensionProcessBindInfo bindInfo; + appRunningManager->AddUIExtensionBindItem(bindId, bindInfo); + auto ret = appRunningManager->QueryUIExtensionBindItemById(bindId, bindInfo); + EXPECT_EQ(ret, ERR_OK); + TAG_LOGI(AAFwkTag::TEST, "AppRunningManager_QueryUIExtensionBindItemById_0100 end"); +} + +/** + * @tc.name: AppRunningManager_QueryUIExtensionBindItemById_0200 + * @tc.desc: Test QueryUIExtensionBindItemById + * @tc.type: FUNC + */ +HWTEST_F(AppRunningManagerThirdTest, AppRunningManager_QueryUIExtensionBindItemById_0200, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningManager_QueryUIExtensionBindItemById_0100 start"); + auto appRunningManager = std::make_shared(); + EXPECT_NE(appRunningManager, nullptr); + int32_t bindId = 0; + UIExtensionProcessBindInfo bindInfo; + auto result = appRunningManager->QueryUIExtensionBindItemById(bindId, bindInfo); + EXPECT_EQ(result, ERR_INVALID_VALUE); + TAG_LOGI(AAFwkTag::TEST, "AppRunningManager_QueryUIExtensionBindItemById_0200 end"); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/test/unittest/app_running_record_test/app_running_record_test.cpp b/test/unittest/app_running_record_test/app_running_record_test.cpp index 7a27a8131e..b05fe9ec74 100644 --- a/test/unittest/app_running_record_test/app_running_record_test.cpp +++ b/test/unittest/app_running_record_test/app_running_record_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2023-2025 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 @@ -409,5 +409,468 @@ HWTEST_F(AppRunningRecordTest, AppRunningRecord_SetStartupTaskData_0100, TestSiz EXPECT_EQ(appRecord->startupTaskData_->insightIntentName, "intentName1"); TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_SetStartupTaskData_0100 end."); } + +/** + * @tc.name: AppRunningRecord_IsLastAbilityRecord_0100 + * @tc.desc: Test IsLastAbilityRecord works. + * @tc.type: FUNC + */ +HWTEST_F(AppRunningRecordTest, AppRunningRecord_IsLastAbilityRecord_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_IsLastAbilityRecord_0100 start."); + std::shared_ptr appInfo = std::make_shared(); + auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); + ASSERT_NE(appRecord, nullptr); + sptr token = new (std::nothrow) MockAbilityToken(); + bool ret = appRecord->IsLastAbilityRecord(token); + EXPECT_FALSE(ret); + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_IsLastAbilityRecord_0100 end."); +} + +/** + * @tc.name: AppRunningRecord_ExtensionAbilityRecordExists_0100 + * @tc.desc: Test ExtensionAbilityRecordExists works. + * @tc.type: FUNC + */ +HWTEST_F(AppRunningRecordTest, AppRunningRecord_ExtensionAbilityRecordExists_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_ExtensionAbilityRecordExists_0100 start."); + std::shared_ptr info = nullptr; + int32_t recordId = 0; + std::string processName = "appRunningRecordProcessName"; + auto appRunningRecord = std::make_shared(info, recordId, processName); + ASSERT_NE(appRunningRecord, nullptr); + bool ret = appRunningRecord->ExtensionAbilityRecordExists(); + EXPECT_FALSE(ret); + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_IsLastAbilityRecord_0100 end."); +} + +/** + * @tc.name: AppRunningRecord_ExtensionAbilityRecordExists_0200 + * @tc.desc: Test ExtensionAbilityRecordExists works. + * @tc.type: FUNC + */ +HWTEST_F(AppRunningRecordTest, AppRunningRecord_ExtensionAbilityRecordExists_0200, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_ExtensionAbilityRecordExists_0200 start."); + std::shared_ptr info = nullptr; + int32_t recordId = 0; + std::string processName = "appRunningRecordProcessName"; + auto appRunningRecord = std::make_shared(info, recordId, processName); + + std::shared_ptr appInfo = std::make_shared(); + std::shared_ptr moduleRunningRecord = std::make_shared(appInfo, nullptr); + + std::shared_ptr abilityInfo = std::make_shared(); + sptr token = nullptr; + auto abilityRecord = std::make_shared(abilityInfo, token, 0); + + std::shared_ptr want = std::make_shared(); + want->SetParam(AAFwk::Want::PARAM_RESV_WINDOW_MODE, + AAFwk::AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING); + abilityRecord->SetWant(want); + moduleRunningRecord->abilities_.emplace(nullptr, abilityRecord); + + std::vector> hapModulesVector; + hapModulesVector.emplace_back(moduleRunningRecord); + std::string hapModulesString = "hapModulesString"; + appRunningRecord->hapModules_.emplace(hapModulesString, hapModulesVector); + bool ret = appRunningRecord->ExtensionAbilityRecordExists(); + EXPECT_TRUE(ret); + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_ExtensionAbilityRecordExists_0200 end."); +} + +/** + * @tc.name: AppRunningRecord_IsLastPageAbilityRecord_0100 + * @tc.desc: Test IsLastPageAbilityRecord works. + * @tc.type: FUNC + */ +HWTEST_F(AppRunningRecordTest, AppRunningRecord_IsLastPageAbilityRecord_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_IsLastPageAbilityRecord_0100 start."); + std::shared_ptr appInfo = std::make_shared(); + auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); + ASSERT_NE(appRecord, nullptr); + sptr token = new (std::nothrow) MockAbilityToken(); + bool ret = appRecord->IsLastPageAbilityRecord(token); + EXPECT_FALSE(ret); + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_IsLastPageAbilityRecord_0100 end."); +} + +/** + * @tc.name: AppRunningRecord_GetBundleNames_0100 + * @tc.desc: Test GetBundleNames works. + * @tc.type: FUNC + */ +HWTEST_F(AppRunningRecordTest, AppRunningRecord_GetBundleNames_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_GetBundleNames_0100 start."); + std::shared_ptr appInfo = std::make_shared(); + auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); + ASSERT_NE(appRecord, nullptr); + appRecord->appInfos_.emplace(appInfo->bundleName, appInfo); + std::vector bundleNames; + appRecord->GetBundleNames(bundleNames); + EXPECT_EQ(bundleNames.size(), 1); + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_GetBundleNames_0100 end."); +} + +/** + * @tc.name: AppRunningRecord_SetScheduleNewProcessRequestState_0100 + * @tc.desc: Test SetScheduleNewProcessRequestState works. + * @tc.type: FUNC + */ +HWTEST_F(AppRunningRecordTest, AppRunningRecord_SetScheduleNewProcessRequestState_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_SetScheduleNewProcessRequestState_0100 start."); + std::shared_ptr appInfo = std::make_shared(); + auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); + ASSERT_NE(appRecord, nullptr); + int32_t requestId = 100; + AAFwk::Want want; + std::string moduleName = "com.example.module"; + appRecord->SetScheduleNewProcessRequestState(requestId, want, moduleName); + ASSERT_NE(appRecord->specifiedProcessRequest_, nullptr); + EXPECT_EQ(appRecord->specifiedProcessRequest_->requestId, requestId); + EXPECT_EQ(appRecord->moduleName_, moduleName); + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_SetScheduleNewProcessRequestState_0100 end."); +} + +/** + * @tc.name: AppRunningRecord_IsNewProcessRequest_0100 + * @tc.desc: Test IsNewProcessRequest works. + * @tc.type: FUNC + */ +HWTEST_F(AppRunningRecordTest, AppRunningRecord_IsNewProcessRequest_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_IsNewProcessRequest_0100 start."); + std::shared_ptr appInfo = std::make_shared(); + auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); + ASSERT_NE(appRecord, nullptr); + appRecord->specifiedProcessRequest_ = std::make_shared(); + bool ret = appRecord->IsNewProcessRequest(); + EXPECT_TRUE(ret); + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_IsNewProcessRequest_0100 end."); +} + +/** + * @tc.name: AppRunningRecord_IsStartSpecifiedAbility_0100 + * @tc.desc: Test IsStartSpecifiedAbility works. + * @tc.type: FUNC + */ +HWTEST_F(AppRunningRecordTest, AppRunningRecord_IsStartSpecifiedAbility_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_IsStartSpecifiedAbility_0100 start."); + std::shared_ptr appInfo = std::make_shared(); + auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); + ASSERT_NE(appRecord, nullptr); + appRecord->specifiedAbilityRequest_ = std::make_shared(); + bool ret = appRecord->IsStartSpecifiedAbility(); + EXPECT_TRUE(ret); + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_IsStartSpecifiedAbility_0100 end."); +} + +/** + * @tc.name: AppRunningRecord_GetNewProcessRequestWant_0100 + * @tc.desc: Test GetNewProcessRequestWant works. + * @tc.type: FUNC + */ +HWTEST_F(AppRunningRecordTest, AppRunningRecord_GetNewProcessRequestWant_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_GetNewProcessRequestWant_0100 start."); + std::shared_ptr appInfo = std::make_shared(); + auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); + ASSERT_NE(appRecord, nullptr); + appRecord->specifiedProcessRequest_ = std::make_shared(); + AAFwk::Want want; + want.SetParam(AAFwk::Want::PARAM_RESV_WINDOW_MODE, + AAFwk::AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING); + appRecord->specifiedProcessRequest_->want = want; + auto retWant = appRecord->GetNewProcessRequestWant(); + auto ret = retWant.GetIntParam(Want::PARAM_RESV_WINDOW_MODE, -1); + EXPECT_EQ(ret, AAFwk::AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING); + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_GetNewProcessRequestWant_0100 end."); +} + +/** + * @tc.name: AppRunningRecord_GetNewProcessRequestWant_0200 + * @tc.desc: Test GetNewProcessRequestWant works. + * @tc.type: FUNC + */ +HWTEST_F(AppRunningRecordTest, AppRunningRecord_GetNewProcessRequestWant_0200, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_GetNewProcessRequestWant_0200 start."); + std::shared_ptr appInfo = std::make_shared(); + auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); + ASSERT_NE(appRecord, nullptr); + appRecord->specifiedProcessRequest_ = nullptr; + auto retWant = appRecord->GetNewProcessRequestWant(); + auto ret = retWant.GetIntParam(Want::PARAM_RESV_WINDOW_MODE, -1); + EXPECT_EQ(ret, -1); + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_GetNewProcessRequestWant_0200 end."); +} + +/** + * @tc.name: AppRunningRecord_GetNewProcessRequestId_0100 + * @tc.desc: Test GetNewProcessRequestId works. + * @tc.type: FUNC + */ +HWTEST_F(AppRunningRecordTest, AppRunningRecord_GetNewProcessRequestId_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_GetNewProcessRequestId_0100 start."); + std::shared_ptr appInfo = std::make_shared(); + auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); + ASSERT_NE(appRecord, nullptr); + appRecord->specifiedProcessRequest_ = std::make_shared(); + appRecord->specifiedProcessRequest_->requestId = 0; + int32_t result = appRecord->GetNewProcessRequestId(); + EXPECT_EQ(result, 0); + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_GetNewProcessRequestId_0100 end."); +} + +/** + * @tc.name: AppRunningRecord_GetNewProcessRequestId_0200 + * @tc.desc: Test GetNewProcessRequestId works. + * @tc.type: FUNC + */ +HWTEST_F(AppRunningRecordTest, AppRunningRecord_GetNewProcessRequestId_0200, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_GetNewProcessRequestId_0200 start."); + std::shared_ptr appInfo = std::make_shared(); + auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); + ASSERT_NE(appRecord, nullptr); + appRecord->specifiedProcessRequest_ = nullptr; + int32_t result = appRecord->GetNewProcessRequestId(); + EXPECT_EQ(result, -1); + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_GetNewProcessRequestId_0200 end."); +} + +/** + * @tc.name: AppRunningRecord_IsDebug_0100 + * @tc.desc: Test IsDebug works. + * @tc.type: FUNC + */ +HWTEST_F(AppRunningRecordTest, AppRunningRecord_IsDebug_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_IsDebug_0100 start."); + std::shared_ptr appInfo = std::make_shared(); + auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); + ASSERT_NE(appRecord, nullptr); + appRecord->isDebugApp_ = true; + appRecord->isNativeDebug_ = false; + appRecord->perfCmd_ = ""; + appRecord->isAttachDebug_ = false; + appRecord->isAssertPause_ = false; + bool ret = appRecord->IsDebug(); + EXPECT_TRUE(ret); + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_IsDebug_0100 end."); +} + +/** + * @tc.name: AppRunningRecord_IsDebug_0100 + * @tc.desc: Test IsDebug works. + * @tc.type: FUNC + */ +HWTEST_F(AppRunningRecordTest, AppRunningRecord_IsDebug_0200, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_IsDebug_0200 start."); + std::shared_ptr appInfo = std::make_shared(); + auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); + ASSERT_NE(appRecord, nullptr); + appRecord->isDebugApp_ = false; + appRecord->isNativeDebug_ = true; + appRecord->perfCmd_ = ""; + appRecord->isAttachDebug_ = false; + appRecord->isAssertPause_ = false; + bool ret = appRecord->IsDebug(); + EXPECT_TRUE(ret); + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_IsDebug_0200 end."); +} + +/** + * @tc.name: AppRunningRecord_IsDebug_0300 + * @tc.desc: Test IsDebug works. + * @tc.type: FUNC + */ +HWTEST_F(AppRunningRecordTest, AppRunningRecord_IsDebug_0300, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_IsDebug_0300 start."); + std::shared_ptr appInfo = std::make_shared(); + auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); + ASSERT_NE(appRecord, nullptr); + appRecord->isDebugApp_ = false; + appRecord->isNativeDebug_ = false; + appRecord->perfCmd_ = "test"; + appRecord->isAttachDebug_ = false; + appRecord->isAssertPause_ = false; + bool ret = appRecord->IsDebug(); + EXPECT_TRUE(ret); + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_IsDebug_0300 end."); +} + +/** + * @tc.name: AppRunningRecord_IsDebug_0400 + * @tc.desc: Test IsDebug works. + * @tc.type: FUNC + */ +HWTEST_F(AppRunningRecordTest, AppRunningRecord_IsDebug_0400, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_IsDebug_0400 start."); + std::shared_ptr appInfo = std::make_shared(); + auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); + ASSERT_NE(appRecord, nullptr); + appRecord->isDebugApp_ = false; + appRecord->isNativeDebug_ = false; + appRecord->perfCmd_ = ""; + appRecord->isAttachDebug_ = true; + appRecord->isAssertPause_ = false; + bool ret = appRecord->IsDebug(); + EXPECT_TRUE(ret); + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_IsDebug_0400 end."); +} + +/** + * @tc.name: AppRunningRecord_IsDebug_0500 + * @tc.desc: Test IsDebug works. + * @tc.type: FUNC + */ +HWTEST_F(AppRunningRecordTest, AppRunningRecord_IsDebug_0500, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_IsDebug_0500 start."); + std::shared_ptr appInfo = std::make_shared(); + auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); + ASSERT_NE(appRecord, nullptr); + appRecord->isDebugApp_ = false; + appRecord->isNativeDebug_ = false; + appRecord->perfCmd_ = ""; + appRecord->isAttachDebug_ = false; + appRecord->isAssertPause_ = true; + bool ret = appRecord->IsDebug(); + EXPECT_TRUE(ret); + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_IsDebug_0500 end."); +} + +/** + * @tc.name: AppRunningRecord_IsDebug_0600 + * @tc.desc: Test IsDebug works. + * @tc.type: FUNC + */ +HWTEST_F(AppRunningRecordTest, AppRunningRecord_IsDebug_0600, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_IsDebug_0600 start."); + std::shared_ptr appInfo = std::make_shared(); + auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); + ASSERT_NE(appRecord, nullptr); + appRecord->isDebugApp_ = false; + appRecord->isNativeDebug_ = false; + appRecord->perfCmd_ = ""; + appRecord->isAttachDebug_ = false; + appRecord->isAssertPause_ = false; + bool ret = appRecord->IsDebug(); + EXPECT_FALSE(ret); + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_IsDebug_0600 end."); +} + +/** + * @tc.name: AppRunningRecord_IsNWebPreload_0100 + * @tc.desc: Test IsNWebPreload works. + * @tc.type: FUNC + */ +HWTEST_F(AppRunningRecordTest, AppRunningRecord_IsNWebPreload_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_IsNWebPreload_0100 start."); + std::shared_ptr appInfo = std::make_shared(); + auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); + ASSERT_NE(appRecord, nullptr); + appRecord->isAllowedNWebPreload_ = true; + bool ret = appRecord->IsNWebPreload(); + EXPECT_TRUE(ret); + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_IsNWebPreload_0100 end."); +} + +/** + * @tc.name: AppRunningRecord_GetNeedLimitPrio_0100 + * @tc.desc: Test GetNeedLimitPrio works. + * @tc.type: FUNC + */ +HWTEST_F(AppRunningRecordTest, AppRunningRecord_GetNeedLimitPrio_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_GetNeedLimitPrio_0100 start."); + std::shared_ptr appInfo = std::make_shared(); + auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); + ASSERT_NE(appRecord, nullptr); + appRecord->isNeedLimitPrio_ = true; + bool ret = appRecord->GetNeedLimitPrio(); + EXPECT_TRUE(ret); + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_GetNeedLimitPrio_0100 end."); +} + +/** + * @tc.name: AppRunningRecord_GetSignCode_0100 + * @tc.desc: Test GetSignCode works. + * @tc.type: FUNC + */ +HWTEST_F(AppRunningRecordTest, AppRunningRecord_GetSignCode_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_GetSignCode_0100 start."); + std::shared_ptr appInfo = std::make_shared(); + auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); + ASSERT_NE(appRecord, nullptr); + std::string signCodeString = "testSignCode"; + appRecord->signCode_ = signCodeString; + std::string result = appRecord->GetSignCode(); + EXPECT_EQ(result, signCodeString); + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_GetSignCode_0100 end."); +} + +/** + * @tc.name: AppRunningRecord_SetNeedLimitPrio_0100 + * @tc.desc: Test SetNeedLimitPrio works. + * @tc.type: FUNC + */ +HWTEST_F(AppRunningRecordTest, AppRunningRecord_SetNeedLimitPrio_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_SetNeedLimitPrio_0100 start."); + std::shared_ptr appInfo = std::make_shared(); + auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); + ASSERT_NE(appRecord, nullptr); + appRecord->SetNeedLimitPrio(true); + EXPECT_TRUE(appRecord->isNeedLimitPrio_); + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_SetNeedLimitPrio_0100 end."); +} + +/** + * @tc.name: AppRunningRecord_SetJointUserId_0100 + * @tc.desc: Test SetJointUserId works. + * @tc.type: FUNC + */ +HWTEST_F(AppRunningRecordTest, AppRunningRecord_SetJointUserId_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_SetJointUserId_0100 start."); + std::shared_ptr appInfo = std::make_shared(); + auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); + ASSERT_NE(appRecord, nullptr); + std::string jointUserId = "testJointUserId"; + appRecord->SetJointUserId(jointUserId); + EXPECT_EQ(appRecord->jointUserId_, jointUserId); + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_SetJointUserId_0100 end."); +} + +/** + * @tc.name: AppRunningRecord_GetUserId_0100 + * @tc.desc: Test GetUserId works. + * @tc.type: FUNC + */ +HWTEST_F(AppRunningRecordTest, AppRunningRecord_GetUserId_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_GetUserId_0100 start."); + std::shared_ptr appInfo = std::make_shared(); + auto appRecord = std::make_shared(appInfo, RECORD_ID, "com.example.child"); + ASSERT_NE(appRecord, nullptr); + appRecord->mainUid_ = BASE_USER_RANGE; + int32_t result = appRecord->GetUserId(); + EXPECT_EQ(result, 1); + TAG_LOGI(AAFwkTag::TEST, "AppRunningRecord_GetUserId_0100 end."); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/test/unittest/insight_intent/insight_intent_execute_manager_second_test/insight_intent_execute_manager_second_test.cpp b/test/unittest/insight_intent/insight_intent_execute_manager_second_test/insight_intent_execute_manager_second_test.cpp index 60d321d2c9..dce151ba6d 100644 --- a/test/unittest/insight_intent/insight_intent_execute_manager_second_test/insight_intent_execute_manager_second_test.cpp +++ b/test/unittest/insight_intent/insight_intent_execute_manager_second_test/insight_intent_execute_manager_second_test.cpp @@ -596,5 +596,302 @@ HWTEST_F(InsightIntentExecuteManagerSecondTest, GetAllIntentExemptionInfo_0100, EXPECT_EQ(result.size(), 2); TAG_LOGI(AAFwkTag::TEST, "end."); } + +/** + * @tc.name: UpdateFuncDecoratorParams_0100 + * @tc.desc: UpdateFuncDecoratorParams_0100 + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(InsightIntentExecuteManagerSecondTest, UpdateFuncDecoratorParams_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "begin."); + AppExecFwk::InsightIntentExecuteParam param; + param.bundleName_ = "test.bundleName"; + param.moduleName_ = "test.entry"; + param.abilityName_ = "test.abilityName"; + param.insightIntentName_ = "PlayMusic"; + param.insightIntentParam_ = nullptr; + param.executeMode_ = AppExecFwk::ExecuteMode::UI_ABILITY_FOREGROUND; + // other member has default value. + auto paramPtr = std::make_shared(param); + AbilityRuntime::ExtractInsightIntentInfo ententInfo; + Want want; + auto ret = InsightIntentExecuteManager::UpdateFuncDecoratorParams(paramPtr, ententInfo, want); + EXPECT_EQ(ret, ERR_INVALID_VALUE); + TAG_LOGI(AAFwkTag::TEST, "end."); +} + +/** + * @tc.name: UpdateFuncDecoratorParams_0200 + * @tc.desc: UpdateFuncDecoratorParams_0200 + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(InsightIntentExecuteManagerSecondTest, UpdateFuncDecoratorParams_0200, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "begin."); + AppExecFwk::InsightIntentExecuteParam param; + param.bundleName_ = "test.bundleName"; + param.moduleName_ = "test.entry"; + param.insightIntentName_ = "PlayMusic"; + param.insightIntentParam_ = nullptr; + param.executeMode_ = AppExecFwk::ExecuteMode::UI_ABILITY_BACKGROUND; + auto paramPtr = std::make_shared(param); + AbilityRuntime::ExtractInsightIntentInfo ententInfo;; + Want want; + auto ret = InsightIntentExecuteManager::UpdateFuncDecoratorParams(paramPtr, ententInfo, want); + EXPECT_EQ(ret, ERR_INVALID_VALUE); + TAG_LOGI(AAFwkTag::TEST, "end."); +} + +/** + * @tc.name: UpdateFuncDecoratorParams_0300 + * @tc.desc: UpdateFuncDecoratorParams_0300 + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(InsightIntentExecuteManagerSecondTest, UpdateFuncDecoratorParams_0300, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "begin."); + AppExecFwk::InsightIntentExecuteParam param; + param.bundleName_ = "test.bundleName"; + param.moduleName_ = "test.entry"; + param.abilityName_ = "test.abilityName"; + param.insightIntentName_ = "PlayMusic"; + param.insightIntentParam_ = nullptr; + param.executeMode_ = AppExecFwk::ExecuteMode::UI_ABILITY_BACKGROUND; + auto paramPtr = std::make_shared(param); + AbilityRuntime::ExtractInsightIntentInfo ententInfo; + ententInfo.decoratorClass = "testClass"; + ententInfo.genericInfo.get().functionName = ""; + Want want; + auto ret = InsightIntentExecuteManager::UpdateFuncDecoratorParams(paramPtr, ententInfo, want); + EXPECT_EQ(ret, ERR_INVALID_VALUE); + TAG_LOGI(AAFwkTag::TEST, "end."); +} + +/** + * @tc.name: UpdateFuncDecoratorParams_0400 + * @tc.desc: UpdateFuncDecoratorParams_0400 + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(InsightIntentExecuteManagerSecondTest, UpdateFuncDecoratorParams_0400, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "begin."); + AppExecFwk::InsightIntentExecuteParam param; + param.bundleName_ = "test.bundleName"; + param.moduleName_ = "test.entry"; + param.abilityName_ = "test.abilityName"; + param.insightIntentName_ = "PlayMusic"; + param.insightIntentParam_ = nullptr; + param.executeMode_ = AppExecFwk::ExecuteMode::UI_ABILITY_BACKGROUND; + auto paramPtr = std::make_shared(param); + AbilityRuntime::ExtractInsightIntentInfo ententInfo; + ententInfo.decoratorClass = ""; + ententInfo.genericInfo.get().functionName = "testFunctionName"; + Want want; + auto ret = InsightIntentExecuteManager::UpdateFuncDecoratorParams(paramPtr, ententInfo, want); + EXPECT_EQ(ret, ERR_INVALID_VALUE); + TAG_LOGI(AAFwkTag::TEST, "end."); +} + +/** + * @tc.name: UpdateFuncDecoratorParams_0500 + * @tc.desc: UpdateFuncDecoratorParams_0500 + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(InsightIntentExecuteManagerSecondTest, UpdateFuncDecoratorParams_0500, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "begin."); + AppExecFwk::InsightIntentExecuteParam param; + param.bundleName_ = "test.bundleName"; + param.moduleName_ = "test.entry"; + param.abilityName_ = "test.abilityName"; + param.insightIntentName_ = "PlayMusic"; + param.insightIntentParam_ = nullptr; + param.executeMode_ = AppExecFwk::ExecuteMode::UI_ABILITY_BACKGROUND; + auto paramPtr = std::make_shared(param); + AbilityRuntime::ExtractInsightIntentInfo ententInfo; + ententInfo.decoratorClass = "testClass"; + ententInfo.genericInfo.get().functionName = "testFunctionName"; + Want want; + auto ret = InsightIntentExecuteManager::UpdateFuncDecoratorParams(paramPtr, ententInfo, want); + EXPECT_EQ(ret, ERR_OK); + TAG_LOGI(AAFwkTag::TEST, "end."); +} + +/** + * @tc.name: GetMainElementName_0100 + * @tc.desc: GetMainElementName_0100 + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(InsightIntentExecuteManagerSecondTest, GetMainElementName_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "begin."); + AppExecFwk::InsightIntentExecuteParam param; + param.bundleName_ = "test.bundleName"; + param.moduleName_ = "test.entry"; + param.abilityName_ = "test.abilityName"; + param.insightIntentName_ = ""; + param.insightIntentParam_ = nullptr; + param.displayId_ = 2; + param.executeMode_ = AppExecFwk::ExecuteMode::UI_ABILITY_FOREGROUND; + auto paramPtr = std::make_shared(param); + paramPtr->moduleName_ = "test.entry"; + std::string retString = InsightIntentExecuteManager::GetMainElementName(paramPtr); + EXPECT_EQ(retString, ""); + TAG_LOGI(AAFwkTag::TEST, "end."); +} + +/** + * @tc.name: UpdatePageDecoratorParams_0100 + * @tc.desc: UpdatePageDecoratorParams_0100 + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(InsightIntentExecuteManagerSecondTest, UpdatePageDecoratorParams_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "begin."); + AppExecFwk::InsightIntentExecuteParam param; + param.bundleName_ = "test.bundleName"; + param.moduleName_ = "test.entry"; + param.abilityName_ = "test.abilityName"; + param.insightIntentName_ = "PlayMusic"; + param.insightIntentParam_ = nullptr; + param.executeMode_ = AppExecFwk::ExecuteMode::UI_ABILITY_BACKGROUND; + // other member has default value. + auto paramPtr = std::make_shared(param); + AbilityRuntime::ExtractInsightIntentInfo intentInfo; + Want want; + auto ret = InsightIntentExecuteManager::UpdatePageDecoratorParams(paramPtr, intentInfo, want); + EXPECT_EQ(ret, ERR_INVALID_VALUE); + TAG_LOGI(AAFwkTag::TEST, "end."); +} + +/** + * @tc.name: UpdatePageDecoratorParams_0200 + * @tc.desc: UpdatePageDecoratorParams_0200 + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(InsightIntentExecuteManagerSecondTest, UpdatePageDecoratorParams_0200, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "begin."); + AppExecFwk::InsightIntentExecuteParam param; + param.bundleName_ = "test.bundleName"; + param.moduleName_ = "test.entry"; + param.abilityName_ = "test.abilityName"; + param.insightIntentName_ = "PlayMusic"; + param.insightIntentParam_ = nullptr; + param.executeMode_ = AppExecFwk::ExecuteMode::UI_ABILITY_FOREGROUND; + // other member has default value. + auto paramPtr = std::make_shared(param); + AbilityRuntime::ExtractInsightIntentInfo intentInfo; + Want want; + auto ret = InsightIntentExecuteManager::UpdatePageDecoratorParams(paramPtr, intentInfo, want); + EXPECT_EQ(ret, ERR_INVALID_VALUE); + TAG_LOGI(AAFwkTag::TEST, "end."); +} + +/** + * @tc.name: UpdatePageDecoratorParams_0300 + * @tc.desc: UpdatePageDecoratorParams_0300 + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(InsightIntentExecuteManagerSecondTest, UpdatePageDecoratorParams_0300, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "begin."); + AppExecFwk::InsightIntentExecuteParam param; + param.bundleName_ = "test.bundleName"; + param.moduleName_ = "test.entry"; + param.abilityName_ = "test.abilityName"; + param.insightIntentName_ = "PlayMusic"; + param.insightIntentParam_ = nullptr; + param.executeMode_ = AppExecFwk::ExecuteMode::UI_ABILITY_FOREGROUND; + // other member has default value. + auto paramPtr = std::make_shared(param); + AbilityRuntime::ExtractInsightIntentInfo intentInfo; + intentInfo.genericInfo.get().pagePath = "testPagePath"; + Want want; + auto ret = InsightIntentExecuteManager::UpdatePageDecoratorParams(paramPtr, intentInfo, want); + EXPECT_EQ(ret, ERR_INVALID_VALUE); + TAG_LOGI(AAFwkTag::TEST, "end."); +} + +/** + * @tc.name: UpdatePageDecoratorParams_0400 + * @tc.desc: UpdatePageDecoratorParams_0400 + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(InsightIntentExecuteManagerSecondTest, UpdatePageDecoratorParams_0400, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "begin."); + AppExecFwk::InsightIntentExecuteParam param; + param.bundleName_ = "test.bundleName"; + param.moduleName_ = "test.entry"; + param.abilityName_ = "test.abilityName"; + param.insightIntentName_ = "PlayMusic"; + param.insightIntentParam_ = nullptr; + param.executeMode_ = AppExecFwk::ExecuteMode::UI_ABILITY_FOREGROUND; + // other member has default value. + auto paramPtr = std::make_shared(param); + AbilityRuntime::ExtractInsightIntentInfo intentInfo; + intentInfo.genericInfo.get().pagePath = "test.abilityName"; + intentInfo.genericInfo.get().uiAbility = ""; + Want want; + auto ret = InsightIntentExecuteManager::UpdatePageDecoratorParams(paramPtr, intentInfo, want); + EXPECT_EQ(ret, ERR_INVALID_VALUE); + TAG_LOGI(AAFwkTag::TEST, "end."); +} + +/** + * @tc.name: UpdatePageDecoratorParams_0500 + * @tc.desc: UpdatePageDecoratorParams_0500 + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(InsightIntentExecuteManagerSecondTest, UpdatePageDecoratorParams_0500, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "begin."); + AppExecFwk::InsightIntentExecuteParam param; + param.bundleName_ = "test.bundleName"; + param.moduleName_ = "test.entry"; + param.abilityName_ = "test.abilityName"; + param.insightIntentName_ = "PlayMusic"; + param.insightIntentParam_ = nullptr; + param.executeMode_ = AppExecFwk::ExecuteMode::UI_ABILITY_FOREGROUND; + // other member has default value. + auto paramPtr = std::make_shared(param); + AbilityRuntime::ExtractInsightIntentInfo intentInfo; + intentInfo.genericInfo.get().pagePath = "test.abilityName"; + intentInfo.genericInfo.get().uiAbility = "test.abilityName"; + Want want; + auto ret = InsightIntentExecuteManager::UpdatePageDecoratorParams(paramPtr, intentInfo, want); + EXPECT_EQ(ret, ERR_OK); + TAG_LOGI(AAFwkTag::TEST, "end."); +} + +/** + * @tc.name: UpdateEntryDecoratorParams_0100 + * @tc.desc: UpdateEntryDecoratorParams_0100 + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(InsightIntentExecuteManagerSecondTest, UpdateEntryDecoratorParams_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "begin."); + Want want; + auto mode = AppExecFwk::ExecuteMode::UI_ABILITY_FOREGROUND; + auto ret = InsightIntentExecuteManager::UpdateEntryDecoratorParams(want, mode); + EXPECT_EQ(ret, ERR_INVALID_VALUE); + TAG_LOGI(AAFwkTag::TEST, "end."); +} + } // namespace AAFwk } // namespace OHOS diff --git a/test/unittest/insight_intent/insight_intent_execute_param_second_test/insight_intent_execute_param_second_test.cpp b/test/unittest/insight_intent/insight_intent_execute_param_second_test/insight_intent_execute_param_second_test.cpp index da8b86e4c2..817b54620c 100644 --- a/test/unittest/insight_intent/insight_intent_execute_param_second_test/insight_intent_execute_param_second_test.cpp +++ b/test/unittest/insight_intent/insight_intent_execute_param_second_test/insight_intent_execute_param_second_test.cpp @@ -16,6 +16,7 @@ #include #include "hilog_tag_wrapper.h" +#include "insight_intent_constant.h" #include "insight_intent_execute_param.h" #include "int_wrapper.h" #include "string_wrapper.h" @@ -29,6 +30,10 @@ namespace OHOS { namespace AAFwk { using InsightIntentExecuteParam = AppExecFwk::InsightIntentExecuteParam; +namespace { +const std::string TEST_INSIGHT_INTENT_NANE = "PlayMusic"; +} + class InsightIntentExecuteParamSecondTest : public testing::Test { public: static void SetUpTestCase(); @@ -82,5 +87,144 @@ HWTEST_F(InsightIntentExecuteParamSecondTest, UpdateInsightIntentCallerInfo_0100 EXPECT_EQ(ret, true); TAG_LOGI(AAFwkTag::TEST, "end."); } +/** + * @tc.name: ReadFromParcel_0100 + * @tc.desc: basic function test of ReadFromParcel + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(InsightIntentExecuteParamSecondTest, ReadFromParcel_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "begin."); + Parcel parcel; + InsightIntentExecuteParam param; + bool ret = param.ReadFromParcel(parcel); + EXPECT_FALSE(ret); + TAG_LOGI(AAFwkTag::TEST, "end."); +} + +/** + * @tc.name: ReadFromParcel_0200 + * @tc.desc: basic function test of ReadFromParcel + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(InsightIntentExecuteParamSecondTest, ReadFromParcel_0200, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "begin."); + Parcel parcel; + WantParams wantParams; + wantParams.SetParam("ohos.insightIntent.executeParam.name", AAFwk::String::Box("test.bundleName")); + wantParams.SetParam("ohos.insightIntent.executeParam.id", AAFwk::String::Box("1")); + wantParams.SetParam("ohos.insightIntent.executeParam.mode", AAFwk::String::Box("execution")); + wantParams.SetParam("ohos.insightIntent.executeParam.param", AAFwk::String::Box("executionParameter")); + wantParams.SetParam("ohos.insightIntent.srcEntry", AAFwk::String::Box("testEntry")); + wantParams.SetParam("ohos.insightIntent.executeParam.uris", AAFwk::String::Box("testUri")); + wantParams.SetParam("ohos.insightIntent.executeParam.flags", AAFwk::String::Box("testFlags")); + parcel.WriteParcelable(&wantParams); + InsightIntentExecuteParam param; + bool ret = param.ReadFromParcel(parcel); + EXPECT_TRUE(ret); + TAG_LOGI(AAFwkTag::TEST, "end."); +} + +/** + * @tc.name: Unmarshalling_0100 + * @tc.desc: basic function test of Unmarshalling + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(InsightIntentExecuteParamSecondTest, Unmarshalling_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "begin."); + Parcel parcel; + InsightIntentExecuteParam param; + auto retPtr = param.Unmarshalling(parcel); + EXPECT_EQ(retPtr, nullptr); + TAG_LOGI(AAFwkTag::TEST, "end."); +} + +/** + * @tc.name: Unmarshalling_0200 + * @tc.desc: basic function test of Unmarshalling + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(InsightIntentExecuteParamSecondTest, Unmarshalling_0200, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "begin."); + Parcel parcel; + WantParams wantParams; + wantParams.SetParam("ohos.insightIntent.executeParam.name", AAFwk::String::Box("test.bundleName")); + wantParams.SetParam("ohos.insightIntent.executeParam.id", AAFwk::String::Box("1")); + wantParams.SetParam("ohos.insightIntent.executeParam.mode", AAFwk::String::Box("execution")); + wantParams.SetParam("ohos.insightIntent.executeParam.param", AAFwk::String::Box("executionParameter")); + wantParams.SetParam("ohos.insightIntent.srcEntry", AAFwk::String::Box("testEntry")); + wantParams.SetParam("ohos.insightIntent.executeParam.uris", AAFwk::String::Box("testUri")); + wantParams.SetParam("ohos.insightIntent.executeParam.flags", AAFwk::String::Box("testFlags")); + parcel.WriteParcelable(&wantParams); + InsightIntentExecuteParam param; + auto retPtr = param.Unmarshalling(parcel); + EXPECT_NE(retPtr, nullptr); + TAG_LOGI(AAFwkTag::TEST, "end."); +} + +/** + * @tc.name: IsInsightIntentPage_0100 + * @tc.desc: basic function test of IsInsightIntentPage + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(InsightIntentExecuteParamSecondTest, IsInsightIntentPage_0100, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "begin."); + Want want; + InsightIntentExecuteParam param; + bool ret = param.IsInsightIntentPage(want); + EXPECT_FALSE(ret); + TAG_LOGI(AAFwkTag::TEST, "end."); +} + +/** + * @tc.name: IsInsightIntentPage_0200 + * @tc.desc: basic function test of IsInsightIntentPage + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(InsightIntentExecuteParamSecondTest, IsInsightIntentPage_0200, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "begin."); + WantParams wantParams; + wantParams.SetParam(AppExecFwk::INSIGHT_INTENT_EXECUTE_PARAM_NAME, AAFwk::String::Box(TEST_INSIGHT_INTENT_NANE)); + wantParams.SetParam(AppExecFwk::INSIGHT_INTENT_DECORATOR_TYPE, + AAFwk::Integer::Box(static_cast(AbilityRuntime::InsightIntentType::DECOR_PAGE))); + Want want; + want.SetParams(wantParams); + InsightIntentExecuteParam param; + bool ret = param.IsInsightIntentPage(want); + EXPECT_TRUE(ret); + TAG_LOGI(AAFwkTag::TEST, "end."); +} + +/** + * @tc.name: IsInsightIntentPage_0300 + * @tc.desc: basic function test of IsInsightIntentPage + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(InsightIntentExecuteParamSecondTest, IsInsightIntentPage_0300, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "begin."); + WantParams wantParams; + wantParams.SetParam(AppExecFwk::INSIGHT_INTENT_EXECUTE_PARAM_NAME, AAFwk::String::Box(TEST_INSIGHT_INTENT_NANE)); + wantParams.SetParam(AppExecFwk::INSIGHT_INTENT_DECORATOR_TYPE, + AAFwk::String::Box(std::to_string(static_cast((AbilityRuntime::InsightIntentType::DECOR_NONE))))); + Want want; + want.SetParams(wantParams); + InsightIntentExecuteParam param; + bool ret = param.IsInsightIntentPage(want); + EXPECT_FALSE(ret); + TAG_LOGI(AAFwkTag::TEST, "end.");; +} } // namespace AAFwk } // namespace OHOS From 2c8b05098ca34573b844f0c5bbf81aec2668afb0 Mon Sep 17 00:00:00 2001 From: zhangzezhong Date: Tue, 3 Jun 2025 13:14:36 +0800 Subject: [PATCH 02/23] add AppRunningStatusModule unittest cases for ability_runtime Signed-off-by: zhangzezhong --- test/unittest/BUILD.gn | 1 + .../ams_app_death_recipient_test.cpp | 40 +- .../app_running_status_module_test/BUILD.gn | 87 ++++ .../app_running_status_module_test.cpp | 396 ++++++++++++++++++ .../exit_resident_process_manager_test.cpp | 44 +- 5 files changed, 564 insertions(+), 4 deletions(-) create mode 100644 test/unittest/app_running_status_module_test/BUILD.gn create mode 100644 test/unittest/app_running_status_module_test/app_running_status_module_test.cpp diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 6371e4398c..ba7c9add66 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -489,6 +489,7 @@ group("unittest") { "app_running_manager_third_test:unittest", "app_running_processes_info_test:unittest", "app_running_record_test:unittest", + "app_running_status_module_test:unittest", "app_scheduler_host_test:unittest", "app_scheduler_proxy_test:unittest", "app_scheduler_test:unittest", diff --git a/test/unittest/ams_app_death_recipient_test/ams_app_death_recipient_test.cpp b/test/unittest/ams_app_death_recipient_test/ams_app_death_recipient_test.cpp index 1033479b2e..fb3f597cd7 100644 --- a/test/unittest/ams_app_death_recipient_test/ams_app_death_recipient_test.cpp +++ b/test/unittest/ams_app_death_recipient_test/ams_app_death_recipient_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2023 Huawei Device Co., Ltd. + * Copyright (c) 2021-2025 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 @@ -227,5 +227,43 @@ HWTEST_F(AppDeathRecipientTest, AppDeathRecipient_002, TestSize.Level1) TAG_LOGI(AAFwkTag::TEST, "AppDeathRecipient_002 end"); } + +/* + * Feature: Ams + * Function: SetIsRenderProcess + * SubFunction: AppDeathRecipient + * FunctionPoints: set render process flag + * EnvConditions: AppDeathRecipient object exists + * CaseDescription: Test setting isRenderProcess_ to true + */ +HWTEST_F(AppDeathRecipientTest, AppDeathRecipient_SetIsRenderProcess_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppDeathRecipient_SetIsRenderProcess_001 start"); + + appDeathRecipientObject_->SetIsRenderProcess(true); + EXPECT_TRUE(appDeathRecipientObject_->isRenderProcess_); + appDeathRecipientObject_->SetIsRenderProcess(false); + EXPECT_FALSE(appDeathRecipientObject_->isRenderProcess_); + TAG_LOGI(AAFwkTag::TEST, "AppDeathRecipient_SetIsRenderProcess_001 end"); +} + +/* + * Feature: Ams + * Function: SetIsChildProcess + * SubFunction: AppDeathRecipient + * FunctionPoints: set child process flag + * EnvConditions: AppDeathRecipient object exists + * CaseDescription: Test setting isChildProcess_ to true + */ +HWTEST_F(AppDeathRecipientTest, AppDeathRecipient_SetIsChildProcess_001, TestSize.Level1) +{ + TAG_LOGI(AAFwkTag::TEST, "AppDeathRecipient_SetIsChildProcess_001 start"); + + appDeathRecipientObject_->SetIsChildProcess(true); + EXPECT_TRUE(appDeathRecipientObject_->isChildProcess_); + appDeathRecipientObject_->SetIsChildProcess(false); + EXPECT_FALSE(appDeathRecipientObject_->isChildProcess_); + TAG_LOGI(AAFwkTag::TEST, "AppDeathRecipient_SetIsChildProcess_001 end"); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/test/unittest/app_running_status_module_test/BUILD.gn b/test/unittest/app_running_status_module_test/BUILD.gn new file mode 100644 index 0000000000..a634045931 --- /dev/null +++ b/test/unittest/app_running_status_module_test/BUILD.gn @@ -0,0 +1,87 @@ +# Copyright (c) 2025 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/ability_runtime/appmgrservice" + +ohos_unittest("app_running_status_module_test") { + module_out_path = module_output_path + + configs = [ "${ability_runtime_services_path}/common:common_config" ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${ability_runtime_utils_path}/global/constant", + "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_innerkits_path}/app_manager/include/appmgr", + "${ability_runtime_services_path}/appmgr/include", + ] + + sources = [ + "${ability_runtime_services_path}/appmgr/src/app_running_status_module.cpp", + "app_running_status_module_test.cpp", + ] + + deps = [ + "${ability_runtime_services_path}/appmgr:libappms", + "${ability_runtime_innerkits_path}/app_manager:app_manager", + ] + + external_deps = [ + "ability_base:base", + "ability_base:session_info", + "ability_base:configuration", + "ability_base:want", + "access_token:libaccesstoken_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "ffrt:libffrt", + "googletest:gmock_main", + "googletest:gtest_main", + "hicollie:libhicollie", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "init:libbeget_proxy", + "init:libbegetutil", + "ipc:ipc_core", + "kv_store:distributeddata_mgr", + "memory_utils:libmeminfo", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "window_manager:libwm", + "window_manager:libwsutils", + "json:nlohmann_json_static", + "jsoncpp:jsoncpp", + ] + + if (ability_runtime_child_process) { + defines = [ "SUPPORT_CHILD_PROCESS" ] + } + +} + +group("unittest") { + testonly = true + + deps = [ ":app_running_status_module_test" ] +} diff --git a/test/unittest/app_running_status_module_test/app_running_status_module_test.cpp b/test/unittest/app_running_status_module_test/app_running_status_module_test.cpp new file mode 100644 index 0000000000..07142c2ad5 --- /dev/null +++ b/test/unittest/app_running_status_module_test/app_running_status_module_test.cpp @@ -0,0 +1,396 @@ +/* + * Copyright (c) 2025 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 "appexecfwk_errors.h" +#define private public +#include "app_running_status_module.h" +#include "appmgr/app_running_status_stub.h" +#undef private +#include "hilog_tag_wrapper.h" + +using namespace testing; +using namespace testing::ext; + +namespace OHOS { +namespace AbilityRuntime { + +class MockAppRunningStatusListener : public AppRunningStatusStub { +public: + void NotifyAppRunningStatus(const std::string &bundle, int32_t uid, RunningStatus runningStatus) override + { + bundle_ = bundle; + uid_ = uid; + runningStatus_ = runningStatus; + notifyCount_++; + } + + std::string bundle_; + int32_t uid_ = 0; + RunningStatus runningStatus_ = RunningStatus::APP_RUNNING_STOP; + int32_t notifyCount_ = 0; +}; + +class AppRunningStatusModuleTest : public testing::Test { +public: + void SetUp() override; + void TearDown() override; + +protected: + std::shared_ptr appRunningStatusModule_ = nullptr; +}; + +void AppRunningStatusModuleTest::SetUp() +{ + appRunningStatusModule_ = std::make_shared(); +} + +void AppRunningStatusModuleTest::TearDown() +{ + appRunningStatusModule_ = nullptr; +} + +/** + * @tc.number: AppRunningStatusModuleTest_RegisterListener_0100 + * @tc.desc: Test RegisterListener with null listener + * @tc.type: FUNC + * @tc.function: RegisterListener + * @tc.subfunction: NA + * @tc.envConditions: NA + */ +HWTEST_F(AppRunningStatusModuleTest, AppRunningStatusModuleTest_RegisterListener_0100, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "AppRunningStatusModuleTest_RegisterListener_0100 start."); + sptr listener; + auto ret = appRunningStatusModule_->RegisterListener(listener); + EXPECT_EQ(ret, ERR_INVALID_OPERATION); +} + +/** + * @tc.number: AppRunningStatusModuleTest_RegisterListener_0200 + * @tc.desc: Test RegisterListener with valid listener + * @tc.type: FUNC + * @tc.function: RegisterListener + * @tc.subfunction: NA + * @tc.envConditions: NA + */ +HWTEST_F(AppRunningStatusModuleTest, AppRunningStatusModuleTest_RegisterListener_0200, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "AppRunningStatusModuleTest_RegisterListener_0200 start."); + sptr listener = new MockAppRunningStatusListener(); + auto ret = appRunningStatusModule_->RegisterListener(listener); + EXPECT_EQ(ret, ERR_OK); +} + +/** + * @tc.number: AppRunningStatusModuleTest_RegisterListener_0300 + * @tc.desc: Test RegisterListener with same listener twice + * @tc.type: FUNC + * @tc.function: RegisterListener + * @tc.subfunction: NA + * @tc.envConditions: NA + */ +HWTEST_F(AppRunningStatusModuleTest, AppRunningStatusModuleTest_RegisterListener_0300, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "AppRunningStatusModuleTest_RegisterListener_0300 start."); + sptr listener = new MockAppRunningStatusListener(); + auto ret = appRunningStatusModule_->RegisterListener(listener); + EXPECT_EQ(ret, ERR_OK); + ret = appRunningStatusModule_->RegisterListener(listener); + EXPECT_EQ(ret, ERR_OK); +} + +/** + * @tc.number: AppRunningStatusModuleTest_UnregisterListener_0100 + * @tc.desc: Test UnregisterListener with null listener + * @tc.type: FUNC + * @tc.function: UnregisterListener + * @tc.subfunction: NA + * @tc.envConditions: NA + */ +HWTEST_F(AppRunningStatusModuleTest, AppRunningStatusModuleTest_UnregisterListener_0100, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "AppRunningStatusModuleTest_UnregisterListener_0100 start."); + sptr listener; + auto ret = appRunningStatusModule_->UnregisterListener(listener); + EXPECT_EQ(ret, ERR_INVALID_VALUE); +} + +/** + * @tc.number: AppRunningStatusModuleTest_UnregisterListener_0200 + * @tc.desc: Test UnregisterListener with unregistered listener + * @tc.type: FUNC + * @tc.function: UnregisterListener + * @tc.subfunction: NA + * @tc.envConditions: NA + */ +HWTEST_F(AppRunningStatusModuleTest, AppRunningStatusModuleTest_UnregisterListener_0200, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "AppRunningStatusModuleTest_UnregisterListener_0200 start."); + sptr listener = new MockAppRunningStatusListener(); + auto ret = appRunningStatusModule_->UnregisterListener(listener); + EXPECT_EQ(ret, ERR_INVALID_OPERATION); +} + +/** + * @tc.number: AppRunningStatusModuleTest_UnregisterListener_0300 + * @tc.desc: Test UnregisterListener with registered listener + * @tc.type: FUNC + * @tc.function: UnregisterListener + * @tc.subfunction: NA + * @tc.envConditions: NA + */ +HWTEST_F(AppRunningStatusModuleTest, AppRunningStatusModuleTest_UnregisterListener_0300, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "AppRunningStatusModuleTest_UnregisterListener_0300 start."); + sptr listener = new MockAppRunningStatusListener(); + + auto ret = appRunningStatusModule_->RegisterListener(listener); + EXPECT_EQ(ret, ERR_OK); + ret = appRunningStatusModule_->UnregisterListener(listener); + EXPECT_EQ(ret, ERR_OK); +} + +/** + * @tc.number: AppRunningStatusModuleTest_NotifyAppRunningStatusEvent_0100 + * @tc.desc: Test NotifyAppRunningStatusEvent with no listeners + * @tc.type: FUNC + * @tc.function: NotifyAppRunningStatusEvent + * @tc.subfunction: NA + * @tc.envConditions: NA + */ +HWTEST_F(AppRunningStatusModuleTest, AppRunningStatusModuleTest_NotifyAppRunningStatusEvent_0100, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "AppRunningStatusModuleTest_NotifyAppRunningStatusEvent_0100 start."); + std::string bundleName = "com.test.bundle"; + int32_t uid = 1000; + RunningStatus runningStatus = RunningStatus::APP_RUNNING_START; + + // Verify no listeners are registered initially + { + std::lock_guard lock(appRunningStatusModule_->listenerMutex_); + EXPECT_TRUE(appRunningStatusModule_->listeners_.empty()); + } + + // Call NotifyAppRunningStatusEvent with no listeners - should complete without errors + appRunningStatusModule_->NotifyAppRunningStatusEvent(bundleName, uid, runningStatus); + + // Verify listeners container remains empty after the call + { + std::lock_guard lock(appRunningStatusModule_->listenerMutex_); + EXPECT_TRUE(appRunningStatusModule_->listeners_.empty()); + } +} + +/** + * @tc.number: AppRunningStatusModuleTest_NotifyAppRunningStatusEvent_0200 + * @tc.desc: Test NotifyAppRunningStatusEvent with registered listener + * @tc.type: FUNC + * @tc.function: NotifyAppRunningStatusEvent + * @tc.subfunction: NA + * @tc.envConditions: NA + */ +HWTEST_F(AppRunningStatusModuleTest, AppRunningStatusModuleTest_NotifyAppRunningStatusEvent_0200, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "AppRunningStatusModuleTest_NotifyAppRunningStatusEvent_0200 start."); + sptr listener = new MockAppRunningStatusListener(); + + // Register listener + auto ret = appRunningStatusModule_->RegisterListener(listener); + EXPECT_EQ(ret, ERR_OK); + + std::string bundleName = "com.test.bundle"; + int32_t uid = 1000; + RunningStatus runningStatus = RunningStatus::APP_RUNNING_START; + + // Notify event + appRunningStatusModule_->NotifyAppRunningStatusEvent(bundleName, uid, runningStatus); + + // Check if listener was notified + EXPECT_EQ(listener->notifyCount_, 1); + EXPECT_EQ(listener->bundle_, bundleName); + EXPECT_EQ(listener->uid_, uid); + EXPECT_EQ(listener->runningStatus_, runningStatus); +} + +/** + * @tc.number: AppRunningStatusModuleTest_NotifyAppRunningStatusEvent_0300 + * @tc.desc: Test NotifyAppRunningStatusEvent with multiple listeners + * @tc.type: FUNC + * @tc.function: NotifyAppRunningStatusEvent + * @tc.subfunction: NA + * @tc.envConditions: NA + */ +HWTEST_F(AppRunningStatusModuleTest, AppRunningStatusModuleTest_NotifyAppRunningStatusEvent_0300, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "AppRunningStatusModuleTest_NotifyAppRunningStatusEvent_0300 start."); + sptr listener1 = new MockAppRunningStatusListener(); + sptr listener2 = new MockAppRunningStatusListener(); + + // Register listeners + auto ret = appRunningStatusModule_->RegisterListener(listener1); + EXPECT_EQ(ret, ERR_OK); + ret = appRunningStatusModule_->RegisterListener(listener2); + EXPECT_EQ(ret, ERR_OK); + + std::string bundleName = "com.test.bundle"; + int32_t uid = 1000; + RunningStatus runningStatus = RunningStatus::APP_RUNNING_STOP; + + // Notify event + appRunningStatusModule_->NotifyAppRunningStatusEvent(bundleName, uid, runningStatus); + + // Check if both listeners were notified + EXPECT_EQ(listener1->notifyCount_, 1); + EXPECT_EQ(listener1->bundle_, bundleName); + EXPECT_EQ(listener1->uid_, uid); + EXPECT_EQ(listener1->runningStatus_, runningStatus); + + EXPECT_EQ(listener2->notifyCount_, 1); + EXPECT_EQ(listener2->bundle_, bundleName); + EXPECT_EQ(listener2->uid_, uid); + EXPECT_EQ(listener2->runningStatus_, runningStatus); +} + +/** + * @tc.number: AppRunningStatusModuleTest_RemoveListenerAndDeathRecipient_0100 + * @tc.desc: Test RemoveListenerAndDeathRecipient with null remote object + * @tc.type: FUNC + * @tc.function: RemoveListenerAndDeathRecipient + * @tc.subfunction: NA + * @tc.envConditions: NA + */ +HWTEST_F(AppRunningStatusModuleTest, AppRunningStatusModuleTest_RemoveListenerAndDeathRecipient_0100, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "AppRunningStatusModuleTest_RemoveListenerAndDeathRecipient_0100 start."); + wptr remote; + auto ret = appRunningStatusModule_->RemoveListenerAndDeathRecipient(remote); + EXPECT_EQ(ret, ERR_INVALID_VALUE); +} + +/** + * @tc.number: AppRunningStatusModuleTest_RemoveListenerAndDeathRecipient_0200 + * @tc.desc: Test RemoveListenerAndDeathRecipient with valid remote object that exists + * @tc.type: FUNC + * @tc.function: RemoveListenerAndDeathRecipient + * @tc.subfunction: NA + * @tc.envConditions: NA + */ +HWTEST_F(AppRunningStatusModuleTest, AppRunningStatusModuleTest_RemoveListenerAndDeathRecipient_0200, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "AppRunningStatusModuleTest_RemoveListenerAndDeathRecipient_0200 start."); + sptr listener = new MockAppRunningStatusListener(); + + // Register listener first + auto ret = appRunningStatusModule_->RegisterListener(listener); + EXPECT_EQ(ret, ERR_OK); + + // Remove listener using remote object + wptr remote = listener->AsObject(); + ret = appRunningStatusModule_->RemoveListenerAndDeathRecipient(remote); + EXPECT_EQ(ret, ERR_OK); +} + +/** + * @tc.number: AppRunningStatusModuleTest_RemoveListenerAndDeathRecipient_0300 + * @tc.desc: Test RemoveListenerAndDeathRecipient with remote object that doesn't exist in listeners + * @tc.type: FUNC + * @tc.function: RemoveListenerAndDeathRecipient + * @tc.subfunction: NA + * @tc.envConditions: NA + */ +HWTEST_F(AppRunningStatusModuleTest, AppRunningStatusModuleTest_RemoveListenerAndDeathRecipient_0300, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "AppRunningStatusModuleTest_RemoveListenerAndDeathRecipient_0300 start."); + sptr listener = new MockAppRunningStatusListener(); + + // Don't register listener, directly try to remove + wptr remote = listener->AsObject(); + auto ret = appRunningStatusModule_->RemoveListenerAndDeathRecipient(remote); + EXPECT_EQ(ret, ERR_INVALID_OPERATION); +} + +/** + * @tc.number: AppRunningStatusModuleTest_NotifyAppRunningStatusEvent_0400 + * @tc.desc: Test NotifyAppRunningStatusEvent with null listener in listeners list + * @tc.type: FUNC + * @tc.function: NotifyAppRunningStatusEvent + * @tc.subfunction: NA + * @tc.envConditions: NA + */ +HWTEST_F(AppRunningStatusModuleTest, AppRunningStatusModuleTest_NotifyAppRunningStatusEvent_0400, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "AppRunningStatusModuleTest_NotifyAppRunningStatusEvent_0400 start."); + sptr listener = new MockAppRunningStatusListener(); + + // Register listener + auto ret = appRunningStatusModule_->RegisterListener(listener); + EXPECT_EQ(ret, ERR_OK); + + { + std::lock_guard lock(appRunningStatusModule_->listenerMutex_); + sptr nullListener = nullptr; + sptr nullRecipient = nullptr; + appRunningStatusModule_->listeners_.emplace(nullListener, nullRecipient); + } + + std::string bundleName = "com.test.bundle"; + int32_t uid = 1000; + RunningStatus runningStatus = RunningStatus::APP_RUNNING_START; + + appRunningStatusModule_->NotifyAppRunningStatusEvent(bundleName, uid, runningStatus); + + EXPECT_EQ(listener->notifyCount_, 1); + EXPECT_EQ(listener->bundle_, bundleName); + EXPECT_EQ(listener->uid_, uid); + EXPECT_EQ(listener->runningStatus_, runningStatus); +} + +/** + * @tc.number: AppRunningStatusModuleTest_ClientDeathRecipient_0200 + * @tc.desc: Test ClientDeathRecipient OnRemoteDied with valid appRunningStatus + * @tc.type: FUNC + * @tc.function: ClientDeathRecipient::OnRemoteDied + * @tc.subfunction: NA + * @tc.envConditions: NA + */ +HWTEST_F(AppRunningStatusModuleTest, AppRunningStatusModuleTest_ClientDeathRecipient_0100, TestSize.Level0) +{ + TAG_LOGD(AAFwkTag::TEST, "AppRunningStatusModuleTest_ClientDeathRecipient_0100 start."); + sptr listener = new MockAppRunningStatusListener(); + + auto ret = appRunningStatusModule_->RegisterListener(listener); + EXPECT_EQ(ret, ERR_OK); + + sptr deathRecipient; + { + std::lock_guard lock(appRunningStatusModule_->listenerMutex_); + auto it = appRunningStatusModule_->listeners_.find(listener); + EXPECT_NE(it, appRunningStatusModule_->listeners_.end()); + deathRecipient = it->second; + } + + wptr remote = listener->AsObject(); + + deathRecipient->OnRemoteDied(remote); + { + std::lock_guard lock(appRunningStatusModule_->listenerMutex_); + auto it2 = appRunningStatusModule_->listeners_.find(listener); + EXPECT_EQ(it2, appRunningStatusModule_->listeners_.end()); + } +} + +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/test/unittest/exit_resident_process_manager_test/exit_resident_process_manager_test.cpp b/test/unittest/exit_resident_process_manager_test/exit_resident_process_manager_test.cpp index 898f1ba7d6..0ed1254ab2 100644 --- a/test/unittest/exit_resident_process_manager_test/exit_resident_process_manager_test.cpp +++ b/test/unittest/exit_resident_process_manager_test/exit_resident_process_manager_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 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 @@ -229,5 +229,43 @@ HWTEST_F(ExitResidentProcessManagerTest, HandleNoRequireBigMemoryOptimization_00 exitResidentProcessManager2->currentBigMemoryState_ = MemoryState::NO_REQUIRE_BIG_MEMORY; EXPECT_NE(exitResidentProcessManager2->HandleNoRequireBigMemoryOptimization(vecInfo), ERR_OK); } -} // namespace AppExecFwk -} // namespace OHOS + +/** + * @tc.name: IsNoRequireBigMemory_001 + * @tc.desc: Verify IsNoRequireBigMemory when state is NO_REQUIRE_BIG_MEMORY + * @tc.type: FUNC + */ +HWTEST_F(ExitResidentProcessManagerTest, IsNoRequireBigMemory_001, TestSize.Level1) +{ + auto exitResidentProcessManager = std::make_shared(); + exitResidentProcessManager->currentBigMemoryState_ = MemoryState::NO_REQUIRE_BIG_MEMORY; + EXPECT_EQ(exitResidentProcessManager->IsNoRequireBigMemory(), true); +} +/** + * @tc.name: RecordExitResidentBundleNameOnRequireBigMemory_002 + * @tc.desc: Verify RecordExitResidentBundleNameOnRequireBigMemory when state is REQUIRE_BIG_MEMORY + * @tc.type: FUNC + */ +HWTEST_F(ExitResidentProcessManagerTest, RecordExitResidentBundleNameOnRequireBigMemory_002, TestSize.Level1) +{ + auto exitResidentProcessManager = std::make_shared(); + exitResidentProcessManager->currentBigMemoryState_ = MemoryState::REQUIRE_BIG_MEMORY; + std::string bundleName = "testBundle"; + int32_t uid = 1000; + EXPECT_EQ(exitResidentProcessManager->RecordExitResidentBundleNameOnRequireBigMemory(bundleName, uid), true); +} + +/** + * @tc.name: IsKilledForUpgradeWeb_002 + * @tc.desc: Verify IsKilledForUpgradeWeb when bundle is in the list + * @tc.type: FUNC + */ +HWTEST_F(ExitResidentProcessManagerTest, IsKilledForUpgradeWeb_002, TestSize.Level1) +{ + auto exitResidentProcessManager = std::make_shared(); + std::string bundleName = "testBundle"; + exitResidentProcessManager->exitResidentBundlesDependedOnWeb_.emplace_back(bundleName, 1000); + EXPECT_EQ(exitResidentProcessManager->IsKilledForUpgradeWeb(bundleName), true); +} +} // namespace AppExecFwk +} // namespace OHOS From d4e5a54214851da7d01455d8863e6cc8aa272af0 Mon Sep 17 00:00:00 2001 From: zhangzezhong Date: Tue, 3 Jun 2025 14:22:07 +0800 Subject: [PATCH 03/23] add StatusBarDelegateManager unittest cases for ability_runtime Signed-off-by: zhangzezhong --- test/unittest/BUILD.gn | 6 +- .../status_bar_delegate_manager_test.cpp | 32 +- .../BUILD.gn | 124 ++ .../mock/include/app_utils.h | 40 + .../include/mock_ability_info_callback_stub.h | 31 + .../mock/include/mock_my_flag.h | 26 + .../include/mock_permission_verification.h | 38 + .../mock/src/app_utils.cpp | 52 + .../mock/src/mock_my_flag.cpp | 22 + .../mock/src/mock_permission_verification.cpp | 26 + ...i_ability_lifecycle_manager_third_test.cpp | 1270 +++++++++++++++++ 11 files changed, 1664 insertions(+), 3 deletions(-) create mode 100644 test/unittest/ui_ability_lifecycle_manager_third_test/BUILD.gn create mode 100644 test/unittest/ui_ability_lifecycle_manager_third_test/mock/include/app_utils.h create mode 100644 test/unittest/ui_ability_lifecycle_manager_third_test/mock/include/mock_ability_info_callback_stub.h create mode 100644 test/unittest/ui_ability_lifecycle_manager_third_test/mock/include/mock_my_flag.h create mode 100644 test/unittest/ui_ability_lifecycle_manager_third_test/mock/include/mock_permission_verification.h create mode 100644 test/unittest/ui_ability_lifecycle_manager_third_test/mock/src/app_utils.cpp create mode 100644 test/unittest/ui_ability_lifecycle_manager_third_test/mock/src/mock_my_flag.cpp create mode 100644 test/unittest/ui_ability_lifecycle_manager_third_test/mock/src/mock_permission_verification.cpp create mode 100644 test/unittest/ui_ability_lifecycle_manager_third_test/ui_ability_lifecycle_manager_third_test.cpp diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index c2ce241226..2ccb60c4eb 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -250,9 +250,9 @@ group("unittest") { "app_mgr_service_test:unittest", "app_mgr_service_third_test:unittest", "app_mgr_stub_test:unittest", + "app_native_spawn_manager_test:unittest", "app_preloader_test:unittest", "app_recovery_test:unittest", - "app_native_spawn_manager_test:unittest", "app_running_manager_fourth_test:unittest", "app_running_manager_second_test:unittest", "app_running_manager_test:unittest", @@ -427,15 +427,16 @@ group("unittest") { "start_other_app_interceptor_test:unittest", "startup_util_test:unittest", "state_utils_test:unittest", - "timeout_state_utils_test:unittest", "stop_user_callback_proxy_test:unittest", "stop_user_callback_stub_test:unittest", "sys_mgr_client_test:unittest", "system_ability_token_callback_stub_test:unittest", "task_data_persistence_mgr_test:unittest", "task_handler_wrap_test:unittest", + "timeout_state_utils_test:unittest", "trigger_Info_test:unittest", "ui_ability_lifecycle_manager_second_test:unittest", + "ui_ability_lifecycle_manager_third_test:unittest", "ui_extension:unittest", "ui_extension_ability_test:unittest", "ui_extension_context_second_test:unittest", @@ -525,6 +526,7 @@ group("unittest") { "start_option_display_id_test:unittest", "status_bar_delegate_manager_test:unittest", "ui_ability_lifecycle_manager_test:unittest", + "ui_ability_lifecycle_manager_third_test:unittest", ] } diff --git a/test/unittest/status_bar_delegate_manager_test/status_bar_delegate_manager_test.cpp b/test/unittest/status_bar_delegate_manager_test/status_bar_delegate_manager_test.cpp index 00cd31823e..f72c023f56 100644 --- a/test/unittest/status_bar_delegate_manager_test/status_bar_delegate_manager_test.cpp +++ b/test/unittest/status_bar_delegate_manager_test/status_bar_delegate_manager_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2023-2025 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 @@ -356,5 +356,35 @@ HWTEST_F(StatusBarDelegateManagerTest, DoCallerProcessDetachment_0400, TestSize. int32_t ret = statusBarDelegate->DoCallerProcessDetachment(abilityRecord); EXPECT_EQ(ret, ERR_INVALID_VALUE); } + +/** + * @tc.name: StatusBarDelegateManager_IsSupportStatusBar_0100 + * @tc.desc: Test IsSupportStatusBar + * @tc.type: FUNC + */ +HWTEST_F(StatusBarDelegateManagerTest, IsSupportStatusBar_0100, TestSize.Level1) +{ + std::shared_ptr statusBarDelegate = std::make_shared(); + EXPECT_NE(statusBarDelegate, nullptr); + sptr mockDelegate = new MockIStatusBarDelegate(); + statusBarDelegate->RegisterStatusBarDelegate(nullptr); + auto ret = statusBarDelegate->IsSupportStatusBar(); + EXPECT_EQ(ret, false); +} + +/** + * @tc.name: StatusBarDelegateManager_IsSupportStatusBar_0200 + * @tc.desc: Test IsSupportStatusBar + * @tc.type: FUNC + */ +HWTEST_F(StatusBarDelegateManagerTest, IsSupportStatusBar_0200, TestSize.Level1) +{ + std::shared_ptr statusBarDelegate = std::make_shared(); + EXPECT_NE(statusBarDelegate, nullptr); + sptr mockDelegate = new MockIStatusBarDelegate(); + statusBarDelegate->RegisterStatusBarDelegate(mockDelegate); + auto ret = statusBarDelegate->IsSupportStatusBar(); + EXPECT_EQ(ret, true); +} } // namespace AAFwk } // namespace OHOS diff --git a/test/unittest/ui_ability_lifecycle_manager_third_test/BUILD.gn b/test/unittest/ui_ability_lifecycle_manager_third_test/BUILD.gn new file mode 100644 index 0000000000..5007587aa0 --- /dev/null +++ b/test/unittest/ui_ability_lifecycle_manager_third_test/BUILD.gn @@ -0,0 +1,124 @@ +# Copyright (c) 2025 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/ability_runtime/abilitymgr" + +ohos_unittest("ui_ability_lifecycle_manager_third_test") { + module_out_path = module_output_path + + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${ability_runtime_services_path}/appdfr/include", + "${ability_runtime_services_path}/abilitymgr/include/", + "${ability_runtime_services_path}/abilitymgr/include/scene_board/", + "${ability_runtime_test_path}/mock/services_abilitymgr_test/libs/ability_scheduler_mock", + "mock/include", + ] + + cflags = [ + "-Dprivate=public", + "-Dprotected=public", + ] + + public_configs = + [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + sources = [ + "${ability_runtime_services_path}/abilitymgr/src/ability_auto_startup_data_manager.cpp", + "${ability_runtime_services_path}/abilitymgr/src/ability_auto_startup_service.cpp", + "${ability_runtime_services_path}/abilitymgr/src/ability_event_handler.cpp", + "${ability_runtime_services_path}/abilitymgr/src/ability_manager_event_subscriber.cpp", + "${ability_runtime_services_path}/abilitymgr/src/app_exit_reason_data_manager.cpp", + "${ability_runtime_services_path}/abilitymgr/src/exit_info_data_manager.cpp", + "${ability_runtime_services_path}/abilitymgr/src/extension_config.cpp", + "${ability_runtime_services_path}/abilitymgr/src/hidden_start_observer_manager.cpp", + "${ability_runtime_services_path}/abilitymgr/src/scene_board/status_bar_delegate_manager.cpp", + "${ability_runtime_services_path}/abilitymgr/src/scene_board/ui_ability_lifecycle_manager.cpp", + "${ability_runtime_services_path}/abilitymgr/src/utils/timeout_state_utils.cpp", + "${ability_runtime_services_path}/common/src/event_report.cpp", + "mock/src/app_utils.cpp", + "mock/src/mock_my_flag.cpp", + "mock/src/mock_permission_verification.cpp", + "ui_ability_lifecycle_manager_third_test.cpp", + ] + + deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_setting", + "${ability_runtime_innerkits_path}/ability_manager:process_options", + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_native_path}/ability/native:auto_startup_callback", + "${ability_runtime_native_path}/appkit:appkit_manager_helper", + "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${ability_runtime_path}/utils/server/startup:startup_util", + "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/common:app_util", + "${ability_runtime_services_path}/common:perm_verification", + "${ability_runtime_services_path}/common:task_handler_wrap", + ] + + external_deps = [ + "ability_base:session_info", + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "config_policy:configpolicy_util", + "dsoftbus:softbus_client", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "googletest:gmock_main", + "googletest:gtest_main", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "init:libbeget_proxy", + "init:libbegetutil", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "window_manager:session_manager_lite", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + external_deps += [ + "window_manager:libdm", + "window_manager:libwsutils", + "window_manager:scene_session", + ] + } + cflags_cc = [] + if (os_dlp_part_enabled) { + cflags_cc += [ "-DWITH_DLP" ] + } +} + +group("unittest") { + testonly = true + + deps = [ ":ui_ability_lifecycle_manager_third_test" ] +} diff --git a/test/unittest/ui_ability_lifecycle_manager_third_test/mock/include/app_utils.h b/test/unittest/ui_ability_lifecycle_manager_third_test/mock/include/app_utils.h new file mode 100644 index 0000000000..98846872ac --- /dev/null +++ b/test/unittest/ui_ability_lifecycle_manager_third_test/mock/include/app_utils.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2025 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 OHOS_ABILITY_RUNTIME_APP_UTILS_H +#define OHOS_ABILITY_RUNTIME_APP_UTILS_H + +#include "nocopyable.h" + +namespace OHOS { +namespace AAFwk { +class AppUtils { +public: + static AppUtils &GetInstance(); + static bool isStartOptionsWithAnimation_; + + ~AppUtils(); + bool IsStartOptionsWithAnimation(); + bool IsStartSpecifiedProcess(); + bool IsStartOptionsWithProcessOptions(); + +private: + AppUtils(); + + DISALLOW_COPY_AND_MOVE(AppUtils); +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_APP_UTILS_H diff --git a/test/unittest/ui_ability_lifecycle_manager_third_test/mock/include/mock_ability_info_callback_stub.h b/test/unittest/ui_ability_lifecycle_manager_third_test/mock/include/mock_ability_info_callback_stub.h new file mode 100644 index 0000000000..8974614d15 --- /dev/null +++ b/test/unittest/ui_ability_lifecycle_manager_third_test/mock/include/mock_ability_info_callback_stub.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2025 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 MOCK_ABILITY_INFO_CALLBACK_STUB_H +#define MOCK_ABILITY_INFO_CALLBACK_STUB_H + +#include "ability_info_callback_stub.h" + +namespace OHOS::AAFwk { +class MockAbilityInfoCallbackStub : public AppExecFwk::AbilityInfoCallbackStub { +public: + void NotifyAbilityToken(const sptr token, const Want &want) override {} + void NotifyStartSpecifiedAbility(const sptr &callerToken, const Want &want, int requestCode, + sptr &extraParam) override {} + void NotifyRestartSpecifiedAbility(const sptr &token) override {} + void NotifyStartAbilityResult(const Want &want, int result) override {} +}; +} // namespace OHOS::AAFwk +#endif // MOCK_ABILITY_INFO_CALLBACK_STUB_H diff --git a/test/unittest/ui_ability_lifecycle_manager_third_test/mock/include/mock_my_flag.h b/test/unittest/ui_ability_lifecycle_manager_third_test/mock/include/mock_my_flag.h new file mode 100644 index 0000000000..fef304a268 --- /dev/null +++ b/test/unittest/ui_ability_lifecycle_manager_third_test/mock/include/mock_my_flag.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 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 MOCK_MY_FLAG_H +#define MOCK_MY_FLAG_H +namespace OHOS { +namespace AAFwk { +class MyFlag { +public: + static int flag_; +}; +} // namespace AAFwk +} // namespace OHOS +#endif // MOCK_MY_FLAG_H diff --git a/test/unittest/ui_ability_lifecycle_manager_third_test/mock/include/mock_permission_verification.h b/test/unittest/ui_ability_lifecycle_manager_third_test/mock/include/mock_permission_verification.h new file mode 100644 index 0000000000..40d216e740 --- /dev/null +++ b/test/unittest/ui_ability_lifecycle_manager_third_test/mock/include/mock_permission_verification.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2025 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 OHOS_ABILITY_RUNTIME_PERMISSION_VERIFICATION_H +#define OHOS_ABILITY_RUNTIME_PERMISSION_VERIFICATION_H + +#include + +#include "ipc_skeleton.h" +#include "mock_my_flag.h" +#include "singleton.h" +#include "want.h" + +namespace OHOS { +namespace AAFwk { + +class PermissionVerification : public DelayedSingleton { +public: + PermissionVerification() = default; + ~PermissionVerification() = default; + + bool VerifyPrepareTerminatePermission(const int &tokenId) const; +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_PERMISSION_VERIFICATION_H \ No newline at end of file diff --git a/test/unittest/ui_ability_lifecycle_manager_third_test/mock/src/app_utils.cpp b/test/unittest/ui_ability_lifecycle_manager_third_test/mock/src/app_utils.cpp new file mode 100644 index 0000000000..8be13999b1 --- /dev/null +++ b/test/unittest/ui_ability_lifecycle_manager_third_test/mock/src/app_utils.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2025 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 "app_utils.h" + +#include "hilog_tag_wrapper.h" + +namespace OHOS { +namespace AAFwk { +bool AppUtils::isStartOptionsWithAnimation_ = false; + +AppUtils::~AppUtils() {} + +AppUtils::AppUtils() {} + +AppUtils &AppUtils::GetInstance() +{ + static AppUtils utils; + return utils; +} + +bool AppUtils::IsStartSpecifiedProcess() +{ + TAG_LOGD(AAFwkTag::DEFAULT, "called %{public}d", AppUtils::isStartOptionsWithAnimation_); + return AppUtils::isStartOptionsWithAnimation_; +} + +bool AppUtils::IsStartOptionsWithProcessOptions() +{ + TAG_LOGD(AAFwkTag::DEFAULT, "called %{public}d", AppUtils::isStartOptionsWithAnimation_); + return AppUtils::isStartOptionsWithAnimation_; +} + +bool AppUtils::IsStartOptionsWithAnimation() +{ + TAG_LOGD(AAFwkTag::DEFAULT, "called %{public}d", AppUtils::isStartOptionsWithAnimation_); + return AppUtils::isStartOptionsWithAnimation_; +} +} // namespace AAFwk +} // namespace OHOS diff --git a/test/unittest/ui_ability_lifecycle_manager_third_test/mock/src/mock_my_flag.cpp b/test/unittest/ui_ability_lifecycle_manager_third_test/mock/src/mock_my_flag.cpp new file mode 100644 index 0000000000..e21af59a45 --- /dev/null +++ b/test/unittest/ui_ability_lifecycle_manager_third_test/mock/src/mock_my_flag.cpp @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2025 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 "mock_my_flag.h" + +namespace OHOS { +namespace AAFwk { +int MyFlag::flag_ = 0; +} // namespace AAFwk +} // namespace OHOS diff --git a/test/unittest/ui_ability_lifecycle_manager_third_test/mock/src/mock_permission_verification.cpp b/test/unittest/ui_ability_lifecycle_manager_third_test/mock/src/mock_permission_verification.cpp new file mode 100644 index 0000000000..b128876d2e --- /dev/null +++ b/test/unittest/ui_ability_lifecycle_manager_third_test/mock/src/mock_permission_verification.cpp @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 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 "mock_permission_verification.h" + +namespace OHOS { +namespace AAFwk { + +bool PermissionVerification::VerifyPrepareTerminatePermission(const int &tokenId) const +{ + return MyFlag::flag_; +} +} // namespace AAFwk +} // namespace OHOS diff --git a/test/unittest/ui_ability_lifecycle_manager_third_test/ui_ability_lifecycle_manager_third_test.cpp b/test/unittest/ui_ability_lifecycle_manager_third_test/ui_ability_lifecycle_manager_third_test.cpp new file mode 100644 index 0000000000..bbd0842c79 --- /dev/null +++ b/test/unittest/ui_ability_lifecycle_manager_third_test/ui_ability_lifecycle_manager_third_test.cpp @@ -0,0 +1,1270 @@ +/* + * Copyright (c) 2025 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 "ability_manager_errors.h" +#include "ability_util.h" +#define private public +#define protected public +#include "ability_record.h" +#include "app_mgr_util.h" +#include "app_utils.h" +#include "scene_board/ui_ability_lifecycle_manager.h" +#undef protected +#undef private +#include "ability_start_setting.h" +#include "app_scheduler.h" +#include "app_mgr_client.h" +#include "display_util.h" +#include "mock_ability_info_callback_stub.h" +#include "process_options.h" +#include "session/host/include/session.h" +#include "session_info.h" +#include "startup_util.h" +#include "status_bar_delegate_interface.h" +#include "scene_board/status_bar_delegate_manager.h" +#include "server_constant.h" +#define private public +#define protected public +#include "ability_manager_service.h" +#undef protected +#undef private +#include "ability_scheduler_mock.h" +#include "hilog_tag_wrapper.h" +#include "mock_my_flag.h" +#include "mock_permission_verification.h" + +using namespace testing; +using namespace testing::ext; + +namespace OHOS { +namespace AAFwk { +namespace { +#ifdef WITH_DLP +const std::string DLP_INDEX = "ohos.dlp.params.index"; +#endif // WITH_DLP +constexpr int32_t TEST_UID = 20010001; +}; +class UIAbilityLifecycleManagerThirdTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; + std::shared_ptr InitAbilityRecord(); +}; + +void UIAbilityLifecycleManagerThirdTest::SetUpTestCase() {} + +void UIAbilityLifecycleManagerThirdTest::TearDownTestCase() {} + +void UIAbilityLifecycleManagerThirdTest::SetUp() {} + +void UIAbilityLifecycleManagerThirdTest::TearDown() {} + +class UIAbilityLifcecycleManagerThirdTestStub : public IRemoteStub { +public: + UIAbilityLifcecycleManagerThirdTestStub() {}; + virtual ~UIAbilityLifcecycleManagerThirdTestStub() {}; + + virtual int OnRemoteRequest( + uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) + { + return 0; + }; + + virtual void OnAbilityConnectDone( + const AppExecFwk::ElementName& element, const sptr& remoteObject, int resultCode) {}; + + /** + * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * + * @param element, service ability's ElementName. + * @param resultCode, ERR_OK on success, others on failure. + */ + virtual void OnAbilityDisconnectDone(const AppExecFwk::ElementName& element, int resultCode) {}; +}; + +std::shared_ptr UIAbilityLifecycleManagerThirdTest::InitAbilityRecord() +{ + AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.unittest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AppExecFwk::AbilityType::PAGE; + std::shared_ptr abilityRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + return abilityRecord; +} + +class MockIStatusBarDelegate : public OHOS::AbilityRuntime::IStatusBarDelegate { +public: + int32_t CheckIfStatusBarItemExists(uint32_t accessTokenId, const std::string &instanceKey, + bool& isExist) + { + return 0; + } + int32_t AttachPidToStatusBarItem(uint32_t accessTokenId, int32_t pid, const std::string &instanceKey) + { + return 0; + } + int32_t DetachPidToStatusBarItem(uint32_t accessTokenId, int32_t pid, const std::string &instanceKey) + { + return 0; + } + sptr AsObject() + { + return nullptr; + } +}; + +class MockIRemoteObject : public IRemoteObject { +public: + MockIRemoteObject() : IRemoteObject(u"mock_i_remote_object") {} + + ~MockIRemoteObject() {} + + int32_t GetObjectRefCount() override + { + return 0; + } + + int SendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override + { + return 0; + } + + bool IsProxyObject() const override + { + return true; + } + + bool CheckObjectLegality() const override + { + return true; + } + + bool AddDeathRecipient(const sptr &recipient) override + { + return true; + } + + bool RemoveDeathRecipient(const sptr &recipient) override + { + return true; + } + + bool Marshalling(Parcel &parcel) const override + { + return true; + } + + sptr AsInterface() override + { + return nullptr; + } + + int Dump(int fd, const std::vector &args) override + { + return 0; + } + + std::u16string GetObjectDescriptor() const + { + std::u16string descriptor = std::u16string(); + return descriptor; + } +}; + +class SysMrgClient { +public: + static SysMrgClient* instance_; + + SysMrgClient* GetInstance() + { + return instance_; + } +}; +SysMrgClient* SysMrgClient::instance_ = nullptr; + +/** + * @tc.name: FindRecordFromTmpMap_001 + * @tc.desc: FindRecordFromTmpMap + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, FindRecordFromTmpMap_001, TestSize.Level1) +{ + auto mgr = std::make_unique(); + + AbilityRequest abilityRequest; + abilityRequest.abilityInfo.name = "Name"; + abilityRequest.abilityInfo.bundleName = "BundleName"; + abilityRequest.abilityInfo.moduleName = "ModuleName"; + abilityRequest.want.SetParam(Want::APP_INSTANCE_KEY, std::string("InstanceKey")); + abilityRequest.want.SetParam(ServerConstant::DLP_INDEX, 5); + + auto callerAbilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + callerAbilityRecord->sessionInfo_ = nullptr; + callerAbilityRecord->SetAppIndex(5); + callerAbilityRecord->SetInstanceKey("InstanceKey"); + + mgr->tmpAbilityMap_ = {{1, callerAbilityRecord}}; + + auto ret = mgr->FindRecordFromTmpMap(abilityRequest); + EXPECT_NE(ret, nullptr); +} + +/** + * @tc.name: CheckSessionInfo_001 + * @tc.desc: CheckSessionInfo + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, CheckSessionInfo_001, TestSize.Level1) +{ + auto mgr = std::make_unique(); + auto currentSessionInfo = sptr::MakeSptr(); + Rosen::SessionInfo info; + sptr session = sptr::MakeSptr(info); + currentSessionInfo->sessionToken = session->AsObject(); + + AbilityRequest abilityRequest; + auto callerAbilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + callerAbilityRecord->sessionInfo_ = nullptr; + + auto ret = mgr->CheckSessionInfo(currentSessionInfo); + EXPECT_EQ(ret, true); +} + +/** + * @tc.name: UIAbilityLifecycleManager_AbilityWindowConfigTransactionDone_0300 + * @tc.desc: AbilityWindowConfigTransactionDone + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, AbilityWindowConfigTransactionDone_003, TestSize.Level1) +{ + auto mgr = std::make_unique(); + + AbilityRequest abilityRequest; + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + + auto token = sptr::MakeSptr(abilityRecord); + abilityRecord->token_ = token; + + mgr->terminateAbilityList_ = { abilityRecord }; + + WindowConfig windowConfig; + + auto ret = mgr->AbilityWindowConfigTransactionDone(token, windowConfig); + + EXPECT_EQ(ret, ERR_OK); +} + +/** + * @tc.name: UIAbilityLifecycleManager_NotifySCBToStartUIAbility_0300 + * @tc.desc: NotifySCBToStartUIAbility + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, NotifySCBToStartUIAbility_003, TestSize.Level1) +{ + auto mgr = std::make_unique(); + + std::map> startUIAbilityCallerTimestamps; + std::vector callerTimestamps = {}; + constexpr int32_t START_UI_ABILITY_PER_SECOND_UPPER_LIMIT = 20; + auto curTimeNs = AbilityUtil::GetSysTimeNs(); + for (int i = 0; i < START_UI_ABILITY_PER_SECOND_UPPER_LIMIT + 2; i++) { + callerTimestamps.emplace_back(curTimeNs); + } + startUIAbilityCallerTimestamps.emplace(2, callerTimestamps); + mgr->startUIAbilityCallerTimestamps_ = startUIAbilityCallerTimestamps; + + AbilityRequest abilityRequest; + abilityRequest.want.SetParam(Want::PARAM_RESV_CALLER_UID, 2); + + auto ret = mgr->NotifySCBToStartUIAbility(abilityRequest); + + EXPECT_EQ(ret, ERR_INVALID_VALUE); +} + +/** + * @tc.name: UIAbilityLifecycleManager_DispatchForeground_0200 + * @tc.desc: DispatchForeground + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, DispatchForeground_002, TestSize.Level1) +{ + auto mgr = std::make_unique(); + + AbilityState state = AbilityState::ACTIVE; + + std::shared_ptr runner; + std::weak_ptr server; + auto handler = std::make_shared(runner, server); + DelayedSingleton::GetInstance()->eventHandler_ = handler; + + auto taskHandler = TaskHandlerWrap::CreateQueueHandler("HelloWorld"); + DelayedSingleton::GetInstance()->taskHandler_ = nullptr; + + std::shared_ptr abilityRecord = nullptr; + + auto ret = mgr->DispatchForeground(abilityRecord, true, state); + + EXPECT_EQ(ret, ERR_INVALID_VALUE); +} + +/** + * @tc.name: UIAbilityLifecycleManager_DispatchForeground_0300 + * @tc.desc: DispatchForeground + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, DispatchForeground_003, TestSize.Level1) +{ + auto mgr = std::make_unique(); + + AbilityState state = AbilityState::ACTIVE; + + std::shared_ptr runner; + std::weak_ptr server; + auto handler = std::make_shared(runner, server); + DelayedSingleton::GetInstance()->eventHandler_ = handler; + + auto taskHandler = TaskHandlerWrap::CreateQueueHandler("HelloWorld"); + DelayedSingleton::GetInstance()->taskHandler_ = nullptr; + + AbilityRequest abilityRequest; + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + abilityRecord->currentState_ = AbilityState::ACTIVATING; + + auto ret = mgr->DispatchForeground(abilityRecord, true, state); + + EXPECT_EQ(ret, ERR_INVALID_VALUE); +} + +/** + * @tc.name: UIAbilityLifecycleManager_DispatchBackground_0200 + * @tc.desc: DispatchBackground + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, DispatchBackground_002, TestSize.Level1) +{ + auto mgr = std::make_shared(); + + auto taskHandler = TaskHandlerWrap::CreateQueueHandler("HelloWorld"); + DelayedSingleton::GetInstance()->taskHandler_ = taskHandler; + + AbilityRequest abilityRequest; + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + abilityRecord->currentState_ = AbilityState::BACKGROUNDING; + + auto ret = mgr->DispatchBackground(abilityRecord); + + EXPECT_EQ(ret, ERR_OK); +} + +/** + * @tc.name: UIAbilityLifecycleManager_UpdateProcessName_0200 + * @tc.desc: UpdateProcessName + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, UpdateProcessName_002, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + sptr sessionInfo = new (std::nothrow) SessionInfo(); + sessionInfo->processOptions = std::make_shared(); + EXPECT_NE(sessionInfo->processOptions, nullptr); + sessionInfo->processOptions->processMode = ProcessMode::NEW_PROCESS_ATTACH_TO_PARENT; + sessionInfo->processOptions->processName = "HeavenlyMe"; + AbilityRequest abilityRequest; + abilityRequest.sessionInfo = sessionInfo; + abilityRequest.abilityInfo.bundleName = "com.example.unittest"; + abilityRequest.abilityInfo.moduleName = "entry"; + abilityRequest.abilityInfo.name = "MainAbility"; + std::shared_ptr abilityRecord = InitAbilityRecord(); + uiAbilityLifecycleManager->UpdateProcessName(abilityRequest, abilityRecord); + EXPECT_EQ("HeavenlyMe", abilityRecord->GetProcessName()); +} + +/** + * @tc.name: UIAbilityLifecycleManager_UpdateAbilityRecordLaunchReason_0500 + * @tc.desc: UpdateAbilityRecordLaunchReason + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, UpdateAbilityRecordLaunchReason_005, TestSize.Level1) +{ + auto mgr = std::make_unique(); + EXPECT_NE(mgr, nullptr); + + AbilityRequest abilityRequest; + abilityRequest.want.SetParam(Want::PARM_LAUNCH_REASON_MESSAGE, std::string("HeavenlyMe")); + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + abilityRecord->lifeCycleStateInfo_.launchParam.launchReasonMessage = "HelloWorld"; + + mgr->UpdateAbilityRecordLaunchReason(abilityRequest, abilityRecord); + auto message = abilityRecord->lifeCycleStateInfo_.launchParam.launchReasonMessage; + EXPECT_EQ(message, "HeavenlyMe"); +} + +/** + * @tc.name: UIAbilityLifecycleManager_UpdateAbilityRecordLaunchReason_0600 + * @tc.desc: UpdateAbilityRecordLaunchReason + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, UpdateAbilityRecordLaunchReason_006, TestSize.Level1) +{ + auto mgr = std::make_unique(); + EXPECT_NE(mgr, nullptr); + Want want; + want.SetParam(Want::PARAM_ABILITY_RECOVERY_RESTART, true); + + AbilityRequest abilityRequest; + abilityRequest.want.SetParam(Want::PARM_LAUNCH_REASON_MESSAGE, std::string("")); + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + abilityRecord->lifeCycleStateInfo_.launchParam.launchReasonMessage = "HelloWorld"; + + mgr->UpdateAbilityRecordLaunchReason(abilityRequest, abilityRecord); + auto message = abilityRecord->lifeCycleStateInfo_.launchParam.launchReasonMessage; + EXPECT_NE(message, ""); +} + +/** + * @tc.name: UIAbilityLifecycleManager_MinimizeUIAbility_0300 + * @tc.desc: MinimizeUIAbility + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, MinimizeUIAbility_003, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + + AbilityRequest abilityRequest; + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + abilityRecord->SetPendingState(AbilityState::FOREGROUND); + + EXPECT_EQ(uiAbilityLifecycleManager->MinimizeUIAbility(abilityRecord, false, 0), ERR_OK); +} + +/** + * @tc.name: UIAbilityLifecycleManager_GetPersistentIdByAbilityRequest_0300 + * @tc.desc: GetPersistentIdByAbilityRequest + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, GetPersistentIdByAbilityRequest_003, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_unique(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + AbilityRequest abilityRequest; + abilityRequest.collaboratorType = CollaboratorType::OTHERS_TYPE; + uiAbilityLifecycleManager->sessionAbilityMap_.clear(); + bool reuse = false; + EXPECT_EQ(uiAbilityLifecycleManager->GetPersistentIdByAbilityRequest(abilityRequest, reuse), 0); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OnStartSpecifiedFailed_0200 + * @tc.desc: OnStartSpecifiedFailed + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, OnStartSpecifiedFailed_002, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + int32_t requestId = 1; + AbilityRequest abilityRequest; + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + + uiAbilityLifecycleManager->hookSpecifiedMap_ = { + {requestId, abilityRecord} + }; + + uiAbilityLifecycleManager->OnStartSpecifiedFailed(requestId); + EXPECT_EQ(uiAbilityLifecycleManager->hookSpecifiedMap_.size(), 0); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OnStartSpecifiedFailed_0300 + * @tc.desc: OnStartSpecifiedFailed + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, OnStartSpecifiedFailed_003, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + int32_t requestId = 1; + AbilityRequest abilityRequest; + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + + uiAbilityLifecycleManager->hookSpecifiedMap_ = { + {2, abilityRecord} + }; + + uiAbilityLifecycleManager->OnStartSpecifiedFailed(requestId); + EXPECT_NE(uiAbilityLifecycleManager->hookSpecifiedMap_.size(), 0); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OnStartSpecifiedProcessResponse_0300 + * @tc.desc: OnStartSpecifiedProcessResponse + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, OnStartSpecifiedProcessResponse_003, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + int32_t requestId = 10; + AbilityRequest abilityRequest; + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + + abilityRequest.abilityInfo.launchMode == AppExecFwk::LaunchMode::SPECIFIED; + auto specifiedRequestPtr = std::make_shared(requestId, abilityRequest); + specifiedRequestPtr->specifiedProcessState = SpecifiedProcessState::STATE_PROCESS; + uiAbilityLifecycleManager->specifiedRequestList_ = { + { "NewKawasaki", { specifiedRequestPtr } } + }; + + uiAbilityLifecycleManager->OnStartSpecifiedProcessResponse("HeavenlyMe", requestId); + + auto listMap = uiAbilityLifecycleManager->specifiedRequestList_.find("NewKawasaki"); + EXPECT_EQ(listMap, uiAbilityLifecycleManager->specifiedRequestList_.end()); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OnStartSpecifiedProcessResponse_0400 + * @tc.desc: OnStartSpecifiedProcessResponse + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, OnStartSpecifiedProcessResponse_004, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + int32_t requestId = 10; + AbilityRequest abilityRequest; + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + + abilityRequest.abilityInfo.launchMode = AppExecFwk::LaunchMode::SINGLETON; + auto specifiedRequestPtr = std::make_shared(requestId, abilityRequest); + specifiedRequestPtr->specifiedProcessState = SpecifiedProcessState::STATE_PROCESS; + uiAbilityLifecycleManager->specifiedRequestList_ = { + {"NewKawasaki", {specifiedRequestPtr}} + }; + + uiAbilityLifecycleManager->OnStartSpecifiedProcessResponse("HeavenlyMe", requestId); + + auto listMap = uiAbilityLifecycleManager->specifiedRequestList_.find("NewKawasaki"); + EXPECT_EQ(listMap, uiAbilityLifecycleManager->specifiedRequestList_.end()); +} + +/** + * @tc.name: UIAbilityLifecycleManager_IsSupportStatusBar_0400 + * @tc.desc: IsSupportStatusBar + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, IsSupportStatusBar_004, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_unique(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + uiAbilityLifecycleManager->statusBarDelegateManager_ = uiAbilityLifecycleManager->GetStatusBarDelegateManager(); + auto delegate = sptr::MakeSptr(); + uiAbilityLifecycleManager->statusBarDelegateManager_->RegisterStatusBarDelegate(delegate); + + auto ret = uiAbilityLifecycleManager->IsSupportStatusBar(); + + EXPECT_EQ(ret, true); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OnAcceptWantResponse_0100 + * @tc.desc: OnAcceptWantResponse + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, OnAcceptWantResponse_001, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + AAFwk::Want want; + std::string flag = ""; + int32_t requestId = 1; + + AbilityRequest abilityRequest; + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + abilityRecord->sessionInfo_ = sptr::MakeSptr(); + + uiAbilityLifecycleManager->hookSpecifiedMap_ = { + {requestId, abilityRecord} + }; + + uiAbilityLifecycleManager->OnAcceptWantResponse(want, flag, requestId); + + auto size = uiAbilityLifecycleManager->hookSpecifiedMap_.size(); + EXPECT_EQ(size, 0); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OnAcceptWantResponse_0200 + * @tc.desc: OnAcceptWantResponse + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, OnAcceptWantResponse_002, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + AAFwk::Want want; + std::string flag = ""; + int32_t requestId = 1; + + AbilityRequest abilityRequest; + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + + uiAbilityLifecycleManager->hookSpecifiedMap_ = { + {requestId, abilityRecord} + }; + + uiAbilityLifecycleManager->OnAcceptWantResponse(want, flag, 2); + + auto size = uiAbilityLifecycleManager->hookSpecifiedMap_.size(); + EXPECT_EQ(size, 1); +} + +/** + * @tc.name: UIAbilityLifecycleManager_MoveAbilityToFront_0100 + * @tc.desc: MoveAbilityToFront + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, MoveAbilityToFront_001, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + AbilityRequest abilityRequest; + abilityRequest.processOptions = std::make_shared(); + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + abilityRecord->sessionInfo_ = sptr::MakeSptr(); + abilityRequest.abilityInfo.launchMode = AppExecFwk::LaunchMode::SPECIFIED; + + AppUtils::isStartOptionsWithAnimation_ = true; + + uiAbilityLifecycleManager->MoveAbilityToFront(abilityRequest, abilityRecord, abilityRecord, nullptr, 0); + + auto sessionInfo = abilityRecord->GetSessionInfo(); + EXPECT_NE(sessionInfo->processOptions, nullptr); +} + +/** + * @tc.name: UIAbilityLifecycleManager_MoveAbilityToFront_0200 + * @tc.desc: MoveAbilityToFront + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, MoveAbilityToFront_002, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + AbilityRequest abilityRequest; + abilityRequest.processOptions = std::make_shared(); + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + abilityRecord->sessionInfo_ = sptr::MakeSptr(); + abilityRequest.abilityInfo.launchMode = AppExecFwk::LaunchMode::SPECIFIED; + + AppUtils::isStartOptionsWithAnimation_ = false; + + uiAbilityLifecycleManager->MoveAbilityToFront(abilityRequest, abilityRecord, abilityRecord, nullptr, 0); + + auto sessionInfo = abilityRecord->GetSessionInfo(); + EXPECT_EQ(sessionInfo->processOptions, nullptr); +} + +/** + * @tc.name: UIAbilityLifecycleManager_MoveAbilityToFront_0300 + * @tc.desc: MoveAbilityToFront + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, MoveAbilityToFront_003, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + AbilityRequest abilityRequest; + abilityRequest.processOptions = std::make_shared(); + abilityRequest.abilityInfo.launchMode = AppExecFwk::LaunchMode::SPECIFIED; + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + abilityRecord->sessionInfo_ = sptr::MakeSptr(); + abilityRecord->want_.SetParam(Want::PARAM_RESV_WINDOW_MODE, + AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED); + + AppUtils::isStartOptionsWithAnimation_ = false; + + auto startOptions = std::make_shared(); + startOptions->windowMode_ = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_SECONDARY; + + uiAbilityLifecycleManager->MoveAbilityToFront(abilityRequest, abilityRecord, abilityRecord, startOptions, 0); + + auto ret = abilityRecord->want_.GetIntParam(Want::PARAM_RESV_WINDOW_MODE, -1); + EXPECT_EQ(ret, AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_SECONDARY); +} + +/** + * @tc.name: UIAbilityLifecycleManager_MoveAbilityToFront_0400 + * @tc.desc: MoveAbilityToFront + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, MoveAbilityToFront_004, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + AbilityRequest abilityRequest; + abilityRequest.processOptions = std::make_shared(); + abilityRequest.abilityInfo.launchMode = AppExecFwk::LaunchMode::SPECIFIED; + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + abilityRecord->sessionInfo_ = sptr::MakeSptr(); + abilityRecord->want_.SetParam(Want::PARAM_RESV_WINDOW_MODE, + AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED); + + AppUtils::isStartOptionsWithAnimation_ = false; + + auto startOptions = std::make_shared(); + startOptions->windowMode_ = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_SECONDARY; + + uiAbilityLifecycleManager->MoveAbilityToFront(abilityRequest, abilityRecord, abilityRecord, nullptr, 0); + + auto ret = abilityRecord->want_.GetIntParam(Want::PARAM_RESV_WINDOW_MODE, -1); + EXPECT_EQ(ret, -1); +} + +/** + * @tc.name: UIAbilityLifecycleManager_CallRequestDone_0100 + * @tc.desc: CallRequestDone + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, CallRequestDone_001, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + AbilityRequest abilityRequest; + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + + auto mockCallStub = sptr::MakeSptr(); + + uiAbilityLifecycleManager->callRequestCache_ = { + {abilityRecord, {abilityRequest}} + }; + + uiAbilityLifecycleManager->CallRequestDone(abilityRecord, mockCallStub); + + EXPECT_EQ(uiAbilityLifecycleManager->callRequestCache_.size(), 0); +} + +/** + * @tc.name: UIAbilityLifecycleManager_CallRequestDone_0200 + * @tc.desc: CallRequestDone + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, CallRequestDone_002, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + AbilityRequest abilityRequest; + auto abilityRecord1 = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + + auto abilityRecord2 = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + + + auto mockCallStub = sptr::MakeSptr(); + + uiAbilityLifecycleManager->callRequestCache_ = { + {abilityRecord1, {abilityRequest}} + }; + + uiAbilityLifecycleManager->CallRequestDone(abilityRecord2, mockCallStub); + + EXPECT_NE(uiAbilityLifecycleManager->callRequestCache_.size(), 0); +} + +/** + * @tc.name: UIAbilityLifecycleManager_MoveMissionToFront_0100 + * @tc.desc: MoveMissionToFront + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, MoveMissionToFront_001, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + int32_t sessionId = 1; + auto startOptions = std::make_shared(); + + startOptions->windowMode_ = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY; + + Rosen::SessionInfo info; + sptr session = sptr::MakeSptr(info); + EXPECT_NE(session, nullptr); + sptr rootSceneSession = session->AsObject(); + uiAbilityLifecycleManager->rootSceneSession_ = rootSceneSession; + + AbilityRequest abilityRequest; + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + abilityRecord->sessionInfo_ = sptr::MakeSptr(); + + uiAbilityLifecycleManager->sessionAbilityMap_ = { + {sessionId, abilityRecord} + }; + + uiAbilityLifecycleManager->MoveMissionToFront(sessionId, startOptions); + + auto ret = abilityRecord->want_.GetIntParam(Want::PARAM_RESV_WINDOW_MODE, -1); + + EXPECT_EQ(ret, AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY); +} + +/** + * @tc.name: UIAbilityLifecycleManager_MoveMissionToFront_0200 + * @tc.desc: MoveMissionToFront + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, MoveMissionToFront_002, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + int32_t sessionId = 1; + + Rosen::SessionInfo info; + sptr session = sptr::MakeSptr(info); + EXPECT_NE(session, nullptr); + sptr rootSceneSession = session->AsObject(); + uiAbilityLifecycleManager->rootSceneSession_ = rootSceneSession; + + AbilityRequest abilityRequest; + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + abilityRecord->sessionInfo_ = sptr::MakeSptr(); + + uiAbilityLifecycleManager->sessionAbilityMap_ = { + {sessionId, abilityRecord} + }; + + uiAbilityLifecycleManager->MoveMissionToFront(sessionId, nullptr); + + auto ret = abilityRecord->want_.GetIntParam(Want::PARAM_RESV_WINDOW_MODE, -1); + + EXPECT_EQ(ret, -1); +} + +/** + * @tc.name: UIAbilityLifecycleManager_MoveMissionToFront_0300 + * @tc.desc: MoveMissionToFront + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, MoveMissionToFront_003, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + int32_t sessionId = 1; + auto startOptions = std::make_shared(); + + startOptions->windowMode_ = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY; + startOptions->displayId_ = 0; + + Rosen::SessionInfo info; + sptr session = sptr::MakeSptr(info); + EXPECT_NE(session, nullptr); + sptr rootSceneSession = session->AsObject(); + uiAbilityLifecycleManager->rootSceneSession_ = rootSceneSession; + + AbilityRequest abilityRequest; + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + abilityRecord->sessionInfo_ = sptr::MakeSptr(); + abilityRecord->sessionInfo_->want.RemoveParam(Want::PARAM_RESV_DISPLAY_ID); + + uiAbilityLifecycleManager->sessionAbilityMap_ = { + {sessionId, abilityRecord} + }; + + uiAbilityLifecycleManager->MoveMissionToFront(sessionId, startOptions); + + auto ret = abilityRecord->sessionInfo_->want.GetIntParam(Want::PARAM_RESV_DISPLAY_ID, -1); + + EXPECT_EQ(ret, DisplayUtil::GetDefaultDisplayId()); +} + +/** + * @tc.name: UIAbilityLifecycleManager_MoveMissionToFront_0400 + * @tc.desc: MoveMissionToFront + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, MoveMissionToFront_004, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + int32_t sessionId = 1; + auto startOptions = std::make_shared(); + + startOptions->windowMode_ = AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY; + startOptions->displayId_ = 1; + + Rosen::SessionInfo info; + sptr session = sptr::MakeSptr(info); + EXPECT_NE(session, nullptr); + sptr rootSceneSession = session->AsObject(); + uiAbilityLifecycleManager->rootSceneSession_ = rootSceneSession; + + AbilityRequest abilityRequest; + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + abilityRecord->sessionInfo_ = sptr::MakeSptr(); + abilityRecord->sessionInfo_->want.RemoveParam(Want::PARAM_RESV_DISPLAY_ID); + + uiAbilityLifecycleManager->sessionAbilityMap_ = { + {sessionId, abilityRecord} + }; + + uiAbilityLifecycleManager->MoveMissionToFront(sessionId, startOptions); + + auto ret = abilityRecord->sessionInfo_->want.GetIntParam(Want::PARAM_RESV_DISPLAY_ID, -1); + + EXPECT_EQ(ret, 1); + EXPECT_NE(ret, DisplayUtil::GetDefaultDisplayId()); +} + +/** + * @tc.name: UIAbilityLifecycleManager_CheckPrepareTerminateTokens_0100 + * @tc.desc: CheckPrepareTerminateTokens + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, CheckPrepareTerminateTokens_001, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + AppUtils::isStartOptionsWithAnimation_ = true; + std::vector> tokens = {}; + uint32_t tokenId = 0; + std::map>> tokensPerModuleName = {}; + + auto ret = uiAbilityLifecycleManager->CheckPrepareTerminateTokens(tokens, tokenId, tokensPerModuleName); + EXPECT_EQ(ret, false); +} + +/** + * @tc.name: UIAbilityLifecycleManager_UpdateSessionInfoBySCB_0100 + * @tc.desc: UpdateSessionInfoBySCB + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, UpdateSessionInfoBySCB_001, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + SessionInfo sessionInfo; + sessionInfo.persistentId = 1; + std::list sessionInfos = { + sessionInfo + }; + std::vector sessionIds = {}; + + auto ret = uiAbilityLifecycleManager->UpdateSessionInfoBySCB(sessionInfos, sessionIds); + EXPECT_EQ(ret, ERR_OK); + EXPECT_NE(sessionIds.size(), 0); + EXPECT_EQ(*sessionIds.rbegin(), 1); +} + +/** + * @tc.name: UIAbilityLifecycleManager_UpdateSessionInfoBySCB_0200 + * @tc.desc: UpdateSessionInfoBySCB + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, UpdateSessionInfoBySCB_002, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + SessionInfo sessionInfo; + sessionInfo.persistentId = 1; + std::list sessionInfos = { + sessionInfo + }; + std::vector sessionIds = {}; + + AbilityRequest abilityRequest; + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + abilityRecord->sessionInfo_ = sptr::MakeSptr(); + uiAbilityLifecycleManager->sessionAbilityMap_ = { + {1, abilityRecord} + }; + + auto ret = uiAbilityLifecycleManager->UpdateSessionInfoBySCB(sessionInfos, sessionIds); + EXPECT_EQ(ret, ERR_OK); + EXPECT_EQ(sessionIds.size(), 0); +} + +/** + * @tc.name: UIAbilityLifecycleManager_RemoveAbilityRequest_0100 + * @tc.desc: RemoveAbilityRequest + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, RemoveAbilityRequest_001, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + int32_t requestId = 0; + auto abilityRequest = std::make_shared(); + + uiAbilityLifecycleManager->startAbilityCheckMap_ = { + {0, abilityRequest} + }; + + uiAbilityLifecycleManager->RemoveAbilityRequest(requestId); + + EXPECT_NE(uiAbilityLifecycleManager->startAbilityCheckMap_.size(), 0); +} + +/** + * @tc.name: UIAbilityLifecycleManager_RemoveAbilityRequest_0200 + * @tc.desc: RemoveAbilityRequest + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, RemoveAbilityRequest_002, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + int32_t requestId = 1; + auto abilityRequest = std::make_shared(); + + uiAbilityLifecycleManager->startAbilityCheckMap_ = { + {1, abilityRequest} + }; + + uiAbilityLifecycleManager->RemoveAbilityRequest(requestId); + + EXPECT_EQ(uiAbilityLifecycleManager->startAbilityCheckMap_.size(), 0); +} + +/** + * @tc.name: UIAbilityLifecycleManager_AddSpecifiedRequest_0200 + * @tc.desc: AddSpecifiedRequest + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, AddSpecifiedRequest_002, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + uiAbilityLifecycleManager->specifiedRequestList_.clear(); + + uiAbilityLifecycleManager->AddSpecifiedRequest(nullptr); + + EXPECT_EQ(uiAbilityLifecycleManager->specifiedRequestList_.size(), 0); +} + +/** + * @tc.name: UIAbilityLifecycleManager_PopAndGetNextSpecified_0100 + * @tc.desc: PopAndGetNextSpecified + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, PopAndGetNextSpecified_001, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + int32_t requestId1 = 1; + int32_t requestId2 = 2; + + AbilityRequest abilityRequest; + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + + auto specifiedRequestPtr = std::make_shared(requestId1, abilityRequest); + specifiedRequestPtr->requestId = 1; + auto specifiedRequest2Ptr = std::make_shared(requestId2, abilityRequest); + specifiedRequest2Ptr->requestId = 2; + + uiAbilityLifecycleManager->specifiedRequestList_ = { + {"NewKawasaki", {specifiedRequestPtr, specifiedRequest2Ptr}} + }; + + auto ret = uiAbilityLifecycleManager->PopAndGetNextSpecified(1); + + EXPECT_EQ(ret, specifiedRequest2Ptr); +} + +/** + * @tc.name: UIAbilityLifecycleManager_IsSpecifiedModuleLoaded_0100 + * @tc.desc: IsSpecifiedModuleLoaded + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, IsSpecifiedModuleLoaded_001, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + AbilityRequest abilityRequest; + + AppMgrUtil::appMgr_ = nullptr; + SysMrgClient::instance_ = nullptr; + + auto ret = uiAbilityLifecycleManager->IsSpecifiedModuleLoaded(abilityRequest); + + EXPECT_EQ(ret, false); +} + +/** + * @tc.name: UIAbilityLifecycleManager_HandleColdAcceptWantDone_0100 + * @tc.desc: HandleColdAcceptWantDone + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, HandleColdAcceptWantDone_001, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + AAFwk::Want want; + + int32_t requestId1 = 1; + AbilityRequest abilityRequest; + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + + auto specifiedRequestPtr = std::make_shared(requestId1, abilityRequest); + + uiAbilityLifecycleManager->sessionAbilityMap_.clear(); + + auto ret = uiAbilityLifecycleManager->HandleColdAcceptWantDone(want, "", *specifiedRequestPtr); + + EXPECT_EQ(ret, false); +} + +/** + * @tc.name: UIAbilityLifecycleManager_HandleColdAcceptWantDone_0200 + * @tc.desc: HandleColdAcceptWantDone + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, HandleColdAcceptWantDone_002, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + AAFwk::Want want; + + int32_t requestId1 = 1; + AbilityRequest abilityRequest; + + auto specifiedRequestPtr = std::make_shared(requestId1, abilityRequest); + specifiedRequestPtr->persistentId = 1; + + uiAbilityLifecycleManager->sessionAbilityMap_ = { + {1, nullptr} + }; + + auto ret = uiAbilityLifecycleManager->HandleColdAcceptWantDone(want, "", *specifiedRequestPtr); + + EXPECT_EQ(ret, false); +} + +/** + * @tc.name: UIAbilityLifecycleManager_HandleColdAcceptWantDone_0300 + * @tc.desc: HandleColdAcceptWantDone + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, HandleColdAcceptWantDone_003, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + AAFwk::Want want; + + int32_t requestId1 = 1; + AbilityRequest abilityRequest; + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + abilityRecord->specifiedFlag_ = "HeavenlyMe"; + + auto specifiedRequestPtr = std::make_shared(requestId1, abilityRequest); + specifiedRequestPtr->persistentId = 1; + + uiAbilityLifecycleManager->sessionAbilityMap_ = { + {1, abilityRecord} + }; + + auto ret = uiAbilityLifecycleManager->HandleColdAcceptWantDone(want, "", *specifiedRequestPtr); + + EXPECT_EQ(ret, false); +} + +/** + * @tc.name: UIAbilityLifecycleManager_HandleColdAcceptWantDone_0400 + * @tc.desc: HandleColdAcceptWantDone + * @tc.type: FUNC + */ +HWTEST_F(UIAbilityLifecycleManagerThirdTest, HandleColdAcceptWantDone_004, TestSize.Level1) +{ + auto uiAbilityLifecycleManager = std::make_shared(); + EXPECT_NE(uiAbilityLifecycleManager, nullptr); + + AAFwk::Want want; + + int32_t requestId1 = 1; + AbilityRequest abilityRequest; + auto abilityRecord = std::make_shared( + abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode); + abilityRecord->specifiedFlag_.clear(); + + auto specifiedRequestPtr = std::make_shared(requestId1, abilityRequest); + specifiedRequestPtr->persistentId = 1; + + uiAbilityLifecycleManager->sessionAbilityMap_ = { + {1, abilityRecord} + }; + + auto ret = uiAbilityLifecycleManager->HandleColdAcceptWantDone(want, "", *specifiedRequestPtr); + + EXPECT_EQ(ret, true); +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file From 9016d5d5763d1013149a645656494787fa960e75 Mon Sep 17 00:00:00 2001 From: linjunjie Date: Sat, 31 May 2025 21:00:32 +0800 Subject: [PATCH 04/23] =?UTF-8?q?=E6=94=AF=E6=8C=81=E6=84=8F=E5=9B=BEentit?= =?UTF-8?q?y=E8=A7=A3=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: linjunjie --- .../extract_insight_intent_profile.h | 14 ++ .../extract_insight_intent_profile.cpp | 136 ++++++++++++++++-- .../extract_insight_intent_profile_test.cpp | 82 ++++++++++- 3 files changed, 217 insertions(+), 15 deletions(-) diff --git a/services/abilitymgr/include/insight_intent/extract_insight_intent_profile.h b/services/abilitymgr/include/insight_intent/extract_insight_intent_profile.h index 7e55c07f61..5c849e2a14 100644 --- a/services/abilitymgr/include/insight_intent/extract_insight_intent_profile.h +++ b/services/abilitymgr/include/insight_intent/extract_insight_intent_profile.h @@ -151,6 +151,18 @@ private: } }; +struct InsightIntentEntityInfo { + std::string decoratorFile; + std::string className; + std::string decoratorType; + std::string entityId; + std::string entityCategory; + std::string parameters; + std::string parentClassName; + + InsightIntentEntityInfo() = default; +}; + // 全量信息 struct ExtractInsightIntentInfo { std::string decoratorFile; @@ -164,6 +176,7 @@ struct ExtractInsightIntentInfo { std::string result; std::string example; std::vector keywords; + std::vector entities {}; ExtractInsightIntentGenericInfo genericInfo; ExtractInsightIntentInfo() = default; @@ -203,6 +216,7 @@ struct ExtractInsightIntentProfileInfo { std::vector executeMode {}; std::string functionName; std::vector functionParams; + std::vector entities {}; }; struct ExtractInsightIntentProfileInfoVec { diff --git a/services/abilitymgr/src/insight_intent/extract_insight_intent_profile.cpp b/services/abilitymgr/src/insight_intent/extract_insight_intent_profile.cpp index 4fcfb556e7..c1174cb706 100644 --- a/services/abilitymgr/src/insight_intent/extract_insight_intent_profile.cpp +++ b/services/abilitymgr/src/insight_intent/extract_insight_intent_profile.cpp @@ -59,6 +59,15 @@ const std::string INSIGHT_INTENT_PARAM_CATEGORY = "paramCategory"; const std::string INSIGHT_INTENT_RESULT = "result"; const std::string INSIGHT_INTENT_EXAMPLE = "example"; +const std::string INSIGHT_INTENT_ENTITES = "entities"; +const std::string INSIGHT_INTENT_ENTITY_DECORETOR_FILE = "decoratorFile"; +const std::string INSIGHT_INTENT_ENTITY_CLASS_NAME = "className"; +const std::string INSIGHT_INTENT_ENTITY_DECORETOR_TYPE = "decoratorType"; +const std::string INSIGHT_INTENT_ENTITY_ID = "entityId"; +const std::string INSIGHT_INTENT_ENTITY_CATEGORY = "entityCategory"; +const std::string INSIGHT_INTENT_ENTITY_PARENT_CLASS_NAME = "parentClassName"; +const std::string INSIGHT_INTENT_ENTITY_PARAMETERS = "parameters"; + enum DecoratorType { DECORATOR_LINK = 0, DECORATOR_PAGE, @@ -113,6 +122,57 @@ void from_json(const nlohmann::json &jsonObject, LinkIntentParamProfileMapping & g_extraParseResult); } +void from_json(const nlohmann::json &jsonObject, InsightIntentEntityInfo &entityInfo) +{ + TAG_LOGD(AAFwkTag::INTENT, "InsightIntentEntityInfo from json"); + const auto &jsonObjectEnd = jsonObject.end(); + AppExecFwk::BMSJsonUtil::GetStrValueIfFindKey(jsonObject, + jsonObjectEnd, + INSIGHT_INTENT_ENTITY_DECORETOR_FILE, + entityInfo.decoratorFile, + false, + g_extraParseResult); + AppExecFwk::BMSJsonUtil::GetStrValueIfFindKey(jsonObject, + jsonObjectEnd, + INSIGHT_INTENT_ENTITY_CLASS_NAME, + entityInfo.className, + true, + g_extraParseResult); + AppExecFwk::BMSJsonUtil::GetStrValueIfFindKey(jsonObject, + jsonObjectEnd, + INSIGHT_INTENT_ENTITY_DECORETOR_TYPE, + entityInfo.decoratorType, + true, + g_extraParseResult); + AppExecFwk::BMSJsonUtil::GetStrValueIfFindKey(jsonObject, + jsonObjectEnd, + INSIGHT_INTENT_ENTITY_ID, + entityInfo.entityId, + true, + g_extraParseResult); + AppExecFwk::BMSJsonUtil::GetStrValueIfFindKey(jsonObject, + jsonObjectEnd, + INSIGHT_INTENT_ENTITY_CATEGORY, + entityInfo.entityCategory, + true, + g_extraParseResult); + AppExecFwk::BMSJsonUtil::GetStrValueIfFindKey(jsonObject, + jsonObjectEnd, + INSIGHT_INTENT_ENTITY_PARENT_CLASS_NAME, + entityInfo.parentClassName, + false, + g_extraParseResult); + + if (jsonObject.find(INSIGHT_INTENT_ENTITY_PARAMETERS) != jsonObjectEnd) { + if (jsonObject.at(INSIGHT_INTENT_ENTITY_PARAMETERS).is_object()) { + entityInfo.parameters = jsonObject[INSIGHT_INTENT_ENTITY_PARAMETERS].dump(); + } else { + TAG_LOGE(AAFwkTag::INTENT, "type error: entity parameters not object"); + g_extraParseResult = ERR_INVALID_VALUE; + } + } +} + void from_json(const nlohmann::json &jsonObject, ExtractInsightIntentProfileInfo &insightIntentInfo) { TAG_LOGD(AAFwkTag::INTENT, "ExtractInsightIntentProfileInfo from json"); @@ -275,6 +335,14 @@ void from_json(const nlohmann::json &jsonObject, ExtractInsightIntentProfileInfo false, g_extraParseResult, ArrayType::STRING); + AppExecFwk::GetValueIfFindKey>(jsonObject, + jsonObjectEnd, + INSIGHT_INTENT_ENTITES, + insightIntentInfo.entities, + JsonType::ARRAY, + false, + g_extraParseResult, + ArrayType::OBJECT); if (jsonObject.find(INSIGHT_INTENT_PARAMETERS) != jsonObjectEnd) { if (jsonObject.at(INSIGHT_INTENT_PARAMETERS).is_object()) { @@ -310,17 +378,40 @@ void from_json(const nlohmann::json &jsonObject, ExtractInsightIntentProfileInfo void to_json(nlohmann::json& jsonObject, const LinkIntentParamProfileMapping &info) { - TAG_LOGI(AAFwkTag::INTENT, "call to link mapping"); + TAG_LOGI(AAFwkTag::INTENT, "LinkIntentParamProfileMapping to json"); jsonObject = nlohmann::json { - {"paramName", info.paramName}, - {"paramMappingName", info.paramMappingName}, - {"paramCategory", info.paramCategory} + {INSIGHT_INTENT_PARAM_NAME, info.paramName}, + {INSIGHT_INTENT_PARAM_MAPPING_NAME, info.paramMappingName}, + {INSIGHT_INTENT_PARAM_CATEGORY, info.paramCategory} }; } +void to_json(nlohmann::json& jsonObject, const InsightIntentEntityInfo &info) +{ + TAG_LOGI(AAFwkTag::INTENT, "InsightIntentEntityInfo to json"); + jsonObject = nlohmann::json { + {INSIGHT_INTENT_ENTITY_DECORETOR_FILE, info.decoratorFile}, + {INSIGHT_INTENT_ENTITY_CLASS_NAME, info.className}, + {INSIGHT_INTENT_ENTITY_DECORETOR_TYPE, info.decoratorType}, + {INSIGHT_INTENT_ENTITY_ID, info.entityId}, + {INSIGHT_INTENT_ENTITY_CATEGORY, info.entityCategory}, + {INSIGHT_INTENT_ENTITY_PARENT_CLASS_NAME, info.parentClassName} + }; + + if (!info.parameters.empty()) { + auto parameters = nlohmann::json::parse(info.parameters, nullptr, false); + if (parameters.is_discarded()) { + TAG_LOGE(AAFwkTag::INTENT, "discarded entity parameters"); + return; + } + + jsonObject[INSIGHT_INTENT_ENTITY_PARAMETERS] = parameters; + } +} + void to_json(nlohmann::json& jsonObject, const ExtractInsightIntentProfileInfo& info) { - TAG_LOGI(AAFwkTag::INTENT, "call to ExtractInsightIntentProfileInfo"); + TAG_LOGI(AAFwkTag::INTENT, "ExtractInsightIntentProfileInfo to json"); jsonObject = nlohmann::json { {INSIGHT_INTENT_DECORETOR_FILE, info.decoratorFile}, @@ -347,7 +438,8 @@ void to_json(nlohmann::json& jsonObject, const ExtractInsightIntentProfileInfo& {INSIGHT_INTENT_ABILITY_NAME, info.abilityName}, {INSIGHT_INTENT_EXECUTE_MODE, info.executeMode}, {INSIGHT_INTENT_FUNCTION_NAME, info.functionName}, - {INSIGHT_INTENT_FUNCTION_PARAMS, info.functionParams} + {INSIGHT_INTENT_FUNCTION_PARAMS, info.functionParams}, + {INSIGHT_INTENT_ENTITES, info.entities} }; if (!info.parameters.empty()) { @@ -434,6 +526,15 @@ bool CheckProfileInfo(const ExtractInsightIntentProfileInfo &insightIntent) return false; } + for (const auto &entity: insightIntent.entities) { + if (entity.className.empty() || entity.entityId.empty()) { + TAG_LOGE(AAFwkTag::INTENT, "entity exist empty param, intentName: %{public}s, " + "className: %{public}s, entityId: %{public}s", + insightIntent.intentName.c_str(), entity.className.c_str(), entity.entityId.c_str()); + return false; + } + } + return CheckProfileSubIntentInfo(insightIntent); } @@ -453,7 +554,6 @@ bool TransformToLinkInfo(const ExtractInsightIntentProfileInfo &insightIntent, I info.paramMapping.push_back(paramMapping); } - // todo: schema模块将insightIntent.parameters解析成info.params info.parameters = insightIntent.parameters; TAG_LOGD(AAFwkTag::INTENT, "link parameters: %{public}s", info.parameters.c_str()); return true; @@ -469,7 +569,6 @@ bool TransformToPageInfo(const ExtractInsightIntentProfileInfo &insightIntent, I TAG_LOGD(AAFwkTag::INTENT, "navigationId: %{public}s", info.navigationId.c_str()); info.navDestinationName = insightIntent.navDestinationName; TAG_LOGD(AAFwkTag::INTENT, "navDestinationName: %{public}s", info.navDestinationName.c_str()); - // todo: schema模块将insightIntent.parameters解析成info.params info.parameters = insightIntent.parameters; TAG_LOGD(AAFwkTag::INTENT, "page parameters: %{public}s", info.parameters.c_str()); return true; @@ -490,8 +589,6 @@ bool TransformToEntryInfo(const ExtractInsightIntentProfileInfo &insightIntent, info.executeMode.emplace_back(mode->second); TAG_LOGI(AAFwkTag::INTENT, "mode: %{public}s", mode->first.c_str()); } - - // todo: schema模块将insightIntent.parameters解析成info.params info.parameters = insightIntent.parameters; TAG_LOGD(AAFwkTag::INTENT, "entry parameters: %{public}s", info.parameters.c_str()); return true; @@ -505,7 +602,6 @@ bool TransformToFunctionInfo(const ExtractInsightIntentProfileInfo &insightInten for (size_t i = 0; i < info.functionParams.size(); i++) { TAG_LOGD(AAFwkTag::INTENT, "functionParams[%{public}zu]: %{public}s", i, info.functionParams[i].c_str()); } - // todo: schema模块将insightIntent.parameters解析成info.params info.parameters = insightIntent.parameters; TAG_LOGD(AAFwkTag::INTENT, "function parameters: %{public}s", info.parameters.c_str()); return true; @@ -524,7 +620,7 @@ bool ExtractInsightIntentProfile::TransformTo(const std::string &profileStr, TAG_LOGD(AAFwkTag::INTENT, "transform profileStr: %{public}s", profileStr.c_str()); auto jsonObject = nlohmann::json::parse(profileStr, nullptr, false); if (jsonObject.is_discarded()) { - TAG_LOGE(AAFwkTag::INTENT, "discarded jsonObject"); + TAG_LOGE(AAFwkTag::INTENT, "discarded jsonObject, profileStr: %{public}s", profileStr.c_str()); return false; } @@ -532,7 +628,8 @@ bool ExtractInsightIntentProfile::TransformTo(const std::string &profileStr, g_extraParseResult = ERR_OK; intentInfos = jsonObject.get(); if (g_extraParseResult != ERR_OK) { - TAG_LOGE(AAFwkTag::INTENT, "parse result: %{public}d", g_extraParseResult); + TAG_LOGE(AAFwkTag::INTENT, "parse result: %{public}d, profileStr: %{public}s", + g_extraParseResult, profileStr.c_str()); g_extraParseResult = ERR_OK; return false; } @@ -557,7 +654,7 @@ bool ExtractInsightIntentProfile::ToJson(const ExtractInsightIntentProfileInfo & } jsonObject[INSIGHT_INTENTS] = nlohmann::json::array({ subJsonObject }); - TAG_LOGD(AAFwkTag::INTENT, "json string: %{public}s", jsonObject.dump().c_str()); + TAG_LOGD(AAFwkTag::INTENT, "to json string: %{public}s", jsonObject.dump().c_str()); return true; } @@ -580,6 +677,17 @@ bool ExtractInsightIntentProfile::ProfileInfoFormat(const ExtractInsightIntentPr info.example = insightIntent.example; info.result = insightIntent.result; info.keywords.assign(insightIntent.keywords.begin(), insightIntent.keywords.end()); + info.entities = insightIntent.entities; + TAG_LOGD(AAFwkTag::INTENT, "entities size: %{public}zu", info.entities.size()); + for (std::vector::const_iterator iter = info.entities.begin(); + iter != info.entities.end(); iter++) { + TAG_LOGD(AAFwkTag::INTENT, "entity decoratorFile: %{public}s, className: %{public}s, " + "decoratorType: %{public}s, entityId: %{public}s, entityCategory: %{public}s, " + "parentClassName: %{public}s, parameters: %{public}s", + (*iter).decoratorFile.c_str(), (*iter).className.c_str(), (*iter).decoratorType.c_str(), + (*iter).entityId.c_str(), (*iter).entityCategory.c_str(), (*iter).parentClassName.c_str(), + (*iter).parameters.c_str()); + } info.genericInfo.bundleName = insightIntent.bundleName; TAG_LOGD(AAFwkTag::INTENT, "bundleName: %{public}s", info.genericInfo.bundleName.c_str()); diff --git a/test/unittest/extract_insight_intent_profile_test/extract_insight_intent_profile_test.cpp b/test/unittest/extract_insight_intent_profile_test/extract_insight_intent_profile_test.cpp index 93e0631916..a07d598a89 100644 --- a/test/unittest/extract_insight_intent_profile_test/extract_insight_intent_profile_test.cpp +++ b/test/unittest/extract_insight_intent_profile_test/extract_insight_intent_profile_test.cpp @@ -213,7 +213,50 @@ namespace { "}" "}" "}" - "}" + "}," + "\"entities\": [" + "{" + "\"decoratorFile\": \"@normalized:N&&&entry/src/main/ets/pages/Index&\"," + "\"className\": \"SongPlayState\"," + "\"decoratorType\": \"@IntentEntityDecorator\"," + "\"entityId\": \"11\"," + "\"entityCategory\": \"entity Category\"," + "\"parentClassName\": \"base\"," + "\"parameters\": {" + "\"type\": \"object\"," + "\"items\": {" + "\"type\": \"array\"," + "\"items\": {" + "\"propertyNames\": {" + "\"enum\": [\"entityId\",\"entityGroupId\",\"gameType\"]" + "}," + "\"type\": \"object\"," + "\"required\": [\"entityId\"]" + "}" + "}" + "}" + "}," + "{" + "\"decoratorFile\": \"@normalized:N&&&entry/src/main/ets/pages/Index&\"," + "\"className\": \"base\"," + "\"decoratorType\": \"@IntentEntityDecorator\"," + "\"entityId\": \"12\"," + "\"entityCategory\": \"entity1 Category\"," + "\"parameters\": {" + "\"type\": \"object\"," + "\"items\": {" + "\"type\": \"array\"," + "\"items\": {" + "\"propertyNames\": {" + "\"enum\": [\"entityId\",\"entityGroupId\",\"gameType\"]" + "}," + "\"type\": \"object\"," + "\"required\": [\"entityId\"]" + "}" + "}" + "}" + "}" + "]" "}," "{" "\"displayDescription\": \"music\"," @@ -348,6 +391,19 @@ HWTEST_F(ExtractInsightIntentProfileTest, TransformTo_0200, TestSize.Level0) EXPECT_EQ(profileInfos.insightIntents[1].example, "exampleBBB"); EXPECT_NE(profileInfos.insightIntents[1].result, ""); + EXPECT_EQ(profileInfos.insightIntents[0].entities.size(), 2); + EXPECT_EQ(profileInfos.insightIntents[0].entities[0].className, "SongPlayState"); + EXPECT_EQ(profileInfos.insightIntents[0].entities[0].decoratorType, "@IntentEntityDecorator"); + EXPECT_EQ(profileInfos.insightIntents[0].entities[0].entityId, "11"); + EXPECT_EQ(profileInfos.insightIntents[0].entities[0].parentClassName, "base"); + EXPECT_NE(profileInfos.insightIntents[0].entities[0].parameters, ""); + EXPECT_EQ(profileInfos.insightIntents[0].entities[1].className, "base"); + EXPECT_EQ(profileInfos.insightIntents[0].entities[1].decoratorType, "@IntentEntityDecorator"); + EXPECT_EQ(profileInfos.insightIntents[0].entities[1].entityId, "12"); + EXPECT_EQ(profileInfos.insightIntents[0].entities[1].parentClassName, ""); + EXPECT_NE(profileInfos.insightIntents[0].entities[1].parameters, ""); + EXPECT_EQ(profileInfos.insightIntents[1].entities.size(), 0); + nlohmann::json jsonObject1; result = ExtractInsightIntentProfile::ToJson(profileInfos.insightIntents[0], jsonObject1); EXPECT_EQ(result, true); @@ -359,6 +415,17 @@ HWTEST_F(ExtractInsightIntentProfileTest, TransformTo_0200, TestSize.Level0) EXPECT_EQ(profileInfos1.insightIntents[0].decoratorType, "@InsightIntentLink"); EXPECT_EQ(profileInfos1.insightIntents[0].intentName, "123"); EXPECT_EQ(profileInfos1.insightIntents[0].example, "exampleAAA"); + EXPECT_EQ(profileInfos1.insightIntents[0].entities.size(), 2); + EXPECT_EQ(profileInfos1.insightIntents[0].entities[0].className, "SongPlayState"); + EXPECT_EQ(profileInfos1.insightIntents[0].entities[0].decoratorType, "@IntentEntityDecorator"); + EXPECT_EQ(profileInfos1.insightIntents[0].entities[0].entityId, "11"); + EXPECT_EQ(profileInfos1.insightIntents[0].entities[0].parentClassName, "base"); + EXPECT_NE(profileInfos1.insightIntents[0].entities[0].parameters, ""); + EXPECT_EQ(profileInfos1.insightIntents[0].entities[1].className, "base"); + EXPECT_EQ(profileInfos1.insightIntents[0].entities[1].decoratorType, "@IntentEntityDecorator"); + EXPECT_EQ(profileInfos1.insightIntents[0].entities[1].entityId, "12"); + EXPECT_EQ(profileInfos1.insightIntents[0].entities[1].parentClassName, ""); + EXPECT_NE(profileInfos1.insightIntents[0].entities[1].parameters, ""); nlohmann::json jsonObject2; result = ExtractInsightIntentProfile::ToJson(profileInfos.insightIntents[1], jsonObject2); @@ -371,12 +438,24 @@ HWTEST_F(ExtractInsightIntentProfileTest, TransformTo_0200, TestSize.Level0) EXPECT_EQ(profileInfos2.insightIntents[0].decoratorType, "@InsightIntentLink"); EXPECT_EQ(profileInfos2.insightIntents[0].intentName, "InsightIntent2"); EXPECT_EQ(profileInfos2.insightIntents[0].example, "exampleBBB"); + EXPECT_EQ(profileInfos2.insightIntents[0].entities.size(), 0); ExtractInsightIntentInfo info1; result = ExtractInsightIntentProfile::ProfileInfoFormat(profileInfos1.insightIntents[0], info1); EXPECT_EQ(result, true); EXPECT_EQ(info1.domain, "game"); EXPECT_NE(info1.result, ""); + EXPECT_EQ(info1.entities.size(), 2); + EXPECT_EQ(info1.entities[0].className, "SongPlayState"); + EXPECT_EQ(info1.entities[0].decoratorType, "@IntentEntityDecorator"); + EXPECT_EQ(info1.entities[0].entityId, "11"); + EXPECT_EQ(info1.entities[0].parentClassName, "base"); + EXPECT_NE(info1.entities[0].parameters, ""); + EXPECT_EQ(info1.entities[1].className, "base"); + EXPECT_EQ(info1.entities[1].decoratorType, "@IntentEntityDecorator"); + EXPECT_EQ(info1.entities[1].entityId, "12"); + EXPECT_EQ(info1.entities[1].parentClassName, ""); + EXPECT_NE(info1.entities[1].parameters, ""); EXPECT_EQ(info1.genericInfo.decoratorType, "@InsightIntentLink"); InsightIntentLinkInfo linkInfo1 = info1.genericInfo.get(); EXPECT_EQ(linkInfo1.uri, "/data/app/base"); @@ -387,6 +466,7 @@ HWTEST_F(ExtractInsightIntentProfileTest, TransformTo_0200, TestSize.Level0) EXPECT_EQ(result, true); EXPECT_EQ(info2.domain, "control"); EXPECT_NE(info2.result, ""); + EXPECT_EQ(info2.entities.size(), 0); EXPECT_EQ(info2.genericInfo.decoratorType, "@InsightIntentLink"); InsightIntentLinkInfo linkInfo2 = info2.genericInfo.get(); EXPECT_EQ(linkInfo2.uri, "/data/app/base"); From f98c8a55630491947283c47201968a1f69a474e5 Mon Sep 17 00:00:00 2001 From: zhangzezhong Date: Thu, 5 Jun 2025 14:42:17 +0800 Subject: [PATCH 05/23] add AbilityStageContext unittest cases for ability_runtime Signed-off-by: zhangzezhong --- test/unittest/BUILD.gn | 1 + .../ability_stage_context_test.cpp | 58 ++- .../context_impl_second_test.cpp | 205 +++++++- .../native_child_process_test/BUILD.gn | 124 +++++ .../mock/include/ipc_cparcel.h | 31 ++ .../mock/include/ipc_inner_object.h | 26 + .../mock/include/mock_child_process_manager.h | 94 ++++ .../mock/src/mock_child_process_manager.cpp | 183 +++++++ .../native_child_process_test.cpp | 310 ++++++++++++ .../extension_record_manager_second_test.cpp | 449 +++++++++++++++++- 10 files changed, 1478 insertions(+), 3 deletions(-) create mode 100644 test/unittest/native_child_process_test/BUILD.gn create mode 100644 test/unittest/native_child_process_test/mock/include/ipc_cparcel.h create mode 100644 test/unittest/native_child_process_test/mock/include/ipc_inner_object.h create mode 100644 test/unittest/native_child_process_test/mock/include/mock_child_process_manager.h create mode 100644 test/unittest/native_child_process_test/mock/src/mock_child_process_manager.cpp create mode 100644 test/unittest/native_child_process_test/native_child_process_test.cpp diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index ca601f1d3e..e5ba5d8c93 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -390,6 +390,7 @@ group("unittest") { "multi_user_config_mgr_test:unittest", "napi_base_context_test:unittest", "napi_common_want_agent_test:unittest", + "native_child_process_test:unittest", "native_runtime_test:unittest", "os_account_manager_wrapper_test:unittest", "page_state_data_test:unittest", diff --git a/test/unittest/ability_stage_context_test/ability_stage_context_test.cpp b/test/unittest/ability_stage_context_test/ability_stage_context_test.cpp index 075a25ec49..0153ce0029 100644 --- a/test/unittest/ability_stage_context_test/ability_stage_context_test.cpp +++ b/test/unittest/ability_stage_context_test/ability_stage_context_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 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 @@ -292,5 +292,61 @@ HWTEST_F(AbilityStageContextTest, AbilityStageContextTest_CreatePluginContext_01 TAG_LOGI(AAFwkTag::TEST, "end"); } #endif + +/** + * @tc.name: AbilityStageContextTest_SetIsPlugin_0100 + * @tc.desc: Ability stage SetIsPlugin test. + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AbilityStageContextTest, AbilityStageContextTest_SetIsPlugin_0100, TestSize.Level1) +{ + auto abilityStageContext = std::make_shared(); + ASSERT_NE(abilityStageContext, nullptr); + + abilityStageContext->contextImpl_ = std::make_shared(); + abilityStageContext->contextImpl_->isPlugin_ = true; + + abilityStageContext->SetIsPlugin(false); + + EXPECT_EQ(abilityStageContext->contextImpl_->isPlugin_, false); +} + +/** + * @tc.name: AbilityStageContextTest_CreateBundleContext_0100 + * @tc.desc: Ability stage CreateBundleContext test. + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AbilityStageContextTest, AbilityStageContextTest_CreateBundleContext_0100, TestSize.Level1) +{ + auto abilityStageContext = std::make_shared(); + ASSERT_NE(abilityStageContext, nullptr); + + abilityStageContext->contextImpl_ = nullptr; + + auto ret = abilityStageContext->CreateBundleContext("HeavenlyMe"); + + EXPECT_EQ(ret, nullptr); +} + +/** + * @tc.name: AbilityStageContextTest_GetSystemPreferencesDir_0100 + * @tc.desc: Ability stage GetSystemPreferencesDir test. + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AbilityStageContextTest, AbilityStageContextTest_GetSystemPreferencesDir_0100, TestSize.Level1) +{ + auto abilityStageContext = std::make_shared(); + ASSERT_NE(abilityStageContext, nullptr); + + std::string preferencesDir = ""; + abilityStageContext->contextImpl_ = nullptr; + + auto ret = abilityStageContext->GetSystemPreferencesDir("HeavenlyMe", false, preferencesDir); + + EXPECT_EQ(ret, ERR_INVALID_VALUE); +} } // namespace AbilityRuntime } // namespace OHOS diff --git a/test/unittest/frameworks_kits_appkit_native_test/context_impl_second_test.cpp b/test/unittest/frameworks_kits_appkit_native_test/context_impl_second_test.cpp index bde981f2ce..106301e1f8 100644 --- a/test/unittest/frameworks_kits_appkit_native_test/context_impl_second_test.cpp +++ b/test/unittest/frameworks_kits_appkit_native_test/context_impl_second_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 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 @@ -233,5 +233,208 @@ HWTEST_F(ContextImplSecondTest, AppExecFwk_AppContext_CreateHspResourceManager_0 GTEST_LOG_(INFO) << "AppExecFwk_AppContext_CreateHspResourceManager_003 end"; } + +/** + * @tc.number: AppExecFwk_AppContext_IsModuleExist_001 + * @tc.name: IsModuleExist + * @tc.desc: Test IsModuleExist. + * @tc.type: FUNC + * @tc.require: issueI5HQEM + */ +HWTEST_F(ContextImplSecondTest, AppExecFwk_AppContext_IsModuleExist_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AppContext_IsModuleExist_001 start"; + + auto contextImpl = std::make_shared(); + + contextImpl->applicationInfo_ = std::make_shared(); + contextImpl->applicationInfo_->moduleInfos.clear(); + + auto ret = contextImpl->IsModuleExist(""); + EXPECT_EQ(ret, false); + + GTEST_LOG_(INFO) << "AppExecFwk_AppContext_IsModuleExist_001 end"; +} + +/** + * @tc.number: AppExecFwk_AppContext_IsModuleExist_002 + * @tc.name: IsModuleExist + * @tc.desc: Test IsModuleExist. + * @tc.type: FUNC + * @tc.require: issueI5HQEM + */ +HWTEST_F(ContextImplSecondTest, AppExecFwk_AppContext_IsModuleExist_002, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AppContext_IsModuleExist_002 start"; + + auto contextImpl = std::make_shared(); + + contextImpl->applicationInfo_ = std::make_shared(); + std::string moduleName = "HeavenlyMeModule"; + std::string moduleSourceDir = "HeavenlyMeModuleSource"; + std::vector preloads = {"Dummy1", "Dummy2"}; + ModuleInfo moduleInfo; + moduleInfo.moduleName = moduleName; + moduleInfo.moduleSourceDir = moduleSourceDir; + moduleInfo.preloads = preloads; + contextImpl->applicationInfo_->moduleInfos = { + moduleInfo + }; + + auto ret = contextImpl->IsModuleExist(moduleName); + EXPECT_EQ(ret, true); + + GTEST_LOG_(INFO) << "AppExecFwk_AppContext_IsModuleExist_002 end"; +} + +/** + * @tc.number: AppExecFwk_AppContext_IsModuleExist_003 + * @tc.name: IsModuleExist + * @tc.desc: Test IsModuleExist. + * @tc.type: FUNC + * @tc.require: issueI5HQEM + */ +HWTEST_F(ContextImplSecondTest, AppExecFwk_AppContext_IsModuleExist_003, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AppContext_IsModuleExist_003 start"; + + auto contextImpl = std::make_shared(); + + contextImpl->applicationInfo_ = std::make_shared(); + std::string moduleName = "HeavenlyMeModule"; + std::string moduleSourceDir = "HeavenlyMeModuleSource"; + std::vector preloads = {"Dummy1", "Dummy2"}; + ModuleInfo moduleInfo; + moduleInfo.moduleName = moduleName; + moduleInfo.moduleSourceDir = moduleSourceDir; + moduleInfo.preloads = preloads; + contextImpl->applicationInfo_->moduleInfos = { + moduleInfo + }; + + auto ret = contextImpl->IsModuleExist("DummyModuleName"); + EXPECT_EQ(ret, false); + + GTEST_LOG_(INFO) << "AppExecFwk_AppContext_IsModuleExist_003 end"; +} + +/** + * @tc.number: AppExecFwk_AppContext_GetPluginInfo_001 + * @tc.name: GetPluginInfo + * @tc.desc: Test GetPluginInfo. + * @tc.type: FUNC + * @tc.require: issueI5HQEM + */ +HWTEST_F(ContextImplSecondTest, AppExecFwk_AppContext_GetPluginInfo_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AppContext_GetPluginInfo_001 start"; + + auto contextImpl = std::make_shared(); + + std::string hostBundleName = ""; + std::string pluginBundleName = "HeavenlyMePluginBundle"; + std::string pluginModuleName = "HeavenlyMePluginModule"; + AppExecFwk::PluginBundleInfo pluginBundleInfo; + + auto ret = contextImpl->GetPluginInfo(hostBundleName, + pluginBundleName, pluginModuleName, pluginBundleInfo); + EXPECT_EQ(ret, false); + + GTEST_LOG_(INFO) << "AppExecFwk_AppContext_GetPluginInfo_001 end"; +} + +/** + * @tc.number: AppExecFwk_AppContext_CreatePluginContext_001 + * @tc.name: CreatePluginContext + * @tc.desc: Test CreatePluginContext. + * @tc.type: FUNC + * @tc.require: issueI5HQEM + */ +HWTEST_F(ContextImplSecondTest, AppExecFwk_AppContext_CreatePluginContext_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AppContext_CreatePluginContext_001 start"; + + auto contextImpl = std::make_shared(); + + std::string pluginBundleName = ""; + std::string moduleName = ""; + std::shared_ptr inputContext = nullptr; + + auto ret = contextImpl->CreatePluginContext(pluginBundleName, + moduleName, inputContext); + EXPECT_EQ(ret, nullptr); + + GTEST_LOG_(INFO) << "AppExecFwk_AppContext_CreatePluginContext_001 end"; +} + +/** + * @tc.number: AppExecFwk_AppContext_CreateSystemHspModuleResourceManager_001 + * @tc.name: CreateSystemHspModuleResourceManager + * @tc.desc: Test CreateSystemHspModuleResourceManager. + * @tc.type: FUNC + * @tc.require: issueI5HQEM + */ +HWTEST_F(ContextImplSecondTest, CreateSystemHspModuleResourceManager_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AppContext_CreateSystemHspModuleResourceManager_001 start"; + + auto contextImpl = std::make_shared(); + + std::string bundleName = ""; + std::string moduleName = ""; + std::shared_ptr resourceManager = nullptr; + + auto ret = contextImpl->CreateSystemHspModuleResourceManager(bundleName, + moduleName, resourceManager); + EXPECT_EQ(ret, ERR_INVALID_VALUE); + + GTEST_LOG_(INFO) << "AppExecFwk_AppContext_CreateSystemHspModuleResourceManager_001 end"; +} + +/** + * @tc.number: AppExecFwk_AppContext_GetHapModuleInfoWithContext_001 + * @tc.name: GetHapModuleInfoWithContext + * @tc.desc: Test GetHapModuleInfoWithContext. + * @tc.type: FUNC + * @tc.require: issueI5HQEM + */ +HWTEST_F(ContextImplSecondTest, GetHapModuleInfoWithContext_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AppContext_GetHapModuleInfoWithContext_001 start"; + + auto contextImpl = std::make_shared(); + + contextImpl->hapModuleInfo_ = std::make_shared(); + auto inputContext = std::make_shared(); + inputContext->hapModuleInfo_ = nullptr; + + auto ret = contextImpl->GetHapModuleInfoWithContext(inputContext); + EXPECT_EQ(ret, nullptr); + + GTEST_LOG_(INFO) << "AppExecFwk_AppContext_GetHapModuleInfoWithContext_001 end"; +} + +/** + * @tc.number: AppExecFwk_AppContext_GetHapModuleInfoWithContext_002 + * @tc.name: GetHapModuleInfoWithContext + * @tc.desc: Test GetHapModuleInfoWithContext. + * @tc.type: FUNC + * @tc.require: issueI5HQEM + */ +HWTEST_F(ContextImplSecondTest, GetHapModuleInfoWithContext_002, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "AppExecFwk_AppContext_GetHapModuleInfoWithContext_002 start"; + + auto contextImpl = std::make_shared(); + + contextImpl->hapModuleInfo_ = std::make_shared(); + auto inputContext = std::make_shared(); + inputContext->hapModuleInfo_ = nullptr; + + auto ret = contextImpl->GetHapModuleInfoWithContext(nullptr); + EXPECT_EQ(ret, contextImpl->hapModuleInfo_); + + GTEST_LOG_(INFO) << "AppExecFwk_AppContext_GetHapModuleInfoWithContext_002 end"; +} } // namespace AppExecFwk } diff --git a/test/unittest/native_child_process_test/BUILD.gn b/test/unittest/native_child_process_test/BUILD.gn new file mode 100644 index 0000000000..b8b179629b --- /dev/null +++ b/test/unittest/native_child_process_test/BUILD.gn @@ -0,0 +1,124 @@ +# Copyright (c) 2025 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/ability_runtime/abilitymgr" + +ohos_unittest("native_child_process_test") { + module_out_path = module_output_path + + include_dirs = [ + "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", + "${ability_runtime_path}/interfaces/inner_api/ability_manager/include/status_bar_delegate", + "${ability_runtime_path}/interfaces/kits/c/ability/ability_runtime/child_process", + "${ability_runtime_path}/interfaces/inner_api/child_process_manager/include", + "${ability_runtime_path}/test/unittest/native_child_process_test/mock/include", + "${ability_runtime_path}/frameworks/native/child_process/include", + "${ability_runtime_services_path}/appdfr/include", + "${ability_runtime_services_path}/abilitymgr/include/", + "${ability_runtime_services_path}/abilitymgr/include/scene_board/", + ] + + public_configs = + [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + + sources = [ + "${ability_runtime_path}/frameworks/native/ability/native/child_process_manager/child_process_manager_error_utils.cpp", + "${ability_runtime_path}/frameworks/native/child_process/src/child_callback_manager.cpp", + "${ability_runtime_path}/frameworks/native/child_process/src/native_child_callback.cpp", + "${ability_runtime_path}/frameworks/native/child_process/src/native_child_process.cpp", + "${ability_runtime_path}/test/unittest/native_child_process_test/mock/src/mock_child_process_manager.cpp", + "${ability_runtime_services_path}/abilitymgr/src/ability_auto_startup_data_manager.cpp", + "${ability_runtime_services_path}/abilitymgr/src/ability_auto_startup_service.cpp", + "${ability_runtime_services_path}/abilitymgr/src/ability_event_handler.cpp", + "${ability_runtime_services_path}/abilitymgr/src/ability_manager_event_subscriber.cpp", + "${ability_runtime_services_path}/abilitymgr/src/app_exit_reason_data_manager.cpp", + "${ability_runtime_services_path}/abilitymgr/src/exit_info_data_manager.cpp", + "${ability_runtime_services_path}/abilitymgr/src/extension_config.cpp", + "${ability_runtime_services_path}/abilitymgr/src/hidden_start_observer_manager.cpp", + "${ability_runtime_services_path}/abilitymgr/src/scene_board/status_bar_delegate_manager.cpp", + "${ability_runtime_services_path}/abilitymgr/src/scene_board/ui_ability_lifecycle_manager.cpp", + "${ability_runtime_services_path}/abilitymgr/src/utils/timeout_state_utils.cpp", + "${ability_runtime_services_path}/common/src/event_report.cpp", + "native_child_process_test.cpp", + ] + + deps = [ + "${ability_runtime_innerkits_path}/ability_manager:ability_manager", + "${ability_runtime_innerkits_path}/ability_manager:ability_start_setting", + "${ability_runtime_innerkits_path}/ability_manager:process_options", + "${ability_runtime_innerkits_path}/app_manager:app_manager", + "${ability_runtime_innerkits_path}/deps_wrapper:ability_deps_wrapper", + "${ability_runtime_native_path}/ability/native:abilitykit_native", + "${ability_runtime_native_path}/ability/native:auto_startup_callback", + "${ability_runtime_native_path}/appkit:appkit_manager_helper", + "${ability_runtime_path}/utils/global/freeze:freeze_util", + "${ability_runtime_path}/utils/server/startup:startup_util", + "${ability_runtime_services_path}/abilitymgr:abilityms", + "${ability_runtime_services_path}/common:app_util", + "${ability_runtime_services_path}/common:perm_verification", + "${ability_runtime_services_path}/common:task_handler_wrap", + ] + + external_deps = [ + "ability_base:session_info", + "ability_base:want", + "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "config_policy:configpolicy_util", + "dsoftbus:softbus_client", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "googletest:gmock_main", + "googletest:gtest_main", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "init:libbeget_proxy", + "init:libbegetutil", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "window_manager:session_manager_lite", + ] + + if (background_task_mgr_continuous_task_enable) { + external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] + } + + if (ability_runtime_graphics) { + external_deps += [ + "window_manager:libdm", + "window_manager:libwsutils", + "window_manager:scene_session", + ] + } + cflags_cc = [] + if (os_dlp_part_enabled) { + cflags_cc += [ "-DWITH_DLP" ] + } +} + +group("unittest") { + testonly = true + + deps = [ ":native_child_process_test" ] +} diff --git a/test/unittest/native_child_process_test/mock/include/ipc_cparcel.h b/test/unittest/native_child_process_test/mock/include/ipc_cparcel.h new file mode 100644 index 0000000000..2ce4812f42 --- /dev/null +++ b/test/unittest/native_child_process_test/mock/include/ipc_cparcel.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2025 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 OHOS_ABILITY_RUNTIME_IPC_CPARCEL_H +#define OHOS_ABILITY_RUNTIME_IPC_CPARCEL_H + +#ifdef __cplusplus +#include +#else +#include +#endif //__cplusplus + +class OHIPCRemoteProxy { +public: + OHIPCRemoteProxy() = default; + ~OHIPCRemoteProxy() = default; +}; + +#endif // OHOS_ABILITY_RUNTIME_IPC_CPARCEL_H \ No newline at end of file diff --git a/test/unittest/native_child_process_test/mock/include/ipc_inner_object.h b/test/unittest/native_child_process_test/mock/include/ipc_inner_object.h new file mode 100644 index 0000000000..c2ddc154ff --- /dev/null +++ b/test/unittest/native_child_process_test/mock/include/ipc_inner_object.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2025 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 OHOS_ABILITY_RUNTIME_IPC_INNER_OBJECT_H +#define OHOS_ABILITY_RUNTIME_IPC_INNER_OBJECT_H + +#include "ipc_cparcel.h" + +OHIPCRemoteProxy* CreateIPCRemoteProxy(OHOS::sptr &ipcRemote) +{ + return std::make_shared().get(); +} + +#endif // OHOS_ABILITY_RUNTIME_IPC_INNER_OBJECT_H \ No newline at end of file diff --git a/test/unittest/native_child_process_test/mock/include/mock_child_process_manager.h b/test/unittest/native_child_process_test/mock/include/mock_child_process_manager.h new file mode 100644 index 0000000000..da3d5af224 --- /dev/null +++ b/test/unittest/native_child_process_test/mock/include/mock_child_process_manager.h @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2025 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 OHOS_ABILITY_RUNTIME_CHILD_PROCESS_MANAGER_H +#define OHOS_ABILITY_RUNTIME_CHILD_PROCESS_MANAGER_H + +#include +#include +#include + +#include "app_mgr_interface.h" +#include "bundle_info.h" +#include "child_process_args.h" +#include "child_process_info.h" +#include "child_process_manager_error_utils.h" +#include "child_process_options.h" +#include "hap_module_info.h" +#include "runtime.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AbilityRuntime { +class ChildProcessManager { +public: + static ChildProcessManager &GetInstance(); + ~ChildProcessManager(); + + static void HandleSigChild(int32_t signo); + bool IsChildProcess(); + bool IsChildProcessBySelfFork(); + ChildProcessManagerErrorCode StartChildProcessBySelfFork(const std::string &srcEntry, pid_t &pid); + ChildProcessManagerErrorCode StartChildProcessByAppSpawnFork(const std::string &srcEntry, pid_t &pid); + ChildProcessManagerErrorCode StartChildProcessWithArgs(const std::string &srcEntry, pid_t &pid, + int32_t childProcessType, const AppExecFwk::ChildProcessArgs &args, + const AppExecFwk::ChildProcessOptions &options); + ChildProcessManagerErrorCode StartNativeChildProcessByAppSpawnFork( + const std::string &libName, const sptr &callbackStub, const std::string &customProcessName = ""); + bool GetBundleInfo(AppExecFwk::BundleInfo &bundleInfo); + bool GetEntryHapModuleInfo(const AppExecFwk::BundleInfo &bundleInfo, AppExecFwk::HapModuleInfo &hapModuleInfo); + bool GetHapModuleInfo(const AppExecFwk::BundleInfo &bundleInfo, const std::string &moduleName, + AppExecFwk::HapModuleInfo &hapModuleInfo); + std::unique_ptr CreateRuntime(const AppExecFwk::BundleInfo &bundleInfo, + const AppExecFwk::HapModuleInfo &hapModuleInfo, const bool fromAppSpawn, const bool jitEnabled); + bool LoadJsFile(const std::string &srcEntry, const AppExecFwk::HapModuleInfo &hapModuleInfo, + std::unique_ptr &runtime, + std::shared_ptr args = nullptr); + bool LoadNativeLib(const std::string &moduleName, const std::string &libPath, + const sptr &mainProcessCb); + bool LoadNativeLibWithArgs(const std::string &moduleName, const std::string &srcEntry, + const std::string &entryFunc, std::shared_ptr args); + void SetForkProcessJITEnabled(bool jitEnabled); + void SetForkProcessDebugOption(const std::string bundleName, const bool isStartWithDebug, const bool isDebugApp, + const bool isStartWithNative); + void SetAppSpawnForkDebugOption(Runtime::DebugOption &debugOption, + std::shared_ptr processInfo); + std::string GetModuleNameFromSrcEntry(const std::string &srcEntry); + + ChildProcessManagerErrorCode startErrorCode_ = ChildProcessManagerErrorCode::ERR_OK; + +private: + ChildProcessManager(); + + bool AllowChildProcessOnDevice(); + ChildProcessManagerErrorCode PreCheckSelfFork(); + ChildProcessManagerErrorCode PreCheck(int32_t childProcessType); + void RegisterSignal(); + void HandleChildProcessBySelfFork(const std::string &srcEntry, const AppExecFwk::BundleInfo &bundleInfo); + bool HasChildProcessRecord(); + sptr GetAppMgr(); + void MakeProcessName(const std::string &srcEntry); + bool IsMultiProcessFeatureApp(const AppExecFwk::BundleInfo &bundleInfo); + + static bool signalRegistered_; + bool isChildProcessBySelfFork_ = false; + int32_t childProcessCount_ = 0; + std::mutex childProcessCountLock_; + + DISALLOW_COPY_AND_MOVE(ChildProcessManager); +}; +} // namespace AAFwk +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_CHILD_PROCESS_MANAGER_H diff --git a/test/unittest/native_child_process_test/mock/src/mock_child_process_manager.cpp b/test/unittest/native_child_process_test/mock/src/mock_child_process_manager.cpp new file mode 100644 index 0000000000..f0fe66d751 --- /dev/null +++ b/test/unittest/native_child_process_test/mock/src/mock_child_process_manager.cpp @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2025 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 "mock_child_process_manager.h" + +namespace OHOS { +namespace AbilityRuntime { +namespace { + bool g_jitEnabled = false; + AbilityRuntime::Runtime::DebugOption g_debugOption; + const std::string MULTI_PROCESS = "multi_process"; +} +bool ChildProcessManager::signalRegistered_ = false; + +ChildProcessManager &ChildProcessManager::GetInstance() +{ + static ChildProcessManager instance; + return instance; +} + +ChildProcessManager::ChildProcessManager() +{ +} + +ChildProcessManager::~ChildProcessManager() +{ +} + +ChildProcessManagerErrorCode ChildProcessManager::StartChildProcessBySelfFork(const std::string &srcEntry, pid_t &pid) +{ + return ChildProcessManagerErrorCode::ERR_OK; +} + +bool ChildProcessManager::IsMultiProcessFeatureApp(const AppExecFwk::BundleInfo &bundleInfo) +{ + return false; +} + +ChildProcessManagerErrorCode ChildProcessManager::StartChildProcessByAppSpawnFork( + const std::string &srcEntry, pid_t &pid) +{ + return ChildProcessManagerErrorCode::ERR_ALREADY_IN_CHILD_PROCESS; +} + +ChildProcessManagerErrorCode ChildProcessManager::StartChildProcessWithArgs( + const std::string &srcEntry, pid_t &pid, int32_t childProcessType, const AppExecFwk::ChildProcessArgs &args, + const AppExecFwk::ChildProcessOptions &options) +{ + return startErrorCode_; +} + +ChildProcessManagerErrorCode ChildProcessManager::StartNativeChildProcessByAppSpawnFork( + const std::string &libName, const sptr &callbackStub, const std::string &customProcessName) +{ + return ChildProcessManagerErrorCode::ERR_OK; +} + +void ChildProcessManager::RegisterSignal() +{ +} + +void ChildProcessManager::HandleSigChild(int32_t signo) +{ +} + +bool ChildProcessManager::AllowChildProcessOnDevice() +{ + return false; +} + +ChildProcessManagerErrorCode ChildProcessManager::PreCheckSelfFork() +{ + return ChildProcessManagerErrorCode::ERR_OK; +} + +ChildProcessManagerErrorCode ChildProcessManager::PreCheck(int32_t childProcessType) +{ + return ChildProcessManagerErrorCode::ERR_OK; +} + +bool ChildProcessManager::IsChildProcess() +{ + return false; +} + +bool ChildProcessManager::IsChildProcessBySelfFork() +{ + return isChildProcessBySelfFork_; +} + +void ChildProcessManager::HandleChildProcessBySelfFork(const std::string &srcEntry, + const AppExecFwk::BundleInfo &bundleInfo) +{ +} + +bool ChildProcessManager::LoadJsFile(const std::string &srcEntry, const AppExecFwk::HapModuleInfo &hapModuleInfo, + std::unique_ptr &runtime, std::shared_ptr args) +{ + return true; +} + +bool ChildProcessManager::LoadNativeLib(const std::string &moduleName, + const std::string &libPath, const sptr &mainProcessCb) +{ + return true; +} + +bool ChildProcessManager::LoadNativeLibWithArgs(const std::string &moduleName, const std::string &srcEntry, + const std::string &entryFunc, std::shared_ptr args) +{ + return true; +} + +std::unique_ptr ChildProcessManager::CreateRuntime(const AppExecFwk::BundleInfo &bundleInfo, + const AppExecFwk::HapModuleInfo &hapModuleInfo, const bool fromAppSpawn, const bool jitEnabled) +{ + return nullptr; +} + +bool ChildProcessManager::GetBundleInfo(AppExecFwk::BundleInfo &bundleInfo) +{ + return false; +} + +bool ChildProcessManager::GetEntryHapModuleInfo(const AppExecFwk::BundleInfo &bundleInfo, + AppExecFwk::HapModuleInfo &hapModuleInfo) +{ + return false; +} + +bool ChildProcessManager::GetHapModuleInfo(const AppExecFwk::BundleInfo &bundleInfo, const std::string &moduleName, + AppExecFwk::HapModuleInfo &hapModuleInfo) +{ + return false; +} + +bool ChildProcessManager::HasChildProcessRecord() +{ + return false; +} + +sptr ChildProcessManager::GetAppMgr() +{ + return nullptr; +} + +void ChildProcessManager::SetForkProcessJITEnabled(bool jitEnabled) +{ + g_jitEnabled = jitEnabled; +} + +void ChildProcessManager::SetForkProcessDebugOption(const std::string bundleName, const bool isStartWithDebug, + const bool isDebugApp, const bool isStartWithNative) +{ +} + +void ChildProcessManager::SetAppSpawnForkDebugOption(Runtime::DebugOption &debugOption, + std::shared_ptr processInfo) +{ +} + +void ChildProcessManager::MakeProcessName(const std::string &srcEntry) +{ +} + +std::string ChildProcessManager::GetModuleNameFromSrcEntry(const std::string &srcEntry) +{ + return ""; +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/native_child_process_test/native_child_process_test.cpp b/test/unittest/native_child_process_test/native_child_process_test.cpp new file mode 100644 index 0000000000..7de4d6e8d1 --- /dev/null +++ b/test/unittest/native_child_process_test/native_child_process_test.cpp @@ -0,0 +1,310 @@ +/* + * Copyright (c) 2025 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 "child_process_args.h" +#include "child_process_configs.h" +#include "child_process_manager_error_utils.h" +#include "mock_child_process_manager.h" +#include "native_child_process.h" +#undef protected +#undef private + +using namespace testing; +using namespace testing::ext; + +namespace OHOS { +namespace AAFwk { +namespace { +#ifdef WITH_DLP +const std::string DLP_INDEX = "ohos.dlp.params.index"; +#endif // WITH_DLP +constexpr int32_t TEST_UID = 20010001; +}; +class NativeChildProcessTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; + + static void MyProcessStartCallback(int errCode, OHIPCRemoteProxy *remoteProxy); +}; + +void NativeChildProcessTest::SetUpTestCase() {} + +void NativeChildProcessTest::TearDownTestCase() {} + +void NativeChildProcessTest::SetUp() {} + +void NativeChildProcessTest::TearDown() {} + +void NativeChildProcessTest::MyProcessStartCallback(int errCode, OHIPCRemoteProxy *remoteProxy) +{ + if (errCode == 0) { + std::cout << "Child process started successfully." << std::endl; + } else { + std::cout << "Failed to start child process, error code: " << errCode << std::endl; + } +} + +/** + * @tc.name: UIAbilityLifecycleManager_OH_Ability_ChildProcessConfigs_SetProcessName_0100 + * @tc.desc: OH_Ability_ChildProcessConfigs_SetProcessName + * @tc.type: FUNC + */ +HWTEST_F(NativeChildProcessTest, OH_Ability_ChildProcessConfigs_SetProcessName_001, TestSize.Level1) +{ + Ability_ChildProcessConfigs configs; + std::string processName = ""; + constexpr int32_t MAX_PROCESS_NAME_LENGTH = 64; + for (int i = 0; i < MAX_PROCESS_NAME_LENGTH + 10; ++i) + { + processName += "A"; + } + + auto ret = OH_Ability_ChildProcessConfigs_SetProcessName(&configs, processName.c_str()); + + EXPECT_EQ(ret, NCP_ERR_INVALID_PARAM); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OH_Ability_ChildProcessConfigs_SetProcessName_0200 + * @tc.desc: OH_Ability_ChildProcessConfigs_SetProcessName + * @tc.type: FUNC + */ +HWTEST_F(NativeChildProcessTest, OH_Ability_ChildProcessConfigs_SetProcessName_002, TestSize.Level1) +{ + Ability_ChildProcessConfigs configs; + std::string processName = ""; + constexpr int32_t MAX_PROCESS_NAME_LENGTH = 64; + for (size_t i = 0; i < MAX_PROCESS_NAME_LENGTH + 10; ++i) + { + processName += "A"; + } + + auto ret = OH_Ability_ChildProcessConfigs_SetProcessName(&configs, processName.c_str()); + + EXPECT_EQ(ret, NCP_ERR_INVALID_PARAM); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OH_Ability_CreateNativeChildProcessWithConfigs_0100 + * @tc.desc: OH_Ability_CreateNativeChildProcessWithConfigs + * @tc.type: FUNC + */ +HWTEST_F(NativeChildProcessTest, OH_Ability_CreateNativeChildProcessWithConfigs_001, TestSize.Level1) +{ + Ability_ChildProcessConfigs configs; + std::string libName = "../ABCD/abcd"; + + auto ret = OH_Ability_CreateNativeChildProcessWithConfigs( + libName.c_str(), &configs, &NativeChildProcessTest::MyProcessStartCallback); + + EXPECT_EQ(ret, NCP_ERR_INVALID_PARAM); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OH_Ability_StartNativeChildProcess_0100 + * @tc.desc: OH_Ability_StartNativeChildProcess + * @tc.type: FUNC + */ +HWTEST_F(NativeChildProcessTest, OH_Ability_StartNativeChildProcess_001, TestSize.Level1) +{ + std::string entry = "HeavenlyMe"; + NativeChildProcess_Args args = {}; + NativeChildProcess_Options options = {}; + int32_t pid = 0; + + auto ret = OH_Ability_StartNativeChildProcess(entry.c_str(), args, options, &pid); + + EXPECT_EQ(ret, NCP_ERR_INVALID_PARAM); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OH_Ability_StartNativeChildProcess_0200 + * @tc.desc: OH_Ability_StartNativeChildProcess + * @tc.type: FUNC + */ +HWTEST_F(NativeChildProcessTest, OH_Ability_StartNativeChildProcess_002, TestSize.Level1) +{ + std::string entry = ":HeavenlyMe:KON"; + NativeChildProcess_Args args = {}; + NativeChildProcess_Options options = {}; + + auto ret = OH_Ability_StartNativeChildProcess(entry.c_str(), args, options, nullptr); + + EXPECT_EQ(ret, NCP_ERR_INVALID_PARAM); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OH_Ability_StartNativeChildProcess_0300 + * @tc.desc: OH_Ability_StartNativeChildProcess + * @tc.type: FUNC + */ +HWTEST_F(NativeChildProcessTest, OH_Ability_StartNativeChildProcess_003, TestSize.Level1) +{ + std::string entry = ":HeavenlyMe:KON"; + NativeChildProcess_Fd head; + head.next = nullptr; + head.fdName = nullptr; + NativeChildProcess_Args args = {}; + args.fdList.head = &head; + NativeChildProcess_Options options = {}; + int32_t pid = 0; + + auto ret = OH_Ability_StartNativeChildProcess(entry.c_str(), args, options, &pid); + + EXPECT_EQ(ret, NCP_ERR_INVALID_PARAM); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OH_Ability_StartNativeChildProcess_0400 + * @tc.desc: OH_Ability_StartNativeChildProcess + * @tc.type: FUNC + */ +HWTEST_F(NativeChildProcessTest, OH_Ability_StartNativeChildProcess_004, TestSize.Level1) +{ + std::string entry = ":HeavenlyMe:KON"; + NativeChildProcess_Args args = {}; + args.fdList.head = nullptr; + NativeChildProcess_Options options = {}; + int32_t pid = 0; + auto &instance = AbilityRuntime::ChildProcessManager::GetInstance(); + instance.startErrorCode_ = AbilityRuntime::ChildProcessManagerErrorCode::ERR_OK; + + auto ret = OH_Ability_StartNativeChildProcess(entry.c_str(), args, options, &pid); + + EXPECT_EQ(ret, NCP_NO_ERROR); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OH_Ability_StartNativeChildProcess_0500 + * @tc.desc: OH_Ability_StartNativeChildProcess + * @tc.type: FUNC + */ +HWTEST_F(NativeChildProcessTest, OH_Ability_StartNativeChildProcess_005, TestSize.Level1) +{ + std::string entry = ":HeavenlyMe:KON"; + NativeChildProcess_Args args = {}; + args.fdList.head = nullptr; + NativeChildProcess_Options options = {}; + int32_t pid = 0; + auto &instance = AbilityRuntime::ChildProcessManager::GetInstance(); + instance.startErrorCode_ = AbilityRuntime::ChildProcessManagerErrorCode::ERR_GET_APP_MGR_FAILED; + + auto ret = OH_Ability_StartNativeChildProcess(entry.c_str(), args, options, &pid); + + EXPECT_EQ(ret, NCP_ERR_SERVICE_ERROR); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OH_Ability_StartNativeChildProcessWithConfigs_0100 + * @tc.desc: OH_Ability_StartNativeChildProcessWithConfigs + * @tc.type: FUNC + */ +HWTEST_F(NativeChildProcessTest, OH_Ability_StartNativeChildProcessWithConfigs_001, TestSize.Level1) +{ + std::string entry = "HeavenlyMe"; + NativeChildProcess_Args args = {}; + args.fdList.head = nullptr; + Ability_ChildProcessConfigs configs; + + auto ret = OH_Ability_StartNativeChildProcessWithConfigs(entry.c_str(), args, &configs, nullptr); + + EXPECT_EQ(ret, NCP_ERR_INVALID_PARAM); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OH_Ability_StartNativeChildProcessWithConfigs_0200 + * @tc.desc: OH_Ability_StartNativeChildProcessWithConfigs + * @tc.type: FUNC + */ +HWTEST_F(NativeChildProcessTest, OH_Ability_StartNativeChildProcessWithConfigs_002, TestSize.Level1) +{ + std::string entry = ":HeavenlyMe:KON"; + NativeChildProcess_Args args = {}; + args.fdList.head = nullptr; + Ability_ChildProcessConfigs configs; + + auto ret = OH_Ability_StartNativeChildProcessWithConfigs(entry.c_str(), args, &configs, nullptr); + + EXPECT_EQ(ret, NCP_ERR_INVALID_PARAM); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OH_Ability_StartNativeChildProcessWithConfigs_0300 + * @tc.desc: OH_Ability_StartNativeChildProcessWithConfigs + * @tc.type: FUNC + */ +HWTEST_F(NativeChildProcessTest, OH_Ability_StartNativeChildProcessWithConfigs_003, TestSize.Level1) +{ + std::string entry = ":HeavenlyMe:KON"; + NativeChildProcess_Fd head; + head.fdName = nullptr; + NativeChildProcess_Args args = {}; + args.fdList.head = &head; + Ability_ChildProcessConfigs configs; + int32_t pid = 1; + + auto ret = OH_Ability_StartNativeChildProcessWithConfigs(entry.c_str(), args, &configs, &pid); + + EXPECT_EQ(ret, NCP_ERR_INVALID_PARAM); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OH_Ability_StartNativeChildProcessWithConfigs_0400 + * @tc.desc: OH_Ability_StartNativeChildProcessWithConfigs + * @tc.type: FUNC + */ +HWTEST_F(NativeChildProcessTest, OH_Ability_StartNativeChildProcessWithConfigs_004, TestSize.Level1) +{ + std::string entry = ":HeavenlyMe:KON"; + NativeChildProcess_Args args = {}; + args.fdList.head = nullptr; + Ability_ChildProcessConfigs configs; + int32_t pid = 1; + auto &instance = AbilityRuntime::ChildProcessManager::GetInstance(); + instance.startErrorCode_ = AbilityRuntime::ChildProcessManagerErrorCode::ERR_OK; + + auto ret = OH_Ability_StartNativeChildProcessWithConfigs(entry.c_str(), args, &configs, &pid); + + EXPECT_EQ(ret, NCP_NO_ERROR); +} + +/** + * @tc.name: UIAbilityLifecycleManager_OH_Ability_StartNativeChildProcessWithConfigs_0500 + * @tc.desc: OH_Ability_StartNativeChildProcessWithConfigs + * @tc.type: FUNC + */ +HWTEST_F(NativeChildProcessTest, OH_Ability_StartNativeChildProcessWithConfigs_005, TestSize.Level1) +{ + std::string entry = ":HeavenlyMe:KON"; + NativeChildProcess_Args args = {}; + args.fdList.head = nullptr; + Ability_ChildProcessConfigs configs; + int32_t pid = 1; + auto &instance = AbilityRuntime::ChildProcessManager::GetInstance(); + instance.startErrorCode_ = AbilityRuntime::ChildProcessManagerErrorCode::ERR_GET_APP_MGR_FAILED; + + auto ret = OH_Ability_StartNativeChildProcessWithConfigs(entry.c_str(), args, &configs, &pid); + + EXPECT_EQ(ret, NCP_ERR_SERVICE_ERROR); +} +} // namespace AAFwk +} // namespace OHOS diff --git a/test/unittest/ui_extension/extension_record_manager_second_test/extension_record_manager_second_test.cpp b/test/unittest/ui_extension/extension_record_manager_second_test/extension_record_manager_second_test.cpp index 917d3d6b8a..820abcd58d 100644 --- a/test/unittest/ui_extension/extension_record_manager_second_test/extension_record_manager_second_test.cpp +++ b/test/unittest/ui_extension/extension_record_manager_second_test/extension_record_manager_second_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 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 @@ -246,5 +246,452 @@ HWTEST_F(ExtensionRecordManagerSecondTest, RemovePreloadUIExtensionRecordById_01 EXPECT_FALSE(extRecordMgr->RemovePreloadUIExtensionRecordById(extensionRecordMapKey, extensionRecordId)); TAG_LOGI(AAFwkTag::TEST, "end."); } + +/** + * @tc.name: GetHostBundleNameForExtensionId_0100 + * @tc.desc: GetHostBundleNameForExtensionId + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(ExtensionRecordManagerSecondTest, GetHostBundleNameForExtensionId_0100, TestSize.Level1) +{ + auto extRecordMgr = std::make_shared(0); + extRecordMgr->extensionRecords_.clear(); + std::string hostBundleName = ""; + + auto ret = extRecordMgr->GetHostBundleNameForExtensionId(1, hostBundleName); + + EXPECT_EQ(ret, ERR_INVALID_VALUE); +} + +/** + * @tc.name: RemoveAllPreloadUIExtensionRecord_0100 + * @tc.desc: RemoveAllPreloadUIExtensionRecord + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(ExtensionRecordManagerSecondTest, RemoveAllPreloadUIExtensionRecord_0100, TestSize.Level1) +{ + auto extRecordMgr = std::make_shared(0); + ExtensionRecordManager::PreLoadUIExtensionMapKey preLoadUIExtensionInfo("1", "2", "3", "4"); + extRecordMgr->preloadUIExtensionMap_ = { + {preLoadUIExtensionInfo, {}} + }; + + extRecordMgr->RemoveAllPreloadUIExtensionRecord(preLoadUIExtensionInfo); + + EXPECT_EQ(extRecordMgr->preloadUIExtensionMap_.size(), 0); +} + +/** + * @tc.name: RemoveAllPreloadUIExtensionRecord_0200 + * @tc.desc: RemoveAllPreloadUIExtensionRecord + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(ExtensionRecordManagerSecondTest, RemoveAllPreloadUIExtensionRecord_0200, TestSize.Level1) +{ + auto extRecordMgr = std::make_shared(0); + ExtensionRecordManager::PreLoadUIExtensionMapKey preLoadUIExtensionInfo1("1", "2", "3", "4"); + ExtensionRecordManager::PreLoadUIExtensionMapKey preLoadUIExtensionInfo2("5", "6", "7", "8"); + extRecordMgr->preloadUIExtensionMap_ = { + {preLoadUIExtensionInfo1, {}} + }; + + extRecordMgr->RemoveAllPreloadUIExtensionRecord(preLoadUIExtensionInfo2); + + EXPECT_EQ(extRecordMgr->preloadUIExtensionMap_.size(), 1); +} + +/** + * @tc.name: RemovePreloadUIExtensionRecordById_0300 + * @tc.desc: RemovePreloadUIExtensionRecordById + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(ExtensionRecordManagerSecondTest, RemovePreloadUIExtensionRecordById_0300, TestSize.Level1) +{ + auto extRecordMgr = std::make_shared(0); + std::tuple extensionRecordMapKey = { + "1", "2", "3", "4" + }; + int32_t extensionRecordId = 1; + ExtensionRecordManager::PreLoadUIExtensionMapKey preLoadUIExtensionInfo1("1", "2", "3", "4"); + ExtensionRecordManager::PreLoadUIExtensionMapKey preLoadUIExtensionInfo2("5", "6", "7", "8"); + AAFwk::AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.unittest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AppExecFwk::AbilityType::EXTENSION; + auto abilityRecord = AAFwk::AbilityRecord::CreateAbilityRecord(abilityRequest); + ASSERT_NE(abilityRecord, nullptr); + auto extensionRecord = std::make_shared(abilityRecord); + extensionRecord->extensionRecordId_ = extensionRecordId; + std::vector> extensionRecords = { + extensionRecord + }; + extRecordMgr->preloadUIExtensionMap_ = { + {preLoadUIExtensionInfo1, extensionRecords} + }; + + auto ret = extRecordMgr->RemovePreloadUIExtensionRecordById(extensionRecordMapKey, extensionRecordId); + + EXPECT_EQ(extRecordMgr->preloadUIExtensionMap_.size(), 0); + EXPECT_EQ(ret, true); +} + + +/** + * @tc.name: RemovePreloadUIExtensionRecordById_0400 + * @tc.desc: RemovePreloadUIExtensionRecordById + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(ExtensionRecordManagerSecondTest, RemovePreloadUIExtensionRecordById_0400, TestSize.Level1) +{ + auto extRecordMgr = std::make_shared(0); + std::tuple extensionRecordMapKey = { + "1", "2", "3", "4" + }; + int32_t extensionRecordId = 1; + int32_t extensionRecordId2 = 2; + ExtensionRecordManager::PreLoadUIExtensionMapKey preLoadUIExtensionInfo1("1", "2", "3", "4"); + ExtensionRecordManager::PreLoadUIExtensionMapKey preLoadUIExtensionInfo2("5", "6", "7", "8"); + AAFwk::AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.unittest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AppExecFwk::AbilityType::EXTENSION; + auto abilityRecord = AAFwk::AbilityRecord::CreateAbilityRecord(abilityRequest); + ASSERT_NE(abilityRecord, nullptr); + auto extensionRecord = std::make_shared(abilityRecord); + extensionRecord->extensionRecordId_ = extensionRecordId; + auto extensionRecord2 = std::make_shared(abilityRecord); + extensionRecord2->extensionRecordId_ = extensionRecordId2; + std::vector> extensionRecords = { + extensionRecord, extensionRecord2 + }; + extRecordMgr->preloadUIExtensionMap_ = { + {preLoadUIExtensionInfo1, extensionRecords} + }; + + auto ret = extRecordMgr->RemovePreloadUIExtensionRecordById(extensionRecordMapKey, extensionRecordId); + + EXPECT_EQ(extRecordMgr->preloadUIExtensionMap_.size(), 1); + EXPECT_EQ(ret, true); +} + +/** + * @tc.name: RemovePreloadUIExtensionRecordById_0500 + * @tc.desc: RemovePreloadUIExtensionRecordById + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(ExtensionRecordManagerSecondTest, RemovePreloadUIExtensionRecordById_0500, TestSize.Level1) +{ + auto extRecordMgr = std::make_shared(0); + + std::tuple extensionRecordMapKey = { + "1", "2", "3", "4" + }; + int32_t extensionRecordId = 1; + int32_t extensionRecordId2 = 2; + int32_t extensionRecordId3 = 3; + ExtensionRecordManager::PreLoadUIExtensionMapKey preLoadUIExtensionInfo1("1", "2", "3", "4"); + ExtensionRecordManager::PreLoadUIExtensionMapKey preLoadUIExtensionInfo2("5", "6", "7", "8"); + AAFwk::AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.unittest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AppExecFwk::AbilityType::EXTENSION; + auto abilityRecord = AAFwk::AbilityRecord::CreateAbilityRecord(abilityRequest); + ASSERT_NE(abilityRecord, nullptr); + auto extensionRecord = std::make_shared(abilityRecord); + extensionRecord->extensionRecordId_ = extensionRecordId; + auto extensionRecord2 = std::make_shared(abilityRecord); + extensionRecord2->extensionRecordId_ = extensionRecordId2; + std::vector> extensionRecords = { + extensionRecord, extensionRecord2 + }; + extRecordMgr->preloadUIExtensionMap_ = { + {preLoadUIExtensionInfo1, extensionRecords} + }; + + auto ret = extRecordMgr->RemovePreloadUIExtensionRecordById(extensionRecordMapKey, extensionRecordId3); + + EXPECT_EQ(extRecordMgr->preloadUIExtensionMap_.size(), 1); + EXPECT_EQ(ret, false); +} + +/** + * @tc.name: RemovePreloadUIExtensionRecord_0200 + * @tc.desc: RemovePreloadUIExtensionRecord + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(ExtensionRecordManagerSecondTest, RemovePreloadUIExtensionRecord_0200, TestSize.Level1) +{ + auto extRecordMgr = std::make_shared(0); + + std::tuple extensionRecordMapKey = { + "1", "2", "3", "4" + }; + extRecordMgr->preloadUIExtensionMap_.clear(); + + auto ret = extRecordMgr->RemovePreloadUIExtensionRecord(extensionRecordMapKey); + + EXPECT_EQ(ret, false); +} + +/** + * @tc.name: GetRootCallerTokenLocked_0200 + * @tc.desc: GetRootCallerTokenLocked + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(ExtensionRecordManagerSecondTest, GetRootCallerTokenLocked_0200, TestSize.Level1) +{ + auto extRecordMgr = std::make_shared(0); + + int32_t extensionRecordId = 0; + AAFwk::AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.unittest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AppExecFwk::AbilityType::EXTENSION; + auto abilityRecord = AAFwk::AbilityRecord::CreateAbilityRecord(abilityRequest); + ASSERT_NE(abilityRecord, nullptr); + extRecordMgr->extensionRecords_.clear(); + + auto ret = extRecordMgr->GetRootCallerTokenLocked(extensionRecordId, abilityRecord); + + EXPECT_EQ(ret, nullptr); +} + +/** + * @tc.name: GetUIExtensionRootHostInfo_0100 + * @tc.desc: GetUIExtensionRootHostInfo + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(ExtensionRecordManagerSecondTest, GetUIExtensionRootHostInfo_0100, TestSize.Level1) +{ + auto extRecordMgr = std::make_shared(0); + + auto ret = extRecordMgr->GetUIExtensionRootHostInfo(nullptr); + + EXPECT_EQ(ret, nullptr); +} + +/** + * @tc.name: GetUIExtensionSessionInfo_0200 + * @tc.desc: GetUIExtensionSessionInfo + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(ExtensionRecordManagerSecondTest, GetUIExtensionSessionInfo_0200, TestSize.Level1) +{ + auto extRecordMgr = std::make_shared(0); + UIExtensionSessionInfo uiExtensionSessionInfo; + + auto ret = extRecordMgr->GetUIExtensionSessionInfo(nullptr, uiExtensionSessionInfo); + + EXPECT_EQ(ret, ERR_NULL_OBJECT); +} + +/** + * @tc.name: GetExtensionRecordById_0100 + * @tc.desc: GetExtensionRecordById + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(ExtensionRecordManagerSecondTest, GetExtensionRecordById_0100, TestSize.Level1) +{ + auto extRecordMgr = std::make_shared(0); + + int32_t extensionRecordId = 1; + AAFwk::AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.unittest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AppExecFwk::AbilityType::EXTENSION; + auto abilityRecord = AAFwk::AbilityRecord::CreateAbilityRecord(abilityRequest); + ASSERT_NE(abilityRecord, nullptr); + + auto extensionRecord = std::make_shared(abilityRecord); + extensionRecord->extensionRecordId_ = extensionRecordId; + + extRecordMgr->extensionRecords_ = { + {extensionRecordId, extensionRecord} + }; + + auto ret = extRecordMgr->GetExtensionRecordById(extensionRecordId); + + EXPECT_EQ(ret, extensionRecord); +} + +/** + * @tc.name: GetExtensionRecordById_0200 + * @tc.desc: GetExtensionRecordById + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(ExtensionRecordManagerSecondTest, GetExtensionRecordById_0200, TestSize.Level1) +{ + auto extRecordMgr = std::make_shared(0); + + int32_t extensionRecordId = 1; + AAFwk::AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.unittest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AppExecFwk::AbilityType::EXTENSION; + auto abilityRecord = AAFwk::AbilityRecord::CreateAbilityRecord(abilityRequest); + ASSERT_NE(abilityRecord, nullptr); + auto extensionRecord = std::make_shared(abilityRecord); + extensionRecord->extensionRecordId_ = extensionRecordId; + extRecordMgr->extensionRecords_.clear(); + extRecordMgr->terminateRecords_.clear(); + + auto ret = extRecordMgr->GetExtensionRecordById(extensionRecordId); + + EXPECT_EQ(ret, nullptr); +} + +/** + * @tc.name: GetExtensionRecordById_0300 + * @tc.desc: GetExtensionRecordById + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(ExtensionRecordManagerSecondTest, GetExtensionRecordById_0300, TestSize.Level1) +{ + auto extRecordMgr = std::make_shared(0); + int32_t extensionRecordId = 1; + + AAFwk::AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.unittest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AppExecFwk::AbilityType::EXTENSION; + auto abilityRecord = AAFwk::AbilityRecord::CreateAbilityRecord(abilityRequest); + ASSERT_NE(abilityRecord, nullptr); + auto extensionRecord = std::make_shared(abilityRecord); + extensionRecord->extensionRecordId_ = extensionRecordId; + extRecordMgr->extensionRecords_.clear(); + extRecordMgr->terminateRecords_ = { + {extensionRecordId, extensionRecord} + }; + + auto ret = extRecordMgr->GetExtensionRecordById(extensionRecordId); + + EXPECT_EQ(ret, extensionRecord); +} + +/** + * @tc.name: QueryPreLoadUIExtensionRecord_0100 + * @tc.desc: QueryPreLoadUIExtensionRecord + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(ExtensionRecordManagerSecondTest, QueryPreLoadUIExtensionRecord_0100, TestSize.Level1) +{ + auto extRecordMgr = std::make_shared(0); + + AppExecFwk::ElementName element; + element.SetAbilityName(""); + element.SetBundleName("HeavenlyMe"); + std::string moduleName = "HeavenlyMe"; + std::string hostBundleName = "HeavenlyMe"; + int32_t recordNum = 1; + + auto ret = extRecordMgr->QueryPreLoadUIExtensionRecord( + element, moduleName, hostBundleName, recordNum); + + EXPECT_EQ(ret, ERR_INVALID_VALUE); +} + +/** + * @tc.name: QueryPreLoadUIExtensionRecord_0200 + * @tc.desc: QueryPreLoadUIExtensionRecord + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(ExtensionRecordManagerSecondTest, QueryPreLoadUIExtensionRecord_0200, TestSize.Level1) +{ + auto extRecordMgr = std::make_shared(0); + + AppExecFwk::ElementName element; + element.SetAbilityName("HeavenlyMe"); + element.SetBundleName("HeavenlyMe"); + std::string moduleName = "HeavenlyMe"; + std::string hostBundleName = "HeavenlyMe"; + int32_t recordNum = 1; + extRecordMgr->preloadUIExtensionMap_.clear(); + + auto ret = extRecordMgr->QueryPreLoadUIExtensionRecord( + element, moduleName, hostBundleName, recordNum); + + EXPECT_EQ(recordNum, 0); + EXPECT_EQ(ret, ERR_OK); +} + +/** + * @tc.name: QueryPreLoadUIExtensionRecord_0300 + * @tc.desc: QueryPreLoadUIExtensionRecord + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(ExtensionRecordManagerSecondTest, QueryPreLoadUIExtensionRecord_0300, TestSize.Level1) +{ + auto extRecordMgr = std::make_shared(0); + + AppExecFwk::ElementName element; + element.SetAbilityName("HeavenlyMeAbility"); + element.SetBundleName("HeavenlyMeBundle"); + std::string moduleName = "HeavenlyMeMoudle"; + std::string hostBundleName = "HeavenlyMeHostBundle"; + int32_t recordNum = 1; + ExtensionRecordManager::PreLoadUIExtensionMapKey extensionMapKey( + "HeavenlyMeAbility", "HeavenlyMeBundle", "HeavenlyMeMoudle", "HeavenlyMeHostBundle"); + extRecordMgr->preloadUIExtensionMap_ = { + {extensionMapKey, {}} + }; + + auto ret = extRecordMgr->QueryPreLoadUIExtensionRecord( + element, moduleName, hostBundleName, recordNum); + + EXPECT_EQ(recordNum, 0); + EXPECT_EQ(ret, ERR_OK); +} + +/** + * @tc.name: QueryPreLoadUIExtensionRecord_0400 + * @tc.desc: QueryPreLoadUIExtensionRecord + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(ExtensionRecordManagerSecondTest, QueryPreLoadUIExtensionRecord_0400, TestSize.Level1) +{ + auto extRecordMgr = std::make_shared(0); + + AppExecFwk::ElementName element; + element.SetAbilityName("HeavenlyMeAbility"); + element.SetBundleName("HeavenlyMeBundle"); + std::string moduleName = "HeavenlyMeMoudle"; + std::string hostBundleName = "HeavenlyMeHostBundle"; + int32_t recordNum = 1; + ExtensionRecordManager::PreLoadUIExtensionMapKey extensionMapKey( + "HeavenlyMeAbility", "HeavenlyMeBundle", "HeavenlyMeMoudle", "HeavenlyMeHostBundle"); + AAFwk::AbilityRequest abilityRequest; + abilityRequest.appInfo.bundleName = "com.example.unittest"; + abilityRequest.abilityInfo.name = "MainAbility"; + abilityRequest.abilityInfo.type = AppExecFwk::AbilityType::EXTENSION; + auto abilityRecord = AAFwk::AbilityRecord::CreateAbilityRecord(abilityRequest); + ASSERT_NE(abilityRecord, nullptr); + auto extensionRecord = std::make_shared(abilityRecord); + extRecordMgr->preloadUIExtensionMap_ = { + {extensionMapKey, {extensionRecord}} + }; + + auto ret = extRecordMgr->QueryPreLoadUIExtensionRecord( + element, moduleName, hostBundleName, recordNum); + + EXPECT_EQ(recordNum, 1); + EXPECT_EQ(ret, ERR_OK); +} } // namespace AbilityRuntime } // namespace OHOS From bab2fdf6aced0497e30ea1f1c05a94d332245dd2 Mon Sep 17 00:00:00 2001 From: wangbing Date: Fri, 6 Jun 2025 17:04:20 +0800 Subject: [PATCH 06/23] call wms interface Signed-off-by: wangbing --- services/abilitymgr/include/kiosk_manager.h | 2 +- services/abilitymgr/src/kiosk_manager.cpp | 21 +++++++++++++++------ 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/services/abilitymgr/include/kiosk_manager.h b/services/abilitymgr/include/kiosk_manager.h index ea7cf33ae7..0cf6d19a6c 100644 --- a/services/abilitymgr/include/kiosk_manager.h +++ b/services/abilitymgr/include/kiosk_manager.h @@ -42,7 +42,7 @@ public: private: KioskManager() = default; DISALLOW_COPY_AND_MOVE(KioskManager); - int32_t ExitKioskModeInner(const std::string &bundleName); + int32_t ExitKioskModeInner(const std::string &bundleName, sptr callerToken = nullptr); bool IsInKioskModeInner(); void notifyKioskModeChanged(bool isInKioskMode); bool IsInWhiteListInner(const std::string &bundleName); diff --git a/services/abilitymgr/src/kiosk_manager.cpp b/services/abilitymgr/src/kiosk_manager.cpp index 75b3abacfa..6dad1f9373 100644 --- a/services/abilitymgr/src/kiosk_manager.cpp +++ b/services/abilitymgr/src/kiosk_manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2023 Huawei Device Co., Ltd. + * Copyright (c) 2025 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 @@ -16,9 +16,10 @@ #include +#include "ability_manager_errors.h" #include "ability_manager_service.h" #include "ability_record.h" -#include "ability_manager_errors.h" +#include "ability_util.h" #include "common_event.h" #include "common_event_manager.h" #include "common_event_support.h" @@ -27,6 +28,7 @@ #include "ipc_skeleton.h" #include "kiosk_manager.h" #include "permission_constants.h" +#include "session_manager_lite.h" #include "singleton.h" #include "utils/want_utils.h" @@ -75,7 +77,9 @@ int32_t KioskManager::UpdateKioskApplicationList(const std::vector for (const auto &app : appList) { whitelist_.insert(app); } - + auto sceneSessionManager = Rosen::SessionManagerLite::GetInstance().GetSceneSessionManagerLiteProxy(); + CHECK_POINTER_AND_RETURN_LOG(sceneSessionManager, ERR_INVALID_VALUE, "sceneSessionManager is nullptr"); + sceneSessionManager->UpdateKioskAppList(appList); return ERR_OK; } @@ -105,7 +109,9 @@ int32_t KioskManager::EnterKioskMode(sptr callerToken) kioskStatus_.kioskBundleUid_ = IPCSkeleton::GetCallingUid(); GetEnterKioskModeCallback()(); notifyKioskModeChanged(true); - + auto sceneSessionManager = Rosen::SessionManagerLite::GetInstance().GetSceneSessionManagerLiteProxy(); + CHECK_POINTER_AND_RETURN_LOG(sceneSessionManager, ERR_INVALID_VALUE, "sceneSessionManager is nullptr"); + sceneSessionManager->EnterKioskMode(callerToken); return ERR_OK; } @@ -117,10 +123,10 @@ int32_t KioskManager::ExitKioskMode(sptr callerToken) return INVALID_PARAMETERS_ERR; } std::lock_guard lock(kioskManagermutex_); - return ExitKioskModeInner(record->GetAbilityInfo().bundleName); + return ExitKioskModeInner(record->GetAbilityInfo().bundleName, callerToken); } -int32_t KioskManager::ExitKioskModeInner(const std::string & bundleName) +int32_t ExitKioskModeInner(const std::string &bundleName, sptr callerToken = nullptr); { if (!IsInWhiteListInner(bundleName)) { return ERR_KIOSK_MODE_NOT_IN_WHITELIST; @@ -132,6 +138,9 @@ int32_t KioskManager::ExitKioskModeInner(const std::string & bundleName) GetExitKioskModeCallback()(); notifyKioskModeChanged(false); kioskStatus_.Clear(); + auto sceneSessionManager = Rosen::SessionManagerLite::GetInstance().GetSceneSessionManagerLiteProxy(); + CHECK_POINTER_AND_RETURN_LOG(sceneSessionManager, ERR_INVALID_VALUE, "sceneSessionManager is nullptr"); + sceneSessionManager->ExitKioskMode(callerToken); return ERR_OK; } From 27a2af5ad6b140ddbde0e0ff8ff494ff4ba858c3 Mon Sep 17 00:00:00 2001 From: yuechunyang Date: Sat, 7 Jun 2025 10:46:26 +0800 Subject: [PATCH 07/23] add keep alive tdd Signed-off-by: yuechunyang --- .../keep_alive_process_manager_test.cpp | 566 ++++++++++++++++++ 1 file changed, 566 insertions(+) diff --git a/test/unittest/keep_alive_process_manager_test/keep_alive_process_manager_test.cpp b/test/unittest/keep_alive_process_manager_test/keep_alive_process_manager_test.cpp index c08e977423..d88f500cb6 100755 --- a/test/unittest/keep_alive_process_manager_test/keep_alive_process_manager_test.cpp +++ b/test/unittest/keep_alive_process_manager_test/keep_alive_process_manager_test.cpp @@ -905,5 +905,571 @@ HWTEST_F(KeepAliveProcessManagerTest, OnAppStateChanged_001, TestSize.Level1) EXPECT_NE(keepAliveProcessManager, nullptr); GTEST_LOG_(INFO) << "OnAppStateChanged_001 end"; } + +/* + * Feature: KeepAliveProcessManager + * Function: SetAppServiceExtensionKeepAlive + * SubFunction: NA + * FunctionPoints:KeepAliveProcessManager SetAppServiceExtensionKeepAlive + * EnvConditions: NA + * CaseDescription: Verify SetAppServiceExtensionKeepAlive + */ +HWTEST_F(KeepAliveProcessManagerTest, SetAppServiceExtensionKeepAlive_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_001 start"; + std::string bundleName = "bundleName"; + bool updataEnable = true; + bool isByEDM = false; + bool isAllowUserToCancel = false; + system::SetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false); + EXPECT_EQ(system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false), false); + auto result = KeepAliveProcessManager::GetInstance().SetAppServiceExtensionKeepAlive(bundleName, + updataEnable, isByEDM, isAllowUserToCancel); + EXPECT_EQ(result, ERR_CAPABILITY_NOT_SUPPORT); + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_001 end"; +} + +/* + * Feature: KeepAliveProcessManager + * Function: SetAppServiceExtensionKeepAlive + * SubFunction: NA + * FunctionPoints:KeepAliveProcessManager SetAppServiceExtensionKeepAlive + * EnvConditions: NA + * CaseDescription: Verify SetAppServiceExtensionKeepAlive + */ +HWTEST_F(KeepAliveProcessManagerTest, SetAppServiceExtensionKeepAlive_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_002 start"; + std::string bundleName = "bundleName"; + bool updataEnable = true; + bool isByEDM = false; + bool isAllowUserToCancel = false; + system::SetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, true); + EXPECT_EQ(system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false), true); + MyFlag::isAllowedToUseSystemAPIFlag_ = false; + auto result = KeepAliveProcessManager::GetInstance().SetAppServiceExtensionKeepAlive(bundleName, + updataEnable, isByEDM, isAllowUserToCancel); + EXPECT_EQ(result, ERR_NOT_SYSTEM_APP); + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_002 end"; +} + +/* + * Feature: KeepAliveProcessManager + * Function: SetAppServiceExtensionKeepAlive + * SubFunction: NA + * FunctionPoints:KeepAliveProcessManager SetAppServiceExtensionKeepAlive + * EnvConditions: NA + * CaseDescription: Verify SetAppServiceExtensionKeepAlive + */ +HWTEST_F(KeepAliveProcessManagerTest, SetAppServiceExtensionKeepAlive_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_003 start"; + std::string bundleName = "bundleName"; + bool updataEnable = true; + bool isByEDM = false; + bool isAllowUserToCancel = false; + system::SetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, true); + EXPECT_EQ(system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false), true); + MyFlag::isAllowedToUseSystemAPIFlag_ = true; + MyFlag::verifyCallingPermissionFlag_ = false; + auto result = KeepAliveProcessManager::GetInstance().SetAppServiceExtensionKeepAlive(bundleName, + updataEnable, isByEDM, isAllowUserToCancel); + EXPECT_EQ(result, CHECK_PERMISSION_FAILED); + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_003 end"; +} + +/* + * Feature: KeepAliveProcessManager + * Function: SetAppServiceExtensionKeepAlive + * SubFunction: NA + * FunctionPoints:KeepAliveProcessManager SetAppServiceExtensionKeepAlive + * EnvConditions: NA + * CaseDescription: Verify SetAppServiceExtensionKeepAlive + */ +HWTEST_F(KeepAliveProcessManagerTest, SetAppServiceExtensionKeepAlive_004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_004 start"; + std::string bundleName = "bundleName"; + bool updataEnable = true; + bool isByEDM = true; + bool isAllowUserToCancel = false; + system::SetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false); + EXPECT_EQ(system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false), false); + auto result = KeepAliveProcessManager::GetInstance().SetAppServiceExtensionKeepAlive(bundleName, + updataEnable, isByEDM, isAllowUserToCancel); + EXPECT_EQ(result, ERR_CAPABILITY_NOT_SUPPORT); + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_004 end"; +} + +/* + * Feature: KeepAliveProcessManager + * Function: SetAppServiceExtensionKeepAlive + * SubFunction: NA + * FunctionPoints:KeepAliveProcessManager SetAppServiceExtensionKeepAlive + * EnvConditions: NA + * CaseDescription: Verify SetAppServiceExtensionKeepAlive + */ +HWTEST_F(KeepAliveProcessManagerTest, SetAppServiceExtensionKeepAlive_005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_005 start"; + std::string bundleName = "bundleName"; + bool updataEnable = true; + bool isByEDM = true; + bool isAllowUserToCancel = false; + system::SetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, true); + EXPECT_EQ(system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false), true); + MyFlag::checkSpecificFlag_ = false; + MyFlag::flag_ = MyFlag::FLAG::IS_SA_CALL; + MyFlag::verifyCallingPermissionFlag_ = false; + auto result = KeepAliveProcessManager::GetInstance().SetAppServiceExtensionKeepAlive(bundleName, + updataEnable, isByEDM, isAllowUserToCancel); + EXPECT_EQ(result, CHECK_PERMISSION_FAILED); + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_005 end"; +} + +/* + * Feature: KeepAliveProcessManager + * Function: SetAppServiceExtensionKeepAlive + * SubFunction: NA + * FunctionPoints:KeepAliveProcessManager SetAppServiceExtensionKeepAlive + * EnvConditions: NA + * CaseDescription: Verify SetAppServiceExtensionKeepAlive + */ +HWTEST_F(KeepAliveProcessManagerTest, SetAppServiceExtensionKeepAlive_006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_006 start"; + std::string bundleName = "bundleName"; + bool updataEnable = true; + bool isByEDM = false; + bool isAllowUserToCancel = false; + system::SetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, true); + EXPECT_EQ(system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false), true); + MyFlag::isAllowedToUseSystemAPIFlag_ = true; + MyFlag::verifyCallingPermissionFlag_ = true; + BundleMgrHelper::getBundleInfoResult = false; + auto result = KeepAliveProcessManager::GetInstance().SetAppServiceExtensionKeepAlive(bundleName, + updataEnable, isByEDM, isAllowUserToCancel); + EXPECT_EQ(result, ERR_NO_U1); + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_006 end"; +} + +/* + * Feature: KeepAliveProcessManager + * Function: SetAppServiceExtensionKeepAlive + * SubFunction: NA + * FunctionPoints:KeepAliveProcessManager SetAppServiceExtensionKeepAlive + * EnvConditions: NA + * CaseDescription: Verify SetAppServiceExtensionKeepAlive + */ +HWTEST_F(KeepAliveProcessManagerTest, SetAppServiceExtensionKeepAlive_007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_007 start"; + std::string bundleName = "bundleName"; + bool updataEnable = true; + bool isByEDM = true; + bool isAllowUserToCancel = false; + system::SetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, true); + EXPECT_EQ(system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false), true); + MyFlag::checkSpecificFlag_ = true; + BundleMgrHelper::getBundleInfoResult = false; + auto result = KeepAliveProcessManager::GetInstance().SetAppServiceExtensionKeepAlive(bundleName, + updataEnable, isByEDM, isAllowUserToCancel); + EXPECT_EQ(result, ERR_NO_U1); + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_007 end"; +} + +/* + * Feature: KeepAliveProcessManager + * Function: SetAppServiceExtensionKeepAlive + * SubFunction: NA + * FunctionPoints:KeepAliveProcessManager SetAppServiceExtensionKeepAlive + * EnvConditions: NA + * CaseDescription: Verify SetAppServiceExtensionKeepAlive + */ +HWTEST_F(KeepAliveProcessManagerTest, SetAppServiceExtensionKeepAlive_008, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_008 start"; + std::string bundleName = "bundleName"; + bool updataEnable = true; + bool isByEDM = false; + bool isAllowUserToCancel = false; + system::SetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, true); + EXPECT_EQ(system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false), true); + MyFlag::isAllowedToUseSystemAPIFlag_ = true; + MyFlag::verifyCallingPermissionFlag_ = true; + BundleMgrHelper::getBundleInfoResult = true; + MainElementUtils::checkAppServiceExtensionResult = false; + auto result = KeepAliveProcessManager::GetInstance().SetAppServiceExtensionKeepAlive(bundleName, + updataEnable, isByEDM, isAllowUserToCancel); + EXPECT_EQ(result, ERR_INVALID_MAIN_ELEMENT_TYPE); + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_008 end"; +} + +/* + * Feature: KeepAliveProcessManager + * Function: SetAppServiceExtensionKeepAlive + * SubFunction: NA + * FunctionPoints:KeepAliveProcessManager SetAppServiceExtensionKeepAlive + * EnvConditions: NA + * CaseDescription: Verify SetAppServiceExtensionKeepAlive + */ +HWTEST_F(KeepAliveProcessManagerTest, SetAppServiceExtensionKeepAlive_009, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_009 start"; + std::string bundleName = "bundleName"; + bool updataEnable = true; + bool isByEDM = true; + bool isAllowUserToCancel = false; + system::SetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, true); + EXPECT_EQ(system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false), true); + MyFlag::checkSpecificFlag_ = true; + BundleMgrHelper::getBundleInfoResult = true; + MainElementUtils::checkAppServiceExtensionResult = false; + auto result = KeepAliveProcessManager::GetInstance().SetAppServiceExtensionKeepAlive(bundleName, + updataEnable, isByEDM, isAllowUserToCancel); + EXPECT_EQ(result, ERR_INVALID_MAIN_ELEMENT_TYPE); + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_009 end"; +} + +/* + * Feature: KeepAliveProcessManager + * Function: SetAppServiceExtensionKeepAlive + * SubFunction: NA + * FunctionPoints:KeepAliveProcessManager SetAppServiceExtensionKeepAlive + * EnvConditions: NA + * CaseDescription: Verify SetAppServiceExtensionKeepAlive + */ +HWTEST_F(KeepAliveProcessManagerTest, SetAppServiceExtensionKeepAlive_010, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_010 start"; + std::string bundleName = "bundleName"; + bool updataEnable = true; + bool isByEDM = false; + bool isAllowUserToCancel = false; + system::SetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, true); + EXPECT_EQ(system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false), true); + MyFlag::isAllowedToUseSystemAPIFlag_ = true; + MyFlag::verifyCallingPermissionFlag_ = true; + BundleMgrHelper::getBundleInfoResult = true; + MainElementUtils::checkAppServiceExtensionResult = true; + AbilityKeepAliveService::callIsKeepAliveResult = false; + AbilityKeepAliveService::callSetAppServiceExtensionResult = INNER_ERR; + auto result = KeepAliveProcessManager::GetInstance().SetAppServiceExtensionKeepAlive(bundleName, + updataEnable, isByEDM, isAllowUserToCancel); + EXPECT_EQ(result, INNER_ERR); + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_010 end"; +} + +/* + * Feature: KeepAliveProcessManager + * Function: SetAppServiceExtensionKeepAlive + * SubFunction: NA + * FunctionPoints:KeepAliveProcessManager SetAppServiceExtensionKeepAlive + * EnvConditions: NA + * CaseDescription: Verify SetAppServiceExtensionKeepAlive + */ +HWTEST_F(KeepAliveProcessManagerTest, SetAppServiceExtensionKeepAlive_011, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_011 start"; + std::string bundleName = "bundleName"; + bool updataEnable = true; + bool isByEDM = true; + bool isAllowUserToCancel = false; + system::SetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, true); + EXPECT_EQ(system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false), true); + MyFlag::checkSpecificFlag_ = true; + BundleMgrHelper::getBundleInfoResult = true; + MainElementUtils::checkAppServiceExtensionResult = true; + AbilityKeepAliveService::callIsKeepAliveResult = false; + AbilityKeepAliveService::callSetAppServiceExtensionResult = INNER_ERR; + auto result = KeepAliveProcessManager::GetInstance().SetAppServiceExtensionKeepAlive(bundleName, + updataEnable, isByEDM, isAllowUserToCancel); + EXPECT_EQ(result, INNER_ERR); + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_011 end"; +} + +/* + * Feature: KeepAliveProcessManager + * Function: SetAppServiceExtensionKeepAlive + * SubFunction: NA + * FunctionPoints:KeepAliveProcessManager SetAppServiceExtensionKeepAlive + * EnvConditions: NA + * CaseDescription: Verify SetAppServiceExtensionKeepAlive + */ +HWTEST_F(KeepAliveProcessManagerTest, SetAppServiceExtensionKeepAlive_012, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_012 start"; + std::string bundleName = "bundleName"; + bool updataEnable = true; + bool isByEDM = false; + bool isAllowUserToCancel = false; + system::SetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, true); + EXPECT_EQ(system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false), true); + MyFlag::isAllowedToUseSystemAPIFlag_ = true; + MyFlag::verifyCallingPermissionFlag_ = true; + BundleMgrHelper::getBundleInfoResult = true; + MainElementUtils::checkAppServiceExtensionResult = true; + AbilityKeepAliveService::callIsKeepAliveResult = false; + AbilityKeepAliveService::callSetAppServiceExtensionResult = ERR_OK; + auto result = KeepAliveProcessManager::GetInstance().SetAppServiceExtensionKeepAlive(bundleName, + updataEnable, isByEDM, isAllowUserToCancel); + EXPECT_EQ(result, ERR_OK); + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_012 end"; +} + +/* + * Feature: KeepAliveProcessManager + * Function: SetAppServiceExtensionKeepAlive + * SubFunction: NA + * FunctionPoints:KeepAliveProcessManager SetAppServiceExtensionKeepAlive + * EnvConditions: NA + * CaseDescription: Verify SetAppServiceExtensionKeepAlive + */ +HWTEST_F(KeepAliveProcessManagerTest, SetAppServiceExtensionKeepAlive_013, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_013 start"; + std::string bundleName = "bundleName"; + bool updataEnable = true; + bool isByEDM = true; + bool isAllowUserToCancel = false; + system::SetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, true); + EXPECT_EQ(system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false), true); + MyFlag::checkSpecificFlag_ = true; + BundleMgrHelper::getBundleInfoResult = true; + MainElementUtils::checkAppServiceExtensionResult = true; + AbilityKeepAliveService::callIsKeepAliveResult = false; + AbilityKeepAliveService::callSetAppServiceExtensionResult = ERR_OK; + auto result = KeepAliveProcessManager::GetInstance().SetAppServiceExtensionKeepAlive(bundleName, + updataEnable, isByEDM, isAllowUserToCancel); + EXPECT_EQ(result, ERR_OK); + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest SetAppServiceExtensionKeepAlive_013 end"; +} + +/* + * Feature: KeepAliveProcessManager + * Function: QueryKeepAliveAppServiceExtensions + * SubFunction: NA + * FunctionPoints:KeepAliveProcessManager QueryKeepAliveAppServiceExtensions + * EnvConditions: NA + * CaseDescription: Verify QueryKeepAliveAppServiceExtensions + */ +HWTEST_F(KeepAliveProcessManagerTest, QueryKeepAliveAppServiceExtensions_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest QueryKeepAliveAppServiceExtensions_001 start"; + std::vector infoList; + bool isByEDM = false; + system::SetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false); + EXPECT_EQ(system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false), false); + auto result = KeepAliveProcessManager::GetInstance().QueryKeepAliveAppServiceExtensions(infoList, + isByEDM); + EXPECT_EQ(result, ERR_CAPABILITY_NOT_SUPPORT); + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest QueryKeepAliveAppServiceExtensions_001 end"; +} + +/* + * Feature: KeepAliveProcessManager + * Function: QueryKeepAliveAppServiceExtensions + * SubFunction: NA + * FunctionPoints:KeepAliveProcessManager QueryKeepAliveAppServiceExtensions + * EnvConditions: NA + * CaseDescription: Verify QueryKeepAliveAppServiceExtensions + */ +HWTEST_F(KeepAliveProcessManagerTest, QueryKeepAliveAppServiceExtensions_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest QueryKeepAliveAppServiceExtensions_002 start"; + std::vector infoList; + bool isByEDM = false; + system::SetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, true); + EXPECT_EQ(system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false), true); + MyFlag::isAllowedToUseSystemAPIFlag_ = false; + auto result = KeepAliveProcessManager::GetInstance().QueryKeepAliveAppServiceExtensions(infoList, + isByEDM); + EXPECT_EQ(result, ERR_NOT_SYSTEM_APP); + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest QueryKeepAliveAppServiceExtensions_002 end"; +} + +/* + * Feature: KeepAliveProcessManager + * Function: QueryKeepAliveAppServiceExtensions + * SubFunction: NA + * FunctionPoints:KeepAliveProcessManager QueryKeepAliveAppServiceExtensions + * EnvConditions: NA + * CaseDescription: Verify QueryKeepAliveAppServiceExtensions + */ +HWTEST_F(KeepAliveProcessManagerTest, QueryKeepAliveAppServiceExtensions_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest QueryKeepAliveAppServiceExtensions_003 start"; + std::vector infoList; + bool isByEDM = false; + system::SetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, true); + EXPECT_EQ(system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false), true); + MyFlag::isAllowedToUseSystemAPIFlag_ = true; + MyFlag::verifyCallingPermissionFlag_ = false; + auto result = KeepAliveProcessManager::GetInstance().QueryKeepAliveAppServiceExtensions(infoList, + isByEDM); + EXPECT_EQ(result, CHECK_PERMISSION_FAILED); + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest QueryKeepAliveAppServiceExtensions_003 end"; +} + +/* + * Feature: KeepAliveProcessManager + * Function: QueryKeepAliveAppServiceExtensions + * SubFunction: NA + * FunctionPoints:KeepAliveProcessManager QueryKeepAliveAppServiceExtensions + * EnvConditions: NA + * CaseDescription: Verify QueryKeepAliveAppServiceExtensions + */ +HWTEST_F(KeepAliveProcessManagerTest, QueryKeepAliveAppServiceExtensions_004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest QueryKeepAliveAppServiceExtensions_004 start"; + std::vector infoList; + bool isByEDM = true; + system::SetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false); + EXPECT_EQ(system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false), false); + auto result = KeepAliveProcessManager::GetInstance().QueryKeepAliveAppServiceExtensions(infoList, + isByEDM); + EXPECT_EQ(result, ERR_CAPABILITY_NOT_SUPPORT); + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest QueryKeepAliveAppServiceExtensions_004 end"; +} + +/* + * Feature: KeepAliveProcessManager + * Function: QueryKeepAliveAppServiceExtensions + * SubFunction: NA + * FunctionPoints:KeepAliveProcessManager QueryKeepAliveAppServiceExtensions + * EnvConditions: NA + * CaseDescription: Verify QueryKeepAliveAppServiceExtensions + */ +HWTEST_F(KeepAliveProcessManagerTest, QueryKeepAliveAppServiceExtensions_005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest QueryKeepAliveAppServiceExtensions_005 start"; + std::vector infoList; + bool isByEDM = true; + system::SetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, true); + EXPECT_EQ(system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false), true); + MyFlag::checkSpecificFlag_ = false; + MyFlag::flag_ = MyFlag::FLAG::IS_SA_CALL; + MyFlag::verifyCallingPermissionFlag_ = false; + auto result = KeepAliveProcessManager::GetInstance().QueryKeepAliveAppServiceExtensions(infoList, + isByEDM); + EXPECT_EQ(result, CHECK_PERMISSION_FAILED); + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest QueryKeepAliveAppServiceExtensions_005 end"; +} + +/* + * Feature: KeepAliveProcessManager + * Function: QueryKeepAliveAppServiceExtensions + * SubFunction: NA + * FunctionPoints:KeepAliveProcessManager QueryKeepAliveAppServiceExtensions + * EnvConditions: NA + * CaseDescription: Verify QueryKeepAliveAppServiceExtensions + */ +HWTEST_F(KeepAliveProcessManagerTest, QueryKeepAliveAppServiceExtensions_006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest QueryKeepAliveAppServiceExtensions_006 start"; + std::vector infoList; + bool isByEDM = false; + system::SetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, true); + EXPECT_EQ(system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false), true); + MyFlag::isAllowedToUseSystemAPIFlag_ = true; + MyFlag::verifyCallingPermissionFlag_ = true; + AbilityKeepAliveService::callQueryAppServiceExtensionResult = INNER_ERR; + auto result = KeepAliveProcessManager::GetInstance().QueryKeepAliveAppServiceExtensions(infoList, + isByEDM); + EXPECT_EQ(result, INNER_ERR); + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest QueryKeepAliveAppServiceExtensions_006 end"; +} + +/* + * Feature: KeepAliveProcessManager + * Function: QueryKeepAliveAppServiceExtensions + * SubFunction: NA + * FunctionPoints:KeepAliveProcessManager QueryKeepAliveAppServiceExtensions + * EnvConditions: NA + * CaseDescription: Verify QueryKeepAliveAppServiceExtensions + */ +HWTEST_F(KeepAliveProcessManagerTest, QueryKeepAliveAppServiceExtensions_007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest QueryKeepAliveAppServiceExtensions_007 start"; + std::vector infoList; + bool isByEDM = true; + system::SetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, true); + EXPECT_EQ(system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false), true); + MyFlag::checkSpecificFlag_ = true; + MyFlag::flag_ = MyFlag::FLAG::IS_SA_CALL; + MyFlag::verifyCallingPermissionFlag_ = false; + AbilityKeepAliveService::callQueryAppServiceExtensionResult = INNER_ERR; + auto result = KeepAliveProcessManager::GetInstance().QueryKeepAliveAppServiceExtensions(infoList, + isByEDM); + EXPECT_EQ(result, INNER_ERR); + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest QueryKeepAliveAppServiceExtensions_007 end"; +} + +/* + * Feature: KeepAliveProcessManager + * Function: QueryKeepAliveAppServiceExtensions + * SubFunction: NA + * FunctionPoints:KeepAliveProcessManager QueryKeepAliveAppServiceExtensions + * EnvConditions: NA + * CaseDescription: Verify QueryKeepAliveAppServiceExtensions + */ +HWTEST_F(KeepAliveProcessManagerTest, QueryKeepAliveAppServiceExtensions_008, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest QueryKeepAliveAppServiceExtensions_008 start"; + std::vector infoList; + bool isByEDM = false; + system::SetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, true); + EXPECT_EQ(system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false), true); + MyFlag::isAllowedToUseSystemAPIFlag_ = true; + MyFlag::verifyCallingPermissionFlag_ = true; + AbilityKeepAliveService::callQueryAppServiceExtensionResult = ERR_OK; + auto result = KeepAliveProcessManager::GetInstance().QueryKeepAliveAppServiceExtensions(infoList, + isByEDM); + EXPECT_EQ(result, ERR_OK); + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest QueryKeepAliveAppServiceExtensions_008 end"; +} + +/* + * Feature: KeepAliveProcessManager + * Function: QueryKeepAliveAppServiceExtensions + * SubFunction: NA + * FunctionPoints:KeepAliveProcessManager QueryKeepAliveAppServiceExtensions + * EnvConditions: NA + * CaseDescription: Verify QueryKeepAliveAppServiceExtensions + */ +HWTEST_F(KeepAliveProcessManagerTest, QueryKeepAliveAppServiceExtensions_009, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest QueryKeepAliveAppServiceExtensions_009 start"; + std::vector infoList; + bool isByEDM = true; + system::SetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, true); + EXPECT_EQ(system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false), true); + MyFlag::checkSpecificFlag_ = true; + MyFlag::flag_ = MyFlag::FLAG::IS_SA_CALL; + MyFlag::verifyCallingPermissionFlag_ = false; + AbilityKeepAliveService::callQueryAppServiceExtensionResult = ERR_OK; + auto result = KeepAliveProcessManager::GetInstance().QueryKeepAliveAppServiceExtensions(infoList, + isByEDM); + EXPECT_EQ(result, ERR_OK); + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest QueryKeepAliveAppServiceExtensions_009 end"; +} + +/* + * Feature: KeepAliveProcessManager + * Function: ClearKeepAliveAppServiceExtension + * SubFunction: NA + * FunctionPoints:KeepAliveProcessManager ClearKeepAliveAppServiceExtension + * EnvConditions: NA + * CaseDescription: Verify ClearKeepAliveAppServiceExtension + */ +HWTEST_F(KeepAliveProcessManagerTest, ClearKeepAliveAppServiceExtension_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest ClearKeepAliveAppServiceExtension_001 start"; + int32_t userId = 100; + AbilityKeepAliveService::callClearKeepAliveAppServiceExtensionResult = ERR_OK; + auto result = KeepAliveProcessManager::GetInstance().ClearKeepAliveAppServiceExtension(userId); + EXPECT_EQ(result, ERR_OK); + GTEST_LOG_(INFO) << "KeepAliveProcessManagerTest ClearKeepAliveAppServiceExtension_001 end"; +} } // namespace AAFwk } // namespace OHOS From e6d2ddf8bcd9a7c8719003c98d9c81e9bfaaa942 Mon Sep 17 00:00:00 2001 From: zhangzezhong Date: Sun, 8 Jun 2025 12:39:35 +0800 Subject: [PATCH 08/23] add ets Signed-off-by: zhangzezhong --- .../ets/@ohos.app.ability.AbilityConstant.ets | 107 ++++++++ .../ets/@ohos.app.ability.StartOptions.ets | 18 ++ frameworks/ets/ets/@ohos.app.ability.Want.ets | 232 ++++++++++++++++++ .../ets/@ohos.app.ability.wantConstant.ets | 66 +++++ frameworks/ets/ets/BUILD.gn | 85 +++++++ frameworks/ets/ets/utils/AbilityUtils.ets | 64 +++++ 6 files changed, 572 insertions(+) create mode 100644 frameworks/ets/ets/@ohos.app.ability.AbilityConstant.ets create mode 100644 frameworks/ets/ets/@ohos.app.ability.StartOptions.ets create mode 100644 frameworks/ets/ets/@ohos.app.ability.Want.ets create mode 100644 frameworks/ets/ets/@ohos.app.ability.wantConstant.ets create mode 100644 frameworks/ets/ets/utils/AbilityUtils.ets diff --git a/frameworks/ets/ets/@ohos.app.ability.AbilityConstant.ets b/frameworks/ets/ets/@ohos.app.ability.AbilityConstant.ets new file mode 100644 index 0000000000..4c72a344a5 --- /dev/null +++ b/frameworks/ets/ets/@ohos.app.ability.AbilityConstant.ets @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2025 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. + */ + +namespace AbilityConstant { + export interface LaunchParam { + launchReason: LaunchReason; + launchReasonMessage?: string; + lastExitReason: LastExitReason; + lastExitMessage: string; + } + + export enum LaunchReason { + UNKNOWN = 0, + START_ABILITY = 1, + CALL = 2, + CONTINUATION = 3, + APP_RECOVERY = 4, + SHARE = 5, + AUTO_STARTUP = 8, + INSIGHT_INTENT = 9, + PREPARE_CONTINUATION = 10, + } + + export enum LastExitReason { + UNKNOWN = 0, + ABILITY_NOT_RESPONDING = 1, + NORMAL = 2, + CPP_CRASH = 3, + JS_ERROR = 4, + APP_FREEZE = 5, + PERFORMANCE_CONTROL = 6, + RESOURCE_CONTROL = 7, + UPGRADE = 8, + USER_REQUEST = 9, + SIGNAL = 10 + } + + export enum OnContinueResult { + AGREE = 0, + REJECT = 1, + MISMATCH = 2 + } + + export enum MemoryLevel { + MEMORY_LEVEL_MODERATE = 0, + MEMORY_LEVEL_LOW = 1, + MEMORY_LEVEL_CRITICAL = 2 + } + + export enum WindowMode { + WINDOW_MODE_UNDEFINED = 0, + WINDOW_MODE_FULLSCREEN = 1, + WINDOW_MODE_SPLIT_PRIMARY = 100, + WINDOW_MODE_SPLIT_SECONDARY = 101, + WINDOW_MODE_FLOATING = 102 + } + + export enum OnSaveResult { + ALL_AGREE = 0, + CONTINUATION_REJECT = 1, + CONTINUATION_MISMATCH = 2, + RECOVERY_AGREE = 3, + RECOVERY_REJECT = 4, + ALL_REJECT + } + + export enum StateType { + CONTINUATION = 0, + APP_RECOVERY = 1 + } + + export enum ContinueState { + ACTIVE = 0, + INACTIVE = 1 + } + + export enum CollaborateResult { + ACCEPT = 0, + REJECT = 1, + } + + export enum PrepareTermination { + TERMINATE_IMMEDIATELY = 0, + CANCEL = 1 + } +} + +class LaunchParamImpl implements AbilityConstant.LaunchParam { + launchReason: AbilityConstant.LaunchReason = AbilityConstant.LaunchReason.UNKNOWN; + launchReasonMessage?: string | undefined; + lastExitReason: AbilityConstant.LastExitReason = AbilityConstant.LastExitReason.UNKNOWN; + lastExitMessage: string = ''; +} + +export default AbilityConstant; diff --git a/frameworks/ets/ets/@ohos.app.ability.StartOptions.ets b/frameworks/ets/ets/@ohos.app.ability.StartOptions.ets new file mode 100644 index 0000000000..c4a6565f60 --- /dev/null +++ b/frameworks/ets/ets/@ohos.app.ability.StartOptions.ets @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2025 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. + */ + +export default class StartOptions { + displayId?: number; +} diff --git a/frameworks/ets/ets/@ohos.app.ability.Want.ets b/frameworks/ets/ets/@ohos.app.ability.Want.ets new file mode 100644 index 0000000000..c1a0ec876e --- /dev/null +++ b/frameworks/ets/ets/@ohos.app.ability.Want.ets @@ -0,0 +1,232 @@ +/* + * Copyright (c) 2025 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 hilog from '@ohos.hilog' + +type valueType = NullishType; +const DOMAIN_ID = 0xD001300; +const TAG = 'WantSerializeTool'; + +class RecordWriter { + private buffer = new StringBuilder(); + private store = new Set(); + + public write(obj: Object): String { + this.writeObject(obj); + return this.buffer.toString(); + } + + private writeObject(obj: NullishType): void { + if (obj === null) { + this.buffer.append('null'); + } else if (obj === undefined) { + this.buffer.append('undefined'); + } else if (obj instanceof String) { + this.buffer.append(JSON.stringify(obj as String)); + } else if (this.writeValueType(obj)) { + // nothing to do + } else if (obj instanceof Array) { + this.writeArray(obj as Object as Array); + } else if (obj instanceof Record) { + this.writeRecord(obj as Object as Record); + } else { + const objType = Type.of(obj); + if (objType instanceof ArrayType) { + this.writeBuildArray(obj, Value.of(obj) as ArrayValue); + } else { + this.buffer.append('null'); + } + } + } + + private writeValueType(obj: Object): boolean { + if (obj instanceof Boolean) { + this.buffer.append(JSON.stringify(obj.unboxed())); + return true; + } else if (obj instanceof Byte) { + this.buffer.append(JSON.stringify(obj.unboxed())); + return true; + } else if (obj instanceof Char) { + this.buffer.append(JSON.stringify(obj.unboxed())); + return true; + } else if (obj instanceof Short) { + this.buffer.append(JSON.stringify(obj.unboxed())); + return true; + } else if (obj instanceof Int) { + this.buffer.append(JSON.stringify(obj.unboxed())); + return true; + } else if (obj instanceof Long) { + this.buffer.append(JSON.stringify(obj.unboxed())); + return true; + } else if (obj instanceof Float) { + this.buffer.append(JSON.stringify(obj.unboxed())); + return true; + } else if (obj instanceof Double) { + this.buffer.append(JSON.stringify(obj.unboxed())); + return true; + } else if (obj instanceof BigInt) { + this.buffer.append(JSON.stringify(obj)); + return true; + } else { + return false; + } + } + + private writeArray(arr: Array): void { + this.buffer.append('['); + const length = arr.length as int; + this.checkReferencesCycle(arr); + this.store.add(arr); + for (let idx = 0; idx < length; idx++) { + if (arr[idx] == null) { + this.buffer.append('null'); + } else { + this.writeObject(arr[idx]); + } + if (idx < length - 1) { + this.buffer.append(','); + } + } + this.store.delete(arr); + this.buffer.append(']'); + } + + private writeBuildArray(arr: Object, arrayValue: ArrayValue): void { + this.buffer.append('['); + const length = arrayValue.getLength() as int; + this.checkReferencesCycle(arr); + this.store.add(arr); + for (let idx = 0; idx < length; idx++) { + let member = arrayValue.getElement(idx).getData(); + if (member == null) { + this.buffer.append('null'); + } else { + this.writeObject(member); + } + if (idx < length - 1) { + this.buffer.append(','); + } + } + this.store.delete(arr); + this.buffer.append(']'); + } + + private writeRecord(rec: Record): void { + this.buffer.append('{'); + this.checkReferencesCycle(rec); + this.store.add(rec); + let isFirst = true; + for (let key of rec.keys()) { + if (rec[key] !== undefined) { + if (!isFirst) { + this.buffer.append(','); + } else { + isFirst = false; + } + this.buffer.append(JSON.stringify(key as String)); + this.buffer.append(':'); + this.writeObject(rec[key]); + } + } + this.store.delete(rec); + this.buffer.append('}'); + } + + private checkReferencesCycle(obj: Object): void { + if (this.store.has(obj)) { + throw new TypeError('cyclic object value'); + } + } +} + +export class RecordSerializeTool { + public static stringifyNoThrow(obj: Record): String { + try { + return RecordSerializeTool.stringify(obj as Object as Record); + } catch (err) { + hilog.error(DOMAIN_ID, TAG, `RecordSerializeTool.stringify error: ${err}`); + return ''; + } + } + + public static parseNoThrow(text: string): Record { + try { + return RecordSerializeTool.parse(text) as Object as Record; + } catch (err) { + hilog.error(DOMAIN_ID, TAG, `RecordSerializeTool.parse error: ${err}`); + return new Record(); + } + } + + public static stringify(obj: Record): String { + return new RecordWriter().write(obj); + } + + public static parse(text: string): Record { + let jsonValue = JSONParser.parse(text); + let res = RecordSerializeTool.jsonValue2Object(jsonValue); + if (!(res instanceof Record)) { + throw new TypeError('RecordSerializeTool parse only used for Record'); + } + return res as Record; + } + + private static jsonValue2Object(value: JSONValue): string | number | boolean | null | + Array | Record { + if (value instanceof JSONString) { + return value.value; + } else if (value instanceof JSONNumber) { + return new Double(value.value); + } else if (value instanceof JSONTrue) { + return new Boolean(true); + } else if (value instanceof JSONFalse) { + return new Boolean(false); + } else if (value instanceof JSONNull) { + return null; + } else if (value instanceof JSONArray) { + let obj = value as JSONArray; + let values = obj.values; + let result: Array = new Array(); + for (let i: int = 0; i < values.length; i++) { + result.push(RecordSerializeTool.jsonValue2Object(values[i])); + } + return result; + } else if (value instanceof JSONObject) { + let obj = value as JSONObject; + let keys: Array = obj.keys_; + let values: Array = obj.values; + let result: Record = new Record(); + for (let i: int = 0; i < keys.length; i++) { + result[keys[i].value] = RecordSerializeTool.jsonValue2Object(values[i]); + } + return result; + } else { + throw new TypeError('unknown JSONValue'); + } + } +} + +export default class Want { + bundleName?: string; + abilityName?: string; + deviceId?: string; + uri?: string; + type?: string; + flags?: number; + action?: string; + parameters?: Record; + entities?: Array; + moduleName?: string; +} diff --git a/frameworks/ets/ets/@ohos.app.ability.wantConstant.ets b/frameworks/ets/ets/@ohos.app.ability.wantConstant.ets new file mode 100644 index 0000000000..721b9d7eed --- /dev/null +++ b/frameworks/ets/ets/@ohos.app.ability.wantConstant.ets @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2025 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. + */ + +namespace wantConstant { + export enum Action { + ACTION_HOME = 'ohos.want.action.home', + ACTION_DIAL = 'ohos.want.action.dial', + ACTION_SEARCH = 'ohos.want.action.search', + ACTION_WIRELESS_SETTINGS = 'ohos.settings.wireless', + ACTION_MANAGE_APPLICATIONS_SETTINGS = 'ohos.settings.manage.applications', + ACTION_APPLICATION_DETAILS_SETTINGS = 'ohos.settings.application.details', + ACTION_SET_ALARM = 'ohos.want.action.setAlarm', + ACTION_SHOW_ALARMS = 'ohos.want.action.showAlarms', + ACTION_SNOOZE_ALARM = 'ohos.want.action.snoozeAlarm', + ACTION_DISMISS_ALARM = 'ohos.want.action.dismissAlarm', + ACTION_DISMISS_TIMER = 'ohos.want.action.dismissTimer', + ACTION_SEND_SMS = 'ohos.want.action.sendSms', + ACTION_CHOOSE = 'ohos.want.action.choose', + ACTION_IMAGE_CAPTURE = 'ohos.want.action.imageCapture', + ACTION_VIDEO_CAPTURE = 'ohos.want.action.videoCapture', + ACTION_SELECT = 'ohos.want.action.select', + ACTION_SEND_DATA = 'ohos.want.action.sendData', + ACTION_SEND_MULTIPLE_DATA = 'ohos.want.action.sendMultipleData', + ACTION_SCAN_MEDIA_FILE = 'ohos.want.action.scanMediaFile', + ACTION_VIEW_DATA = 'ohos.want.action.viewData', + ACTION_EDIT_DATA = 'ohos.want.action.editData', + INTENT_PARAMS_INTENT = 'ability.want.params.INTENT', + INTENT_PARAMS_TITLE = 'ability.want.params.TITLE', + ACTION_FILE_SELECT = 'ohos.action.fileSelect', + PARAMS_STREAM = 'ability.params.stream', + ACTION_APP_ACCOUNT_OAUTH = 'ohos.account.appAccount.action.oauth' + } + + export enum Flags { + FLAG_AUTH_READ_URI_PERMISSION = 0x00000001, + FLAG_AUTH_WRITE_URI_PERMISSION = 0x00000002, + FLAG_ABILITY_FORWARD_RESULT = 0x00000004, + FLAG_ABILITY_CONTINUATION = 0x00000008, + FLAG_NOT_OHOS_COMPONENT = 0x00000010, + FLAG_ABILITY_FORM_ENABLED = 0x00000020, + FLAG_AUTH_PERSISTABLE_URI_PERMISSION = 0x00000040, + FLAG_AUTH_PREFIX_URI_PERMISSION = 0x00000080, + FLAG_ABILITYSLICE_MULTI_DEVICE = 0x00000100, + FLAG_START_FOREGROUND_ABILITY = 0x00000200, + FLAG_ABILITY_CONTINUATION_REVERSIBLE = 0x00000400, + FLAG_INSTALL_ON_DEMAND = 0x00000800, + FLAG_INSTALL_WITH_BACKGROUND_MODE = 0x80000000, + FLAG_ABILITY_CLEAR_MISSION = 0x00008000, + FLAG_ABILITY_NEW_MISSION = 0x10000000, + FLAG_ABILITY_MISSION_TOP = 0x20000000 + } +} + +export default wantConstant; diff --git a/frameworks/ets/ets/BUILD.gn b/frameworks/ets/ets/BUILD.gn index 4c90291f2d..9f07fdb185 100644 --- a/frameworks/ets/ets/BUILD.gn +++ b/frameworks/ets/ets/BUILD.gn @@ -31,8 +31,93 @@ ohos_prebuilt_etc("ability_runtime_base_context_abc_etc") { deps = [ ":ability_runtime_base_context_abc" ] } +generate_static_abc("ability_runtime_ability_utils_abc") { + base_url = "./" + files = [ "./utils/AbilityUtils.ets" ] + + is_boot_abc = "True" + device_dst_file = "/system/framework/ability_runtime_ability_utils_abc.abc" +} + +ohos_prebuilt_etc("ability_runtime_ability_utils_abc_etc") { + source = "$target_out_dir/ability_runtime_ability_utils_abc.abc" + module_install_dir = "framework" + subsystem_name = "ability" + part_name = "ability_runtime" + deps = [ ":ability_runtime_ability_utils_abc" ] +} + +generate_static_abc("ability_runtime_ability_constant_abc") { + base_url = "./" + files = [ "./@ohos.app.ability.AbilityConstant.ets" ] + + is_boot_abc = "True" + device_dst_file = "/system/framework/ability_runtime_ability_constant_abc.abc" +} + +ohos_prebuilt_etc("ability_runtime_ability_constant_abc_etc") { + source = "$target_out_dir/ability_runtime_ability_constant_abc.abc" + module_install_dir = "framework" + subsystem_name = "ability" + part_name = "ability_runtime" + deps = [ ":ability_runtime_ability_constant_abc" ] +} + +generate_static_abc("ability_runtime_start_options_abc") { + base_url = "./" + files = [ "./@ohos.app.ability.StartOptions.ets" ] + + is_boot_abc = "True" + device_dst_file = "/system/framework/ability_runtime_start_options_abc.abc" +} + +ohos_prebuilt_etc("ability_runtime_start_options_abc_etc") { + source = "$target_out_dir/ability_runtime_start_options_abc.abc" + module_install_dir = "framework" + subsystem_name = "ability" + part_name = "ability_runtime" + deps = [ ":ability_runtime_start_options_abc" ] +} + +generate_static_abc("ability_runtime_want_abc") { + base_url = "./" + files = [ "./@ohos.app.ability.Want.ets" ] + + is_boot_abc = "True" + device_dst_file = "/system/framework/ability_runtime_want_abc.abc" +} + +ohos_prebuilt_etc("ability_runtime_want_abc_etc") { + source = "$target_out_dir/ability_runtime_want_abc.abc" + module_install_dir = "framework" + subsystem_name = "ability" + part_name = "ability_runtime" + deps = [ ":ability_runtime_want_abc" ] +} + +generate_static_abc("ability_runtime_want_constant_abc") { + base_url = "./" + files = [ "./@ohos.app.ability.wantConstant.ets" ] + + is_boot_abc = "True" + device_dst_file = "/system/framework/ability_runtime_want_constant_abc.abc" +} + +ohos_prebuilt_etc("ability_runtime_want_constant_abc_etc") { + source = "$target_out_dir/ability_runtime_want_constant_abc.abc" + module_install_dir = "framework" + subsystem_name = "ability" + part_name = "ability_runtime" + deps = [ ":ability_runtime_want_constant_abc" ] +} + group("ets_packages") { deps = [ + ":ability_runtime_ability_constant_abc_etc", + ":ability_runtime_ability_utils_abc_etc", ":ability_runtime_base_context_abc_etc", + ":ability_runtime_start_options_abc_etc", + ":ability_runtime_want_abc_etc", + ":ability_runtime_want_constant_abc_etc", ] } diff --git a/frameworks/ets/ets/utils/AbilityUtils.ets b/frameworks/ets/ets/utils/AbilityUtils.ets new file mode 100644 index 0000000000..573c5d3a20 --- /dev/null +++ b/frameworks/ets/ets/utils/AbilityUtils.ets @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2025 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 hilog from '@ohos.hilog' + +const DOMAIN_ID = 0xD001300; +const TAG = 'AbilityUtils'; +const LEVEL = 100; + +export class AbilityUtils { + public static getClassType(obj: Object): ClassType | undefined { + try { + let type = Type.of(obj); + return type as ClassType; + } catch (err) { + hilog.error(DOMAIN_ID, TAG, `getClassType error: ${err}`); + return undefined; + } + } + + public static isOverride(type: ClassType, methodName: string, stopBaseClassType: ClassType): boolean | undefined { + let currType = type; + let level = 0; + while (!currType.equals(stopBaseClassType)) { + try { + for (let methodIdx = 0; methodIdx < currType.getMethodsNum(); methodIdx++) { + const method = currType.getMethod(methodIdx) + if (method.getName().equals(methodName)) { + if (!method.isInherited()) { + return true; + } + } + } + let baseType = currType.getBaseType(); + if (baseType.equals(currType)) { + hilog.error(DOMAIN_ID, TAG, `isOverride: baseType equals currType (${currType.getName()})`); + return undefined; + } + level++; + if (level >= LEVEL) { + hilog.error(DOMAIN_ID, TAG, `isOverride: inheritance level >= ${LEVEL}, abort`); + return undefined; + } + currType = baseType; + } catch (err) { + hilog.error(DOMAIN_ID, TAG, `isOverride error: ${err}`); + return undefined; + } + } + return false; + } +} From 7b4b6c1c05268b83b8a2e20228a2e86cf6d3aeac Mon Sep 17 00:00:00 2001 From: zhangzezhong Date: Sun, 8 Jun 2025 12:42:30 +0800 Subject: [PATCH 09/23] add CreateEtsLaunchParam Signed-off-by: zhangzezhong --- .../ani/ani_common/src/ani_common_util.cpp | 6 +- .../ani/ani_common/src/ani_common_want.cpp | 4 + .../ets/ani/enum_convert/ani_enum_convert.h | 12 +- .../runtime/ets_data_struct_converter.cpp | 106 ++++++++++++++++++ interfaces/inner_api/runtime/BUILD.gn | 2 + .../include/ets_data_struct_converter.h | 27 +++++ 6 files changed, 148 insertions(+), 9 deletions(-) create mode 100644 frameworks/native/runtime/ets_data_struct_converter.cpp create mode 100644 interfaces/inner_api/runtime/include/ets_data_struct_converter.h diff --git a/frameworks/ets/ani/ani_common/src/ani_common_util.cpp b/frameworks/ets/ani/ani_common/src/ani_common_util.cpp index d909518810..8d2a996100 100644 --- a/frameworks/ets/ani/ani_common/src/ani_common_util.cpp +++ b/frameworks/ets/ani/ani_common/src/ani_common_util.cpp @@ -93,7 +93,7 @@ bool GetFieldBoolByName(ani_env *env, ani_object object, const char *name, bool return false; } ani_boolean isUndefined = true; - if ((status = env->Reference_IsUndefined(object, &isUndefined)) != ANI_OK) { + if ((status = env->Reference_IsUndefined(field, &isUndefined)) != ANI_OK) { TAG_LOGE(AAFwkTag::ANI, "status: %{public}d", status); return false; } @@ -103,7 +103,7 @@ bool GetFieldBoolByName(ani_env *env, ani_object object, const char *name, bool } ani_boolean aniValue = false; if ((status = env->Object_CallMethodByName_Boolean( - reinterpret_cast(object), "booleanValue", nullptr, &aniValue)) != ANI_OK) { + reinterpret_cast(field), "booleanValue", nullptr, &aniValue)) != ANI_OK) { TAG_LOGE(AAFwkTag::ANI, "status: %{public}d", status); return false; } @@ -143,7 +143,7 @@ bool GetFieldStringByName(ani_env *env, ani_object object, const char *name, std return false; } ani_boolean isUndefined = true; - if ((status = env->Reference_IsUndefined(object, &isUndefined)) != ANI_OK) { + if ((status = env->Reference_IsUndefined(field, &isUndefined)) != ANI_OK) { TAG_LOGE(AAFwkTag::ANI, "status: %{public}d", status); return false; } diff --git a/frameworks/ets/ani/ani_common/src/ani_common_want.cpp b/frameworks/ets/ani/ani_common/src/ani_common_want.cpp index 0f6f8ad80c..0fcacfbf24 100644 --- a/frameworks/ets/ani/ani_common/src/ani_common_want.cpp +++ b/frameworks/ets/ani/ani_common/src/ani_common_want.cpp @@ -61,6 +61,10 @@ bool InnerUnwrapWantParams(ani_env* env, ani_object wantObject, AAFwk::WantParam ani_object WrapWant(ani_env *env, const AAFwk::Want &want) { TAG_LOGD(AAFwkTag::ANI, "WrapWant called"); + if (env == nullptr) { + TAG_LOGE(AAFwkTag::ANI, "null env"); + return nullptr; + } ani_class cls = nullptr; ani_status status = ANI_ERROR; ani_method method = nullptr; diff --git a/frameworks/ets/ani/enum_convert/ani_enum_convert.h b/frameworks/ets/ani/enum_convert/ani_enum_convert.h index 6234c8bc88..a61bbe0b3d 100644 --- a/frameworks/ets/ani/enum_convert/ani_enum_convert.h +++ b/frameworks/ets/ani/enum_convert/ani_enum_convert.h @@ -47,7 +47,7 @@ static bool EnumConvert_EtsToNative(ani_env *env, ani_enum_item enumItem, T &res ani_int intValue{}; status = env->EnumItem_GetValue_Int(enumItem, &intValue); if (ANI_OK != status) { - TAG_LOGE(AAFwkTag::EtsRUNTIME, "EnumConvert_EtsToNative failed, status : %{public}d", status); + TAG_LOGE(AAFwkTag::ETSRUNTIME, "EnumConvert_EtsToNative failed, status : %{public}d", status); return false; } result = static_cast(intValue); @@ -56,12 +56,12 @@ static bool EnumConvert_EtsToNative(ani_env *env, ani_enum_item enumItem, T &res ani_string strValue{}; status = env->EnumItem_GetValue_String(enumItem, &strValue); if (ANI_OK != status) { - TAG_LOGE(AAFwkTag::EtsRUNTIME, "EnumItem_GetValue_String failed, status : %{public}d", status); + TAG_LOGE(AAFwkTag::ETSRUNTIME, "EnumItem_GetValue_String failed, status : %{public}d", status); return false; } return GetStdString(env, strValue, result); } else { - TAG_LOGE(AAFwkTag::EtsRUNTIME, "Enum convert failed: type not supported"); + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Enum convert failed: type not supported"); return false; } } @@ -78,7 +78,7 @@ static bool EnumConvert_NativeToEts(ani_env *env, const char *enumName, const T ani_enum aniEnum{}; ani_status status = env->FindEnum(enumName, &aniEnum); if (ANI_OK != status) { - TAG_LOGE(AAFwkTag::EtsRUNTIME, "Enum convert FindEnum failed: %{public}s status: %{public}d", enumName, status); + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Enum convert FindEnum failed: %{public}s status: %{public}d", enumName, status); return false; } constexpr int32_t loopMaxNum = 1000; @@ -86,7 +86,7 @@ static bool EnumConvert_NativeToEts(ani_env *env, const char *enumName, const T ani_enum_item enumItem{}; status = env->Enum_GetEnumItemByIndex(aniEnum, index, &enumItem); if (ANI_OK != status) { - TAG_LOGE(AAFwkTag::EtsRUNTIME, + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Enum convert Enum_GetEnumItemByIndex failed: enumName:%{public}s index:%{public}d status:%{public}d", enumName, index, status); return false; @@ -98,7 +98,7 @@ static bool EnumConvert_NativeToEts(ani_env *env, const char *enumName, const T return true; } } - TAG_LOGE(AAFwkTag::EtsRUNTIME, "EnumConvert_NativeToEts failed enumName: %{public}s", enumName); + TAG_LOGE(AAFwkTag::ETSRUNTIME, "EnumConvert_NativeToEts failed enumName: %{public}s", enumName); return false; } } diff --git a/frameworks/native/runtime/ets_data_struct_converter.cpp b/frameworks/native/runtime/ets_data_struct_converter.cpp new file mode 100644 index 0000000000..a3bf58cd7a --- /dev/null +++ b/frameworks/native/runtime/ets_data_struct_converter.cpp @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2025 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 "ets_data_struct_converter.h" + +#include "ani_enum_convert.h" +#include "hilog_tag_wrapper.h" + +namespace OHOS { +namespace AbilityRuntime { +namespace { +constexpr const char *CLASSNAME_LAUNCHPARAM = "L@ohos/app/ability/AbilityConstant/LaunchParamImpl"; +constexpr const char *CLASSNAME_LAUNCHREASON = "L@ohos/app/ability/AbilityConstant/AbilityConstant/LaunchReason;"; +constexpr const char *CLASSNAME_LAST_EXITREASION = "L@ohos/app/ability/AbilityConstant/AbilityConstant/LastExitReason"; + +ani_string GetAniString(ani_env *env, const std::string &str) +{ + if (env == nullptr) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "null env"); + return nullptr; + } + ani_string aniStr = nullptr; + ani_status status = env->String_NewUTF8(str.c_str(), str.size(), &aniStr); + if (status != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Failed to getAniString, status : %{public}d", status); + return nullptr; + } + return aniStr; +} + +bool WrapLaunchParamInner(ani_env *env, const AAFwk::LaunchParam &launchParam, ani_object &object) +{ + ani_status status = ANI_ERROR; + ani_enum_item launchReasonItem {}; + OHOS::AAFwk::AniEnumConvertUtil::EnumConvert_NativeToEts( + env, CLASSNAME_LAUNCHREASON, launchParam.launchReason, launchReasonItem); + if ((status = env->Object_SetPropertyByName_Ref(object, "launchReason", launchReasonItem)) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Failed to set launchReason"); + return false; + } + + ani_enum_item lastExitReasonItem {}; + OHOS::AAFwk::AniEnumConvertUtil::EnumConvert_NativeToEts( + env, CLASSNAME_LAST_EXITREASION, launchParam.lastExitReason, lastExitReasonItem); + if ((status = env->Object_SetPropertyByName_Ref(object, "lastExitReason", lastExitReasonItem)) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Failed to set lastExitReason"); + return false; + } + return true; +} +} // namespace + +bool WrapLaunchParam(ani_env *env, const AAFwk::LaunchParam &launchParam, ani_object &object) +{ + ani_method method = nullptr; + ani_status status = ANI_ERROR; + ani_class cls = nullptr; + if (env == nullptr) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "null env"); + return false; + } + if ((status = env->FindClass(CLASSNAME_LAUNCHPARAM, &cls)) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Failed to find lanchParam Class, status : %{public}d", status); + return false; + } + if (cls == nullptr) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "null cls"); + return false; + } + if ((status = env->Class_FindMethod(cls, "", ":V", &method)) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Failed to find method, status : %{public}d", status); + return false; + } + if (method == nullptr) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "null method"); + return false; + } + if ((status = env->Object_New(cls, method, &object)) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Failed to create object, status : %{public}d", status); + return false; + } + if (object == nullptr) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "null object"); + return false; + } + if ((status = env->Object_SetPropertyByName_Ref( + object, "lastExitMessage", GetAniString(env, launchParam.lastExitMessage))) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Failed to set lastExitMessage"); + return false; + } + return WrapLaunchParamInner(env, launchParam, object); +} +} // namespace AbilityRuntime +} // namespace OHOS diff --git a/interfaces/inner_api/runtime/BUILD.gn b/interfaces/inner_api/runtime/BUILD.gn index 836d126b83..ace9ee9c4f 100644 --- a/interfaces/inner_api/runtime/BUILD.gn +++ b/interfaces/inner_api/runtime/BUILD.gn @@ -60,6 +60,7 @@ ohos_shared_library("runtime") { sources = [ "${ability_runtime_native_path}/appkit/ability_bundle_manager_helper/bundle_mgr_helper.cpp", + "${ability_runtime_native_path}/runtime/ets_data_struct_converter.cpp", "${ability_runtime_native_path}/runtime/hdc_register.cpp", "${ability_runtime_native_path}/runtime/js_app_process_state.cpp", "${ability_runtime_native_path}/runtime/js_data_struct_converter.cpp", @@ -122,6 +123,7 @@ ohos_shared_library("runtime") { "jsoncpp:jsoncpp", "napi:ace_napi", "resource_management:global_resmgr", + "runtime_core:ani", "samgr:samgr_proxy", "zlib:shared_libz", "faultloggerd:libfaultloggerd", diff --git a/interfaces/inner_api/runtime/include/ets_data_struct_converter.h b/interfaces/inner_api/runtime/include/ets_data_struct_converter.h new file mode 100644 index 0000000000..1f19676818 --- /dev/null +++ b/interfaces/inner_api/runtime/include/ets_data_struct_converter.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2025 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 OHOS_ABILITY_RUNTIME_ETS_DATA_STRUCT_CONVERTER_H +#define OHOS_ABILITY_RUNTIME_ETS_DATA_STRUCT_CONVERTER_H + +#include "ani.h" +#include "launch_param.h" + +namespace OHOS { +namespace AbilityRuntime { +bool WrapLaunchParam(ani_env *env, const AAFwk::LaunchParam &launchParam, ani_object &object); +} // namespace AbilityRuntime +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_ETS_DATA_STRUCT_CONVERTER_H From 8336ffafd9b5d32a74d714471999ec798113dae5 Mon Sep 17 00:00:00 2001 From: zhangzezhong Date: Mon, 9 Jun 2025 11:36:16 +0800 Subject: [PATCH 10/23] =?UTF-8?q?ips=20=E7=8B=AC=E7=AB=8B=E7=BC=96?= =?UTF-8?q?=E8=AF=91=E6=8A=A5=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: zhangzezhong --- frameworks/ets/ani/ani_common/BUILD.gn | 1 + 1 file changed, 1 insertion(+) diff --git a/frameworks/ets/ani/ani_common/BUILD.gn b/frameworks/ets/ani/ani_common/BUILD.gn index aecd68ca12..2d67c749d7 100644 --- a/frameworks/ets/ani/ani_common/BUILD.gn +++ b/frameworks/ets/ani/ani_common/BUILD.gn @@ -68,6 +68,7 @@ ohos_shared_library("ani_common") { "eventhandler:libeventhandler", "hilog:libhilog", "ipc:ipc_core", + "ipc:ipc_napi", "json:nlohmann_json_static", "napi:ace_napi", "runtime_core:ani", From 532783d6d6644bc1e0286c7f2fa50e6960d1450c Mon Sep 17 00:00:00 2001 From: zhangzezhong Date: Mon, 9 Jun 2025 14:24:32 +0800 Subject: [PATCH 11/23] add ets environment Signed-off-by: zhangzezhong --- bundle.json | 11 + ets_environment/ets_environment.gni | 14 + .../frameworks/ets_environment/BUILD.gn | 63 ++++ .../ets_environment/src/dynamic_loader.cpp | 194 ++++++++++ .../ets_environment/src/ets_environment.cpp | 356 ++++++++++++++++++ .../interfaces/inner_api/dynamic_loader.h | 31 ++ .../interfaces/inner_api/ets_environment.h | 72 ++++ .../inner_api/ets_exception_callback.h | 34 ++ ets_environment/test/unittest/BUILD.gn | 21 ++ .../unittest/ets_environment_test/BUILD.gn | 60 +++ .../ets_environment_test.cpp | 104 +++++ 11 files changed, 960 insertions(+) create mode 100644 ets_environment/ets_environment.gni create mode 100644 ets_environment/frameworks/ets_environment/BUILD.gn create mode 100644 ets_environment/frameworks/ets_environment/src/dynamic_loader.cpp create mode 100644 ets_environment/frameworks/ets_environment/src/ets_environment.cpp create mode 100644 ets_environment/interfaces/inner_api/dynamic_loader.h create mode 100644 ets_environment/interfaces/inner_api/ets_environment.h create mode 100644 ets_environment/interfaces/inner_api/ets_exception_callback.h create mode 100644 ets_environment/test/unittest/BUILD.gn create mode 100644 ets_environment/test/unittest/ets_environment_test/BUILD.gn create mode 100644 ets_environment/test/unittest/ets_environment_test/ets_environment_test.cpp diff --git a/bundle.json b/bundle.json index 38fc7eb4e9..056e37abc1 100644 --- a/bundle.json +++ b/bundle.json @@ -130,6 +130,7 @@ "//foundation/ability/ability_runtime/frameworks/cj:cj_ability_packages", "//foundation/ability/ability_runtime/frameworks/js/napi:napi_packages", "//foundation/ability/ability_runtime/cj_environment/frameworks/cj_environment:cj_environment", + "//foundation/ability/ability_runtime/ets_environment/frameworks/ets_environment:ets_environment", "//foundation/ability/ability_runtime/js_environment/frameworks/js_environment:js_environment", "//foundation/ability/ability_runtime/services/abilitymgr/etc:appfwk_etc", "//foundation/ability/ability_runtime/services/dialog_ui/ams_system_dialog:dialog_hap", @@ -249,6 +250,15 @@ }, "name": "//foundation/ability/ability_runtime/js_environment/frameworks/js_environment:js_environment" }, + { + "header": { + "header_base": "//foundation/ability/ability_runtime/ets_environment/interfaces/inner_api", + "header_files": [ + "ets_environment.h" + ] + }, + "name": "//foundation/ability/ability_runtime/ets_environment/frameworks/ets_environment:ets_environment" + }, { "header": { "header_base": "//foundation/ability/ability_runtime/cj_environment/interfaces/inner_api", @@ -655,6 +665,7 @@ "//foundation/ability/ability_runtime/tools/test:systemtest", "//foundation/ability/ability_runtime/tools/test:unittest", "//foundation/ability/ability_runtime/cj_environment/test/unittest:unittest", + "//foundation/ability/ability_runtime/ets_environment/test/unittest:unittest", "//foundation/ability/ability_runtime/js_environment/test/unittest:unittest", "//foundation/ability/ability_runtime/service_router_framework:test_target" ] diff --git a/ets_environment/ets_environment.gni b/ets_environment/ets_environment.gni new file mode 100644 index 0000000000..b044edbd9d --- /dev/null +++ b/ets_environment/ets_environment.gni @@ -0,0 +1,14 @@ +# Copyright (c) 2025 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. + +base_path = "//foundation/ability/ability_runtime/ets_environment" diff --git a/ets_environment/frameworks/ets_environment/BUILD.gn b/ets_environment/frameworks/ets_environment/BUILD.gn new file mode 100644 index 0000000000..a3f1835114 --- /dev/null +++ b/ets_environment/frameworks/ets_environment/BUILD.gn @@ -0,0 +1,63 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/ability/ability_runtime/ability_runtime.gni") +import("../../ets_environment.gni") + +config("public_ets_environment_config") { + include_dirs = [ + "include", + "${ability_runtime_path}/ets_environment/interfaces/inner_api", + "${ability_runtime_path}/interfaces/inner_api", + "${ability_runtime_services_path}/common/include", + ] +} + +ohos_shared_library("ets_environment") { + branch_protector_ret = "pac_ret" + + public_configs = [ ":public_ets_environment_config" ] + + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + + sources = [ + "src/dynamic_loader.cpp", + "src/ets_environment.cpp", + ] + + defines = [] + + external_deps = [ + "c_utils:utils", + "eventhandler:libeventhandler", + "faultloggerd:libunwinder", + "hilog:libhilog", + "json:nlohmann_json_static", + "napi:ace_napi", + "runtime_core:ani", + ] + + if (ability_runtime_graphics) { + defines = [ "SUPPORT_GRAPHICS" ] + external_deps += [ "ace_engine:ace_uicontent" ] + } + + subsystem_name = "ability" + innerapi_tags = [ "platformsdk_indirect" ] + part_name = "ability_runtime" +} diff --git a/ets_environment/frameworks/ets_environment/src/dynamic_loader.cpp b/ets_environment/frameworks/ets_environment/src/dynamic_loader.cpp new file mode 100644 index 0000000000..6b29349374 --- /dev/null +++ b/ets_environment/frameworks/ets_environment/src/dynamic_loader.cpp @@ -0,0 +1,194 @@ +/* + * Copyright (c) 2025 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 "dynamic_loader.h" + +#include +#include +#include +#include +#include + +#include "hilog_tag_wrapper.h" + +namespace OHOS { +namespace EtsEnv { +namespace { +constexpr int32_t ERROR_BUF_SIZE = 255; +static char g_dlError[ERROR_BUF_SIZE]; +static std::unordered_set g_hasInited; +static std::string g_sharedLibsSonames = ""; +constexpr int32_t OUT_OF_MEMORY = 12; +constexpr int32_t FILE_EXISTS = 17; +constexpr int32_t INVALID_ARGUMENT = 22; + +static void ReadDlError() +{ + char *errMsg = dlerror(); + if (!errMsg) { + return; + } + auto ends = sprintf_s(g_dlError, sizeof(g_dlError), "%s", errMsg); + if (ends >= ERROR_BUF_SIZE) { + g_dlError[ERROR_BUF_SIZE - 1] = '\0'; + } else { + g_dlError[ends] = '\0'; + } +} + +static void InitSharedLibsSonames() +{ + if (!g_sharedLibsSonames.empty()) { + return; + } + g_sharedLibsSonames = + // bionic library + "libc.so:" + "libdl.so:" + "libm.so:" + "libz.so:" + "libclang_rt.asan.so:" + "libclang_rt.tsan.so:" + // z library + "libace_napi.z.so:" + "libace_ndk.z.so:" + "libbundle_ndk.z.so:" + "libdeviceinfo_ndk.z.so:" + "libEGL.so:" + "libGLESv3.so:" + "libhiappevent_ndk.z.so:" + "libhuks_ndk.z.so:" + "libhukssdk.z.so:" + "libnative_drawing.so:" + "libnative_window.so:" + "libnative_buffer.so:" + "libnative_vsync.so:" + "libOpenSLES.so:" + "libpixelmap_ndk.z.so:" + "libimage_ndk.z.so:" + "libimage_receiver_ndk.z.so:" + "libimage_source_ndk.z.so:" + "librawfile.z.so:" + "libuv.so:" + "libhilog.so:" + "libnative_image.so:" + "libnative_media_adec.so:" + "libnative_media_aenc.so:" + "libnative_media_codecbase.so:" + "libnative_media_core.so:" + "libnative_media_vdec.so:" + "libnative_media_venc.so:" + "libnative_media_avmuxer.so:" + "libnative_media_avdemuxer.so:" + "libnative_media_avsource.so:" + "libnative_avscreen_capture.so:" + "libavplayer.so:" + // adaptor library + "libohosadaptor.so:" + "libusb_ndk.z.so:" + "libvulkan.so:" + // runtime library + "libarkaotmanager.so:" + "libarktarget_options.so:" + "libhmicui18n.z.so:" + "libes2panda-public.so:" + "libes2panda-lib.so:" + "libhmicuuc.z.so:" + "libarkcompiler.so:" + "libarkassembler.so:" + "libarkfile.so:" + "libarkziparchive.so:" + "libarkbase.so:" + "libc_secshared.so:" + "libhilog_ndk.z.so:" + "libarkplatform.so"; +} +} // namespace + +void DynamicInitNamespace(Dl_namespace *ns, void *parent, const char *entries, const char *name) +{ + if (ns == nullptr || entries == nullptr || name == nullptr) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Invaild args for init namespace."); + return; + } + if (g_hasInited.count(std::string(name))) { + return; + } + dlns_init(ns, name); + auto status = dlns_create2(ns, entries, 0); + std::string errMsg; + if (status != 0) { + switch (status) { + case FILE_EXISTS: + errMsg = "dlns_create failed: File exists"; + break; + case INVALID_ARGUMENT: + errMsg = "dlns_create failed: Invalid argument"; + break; + case OUT_OF_MEMORY: + errMsg = "dlns_create failed: Out of memory"; + break; + default: + errMsg = "dlns_create failed, status: " + std::to_string(status); + } + if (sprintf_s(g_dlError, sizeof(g_dlError), errMsg.c_str()) == -1) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Fail to generate error msg."); + return; + } + return; + } + if (parent) { + dlns_inherit((Dl_namespace *)parent, ns, "allow_all_shared_libs"); + } + Dl_namespace current; + dlns_get(nullptr, ¤t); + if (strcmp(name, "ets_app") != 0) { + dlns_inherit(ns, ¤t, "allow_all_shared_libs"); + } else { + InitSharedLibsSonames(); + dlns_inherit(ns, ¤t, g_sharedLibsSonames.c_str()); + } + g_hasInited.insert(std::string(name)); +} + +void *DynamicLoadLibrary(Dl_namespace *ns, const char *dlPath, uint32_t mode) +{ + if (ns == nullptr) { + dlns_get("ets_app", ns); + } + + auto result = dlopen_ns(ns, dlPath, mode | RTLD_GLOBAL | RTLD_NOW); + if (!result) { + ReadDlError(); + } + return result; +} + +void *DynamicFindSymbol(void *so, const char *symbol) +{ + return dlsym(so, symbol); +} + +void DynamicFreeLibrary(void *so) +{ + (void)dlclose(so); +} + +const char *DynamicGetError() +{ + return g_dlError; +} +} // namespace EtsEnv +} // namespace OHOS \ No newline at end of file diff --git a/ets_environment/frameworks/ets_environment/src/ets_environment.cpp b/ets_environment/frameworks/ets_environment/src/ets_environment.cpp new file mode 100644 index 0000000000..ef09b6afd0 --- /dev/null +++ b/ets_environment/frameworks/ets_environment/src/ets_environment.cpp @@ -0,0 +1,356 @@ +/* + * Copyright (c) 2025 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 "ets_environment.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "dynamic_loader.h" +#include "elf_factory.h" +#include "event_handler.h" +#include "hilog_tag_wrapper.h" +#include "unwinder.h" + +#ifdef SUPPORT_GRAPHICS +#include "ui_content.h" +#endif // SUPPORT_GRAPHICS + +namespace OHOS { +namespace EtsEnv { +namespace { +const char ETS_CREATE_VM[] = "ANI_CreateVM"; +const char ETS_ANI_GET_CREATEDVMS[] = "ANI_GetCreatedVMs"; +const char ETS_LIB_PATH[] = "libets_interop_js_napi.z.so"; +const char BOOT_PATH[] = "/system/framework/bootpath.json"; +const char BACKTRACE[] = "=====================Backtrace========================"; + +using CreateVMETSRuntimeType = ani_status (*)(const ani_options *options, uint32_t version, ani_vm **result); +using ANIGetCreatedVMsType = ani_status (*)(ani_vm **vms_buffer, ani_size vms_buffer_length, ani_size *result); + +const char ETS_SDK_NSNAME[] = "ets_sdk"; +const char ETS_SYS_NSNAME[] = "ets_system"; +} // namespace + +ETSRuntimeAPI ETSEnvironment::lazyApis_ {}; + +bool ETSEnvironment::LoadBootPathFile(std::string &bootfiles) +{ + std::ifstream inFile; + inFile.open(BOOT_PATH, std::ios::in); + if (!inFile.is_open()) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "read json error"); + return false; + } + nlohmann::json jsonObject = nlohmann::json::parse(inFile); + if (jsonObject.is_discarded()) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "json discarded error"); + inFile.close(); + return false; + } + + if (jsonObject.is_null() || jsonObject.empty()) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "invalid json"); + inFile.close(); + return false; + } + + for (const auto &[key, value] : jsonObject.items()) { + if (!value.is_null() && value.is_string()) { + std::string jsonValue = value.get(); + if (jsonValue.empty()) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "json value of %{public}s is empty", key.c_str()); + continue; + } + if (!bootfiles.empty()) { + bootfiles += ":"; + } + bootfiles += jsonValue.c_str(); + } + } + inFile.close(); + return true; +} + +bool ETSEnvironment::LoadRuntimeApis() +{ + static bool isRuntimeApiLoaded { false }; + if (isRuntimeApiLoaded) { + return true; + } + + Dl_namespace ns; + dlns_get(ETS_SDK_NSNAME, &ns); + auto dso = DynamicLoadLibrary(&ns, ETS_LIB_PATH, 1); + if (!dso) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "load library failed: %{public}s", ETS_LIB_PATH); + return false; + } + + if (!LoadSymbolCreateVM(dso, lazyApis_) || + !LoadSymbolANIGetCreatedVMs(dso, lazyApis_)) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "load symbol failed"); + return false; + } + + isRuntimeApiLoaded = true; + return true; +} + +std::string ETSEnvironment::GetBuildId(std::string stack) +{ + std::stringstream ss(stack); + std::string tempStr = ""; + std::string addBuildId = ""; + int i = 0; + while (std::getline(ss, tempStr)) { + auto spitlPos = tempStr.rfind(" "); + if (spitlPos != std::string::npos) { + HiviewDFX::RegularElfFactory elfFactory(tempStr.substr(spitlPos + 1)); + auto elfFile = elfFactory.Create(); + if (elfFile == nullptr) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "null elfFile"); + break; + } + std::string buildId = elfFile->GetBuildId(); + if (i != 0 && !buildId.empty()) { + addBuildId += tempStr + "(" + buildId + ")" + "\n"; + } else { + addBuildId += tempStr + "\n"; + } + } + i++; + } + return addBuildId; +} + +void ETSEnvironment::RegisterUncaughtExceptionHandler(const ETSUncaughtExceptionInfo &handle) +{ + TAG_LOGD(AAFwkTag::ETSRUNTIME, "RegisterUncaughtExceptionHandler called"); + uncaughtExceptionInfo_ = handle; +} + +bool ETSEnvironment::LoadSymbolCreateVM(void *handle, ETSRuntimeAPI &apis) +{ + auto symbol = dlsym(handle, ETS_CREATE_VM); + if (symbol == nullptr) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "runtime api not found: %{public}s", ETS_CREATE_VM); + return false; + } + apis.ANI_CreateVM = reinterpret_cast(symbol); + + return true; +} + +bool ETSEnvironment::LoadSymbolANIGetCreatedVMs(void *handle, ETSRuntimeAPI &apis) +{ + auto symbol = dlsym(handle, ETS_ANI_GET_CREATEDVMS); + if (symbol == nullptr) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "runtime api not found: %{public}s", ETS_ANI_GET_CREATEDVMS); + return false; + } + apis.ANI_GetCreatedVMs = reinterpret_cast(symbol); + + return true; +} + +void ETSEnvironment::InitETSSDKNS(const std::string &path) +{ + TAG_LOGD(AAFwkTag::ETSRUNTIME, "InitETSSDKNS: %{public}s", path.c_str()); + Dl_namespace ndk; + Dl_namespace ns; + DynamicInitNamespace(&ns, nullptr, path.c_str(), ETS_SDK_NSNAME); + dlns_get("ndk", &ndk); + dlns_inherit(&ns, &ndk, "allow_all_shared_libs"); +} + +void ETSEnvironment::InitETSSysNS(const std::string &path) +{ + TAG_LOGD(AAFwkTag::ETSRUNTIME, "InitETSSysNS: %{public}s", path.c_str()); + Dl_namespace ets_sdk; + Dl_namespace ndk; + Dl_namespace ns; + dlns_get(ETS_SDK_NSNAME, &ets_sdk); + DynamicInitNamespace(&ns, &ets_sdk, path.c_str(), ETS_SYS_NSNAME); + dlns_get("ndk", &ndk); + dlns_inherit(&ns, &ndk, "allow_all_shared_libs"); +} + +bool ETSEnvironment::Initialize(napi_env napiEnv, std::vector &options) +{ + TAG_LOGD(AAFwkTag::ETSRUNTIME, "StartRuntime called"); + if (!LoadRuntimeApis()) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "LoadRuntimeApis failed"); + return false; + } + std::string bootfiles; + if (!LoadBootPathFile(bootfiles)) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "LoadBootPathFile failed"); + return false; + } + const std::string optionPrefix = "--ext:"; + // Create boot-panda-files options + std::string bootString = optionPrefix + "--boot-panda-files=" + bootfiles; + TAG_LOGI(AAFwkTag::ETSRUNTIME, "bootString %{public}s", bootString.c_str()); + options.push_back(ani_option { bootString.c_str(), nullptr }); + std::string schedulingExternal = optionPrefix + "--coroutine-enable-external-scheduling=true"; + ani_option schedulingExternalOption = { schedulingExternal.data(), nullptr }; + options.push_back(schedulingExternalOption); + + std::string forbiddenJIT = optionPrefix + "--compiler-enable-jit=false"; + ani_option forbiddenJITOption = { forbiddenJIT.data(), nullptr }; + options.push_back(forbiddenJITOption); + options.push_back(ani_option { "--ext:--log-level=info", nullptr }); + std::string enableVerfication = optionPrefix + "--verification-enabled=true"; + ani_option enableVerficationOption = { enableVerfication.data(), nullptr }; + options.push_back(enableVerficationOption); + + std::string verificationMode = optionPrefix + "--verification-mode=on-the-fly"; + ani_option verificationModeOption = { verificationMode.data(), nullptr }; + options.push_back(verificationModeOption); + + std::string interop = optionPrefix + "interop"; + ani_option interopOption = { interop.data(), (void *)napiEnv }; + options.push_back(interopOption); + ani_options optionsPtr = { options.size(), options.data() }; + ani_status status = ANI_ERROR; + if ((status = lazyApis_.ANI_CreateVM(&optionsPtr, ANI_VERSION_1, &vmEntry_.aniVm_)) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "ANI_CreateVM failed %{public}d", status); + return false; + } + if ((status = vmEntry_.aniVm_->GetEnv(ANI_VERSION_1, &vmEntry_.aniEnv_)) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "GetEnv failed %{public}d", status); + return false; + } + return true; +} + +ani_env *ETSEnvironment::GetAniEnv() +{ + return vmEntry_.aniEnv_; +} + +void ETSEnvironment::HandleUncaughtError() +{ + TAG_LOGD(AAFwkTag::ETSRUNTIME, "HandleUncaughtError called"); + const EtsEnv::ETSErrorObject errorObj = GetETSErrorObject(); + std::string errorStack = errorObj.stack; + if (errorStack.empty()) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "errorStack is empty"); + return; + } + TAG_LOGE(AAFwkTag::ETSRUNTIME, "errorObj.name:%{public}s, errorObj.message:%{public}s,errorObj.stack:%{public}s", + errorObj.name.c_str(), errorObj.message.c_str(), errorObj.stack.c_str()); + std::string summary = "Error name:" + errorObj.name + "\n"; + summary += "Error message:" + errorObj.message + "\n"; + if (errorStack.find(BACKTRACE) != std::string::npos) { + summary += "Stacktrace:\n" + GetBuildId(errorStack); + } else { + summary += "Stacktrace:\n" + errorStack; + } +#ifdef SUPPORT_GRAPHICS + std::string str = Ace::UIContent::GetCurrentUIStackInfo(); + if (!str.empty()) { + summary.append(str); + } +#endif // SUPPORT_GRAPHICS + if (uncaughtExceptionInfo_.uncaughtTask) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "uncaughtTask called"); + uncaughtExceptionInfo_.uncaughtTask(summary, errorObj); + } +} + +EtsEnv::ETSErrorObject ETSEnvironment::GetETSErrorObject() +{ + TAG_LOGD(AAFwkTag::ETSRUNTIME, "GetETSErrorObject called"); + ani_boolean errorExists = ANI_FALSE; + ani_status status = ANI_ERROR; + auto aniEnv = GetAniEnv(); + if (aniEnv == nullptr) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "null env"); + return EtsEnv::ETSErrorObject(); + } + if ((status = aniEnv->ExistUnhandledError(&errorExists)) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "ExistUnhandledError failed, status : %{public}d", status); + return EtsEnv::ETSErrorObject(); + } + if (errorExists == ANI_FALSE) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "not exist error"); + return EtsEnv::ETSErrorObject(); + } + ani_error aniError = nullptr; + if ((status = aniEnv->GetUnhandledError(&aniError)) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "GetUnhandledError failed, status : %{public}d", status); + return EtsEnv::ETSErrorObject(); + } + if ((status = aniEnv->ResetError()) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "ResetError failed, status : %{public}d", status); + return EtsEnv::ETSErrorObject(); + } + std::string errorMsg = GetErrorProperty(aniError, "message"); + std::string errorName = GetErrorProperty(aniError, "name"); + std::string errorStack = GetErrorProperty(aniError, "stack"); + const EtsEnv::ETSErrorObject errorObj = { + .name = errorName, + .message = errorMsg, + .stack = errorStack + }; + return errorObj; +} + +std::string ETSEnvironment::GetErrorProperty(ani_error aniError, const char *property) +{ + TAG_LOGD(AAFwkTag::ETSRUNTIME, "GetErrorProperty called"); + auto aniEnv = GetAniEnv(); + std::string propertyValue; + ani_status status = ANI_ERROR; + ani_type errorType = nullptr; + if ((status = aniEnv->Object_GetType(aniError, &errorType)) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Object_GetType failed, status : %{public}d", status); + return propertyValue; + } + ani_method getterMethod = nullptr; + if ((status = aniEnv->Class_FindGetter(static_cast(errorType), property, &getterMethod)) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Class_FindGetter failed, status : %{public}d", status); + return propertyValue; + } + ani_ref aniRef = nullptr; + if ((status = aniEnv->Object_CallMethod_Ref(aniError, getterMethod, &aniRef)) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Object_CallMethod_Ref failed, status : %{public}d", status); + return propertyValue; + } + ani_string aniString = reinterpret_cast(aniRef); + ani_size sz {}; + if ((status = aniEnv->String_GetUTF8Size(aniString, &sz)) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "String_GetUTF8Size failed, status : %{public}d", status); + return propertyValue; + } + propertyValue.resize(sz + 1); + if ((status = aniEnv->String_GetUTF8SubString( + aniString, 0, sz, propertyValue.data(), propertyValue.size(), &sz))!= ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "String_GetUTF8SubString failed, status : %{public}d", status); + return propertyValue; + } + propertyValue.resize(sz); + return propertyValue; +} +} // namespace EtsEnv +} // namespace OHOS diff --git a/ets_environment/interfaces/inner_api/dynamic_loader.h b/ets_environment/interfaces/inner_api/dynamic_loader.h new file mode 100644 index 0000000000..6155e797e8 --- /dev/null +++ b/ets_environment/interfaces/inner_api/dynamic_loader.h @@ -0,0 +1,31 @@ +/* +* Copyright (c) 2025 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 OHOS_ABILITY_RUNTIME_DYNAMIC_LOADER_H +#define OHOS_ABILITY_RUNTIME_DYNAMIC_LOADER_H + +#include +#include + +namespace OHOS { +namespace EtsEnv { +void *DynamicLoadLibrary(Dl_namespace *ns, const char *dlPath, uint32_t mode); +void *DynamicFindSymbol(void *so, const char *symbol); +const char *DynamicGetError(); +void DynamicFreeLibrary(void *so); +void DynamicInitNamespace(Dl_namespace *ns, void *parent, const char *entries, const char *name); +} // namespace EtsEnv +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_DYNAMIC_LOADER_H diff --git a/ets_environment/interfaces/inner_api/ets_environment.h b/ets_environment/interfaces/inner_api/ets_environment.h new file mode 100644 index 0000000000..2c37be0747 --- /dev/null +++ b/ets_environment/interfaces/inner_api/ets_environment.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2025 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 OHOS_ABILITY_RUNTIME_ETS_ENVIRONMENT_H +#define OHOS_ABILITY_RUNTIME_ETS_ENVIRONMENT_H + +#include +#include +#include +#include + +#include "ani.h" +#include "ets_exception_callback.h" +#include "event_handler.h" +#include "napi/native_api.h" + +namespace OHOS { +namespace EtsEnv { +struct ETSRuntimeAPI { + ani_status (*ANI_GetCreatedVMs)(ani_vm **vms_buffer, ani_size vms_buffer_length, ani_size *result); + ani_status (*ANI_CreateVM)(const ani_options *options, uint32_t version, ani_vm **result); +}; + +class ETSEnvironment final : public std::enable_shared_from_this { +public: + ETSEnvironment() {}; + + static void InitETSSDKNS(const std::string &path); + static void InitETSSysNS(const std::string &path); + + bool Initialize(napi_env napiEnv, std::vector &options); + void RegisterUncaughtExceptionHandler(const ETSUncaughtExceptionInfo &handle); + ani_env *GetAniEnv(); + void HandleUncaughtError(); + + struct VMEntry { + ani_vm *aniVm_; + ani_env *aniEnv_; + VMEntry() + { + aniVm_ = nullptr; + aniEnv_ = nullptr; + } + }; + +private: + bool LoadRuntimeApis(); + bool LoadSymbolCreateVM(void *handle, ETSRuntimeAPI &apis); + bool LoadSymbolANIGetCreatedVMs(void *handle, ETSRuntimeAPI &apis); + bool LoadBootPathFile(std::string &bootfiles); + std::string GetBuildId(std::string stack); + EtsEnv::ETSErrorObject GetETSErrorObject(); + std::string GetErrorProperty(ani_error aniError, const char *property); + static ETSRuntimeAPI lazyApis_; + VMEntry vmEntry_; + ETSUncaughtExceptionInfo uncaughtExceptionInfo_; +}; +} // namespace EtsEnv +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_ETS_ENVIRONMENT_H diff --git a/ets_environment/interfaces/inner_api/ets_exception_callback.h b/ets_environment/interfaces/inner_api/ets_exception_callback.h new file mode 100644 index 0000000000..2d935af7f1 --- /dev/null +++ b/ets_environment/interfaces/inner_api/ets_exception_callback.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2025 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 OHOS_ABILITY_RUNTIME_ETS_EXCEPTION_CALLBACK_H +#define OHOS_ABILITY_RUNTIME_ETS_EXCEPTION_CALLBACK_H + +#include + +namespace OHOS { +namespace EtsEnv { +struct ETSErrorObject { + std::string name; + std::string message; + std::string stack; +}; + +struct ETSUncaughtExceptionInfo { + std::function uncaughtTask; +}; +} // namespace EtsEnv +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_ETS_EXCEPTION_CALLBACK_H diff --git a/ets_environment/test/unittest/BUILD.gn b/ets_environment/test/unittest/BUILD.gn new file mode 100644 index 0000000000..4af24efede --- /dev/null +++ b/ets_environment/test/unittest/BUILD.gn @@ -0,0 +1,21 @@ +# Copyright (c) 2025 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("../../ets_environment.gni") + +group("unittest") { + testonly = true + + deps = [ "ets_environment_test:unittest" ] +} \ No newline at end of file diff --git a/ets_environment/test/unittest/ets_environment_test/BUILD.gn b/ets_environment/test/unittest/ets_environment_test/BUILD.gn new file mode 100644 index 0000000000..3ec707a5a4 --- /dev/null +++ b/ets_environment/test/unittest/ets_environment_test/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2025 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("../../../../ability_runtime.gni") +import("../../../ets_environment.gni") + +module_output_path = "ability_runtime/ets_environment" + +template("ets_environment_test_template") { + ohos_unittest(target_name) { + forward_variables_from(invoker, [ "sources" ]) + module_out_path = module_output_path + + include_dirs = [ + "${ability_runtime_native_path}/runtime", + "${ability_runtime_path}/interfaces/inner_api/runtime/include", + "${ability_runtime_path}/interfaces/inner_api", + "${ability_runtime_path}/ets_environment/interfaces/inner_api", + ] + + configs = [] + + deps = [] + + external_deps = [ + "ability_runtime:runtime", + "ability_runtime:ets_environment", + "c_utils:utils", + "ets_runtime:libark_jsruntime", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "googletest:gmock_main", + "googletest:gtest_main", + "hilog:libhilog", + "napi:ace_napi", + "runtime_core:ani", + ] + } +} + +ets_environment_test_template("ets_environment_basic_test") { + sources = [ "ets_environment_test.cpp" ] +} + +group("unittest") { + testonly = true + + deps = [ ":ets_environment_basic_test" ] +} \ No newline at end of file diff --git a/ets_environment/test/unittest/ets_environment_test/ets_environment_test.cpp b/ets_environment/test/unittest/ets_environment_test/ets_environment_test.cpp new file mode 100644 index 0000000000..2afb45f0f7 --- /dev/null +++ b/ets_environment/test/unittest/ets_environment_test/ets_environment_test.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2025 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 +#include +#include + +#include "runtime.h" +#define private public +#include "ets_environment.h" +#undef private + +using namespace testing; +using namespace testing::ext; +using namespace testing::mt; + +namespace { +bool g_callbackModuleFlag; +} + +namespace OHOS { +namespace EtsEnv { +const std::string TEST_ABILITY_NAME = "ContactsDataAbility"; + +class EtsEnvironmentTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; +}; + +void EtsEnvironmentTest::SetUpTestCase() {} + +void EtsEnvironmentTest::TearDownTestCase() {} + +void EtsEnvironmentTest::SetUp() {} + +void EtsEnvironmentTest::TearDown() {} + +namespace { +void CallBackModuleFunc() +{ + g_callbackModuleFlag = true; +} +} // namespace + +/** + * @tc.name: LoadBootPathFile_0100 + * @tc.desc: LoadBootPathFile. + * @tc.type: FUNC + */ +HWTEST_F(EtsEnvironmentTest, LoadBootPathFile_0100, TestSize.Level0) +{ + auto etsEnv = std::make_shared(); + ASSERT_NE(etsEnv, nullptr); + std::string str = "LoadBootPathFile"; + bool bVal = etsEnv->LoadBootPathFile(str); + EXPECT_EQ(bVal, true); +} +/** + * @tc.name: LoadRuntimeApis_0100 + * @tc.desc: LoadRuntimeApis. + * @tc.type: FUNC + */ +HWTEST_F(EtsEnvironmentTest, LoadRuntimeApis_0100, TestSize.Level0) +{ + auto etsEnv = std::make_shared(); + ASSERT_NE(etsEnv, nullptr); + bool bVal = etsEnv->LoadRuntimeApis(); + EXPECT_EQ(bVal, true); +} + +/** + * @tc.name: GetAniEnv_0100 + * @tc.desc: GetAniEnv. + * @tc.type: FUNC + */ +HWTEST_F(EtsEnvironmentTest, GetAniEnv_0100, TestSize.Level0) +{ + auto etsEnv = std::make_shared(); + ETSEnvironment::VMEntry vMEntryOld = etsEnv->vmEntry_; + ETSEnvironment::VMEntry vmEntry; + vmEntry.aniEnv_ = nullptr; + etsEnv->vmEntry_ = vmEntry; + auto result = etsEnv->GetAniEnv(); + EXPECT_EQ(result, nullptr); + etsEnv->vmEntry_ = vMEntryOld; +} + +} // namespace StsEnv +} // namespace OHOS \ No newline at end of file From a84a2b547d68536d4ce38b675b311421443dda6a Mon Sep 17 00:00:00 2001 From: zhangzezhong Date: Mon, 9 Jun 2025 16:22:50 +0800 Subject: [PATCH 12/23] upd cj NapiSetUIContent Signed-off-by: zhangzezhong --- .../ui_extension_base/cj_ui_extension_content_session.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frameworks/native/ability/native/ui_extension_base/cj_ui_extension_content_session.cpp b/frameworks/native/ability/native/ui_extension_base/cj_ui_extension_content_session.cpp index 84bf007862..67a9c2556d 100644 --- a/frameworks/native/ability/native/ui_extension_base/cj_ui_extension_content_session.cpp +++ b/frameworks/native/ability/native/ui_extension_base/cj_ui_extension_content_session.cpp @@ -62,7 +62,7 @@ int32_t CJUIExtensionContentSession::LoadContent(const std::string& path) uiWindow_->TriggerBindModalUIExtension(); isFirstTriggerBindModal_ = false; } - Rosen::WMError ret = uiWindow_->NapiSetUIContent(path, nullptr, nullptr, + Rosen::WMError ret = uiWindow_->NapiSetUIContent(path, (napi_env)nullptr, nullptr, Rosen::BackupAndRestoreType::NONE, sessionInfo_->parentToken); if (ret != Rosen::WMError::WM_OK) { TAG_LOGE(AAFwkTag::UI_EXT, "NapiSetUIContent failed, ret=%{public}d", ret); From b8569dee165698e1e0dc708ea69109f62fd7820d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=83=AD=E5=85=B4=E6=AD=A6?= <951620110@qq.com> Date: Mon, 9 Jun 2025 08:42:20 +0000 Subject: [PATCH 13/23] =?UTF-8?q?=E4=BD=BF=E8=83=BDerrormanage=20=E6=88=96?= =?UTF-8?q?recovery=E6=97=B6=EF=BC=8C=E6=AD=A3=E7=A1=AE=E8=AE=B0=E5=BD=95l?= =?UTF-8?q?astexitreason?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 郭兴武 <951620110@qq.com> --- frameworks/native/appkit/app/main_thread.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frameworks/native/appkit/app/main_thread.cpp b/frameworks/native/appkit/app/main_thread.cpp index 5d12647990..0e856912f1 100644 --- a/frameworks/native/appkit/app/main_thread.cpp +++ b/frameworks/native/appkit/app/main_thread.cpp @@ -1912,6 +1912,8 @@ void MainThread::InitUncatchableTask(JsEnv::UncatchableTask &uncatchableTask, co ErrorObject appExecErrorObj = { errorObject.name, errorObject.message, errorObject.stack}; auto napiEnv = (static_cast(*appThread->application_->GetRuntime())).GetNapiEnv(); + AAFwk::ExitReason exitReason = { REASON_JS_ERROR, errorObject.name }; + AbilityManagerClient::GetInstance()->RecordAppExitReason(exitReason); if (!isUncatchable && NapiErrorManager::GetInstance()->NotifyUncaughtException(napiEnv, summary, appExecErrorObj.name, appExecErrorObj.message, appExecErrorObj.stack)) { return; @@ -1936,8 +1938,6 @@ void MainThread::InitUncatchableTask(JsEnv::UncatchableTask &uncatchableTask, co TAG_LOGW(AAFwkTag::APPKIT, "hisysevent write result=%{public}d, send event [FRAMEWORK,PROCESS_KILL]," " pid=%{public}d, processName=%{public}s, msg=%{public}s, foreground=%{public}d, isUncatchable=%{public}d", result, pid, processName.c_str(), KILL_REASON, foreground, isUncatchable); - AAFwk::ExitReason exitReason = { REASON_JS_ERROR, errorObject.name }; - AbilityManagerClient::GetInstance()->RecordAppExitReason(exitReason); _exit(JS_ERROR_EXIT); }; } From 7e389a1034557feb9dca16a183ed69b1146dc5e8 Mon Sep 17 00:00:00 2001 From: xiehd Date: Mon, 9 Jun 2025 21:02:55 +0800 Subject: [PATCH 14/23] fix uiextension closeFd Signed-off-by: xiehd --- services/abilitymgr/src/ability_manager_stub.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/services/abilitymgr/src/ability_manager_stub.cpp b/services/abilitymgr/src/ability_manager_stub.cpp index f54aaef502..c51b8bfd8c 100644 --- a/services/abilitymgr/src/ability_manager_stub.cpp +++ b/services/abilitymgr/src/ability_manager_stub.cpp @@ -1130,6 +1130,7 @@ int AbilityManagerStub::TerminateUIExtensionAbilityInner(MessageParcel &data, Me int resultCode = data.ReadInt32(); Want *resultWant = data.ReadParcelable(); int32_t result = TerminateUIExtensionAbility(extensionSessionInfo, resultCode, resultWant); + extensionSessionInfo->want.CloseAllFd(); reply.WriteInt32(result); if (resultWant != nullptr) { delete resultWant; @@ -1183,6 +1184,7 @@ int AbilityManagerStub::MinimizeUIExtensionAbilityInner(MessageParcel &data, Mes } auto fromUser = data.ReadBool(); int32_t result = MinimizeUIExtensionAbility(extensionSessionInfo, fromUser); + extensionSessionInfo->want.CloseAllFd(); reply.WriteInt32(result); return NO_ERROR; } From 968d9f0bee40e9b34b9435bd0b9ed7499e30ab73 Mon Sep 17 00:00:00 2001 From: wangbing Date: Mon, 9 Jun 2025 21:49:59 +0800 Subject: [PATCH 15/23] fix issue Signed-off-by: wangbing --- services/abilitymgr/include/kiosk_manager.h | 2 +- services/abilitymgr/src/kiosk_manager.cpp | 14 +++++++------- .../ability_manager_proxy_fourth_test/BUILD.gn | 1 + .../ability_manager_service_twelfth_test/BUILD.gn | 1 + 4 files changed, 10 insertions(+), 8 deletions(-) diff --git a/services/abilitymgr/include/kiosk_manager.h b/services/abilitymgr/include/kiosk_manager.h index 25b947af56..620498d01f 100644 --- a/services/abilitymgr/include/kiosk_manager.h +++ b/services/abilitymgr/include/kiosk_manager.h @@ -42,7 +42,7 @@ public: private: KioskManager() = default; DISALLOW_COPY_AND_MOVE(KioskManager); - int32_t ExitKioskModeInner(const std::string &bundleName, sptr callerToken = nullptr); + int32_t ExitKioskModeInner(const std::string &bundleName, sptr callerToken); bool IsInKioskModeInner(); void NotifyKioskModeChanged(bool isInKioskMode); bool IsInWhiteListInner(const std::string &bundleName); diff --git a/services/abilitymgr/src/kiosk_manager.cpp b/services/abilitymgr/src/kiosk_manager.cpp index 8d3527ab90..d373ba9b8b 100644 --- a/services/abilitymgr/src/kiosk_manager.cpp +++ b/services/abilitymgr/src/kiosk_manager.cpp @@ -47,7 +47,7 @@ void KioskManager::OnAppStop(const AppInfo &info) } std::lock_guard lock(kioskManagermutex_); if (IsInKioskModeInner() && IsInWhiteListInner(info.bundleName)) { - ExitKioskModeInner(info.bundleName); + ExitKioskModeInner(info.bundleName, nullptr); } } @@ -67,7 +67,7 @@ int32_t KioskManager::UpdateKioskApplicationList(const std::vector if (IsInKioskModeInner()) { auto it = std::find(appList.begin(), appList.end(), kioskStatus_.kioskBundleName_); if (it == appList.end()) { - auto ret = ExitKioskModeInner(kioskStatus_.kioskBundleName_); + auto ret = ExitKioskModeInner(kioskStatus_.kioskBundleName_, nullptr); if (ret != ERR_OK) { return ret; } @@ -78,7 +78,7 @@ int32_t KioskManager::UpdateKioskApplicationList(const std::vector whitelist_.insert(app); } auto sceneSessionManager = Rosen::SessionManagerLite::GetInstance().GetSceneSessionManagerLiteProxy(); - CHECK_POINTER_AND_RETURN_LOG(sceneSessionManager, ERR_INVALID_VALUE, "sceneSessionManager is nullptr"); + CHECK_POINTER_AND_RETURN_LOG(sceneSessionManager, INNER_ERR, "sceneSessionManager is nullptr"); sceneSessionManager->UpdateKioskAppList(appList); return ERR_OK; } @@ -108,9 +108,9 @@ int32_t KioskManager::EnterKioskMode(sptr callerToken) kioskStatus_.kioskBundleName_ = bundleName; kioskStatus_.kioskBundleUid_ = IPCSkeleton::GetCallingUid(); GetEnterKioskModeCallback()(); - notifyKioskModeChanged(true); + NotifyKioskModeChanged(true); auto sceneSessionManager = Rosen::SessionManagerLite::GetInstance().GetSceneSessionManagerLiteProxy(); - CHECK_POINTER_AND_RETURN_LOG(sceneSessionManager, ERR_INVALID_VALUE, "sceneSessionManager is nullptr"); + CHECK_POINTER_AND_RETURN_LOG(sceneSessionManager, INNER_ERR, "sceneSessionManager is nullptr"); sceneSessionManager->EnterKioskMode(callerToken); return ERR_OK; } @@ -126,7 +126,7 @@ int32_t KioskManager::ExitKioskMode(sptr callerToken) return ExitKioskModeInner(record->GetAbilityInfo().bundleName, callerToken); } -int32_t ExitKioskModeInner(const std::string &bundleName, sptr callerToken = nullptr); +int32_t KioskManager::ExitKioskModeInner(const std::string &bundleName, sptr callerToken) { if (!IsInWhiteListInner(bundleName)) { return ERR_KIOSK_MODE_NOT_IN_WHITELIST; @@ -139,7 +139,7 @@ int32_t ExitKioskModeInner(const std::string &bundleName, sptr ca NotifyKioskModeChanged(false); kioskStatus_.Clear(); auto sceneSessionManager = Rosen::SessionManagerLite::GetInstance().GetSceneSessionManagerLiteProxy(); - CHECK_POINTER_AND_RETURN_LOG(sceneSessionManager, ERR_INVALID_VALUE, "sceneSessionManager is nullptr"); + CHECK_POINTER_AND_RETURN_LOG(sceneSessionManager, INNER_ERR, "sceneSessionManager is nullptr"); sceneSessionManager->ExitKioskMode(callerToken); return ERR_OK; } diff --git a/test/unittest/ability_manager_proxy_fourth_test/BUILD.gn b/test/unittest/ability_manager_proxy_fourth_test/BUILD.gn index cb04b82cd9..660c33c3f5 100644 --- a/test/unittest/ability_manager_proxy_fourth_test/BUILD.gn +++ b/test/unittest/ability_manager_proxy_fourth_test/BUILD.gn @@ -77,6 +77,7 @@ ohos_unittest("ability_manager_proxy_fourth_test") { "napi:ace_napi", "samgr:samgr_proxy", "hisysevent:libhisysevent", + "window_manager:session_manager_lite", ] if (background_task_mgr_continuous_task_enable) { diff --git a/test/unittest/ability_manager_service_twelfth_test/BUILD.gn b/test/unittest/ability_manager_service_twelfth_test/BUILD.gn index 3494633e37..2eecc986dc 100644 --- a/test/unittest/ability_manager_service_twelfth_test/BUILD.gn +++ b/test/unittest/ability_manager_service_twelfth_test/BUILD.gn @@ -114,6 +114,7 @@ ohos_unittest("ability_manager_service_twelfth_test") { "relational_store:native_dataability", "safwk:api_cache_manager", "samgr:samgr_proxy", + "window_manager:session_manager_lite", ] if (ability_runtime_graphics) { From ae41f2db91b052a3afbe1e2ce102ad35b72445cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AE=B5=E5=97=A3=E9=92=8A?= Date: Mon, 9 Jun 2025 18:07:23 +0800 Subject: [PATCH 16/23] =?UTF-8?q?:=E5=A2=9E=E5=8A=A0udKey=E7=9A=84caller?= =?UTF-8?q?=E6=96=B9=E5=88=A4=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 段嗣钊 Change-Id: Ic99bbe2454823b362537b20f9284e966669b87ee --- .../include/ability_manager_errors.h | 2 + services/uripermmgr/include/upms_udmf_utils.h | 1 + .../uripermmgr/include/uri_permission_utils.h | 6 +- services/uripermmgr/src/upms_udmf_utils.cpp | 19 ++++++ .../uri_permission_impl_test/BUILD.gn | 3 +- .../mock/include/udmf_client.h | 2 + .../mock/include/uri_permission_utils.h | 45 +++++++++++++ .../mock/src/mock_uri_permission_utils.cpp | 20 +----- .../mock/src/udmf_client.cpp | 6 ++ .../udmf_utils_test.cpp | 63 ++++++++++++++++++- 10 files changed, 142 insertions(+), 25 deletions(-) create mode 100644 test/unittest/uri_permission_impl_test/mock/include/uri_permission_utils.h diff --git a/interfaces/inner_api/ability_manager/include/ability_manager_errors.h b/interfaces/inner_api/ability_manager/include/ability_manager_errors.h index a0178aa914..87c485af11 100644 --- a/interfaces/inner_api/ability_manager/include/ability_manager_errors.h +++ b/interfaces/inner_api/ability_manager/include/ability_manager_errors.h @@ -842,6 +842,8 @@ enum { ERR_UPMS_GRANT_URI_PERMISSION_FAILED = 2097347, + ERR_UPMS_KEY_IS_NOT_CREATE_BY_CALLER = 2097348, + /** * Result (2097351) target not in whitelist. */ diff --git a/services/uripermmgr/include/upms_udmf_utils.h b/services/uripermmgr/include/upms_udmf_utils.h index 8d482500ef..7ff514175c 100644 --- a/services/uripermmgr/include/upms_udmf_utils.h +++ b/services/uripermmgr/include/upms_udmf_utils.h @@ -29,6 +29,7 @@ public: private: static int32_t GetBatchData(const std::string &key, std::vector &uris); static int32_t AddPrivilege(const std::string &key, uint32_t tokenId, const std::string &readPermission); + static bool IsUdKeyCreateByCaller(uint32_t callerTokenId, const std::string &key); }; } // OHOS } // AAFwk diff --git a/services/uripermmgr/include/uri_permission_utils.h b/services/uripermmgr/include/uri_permission_utils.h index 3756f27ffe..bf0ee1aeb4 100644 --- a/services/uripermmgr/include/uri_permission_utils.h +++ b/services/uripermmgr/include/uri_permission_utils.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_ABILITY_RUNTIME_URI_PERMISSION_EVENT_H -#define OHOS_ABILITY_RUNTIME_URI_PERMISSION_EVENT_H +#ifndef OHOS_ABILITY_RUNTIME_URI_PERMISSION_UTILS_H +#define OHOS_ABILITY_RUNTIME_URI_PERMISSION_UTILS_H #include "bundle_mgr_helper.h" #include "event_report.h" @@ -52,4 +52,4 @@ private: }; } // OHOS } // AAFwk -#endif // OHOS_ABILITY_RUNTIME_URI_PERMISSION_EVENT_H \ No newline at end of file +#endif // OHOS_ABILITY_RUNTIME_URI_PERMISSION_UTILS_H \ No newline at end of file diff --git a/services/uripermmgr/src/upms_udmf_utils.cpp b/services/uripermmgr/src/upms_udmf_utils.cpp index 1196ee02b7..3664052b27 100644 --- a/services/uripermmgr/src/upms_udmf_utils.cpp +++ b/services/uripermmgr/src/upms_udmf_utils.cpp @@ -20,6 +20,7 @@ #include "hitrace_meter.h" #include "in_process_call_wrapper.h" #include "udmf_client.h" +#include "uri_permission_utils.h" #include "uri.h" namespace OHOS { @@ -85,10 +86,28 @@ int32_t UDMFUtils::AddPrivilege(const std::string &key, uint32_t tokenId, const return ret; } +bool UDMFUtils::IsUdKeyCreateByCaller(uint32_t callerTokenId, const std::string &key) +{ + HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__); + auto keyAuthority = IN_PROCESS_CALL(UDMF::UdmfClient::GetInstance().GetBundleNameByUdKey(key)); + std::string callerAuthority; + UPMSUtils::GetAlterableBundleNameByTokenId(callerTokenId, callerAuthority); + if (callerAuthority != keyAuthority) { + TAG_LOGE(AAFwkTag::URIPERMMGR, "Authority: %{public}s-%{public}s", + keyAuthority.c_str(), callerAuthority.c_str()); + return false; + } + return true; +} + int32_t UDMFUtils::ProcessUdmfKey(const std::string &key, uint32_t callerTokenId, uint32_t targetTokenId, std::vector &uris) { // To check if the key belong to callerTokenId + if (!IsUdKeyCreateByCaller(callerTokenId, key)) { + TAG_LOGE(AAFwkTag::URIPERMMGR, "Key is not create by caller"); + return ERR_UPMS_KEY_IS_NOT_CREATE_BY_CALLER; + } auto ret = AddPrivilege(key, targetTokenId, ""); if (ret != ERR_OK) { TAG_LOGE(AAFwkTag::URIPERMMGR, "AddPrivilege failed:%{public}d", ret); diff --git a/test/unittest/uri_permission_impl_test/BUILD.gn b/test/unittest/uri_permission_impl_test/BUILD.gn index e484e62edd..939e088f60 100755 --- a/test/unittest/uri_permission_impl_test/BUILD.gn +++ b/test/unittest/uri_permission_impl_test/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2023-2024 Huawei Device Co., Ltd. +# Copyright (c) 2023-2025 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 @@ -193,6 +193,7 @@ ohos_unittest("upms_udmf_utils_test") { sources = [ "${ability_runtime_services_path}/uripermmgr/src/upms_udmf_utils.cpp", "mock/src/mock_my_flag.cpp", + "mock/src/mock_uri_permission_utils.cpp", "mock/src/udmf_client.cpp", "udmf_utils_test.cpp", ] diff --git a/test/unittest/uri_permission_impl_test/mock/include/udmf_client.h b/test/unittest/uri_permission_impl_test/mock/include/udmf_client.h index 18832aebff..954bba05d1 100644 --- a/test/unittest/uri_permission_impl_test/mock/include/udmf_client.h +++ b/test/unittest/uri_permission_impl_test/mock/include/udmf_client.h @@ -92,11 +92,13 @@ class UdmfClient { int32_t GetBatchData(const QueryOption &query, std::vector &unifiedDataset); int32_t AddPrivilege(const QueryOption &query, const Privilege &privilege); + std::string GetBundleNameByUdKey(const std::string &key); static void Init(); static std::vector unifiedData_; static int32_t getBatchDataRet_; static int32_t addPrivilegeRet_; static int32_t privilegeTokenId_; + static std::string keyAuthority; private: UdmfClient() {}; diff --git a/test/unittest/uri_permission_impl_test/mock/include/uri_permission_utils.h b/test/unittest/uri_permission_impl_test/mock/include/uri_permission_utils.h new file mode 100644 index 0000000000..fe11c6703d --- /dev/null +++ b/test/unittest/uri_permission_impl_test/mock/include/uri_permission_utils.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2025 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 OHOS_ABILITY_RUNTIME_URI_PERMISSION_UTILS_H +#define OHOS_ABILITY_RUNTIME_URI_PERMISSION_UTILS_H + +#include "uri.h" + +namespace OHOS { +namespace AAFwk { + +class UPMSUtils { +public: + static bool SendShareUnPrivilegeUriEvent(uint32_t callTokenId, uint32_t targetTokenId); + static bool SendSystemAppGrantUriPermissionEvent(uint32_t callerTokenId, uint32_t targetTokenId, + const std::vector &uriVec, const std::vector &resVec); + static int32_t GetCurrentAccountId(); + static bool IsFoundationCall(); + static bool IsSAOrSystemAppCall(); + static bool IsSystemAppCall(); + static bool CheckIsSystemAppByTokenId(uint32_t tokenId); + static bool GetDirByBundleNameAndAppIndex(const std::string &bundleName, int32_t appIndex, std::string &dirName); + static bool GetBundleNameByTokenId(uint32_t tokenId, std::string &bundleName); + static bool GetAlterableBundleNameByTokenId(uint32_t tokenId, std::string &bundleName); + static int32_t GetAppIdByBundleName(const std::string &bundleName, std::string &appId); + static int32_t GetTokenIdByBundleName(const std::string &bundleName, int32_t appIndex, uint32_t &tokenId); + static bool CheckUriTypeIsValid(Uri &uri); + static bool GetBundleApiTargetVersion(const std::string &bundleName, int32_t &targetApiVersion); + static bool IsDocsCloudUri(Uri &uri); +}; +} // OHOS +} // AAFwk +#endif // OHOS_ABILITY_RUNTIME_URI_PERMISSION_UTILS_H \ No newline at end of file diff --git a/test/unittest/uri_permission_impl_test/mock/src/mock_uri_permission_utils.cpp b/test/unittest/uri_permission_impl_test/mock/src/mock_uri_permission_utils.cpp index 7f98429ff9..1813d4290b 100644 --- a/test/unittest/uri_permission_impl_test/mock/src/mock_uri_permission_utils.cpp +++ b/test/unittest/uri_permission_impl_test/mock/src/mock_uri_permission_utils.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2024-2025 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 @@ -22,11 +22,6 @@ namespace OHOS { namespace AAFwk { using MyFlag = OHOS::AAFwk::MyFlag; -std::shared_ptr UPMSUtils::ConnectManagerHelper() -{ - return bundleMgrHelper_; -} - bool UPMSUtils::SendShareUnPrivilegeUriEvent(uint32_t callerTokenId, uint32_t targetTokenId) { return true; @@ -38,12 +33,6 @@ bool UPMSUtils::SendSystemAppGrantUriPermissionEvent(uint32_t callerTokenId, uin return true; } -bool UPMSUtils::CheckAndCreateEventInfo(uint32_t callerTokenId, uint32_t targetTokenId, - EventInfo &eventInfo) -{ - return true; -} - int32_t UPMSUtils::GetCurrentAccountId() { return 1; @@ -64,11 +53,6 @@ bool UPMSUtils::IsSystemAppCall() return MyFlag::isSystemAppCall_; } -bool UPMSUtils::CheckIsSystemAppByBundleName(std::string &bundleName) -{ - return MyFlag::upmsUtilsCheckIsSystemAppByBundleNameRet_; -} - bool UPMSUtils::GetBundleApiTargetVersion(const std::string &bundleName, int32_t &targetApiVersion) { return true; @@ -118,7 +102,5 @@ bool UPMSUtils::IsDocsCloudUri(Uri &uri) { return MyFlag::isDocsCloudUri_; } - -std::shared_ptr UPMSUtils::bundleMgrHelper_ = nullptr; } // namespace AAFwk } // namespace OHOS diff --git a/test/unittest/uri_permission_impl_test/mock/src/udmf_client.cpp b/test/unittest/uri_permission_impl_test/mock/src/udmf_client.cpp index 8128ea19d9..98b6848466 100644 --- a/test/unittest/uri_permission_impl_test/mock/src/udmf_client.cpp +++ b/test/unittest/uri_permission_impl_test/mock/src/udmf_client.cpp @@ -45,9 +45,15 @@ int32_t UdmfClient::AddPrivilege(const QueryOption &query, const Privilege &priv return addPrivilegeRet_; } +std::string UdmfClient::GetBundleNameByUdKey(const std::string &key) +{ + return keyAuthority; +} + int32_t UdmfClient::getBatchDataRet_ = 0; int32_t UdmfClient::addPrivilegeRet_ = 0; int32_t UdmfClient::privilegeTokenId_ = 10000; std::vector UdmfClient::unifiedData_ = {}; +std::string UdmfClient::keyAuthority = ""; } // OHOS } // UDMF \ No newline at end of file diff --git a/test/unittest/uri_permission_impl_test/udmf_utils_test.cpp b/test/unittest/uri_permission_impl_test/udmf_utils_test.cpp index e4bababb50..36f2f24797 100644 --- a/test/unittest/uri_permission_impl_test/udmf_utils_test.cpp +++ b/test/unittest/uri_permission_impl_test/udmf_utils_test.cpp @@ -15,9 +15,9 @@ #include -#include "udmf_client.h" - #include "ability_manager_errors.h" +#include "mock_my_flag.h" +#include "udmf_client.h" #define private public #include "upms_udmf_utils.h" #undef private @@ -44,6 +44,7 @@ void UriPermissionImplUdmfUtilsTest::TearDownTestCase(void) void UriPermissionImplUdmfUtilsTest::SetUp() { UDMF::UdmfClient::Init(); + MyFlag::Init(); } void UriPermissionImplUdmfUtilsTest::TearDown() @@ -288,5 +289,63 @@ HWTEST_F(UriPermissionImplUdmfUtilsTest, ProcessUdmfKey_0400, TestSize.Level1) auto ret = UDMFUtils::ProcessUdmfKey(key, callerTokenId, targetTokenId, uris); EXPECT_EQ(ret, ERR_OK); } + +/** + * @tc.number: ProcessUdmfKey_0500 + * @tc.desc: Test ProcessUdmfKey works, ProcessUdmfKey failed, key is not create by caller. + * @tc.type: FUNC + */ +HWTEST_F(UriPermissionImplUdmfUtilsTest, ProcessUdmfKey_0500, TestSize.Level1) +{ + std::string uri = "file://com.example.test/temp.txt"; + std::string key = "udmfKey"; + uint32_t callerTokenId = 100001; + uint32_t targetTokenId = 100002; + std::vector uris; + // callerAuthority + MyFlag::upmsUtilsGetAlterBundleNameByTokenIdRet_ = 0; + MyFlag::upmsUtilsAlterBundleName_ = "com.example.test"; + // keyAuthority + UDMF::UdmfClient::keyAuthority = "com.example.test1"; + // processUdmfKey + auto ret = UDMFUtils::ProcessUdmfKey(key, callerTokenId, targetTokenId, uris); + EXPECT_EQ(ret, ERR_UPMS_KEY_IS_NOT_CREATE_BY_CALLER); +} + +/** + * @tc.number: UriPermissionImplUdmfUtilsTest_IsUdKeyCreateByCaller_001 + * @tc.desc: callerAuthority equal to keyAuthority. + * @tc.type: FUNC + */ +HWTEST_F(UriPermissionImplUdmfUtilsTest, IsUdKeyCreateByCaller_001, TestSize.Level1) +{ + std::string key = "udmf://Picker/com.example.test/aaa"; + uint32_t callerTokenId = 100001; + // callerAuthority + MyFlag::upmsUtilsGetAlterBundleNameByTokenIdRet_ = 0; + MyFlag::upmsUtilsAlterBundleName_ = "com.example.test"; + // keyAuthority + UDMF::UdmfClient::keyAuthority = "com.example.test"; + bool ret = UDMFUtils::IsUdKeyCreateByCaller(callerTokenId, key); + EXPECT_EQ(ret, true); +} + +/** + * @tc.number: UriPermissionImplUdmfUtilsTest_IsUdKeyCreateByCaller_002 + * @tc.desc: callerAuthority do not equal to keyAuthority. + * @tc.type: FUNC + */ +HWTEST_F(UriPermissionImplUdmfUtilsTest, IsUdKeyCreateByCaller_002, TestSize.Level1) +{ + std::string key = "udmf://Picker/com.example.test/aaa"; + uint32_t callerTokenId = 100001; + // callerAuthority + MyFlag::upmsUtilsGetAlterBundleNameByTokenIdRet_ = 0; + MyFlag::upmsUtilsAlterBundleName_ = "com.example.test"; + // keyAuthority + UDMF::UdmfClient::keyAuthority = "com.example.test1"; + bool ret = UDMFUtils::IsUdKeyCreateByCaller(callerTokenId, key); + EXPECT_EQ(ret, false); +} } // namespace AAFwk } // namespace OHOS \ No newline at end of file From 9a4647bf83d0c425ff50eb724b4b3bdf4114c478 Mon Sep 17 00:00:00 2001 From: wangbing Date: Mon, 9 Jun 2025 21:57:28 +0800 Subject: [PATCH 17/23] fix issue Signed-off-by: wangbing --- .../ability_business_error.cpp | 15 ++++++++++++++- .../ability_business_error.h | 10 +++++++++- services/abilitymgr/src/kiosk_manager.cpp | 19 +++++++++++++++++++ 3 files changed, 42 insertions(+), 2 deletions(-) diff --git a/frameworks/native/ability/native/ability_business_error/ability_business_error.cpp b/frameworks/native/ability/native/ability_business_error/ability_business_error.cpp index 537801defb..477a1cc50a 100644 --- a/frameworks/native/ability/native/ability_business_error/ability_business_error.cpp +++ b/frameworks/native/ability/native/ability_business_error/ability_business_error.cpp @@ -118,6 +118,11 @@ constexpr const char* ERR_MSG_INVALID_TARGET_TOKENID = "The target token ID is i constexpr const char* ERROR_MSG_INVALID_MAIN_ELEMENT_TYPE = "Invalid main element type"; constexpr const char* ERROR_MSG_CHANGE_KEEP_ALIVE = "Can not change keep alive status"; constexpr const char* ERROR_MSG_NO_U1 = "The target bundle is not in u1"; +constexpr const char* ERROR_MSG_KIOSK_MODE_NOT_IN_WHITELIST = "The current application is not in the kiosk whitelist."; +constexpr const char* ERROR_MSG_ALREADY_IN_KIOSK_MODE = "The system is already in the kiosk mode."; +constexpr const char* ERROR_MSG_NOT_IN_KIOSK_MODE = + "The current application is not in the kiosk mode. Exit is not allowed."; +constexpr const char* ERROR_MSG_APP_NOT_IN_FOCUS = "The current ability is not foreground."; // follow ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST of appexecfwk_errors.h in bundle_framework constexpr int32_t ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST = 8521220; @@ -205,6 +210,10 @@ static std::unordered_map ERR_CODE_MAP = { { AbilityErrorCode::ERROR_CODE_INVALID_MAIN_ELEMENT_TYPE, ERROR_MSG_INVALID_MAIN_ELEMENT_TYPE}, { AbilityErrorCode::ERROR_CODE_CHANGE_KEEP_ALIVE, ERROR_MSG_CHANGE_KEEP_ALIVE}, { AbilityErrorCode::ERROR_CODE_NO_U1, ERROR_MSG_NO_U1}, + { AbilityErrorCode::ERROR_CODE_KIOSK_MODE_NOT_IN_WHITELIST, ERROR_MSG_KIOSK_MODE_NOT_IN_WHITELIST}, + { AbilityErrorCode::ERROR_CODE_ALREADY_IN_KIOSK_MODE, ERROR_MSG_ALREADY_IN_KIOSK_MODE}, + { AbilityErrorCode::ERROR_CODE_NOT_IN_KIOSK_MODE, ERROR_MSG_NOT_IN_KIOSK_MODE}, + { AbilityErrorCode::ERROR_CODE_APP_NOT_IN_FOCUS, ERROR_MSG_APP_NOT_IN_FOCUS}, }; static std::unordered_map INNER_TO_JS_ERROR_CODE_MAP { @@ -294,6 +303,10 @@ static std::unordered_map INNER_TO_JS_ERROR_CODE_MAP {ERR_INVALID_MAIN_ELEMENT_TYPE, AbilityErrorCode::ERROR_CODE_INVALID_MAIN_ELEMENT_TYPE}, {ERR_CHANGE_KEEP_ALIVE, AbilityErrorCode::ERROR_CODE_CHANGE_KEEP_ALIVE}, {ERR_NO_U1, AbilityErrorCode::ERROR_CODE_NO_U1}, + {ERR_KIOSK_MODE_NOT_IN_WHITELIST, AbilityErrorCode::ERROR_CODE_KIOSK_MODE_NOT_IN_WHITELIST}, + {ERR_ALREADY_IN_KIOSK_MODE, AbilityErrorCode::ERROR_CODE_ALREADY_IN_KIOSK_MODE}, + {ERR_NOT_IN_KIOSK_MODE, AbilityErrorCode::ERROR_CODE_NOT_IN_KIOSK_MODE}, + {ERR_APP_NOT_IN_FOCUS, AbilityErrorCode::ERROR_CODE_APP_NOT_IN_FOCUS}, }; } @@ -322,4 +335,4 @@ AbilityErrorCode GetJsErrorCodeByNativeError(int32_t errCode) return AbilityErrorCode::ERROR_CODE_INNER; } } // namespace AbilityRuntime -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/interfaces/kits/native/ability/native/ability_business_error/ability_business_error.h b/interfaces/kits/native/ability/native/ability_business_error/ability_business_error.h index 7ea10403ac..ef04055073 100644 --- a/interfaces/kits/native/ability/native/ability_business_error/ability_business_error.h +++ b/interfaces/kits/native/ability/native/ability_business_error/ability_business_error.h @@ -254,6 +254,14 @@ enum class AbilityErrorCode { // can not change keep alive status ERROR_CODE_CHANGE_KEEP_ALIVE = 16000203, + ERROR_CODE_KIOSK_MODE_NOT_IN_WHITELIST = 16000110, + + ERROR_CODE_ALREADY_IN_KIOSK_MODE = 16000111, + + ERROR_CODE_NOT_IN_KIOSK_MODE = 16000112, + + ERROR_CODE_APP_NOT_IN_FOCUS = 16000113, + // target bundle is not in u1 ERROR_CODE_NO_U1 = 16000204, @@ -265,4 +273,4 @@ std::string GetNoPermissionErrorMsg(const std::string& permission); AbilityErrorCode GetJsErrorCodeByNativeError(int32_t errCode); } // namespace AbilityRuntime } // namespace OHOS -#endif \ No newline at end of file +#endif diff --git a/services/abilitymgr/src/kiosk_manager.cpp b/services/abilitymgr/src/kiosk_manager.cpp index 6b86e04fe7..7ede34f993 100644 --- a/services/abilitymgr/src/kiosk_manager.cpp +++ b/services/abilitymgr/src/kiosk_manager.cpp @@ -32,6 +32,8 @@ namespace OHOS { namespace AAFwk { +constexpr char PRODUCT_APPBOOT_SETTING_ENABLED[] = "const.product.appboot.setting.enabled"; + KioskManager &KioskManager::GetInstance() { static KioskManager manager; @@ -51,6 +53,11 @@ void KioskManager::OnAppStop(const AppInfo &info) int32_t KioskManager::UpdateKioskApplicationList(const std::vector &appList) { + if (!system::GetBoolParameter(PRODUCT_APPBOOT_SETTING_ENABLED, false)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Disabled config"); + return ERR_NOT_SUPPORTED_PRODUCT_TYPE; + } + if (!PermissionVerification::GetInstance()->IsSystemAppCall() && !PermissionVerification::GetInstance()->IsSACall()) { TAG_LOGE(AAFwkTag::ABILITYMGR, "not system app"); @@ -81,6 +88,10 @@ int32_t KioskManager::UpdateKioskApplicationList(const std::vector int32_t KioskManager::EnterKioskMode(sptr callerToken) { + if (!system::GetBoolParameter(PRODUCT_APPBOOT_SETTING_ENABLED, false)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Disabled config"); + return ERR_NOT_SUPPORTED_PRODUCT_TYPE; + } auto record = Token::GetAbilityRecordByToken(callerToken); if (!record) { TAG_LOGE(AAFwkTag::ABILITYMGR, "record null"); @@ -111,6 +122,10 @@ int32_t KioskManager::EnterKioskMode(sptr callerToken) int32_t KioskManager::ExitKioskMode(sptr callerToken) { + if (!system::GetBoolParameter(PRODUCT_APPBOOT_SETTING_ENABLED, false)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Disabled config"); + return ERR_NOT_SUPPORTED_PRODUCT_TYPE; + } auto record = Token::GetAbilityRecordByToken(callerToken); if (!record) { TAG_LOGE(AAFwkTag::ABILITYMGR, "record null"); @@ -137,6 +152,10 @@ int32_t KioskManager::ExitKioskModeInner(const std::string & bundleName) int32_t KioskManager::GetKioskStatus(KioskStatus &kioskStatus) { + if (!system::GetBoolParameter(PRODUCT_APPBOOT_SETTING_ENABLED, false)) { + TAG_LOGE(AAFwkTag::ABILITYMGR, "Disabled config"); + return ERR_NOT_SUPPORTED_PRODUCT_TYPE; + } if (!PermissionVerification::GetInstance()->IsSystemAppCall()) { TAG_LOGE(AAFwkTag::ABILITYMGR, "not system app"); return ERR_NOT_SYSTEM_APP; From bedb9e6c813b6da1e213fa0fea3a81fa88b05235 Mon Sep 17 00:00:00 2001 From: zhangzezhong Date: Mon, 9 Jun 2025 22:06:40 +0800 Subject: [PATCH 18/23] add ets runtime Signed-off-by: zhangzezhong --- frameworks/native/runtime/ets_runtime.cpp | 481 ++++++++++++++++++ .../inner_api/runtime/include/ets_runtime.h | 105 ++++ test/unittest/runtime_test/BUILD.gn | 50 ++ .../runtime_test/ets_runtime_test.cpp | 223 ++++++++ 4 files changed, 859 insertions(+) create mode 100644 frameworks/native/runtime/ets_runtime.cpp create mode 100644 interfaces/inner_api/runtime/include/ets_runtime.h create mode 100644 test/unittest/runtime_test/ets_runtime_test.cpp diff --git a/frameworks/native/runtime/ets_runtime.cpp b/frameworks/native/runtime/ets_runtime.cpp new file mode 100644 index 0000000000..f851bf77ff --- /dev/null +++ b/frameworks/native/runtime/ets_runtime.cpp @@ -0,0 +1,481 @@ +/* + * Copyright (c) 2025 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 "ets_runtime.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "accesstoken_kit.h" +#include "config_policy_utils.h" +#include "connect_server_manager.h" +#include "constants.h" +#include "extract_resource_manager.h" +#include "extractor.h" +#include "file_ex.h" +#include "file_mapper.h" +#include "file_path_utils.h" +#include "hdc_register.h" +#include "hilog_tag_wrapper.h" +#include "hitrace_meter.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "module_checker_delegate.h" +#include "parameters.h" +#include "source_map.h" +#include "source_map_operator.h" +#include "ets_environment.h" +#include "syscap_ts.h" +#include "system_ability_definition.h" + +#ifdef SUPPORT_SCREEN +#include "ace_forward_compatibility.h" +#include "declarative_module_preloader.h" +#include "hot_reloader.h" +#endif //SUPPORT_SCREEN + +using namespace OHOS::AbilityBase; +using Extractor = OHOS::AbilityBase::Extractor; + +namespace OHOS { +namespace AbilityRuntime { +namespace { +#ifdef APP_USE_ARM64 +const std::string SANDBOX_LIB_PATH = "/system/lib64"; +const std::string ETS_RT_PATH = SANDBOX_LIB_PATH; +const std::string ETS_SYSLIB_PATH = + "/system/lib64:/system/lib64/platformsdk:/system/lib64/module:/system/lib64/ndk"; +#else +const std::string SANDBOX_LIB_PATH = "/system/lib"; +const std::string ETS_RT_PATH = SANDBOX_LIB_PATH; +const std::string ETS_SYSLIB_PATH = + "/system/lib:/system/lib/platformsdk:/system/lib/module:/system/lib/ndk"; +#endif +constexpr char BUNDLE_INSTALL_PATH[] = "/data/storage/el1/bundle/"; +constexpr char SANDBOX_ARK_CACHE_PATH[] = "/data/storage/ark-cache/"; +constexpr char MERGE_ABC_PATH[] = "/ets/modules_static.abc"; +constexpr char ENTRY_PATH_MAP_FILE[] = "/system/framework/entrypath.json"; // will deprecated +constexpr char ENTRY_PATH_MAP_KEY[] = "entryPath"; // will deprecated +constexpr char DEFAULT_ENTRY_ABILITY_CLASS[] = "entry/src/main/ets/entryability/EntryAbility/EntryAbility"; +constexpr int32_t DOT_START_LEN = 2; + +class EntryPathManager { +public: + static EntryPathManager &GetInstance() + { + static EntryPathManager instance; + return instance; + } + + bool Init() + { + std::ifstream inFile; + inFile.open(ENTRY_PATH_MAP_FILE, std::ios::in); + if (!inFile.is_open()) { + TAG_LOGD(AAFwkTag::ETSRUNTIME, "no entrypath file"); + return false; + } + nlohmann::json filePathsJson; + inFile >> filePathsJson; + if (filePathsJson.is_discarded()) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "json discarded error"); + inFile.close(); + return false; + } + + if (filePathsJson.is_null() || filePathsJson.empty()) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "invalid json"); + inFile.close(); + return false; + } + + if (!filePathsJson.contains(ENTRY_PATH_MAP_KEY)) { + TAG_LOGD(AAFwkTag::ETSRUNTIME, "no entrypath key"); + return false; + } + const auto &entryPathMap = filePathsJson[ENTRY_PATH_MAP_KEY]; + if (!entryPathMap.is_object()) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "entrypath is not object"); + return false; + } + + for (const auto &entryPath : entryPathMap.items()) { + std::string key = entryPath.key(); + if (!entryPath.value().is_string()) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "val is not string, key: %{public}s", key.c_str()); + continue; + } + std::string val = entryPath.value(); + TAG_LOGD(AAFwkTag::ETSRUNTIME, "key: %{public}s, value: %{public}s", key.c_str(), val.c_str()); + entryPathMap_.emplace(key, val); + } + inFile.close(); + return true; + } + + std::string GetEntryPath(const std::string &srcEntry) + { + auto const &iter = entryPathMap_.find(srcEntry); + if (iter == entryPathMap_.end()) { + if (StartsWithDotSlash(srcEntry)) { + TAG_LOGD(AAFwkTag::ETSRUNTIME, "not found srcEntry: %{public}s", srcEntry.c_str()); + return DEFAULT_ENTRY_ABILITY_CLASS; + } + TAG_LOGD(AAFwkTag::ETSRUNTIME, "srcEntry as class: %{public}s", srcEntry.c_str()); + return HandleOhmUrlSrcEntry(srcEntry); + } + TAG_LOGD(AAFwkTag::ETSRUNTIME, "found srcEntry: %{public}s, output: %{public}s", + srcEntry.c_str(), iter->second.c_str()); + return iter->second; + } + +private: + EntryPathManager() = default; + + ~EntryPathManager() = default; + + static bool StartsWithDotSlash(const std::string &str) + { + if (str.length() < DOT_START_LEN) { + return false; + } + std::string prefix = str.substr(0, DOT_START_LEN); + return prefix == "./"; + } + + static std::string HandleOhmUrlSrcEntry(const std::string &srcEntry) + { + size_t lastSlashPos = srcEntry.rfind('/'); + if (lastSlashPos == std::string::npos) { + std::string fileName = srcEntry; + // If there is no slash, the entire string is processed directly. + HandleOhmUrlFileName(fileName); + return fileName; + } + std::string base = srcEntry.substr(0, lastSlashPos + 1); + std::string fileName = srcEntry.substr(lastSlashPos + 1); + HandleOhmUrlFileName(fileName); + return base + fileName; + } + + static void HandleOhmUrlFileName(std::string &fileName) + { + size_t colonPos = fileName.rfind(':'); + if (colonPos != std::string::npos) { + // : => / + fileName.replace(colonPos, 1, "/"); + } else { + // => / + fileName = fileName + "/" + fileName; + } + } + + std::map entryPathMap_ {}; +}; +} // namespace + +AppLibPathVec ETSRuntime::appLibPaths_; + +std::unique_ptr ETSRuntime::Create(const Options &options, Runtime *jsRuntime) +{ + TAG_LOGD(AAFwkTag::ETSRUNTIME, "Create called"); + if (jsRuntime == nullptr) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "null jsRuntime"); + return std::unique_ptr(); + } + std::unique_ptr instance; + if (!options.preload) { + auto preloadedInstance = Runtime::GetPreloaded(); +#ifdef SUPPORT_SCREEN + // reload ace if compatible mode changes + if (Ace::AceForwardCompatibility::PipelineChanged() && preloadedInstance) { + preloadedInstance.reset(); + } +#endif + if (preloadedInstance && preloadedInstance->GetLanguage() == Runtime::Language::ETS) { + instance.reset(static_cast(preloadedInstance.release())); + } else { + instance = std::make_unique(); + } + } else { + instance = std::make_unique(); + } + + if (!instance->Initialize(options, jsRuntime)) { + return std::unique_ptr(); + } + EntryPathManager::GetInstance().Init(); + + return instance; +} + +void ETSRuntime::SetAppLibPath(const AppLibPathMap &appLibPaths) +{ + TAG_LOGD(AAFwkTag::ETSRUNTIME, "SetAppLibPath called"); + EtsEnv::ETSEnvironment::InitETSSDKNS(ETS_RT_PATH); + EtsEnv::ETSEnvironment::InitETSSysNS(ETS_SYSLIB_PATH); +} + +bool ETSRuntime::Initialize(const Options &options, Runtime *jsRuntime) +{ + TAG_LOGD(AAFwkTag::ETSRUNTIME, "Initialize called"); + if (options.lang != GetLanguage()) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "language mismatch"); + return false; + } + + if (!CreateEtsEnv(options, jsRuntime)) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Create etsEnv failed"); + return false; + } + + apiTargetVersion_ = options.apiTargetVersion; + TAG_LOGD(AAFwkTag::ETSRUNTIME, "Initialize: %{public}d", apiTargetVersion_); + + return true; +} + +void ETSRuntime::RegisterUncaughtExceptionHandler(void *uncaughtExceptionInfo) +{ + if (etsEnv_ == nullptr) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "null etsEnv_"); + return; + } + + if (uncaughtExceptionInfo == nullptr) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "null uncaughtExceptionInfo"); + return; + } + + auto handle = static_cast(uncaughtExceptionInfo); + if (handle != nullptr) { + etsEnv_->RegisterUncaughtExceptionHandler(*handle); + } +} + +ETSRuntime::~ETSRuntime() +{ + TAG_LOGD(AAFwkTag::ETSRUNTIME, "~ETSRuntime called"); + Deinitialize(); +} + +void ETSRuntime::Deinitialize() +{ + TAG_LOGD(AAFwkTag::ETSRUNTIME, "Deinitialize called"); +} + +bool ETSRuntime::CreateEtsEnv(const Options &options, Runtime *jsRuntime) +{ + TAG_LOGD(AAFwkTag::ETSRUNTIME, "CreateEtsEnv called"); + etsEnv_ = std::make_shared(); + std::vector aniOptions; + std::string aotFileString = ""; + if (!options.arkNativeFilePath.empty()) { + std::string aotFilePath = SANDBOX_ARK_CACHE_PATH + options.arkNativeFilePath + options.moduleName + ".an"; + aotFileString = "--ext:--aot-file=" + aotFilePath; + aniOptions.push_back(ani_option { aotFileString.c_str(), nullptr }); + TAG_LOGI(AAFwkTag::ETSRUNTIME, "aotFileString: %{public}s", aotFileString.c_str()); + aniOptions.push_back(ani_option { "--ext:--enable-an", nullptr }); + } + + if (!etsEnv_->Initialize(static_cast(jsRuntime)->GetNapiEnv(), aniOptions)) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Init EtsEnv failed"); + return false; + } + + return true; +} + +ani_env *ETSRuntime::GetAniEnv() +{ + if (etsEnv_ == nullptr) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "null etsEnv_"); + return nullptr; + } + return etsEnv_->GetAniEnv(); +} + +void ETSRuntime::PreloadModule(const std::string &moduleName, const std::string &hapPath, + bool isEsMode, bool useCommonTrunk) +{ + TAG_LOGD(AAFwkTag::ETSRUNTIME, "moduleName: %{public}s", moduleName.c_str()); + ani_env *aniEnv = GetAniEnv(); + if (aniEnv == nullptr) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "GetAniEnv failed"); + return; + } + + ani_class cls = nullptr; + ani_object object = nullptr; + if (!LoadAbcLinker(aniEnv, moduleName, cls, object)) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "LoadAbcLinker failed"); + return; + } + return; +} + +std::unique_ptr ETSRuntime::LoadModule(const std::string &moduleName, + const std::string &modulePath, const std::string &hapPath, bool esmodule, bool useCommonChunk, + const std::string &srcEntrance) +{ + TAG_LOGD(AAFwkTag::ETSRUNTIME, "Load module(%{public}s, %{public}s, %{public}s, %{public}s)", + moduleName.c_str(), modulePath.c_str(), hapPath.c_str(), srcEntrance.c_str()); + + std::string path = moduleName; + auto pos = path.find("::"); + if (pos != std::string::npos) { + path.erase(pos, path.size() - pos); + moduleName_ = path; + } + TAG_LOGD(AAFwkTag::ETSRUNTIME, "moduleName_(%{public}s, path %{public}s", + moduleName_.c_str(), path.c_str()); + + std::string fileName; + if (!hapPath.empty()) { + fileName.append(codePath_).append(Constants::FILE_SEPARATOR).append(modulePath); + std::regex pattern(std::string(Constants::FILE_DOT) + std::string(Constants::FILE_SEPARATOR)); + fileName = std::regex_replace(fileName, pattern, ""); + } else { + if (!MakeFilePath(codePath_, modulePath, fileName)) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "make module file path: %{public}s failed", modulePath.c_str()); + return nullptr; + } + } + std::unique_ptr etsNativeReference = LoadEtsModule(moduleName, fileName, hapPath, srcEntrance); + return etsNativeReference; +} + +bool ETSRuntime::LoadAbcLinker(ani_env *env, const std::string &moduleName, ani_class &abcCls, ani_object &abcObj) +{ + if (env == nullptr) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "null env"); + return false; + } + ani_class stringCls = nullptr; + if (env->FindClass("Lstd/core/String;", &stringCls) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "FindClass Lstd/core/String Failed"); + return false; + } + std::string modulePath = BUNDLE_INSTALL_PATH + moduleName + MERGE_ABC_PATH; + ani_string aniStr; + if (env->String_NewUTF8(modulePath.c_str(), modulePath.size(), &aniStr) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "String_NewUTF8 modulePath Failed"); + return false; + } + ani_ref undefinedRef; + if (env->GetUndefined(&undefinedRef) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "GetUndefined failed"); + return false; + } + ani_array_ref refArray; + if (env->Array_New_Ref(stringCls, 1, undefinedRef, &refArray) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Array_New_Ref Failed"); + return false; + } + if (env->Array_Set_Ref(refArray, 0, aniStr) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Array_Set_Ref Failed"); + return false; + } + if (env->FindClass("Lstd/core/AbcRuntimeLinker;", &abcCls) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "FindClass AbcRuntimeLinker failed"); + return false; + } + ani_method method = nullptr; + if (env->Class_FindMethod(abcCls, "", "Lstd/core/RuntimeLinker;[Lstd/core/String;:V", &method) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Class_FindMethod ctor failed"); + return false; + } + env->ResetError(); + if (env->Object_New(abcCls, method, &abcObj, undefinedRef, refArray) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Object_New AbcRuntimeLinker failed"); + HandleUncaughtError(); + return false; + } + return true; +} + +std::unique_ptr ETSRuntime::LoadEtsModule(const std::string &moduleName, + const std::string &fileName, const std::string &hapPath, const std::string &srcEntrance) +{ + auto etsNativeReference = std::make_unique(); + ani_env *aniEnv = GetAniEnv(); + if (aniEnv == nullptr) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "GetAniEnv failed"); + return std::make_unique(); + } + ani_class cls = nullptr; + ani_object object = nullptr; + if (!LoadAbcLinker(aniEnv, moduleName_, cls, object)) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "LoadAbcLinker failed"); + return std::make_unique(); + } + ani_method loadClassMethod = nullptr; + if (aniEnv->Class_FindMethod(cls, "loadClass", "Lstd/core/String;Z:Lstd/core/Class;", &loadClassMethod) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Class_FindMethod loadClass failed"); + return std::make_unique(); + } + std::string entryPath = EntryPathManager::GetInstance().GetEntryPath(srcEntrance); + ani_string entryClassStr; + aniEnv->String_NewUTF8(entryPath.c_str(), entryPath.length(), &entryClassStr); + ani_class entryClass = nullptr; + ani_ref entryClassRef = nullptr; + if (aniEnv->Object_CallMethod_Ref(object, loadClassMethod, &entryClassRef, entryClassStr, false) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Object_CallMethod_Ref loadClassMethod failed"); + return std::make_unique(); + } else { + entryClass = static_cast(entryClassRef); + } + ani_method entryMethod = nullptr; + if (aniEnv->Class_FindMethod(entryClass, "", ":V", &entryMethod) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Class_FindMethod ctor failed"); + return std::make_unique(); + } + ani_object entryObject = nullptr; + if (aniEnv->Object_New(entryClass, entryMethod, &entryObject) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "Object_New AbcRuntimeLinker failed"); + return std::make_unique(); + } + ani_ref entryObjectRef = nullptr; + if (aniEnv->GlobalReference_Create(entryObject, &entryObjectRef) != ANI_OK) { + TAG_LOGE(AAFwkTag::ETSRUNTIME, "GlobalReference_Create failed"); + return std::make_unique(); + } + etsNativeReference->aniCls = entryClass; + etsNativeReference->aniObj = entryObject; + etsNativeReference->aniRef = entryObjectRef; + return etsNativeReference; +} + +void ETSRuntime::HandleUncaughtError() +{ + TAG_LOGD(AAFwkTag::ETSRUNTIME, "HandleUncaughtError called"); + if (etsEnv_ == nullptr) { + return; + } + etsEnv_->HandleUncaughtError(); +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/inner_api/runtime/include/ets_runtime.h b/interfaces/inner_api/runtime/include/ets_runtime.h new file mode 100644 index 0000000000..7b1126f1c0 --- /dev/null +++ b/interfaces/inner_api/runtime/include/ets_runtime.h @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2025 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 OHOS_ABILITY_RUNTIME_ETS_RUNTIME_H +#define OHOS_ABILITY_RUNTIME_ETS_RUNTIME_H + +#include +#include +#include +#include +#include +#include +#include + +#include "runtime.h" +#include "js_runtime.h" +#include "ets_exception_callback.h" +#include "ani.h" + +using AppLibPathMap = std::map>; +using AppLibPathVec = std::vector; + +namespace OHOS { +namespace EtsEnv { +class ETSEnvironment; +} // namespace EtsEnv + +namespace AbilityRuntime { +struct ETSNativeReference { + ani_class aniCls = nullptr; + ani_object aniObj = nullptr; + ani_ref aniRef = nullptr; +}; + +class ETSRuntime : public Runtime { +public: + static std::unique_ptr Create(const Options &options, Runtime *jsRuntime); + static void SetAppLibPath(const AppLibPathMap &appLibPaths); + ~ETSRuntime() override; + Language GetLanguage() const override + { + return Language::ETS; + } + + void StartDebugMode(const DebugOption debugOption) override {} + void DumpHeapSnapshot(bool isPrivate) override {} + void NotifyApplicationState(bool isBackground) override {} + bool SuspendVM(uint32_t tid) override { return false; } + void ResumeVM(uint32_t tid) override {} + void PreloadSystemModule(const std::string &moduleName) override {} + void PreloadMainAbility(const std::string &moduleName, const std::string &srcPath, const std::string &hapPath, + bool isEsMode, const std::string &srcEntrance) override {} + void PreloadModule(const std::string &moduleName, const std::string &srcPath, const std::string &hapPath, + bool isEsMode, bool useCommonTrunk) override {} + void PreloadModule( + const std::string &moduleName, const std::string &hapPath, bool isEsMode, bool useCommonTrunk) override; + void FinishPreload() override {} + bool LoadRepairPatch(const std::string &patchFile, const std::string &baseFile) override { return false; } + bool NotifyHotReloadPage() override { return false; } + bool UnLoadRepairPatch(const std::string &patchFile) override { return false; } + void RegisterQuickFixQueryFunc(const std::map &moduleAndPath) override {}; + void StartProfiler(const DebugOption debugOption) override {}; + void SetModuleLoadChecker(const std::shared_ptr moduleCheckerDelegate) const override {} + void SetDeviceDisconnectCallback(const std::function &cb) override {}; + void DestroyHeapProfiler() override {}; + void ForceFullGC() override {}; + void ForceFullGC(uint32_t tid) override {}; + void DumpHeapSnapshot(uint32_t tid, bool isFullGC, bool isBinary = false) override {}; + void DumpCpuProfile() override {}; + void AllowCrossThreadExecution() override {}; + void GetHeapPrepare() override {}; + void RegisterUncaughtExceptionHandler(void *uncaughtExceptionInfo) override; + ani_env *GetAniEnv(); + std::unique_ptr LoadModule(const std::string &moduleName, const std::string &modulePath, + const std::string &hapPath, bool esmodule, bool useCommonChunk, const std::string &srcEntrance); + std::unique_ptr LoadEtsModule(const std::string &moduleName, const std::string &fileName, + const std::string &hapPath, const std::string &srcEntrance); + void HandleUncaughtError(); + +private: + bool Initialize(const Options &options, Runtime *jsRuntime); + void Deinitialize(); + bool CreateEtsEnv(const Options &options, Runtime *jsRuntime); + bool LoadAbcLinker(ani_env *env, const std::string &moduleName, ani_class &abcCls, ani_object &abcObj); + std::shared_ptr etsEnv_; + int32_t apiTargetVersion_ = 0; + std::string codePath_; + static AppLibPathVec appLibPaths_; + std::string moduleName_; +}; +} // namespace AbilityRuntime +} // namespace OHOS +#endif // OHOS_ABILITY_RUNTIME_ETS_RUNTIME_H diff --git a/test/unittest/runtime_test/BUILD.gn b/test/unittest/runtime_test/BUILD.gn index 809d3c1d52..98e40c9dfd 100644 --- a/test/unittest/runtime_test/BUILD.gn +++ b/test/unittest/runtime_test/BUILD.gn @@ -232,6 +232,56 @@ ohos_unittest("js_worker_test") { ] } +ohos_unittest("ets_runtime_test") { + module_out_path = module_output_path + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "../../cfi_blocklist.txt" + } + branch_protector_ret = "pac_ret" + + include_dirs = [ + "${ability_runtime_innerkits_path}/runtime/include", + "${ability_runtime_path}/interfaces/inner_api", + "${ability_runtime_path}/ets_environment/interfaces/inner_api", + "${ability_runtime_path}/ets_environment/frameworks/ets_environment/include", + "${ability_runtime_native_path}/runtime", + "${ability_runtime_native_path}/runtime/utils/include", + ] + + sources = [ + "${ability_runtime_path}/ets_environment/frameworks/ets_environment/src/dynamic_loader.cpp", + "${ability_runtime_path}/ets_environment/frameworks/ets_environment/src/ets_environment.cpp", + "ets_runtime_test.cpp", + ] + + configs = [ "${ability_runtime_services_path}/abilitymgr:abilityms_config" ] + deps = [] + + external_deps = [ + "ability_runtime:runtime", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "eventhandler:libeventhandler", + "faultloggerd:libunwinder", + "ffrt:libffrt", + "googletest:gmock_main", + "googletest:gtest_main", + "hilog:libhilog", + "ipc:ipc_core", + "json:nlohmann_json_static", + "napi:ace_napi", + "runtime_core:ani", + ] + + if (ability_runtime_graphics) { + defines = [ "SUPPORT_GRAPHICS" ] + external_deps += [ "ace_engine:ace_uicontent" ] + } +} + group("unittest") { testonly = true diff --git a/test/unittest/runtime_test/ets_runtime_test.cpp b/test/unittest/runtime_test/ets_runtime_test.cpp new file mode 100644 index 0000000000..192fe17287 --- /dev/null +++ b/test/unittest/runtime_test/ets_runtime_test.cpp @@ -0,0 +1,223 @@ +/* + * Copyright (c) 2025 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 private public +#define protected public +#include "ets_environment.h" +#include "ets_runtime.h" +#undef private +#undef protected +#include "hilog_tag_wrapper.h" +#include "js_runtime.h" +#include "runtime.h" +#include "ets_environment.h" + +using namespace testing; +using namespace testing::ext; +using namespace testing::mt; + +namespace OHOS { +namespace AbilityRuntime { +namespace { +const std::string TEST_BUNDLE_NAME = "com.ohos.contactsdataability"; +const std::string TEST_MODULE_NAME = ".ContactsDataAbility"; +const std::string TEST_ABILITY_NAME = "ContactsDataAbility"; +const std::string TEST_CODE_PATH = "/data/storage/el1/bundle"; +const std::string TEST_HAP_PATH = "/system/app/com.ohos.contactsdataabilityContacts_DataAbility.hap"; +const std::string TEST_LIB_PATH = "/data/storage/el1/bundle/lib/"; +const std::string TEST_MODULE_PATH = "/data/storage/el1/bundle/curJsModulePath"; +} // namespace + +class EtsRuntimeTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; + + Runtime::Options options_; +}; + +void EtsRuntimeTest::SetUpTestCase() {} + +void EtsRuntimeTest::TearDownTestCase() {} + +void EtsRuntimeTest::SetUp() +{ + Runtime::Options newOptions; + options_ = newOptions; + options_.bundleName = TEST_BUNDLE_NAME; + options_.codePath = TEST_CODE_PATH; + options_.loadAce = false; + options_.isBundle = true; + options_.preload = false; + std::shared_ptr eventRunner = AppExecFwk::EventRunner::Create(TEST_ABILITY_NAME); + options_.eventRunner = eventRunner; +} + +void EtsRuntimeTest::TearDown() {} + +/** + * @tc.name: Create_100 + * @tc.desc: EtsRuntime test for Create Initialize failed. + * @tc.type: FUNC + */ +HWTEST_F(EtsRuntimeTest, Create_100, TestSize.Level1) +{ + options_.lang = Runtime::Language::JS; + options_.preload = true; + options_.isStageModel = false; + auto jsRuntime = JsRuntime::Create(options_); + auto etsRuntime = ETSRuntime::Create(options_, jsRuntime.get()); + EXPECT_EQ(etsRuntime, nullptr); + options_.lang = Runtime::Language::ETS; + options_.preload = false; + options_.isStageModel = true; +} + +/** + * @tc.name: SetAppLibPath_100 + * @tc.desc: EtsRuntime test for SetAppLibPath. + * @tc.type: FUNC + */ +HWTEST_F(EtsRuntimeTest, SetAppLibPath_100, TestSize.Level1) +{ + std::map> testPathMap; + testPathMap["com.example.app"] = { "/data/abc", "/data/def" }; + testPathMap["com.example.demo"] = { "/data/demo/es", "/data/demo/ts" }; + std::unique_ptr etsRuntime = std::make_unique(); + etsRuntime->SetAppLibPath(testPathMap); + EXPECT_NE(testPathMap.size(), 0); +} + +/** + * @tc.name: Initialize_100 + * @tc.desc: EtsRuntime test for Initialize lang is not ETS. + * @tc.type: FUNC + */ +HWTEST_F(EtsRuntimeTest, Initialize_100, TestSize.Level1) +{ + options_.lang = Runtime::Language::JS; + Runtime *jsRuntime = nullptr; + std::unique_ptr etsRuntime = std::make_unique(); + bool result = etsRuntime->Initialize(options_, jsRuntime); + EXPECT_EQ(result, false); + options_.lang = Runtime::Language::ETS; +} + +/** + * @tc.name: Initialize_200 + * @tc.desc: EtsRuntime test for Initialize lang is not ETS. + * @tc.type: FUNC + */ +HWTEST_F(EtsRuntimeTest, Initialize_200, TestSize.Level1) +{ + options_.lang = Runtime::Language::JS; + Runtime *jsRuntime = nullptr; + std::unique_ptr etsRuntime = std::make_unique(); + bool result = etsRuntime->Initialize(options_, jsRuntime); + EXPECT_EQ(result, false); + options_.lang = Runtime::Language::ETS; +} + +/** + * @tc.name: Deinitialize_100 + * @tc.desc: EtsRuntime test for Deinitialize. + * @tc.type: FUNC + */ +HWTEST_F(EtsRuntimeTest, Deinitialize_100, TestSize.Level1) +{ + std::unique_ptr etsRuntime = std::make_unique(); + std::shared_ptr etsEnv = etsRuntime->etsEnv_; + + etsRuntime->etsEnv_ == nullptr; + etsRuntime->Deinitialize(); + EXPECT_EQ(etsRuntime->etsEnv_, nullptr); + + etsRuntime->etsEnv_ = std::make_shared(); + etsRuntime->Deinitialize(); + EXPECT_NE(etsRuntime->etsEnv_, nullptr); + etsRuntime->etsEnv_ = etsEnv; +} + +/** + * @tc.name: GetAniEnv_100 + * @tc.desc: EtsRuntime test for GetAniEnv. + * @tc.type: FUNC + */ +HWTEST_F(EtsRuntimeTest, GetAniEnv_100, TestSize.Level1) +{ + std::unique_ptr etsRuntime = std::make_unique(); + std::shared_ptr etsEnv = etsRuntime->etsEnv_; + + etsRuntime->etsEnv_ == nullptr; + auto env = etsRuntime->GetAniEnv(); + EXPECT_EQ(env, nullptr); + + env = nullptr; + etsRuntime->etsEnv_ = std::make_shared(); + env = etsRuntime->GetAniEnv(); + EXPECT_EQ(env, nullptr); + etsRuntime->etsEnv_ = etsEnv; +} + +/** + * @tc.name: LoadModule_100 + * @tc.desc: EtsRuntime test for LoadModule. + * @tc.type: FUNC + */ +HWTEST_F(EtsRuntimeTest, LoadModule_100, TestSize.Level1) +{ + std::unique_ptr etsRuntime = std::make_unique(); + + std::string moduleName = TEST_MODULE_NAME; + moduleName += "::"; + std::string modulePath = TEST_MODULE_PATH; + std::string hapPath = ""; + bool esmodule = true; + bool useCommonChunk = false; + std::string srcEntrance = ""; + + auto env = etsRuntime->LoadModule(moduleName, modulePath, hapPath, esmodule, useCommonChunk, srcEntrance); + EXPECT_EQ(env, nullptr); + + env = nullptr; + hapPath = TEST_HAP_PATH; + env = etsRuntime->LoadModule(moduleName, modulePath, hapPath, esmodule, useCommonChunk, srcEntrance); + EXPECT_NE(env, nullptr); +} + +/** + * @tc.name: LoadEtsModule_100 + * @tc.desc: EtsRuntime test for LoadEtsModule. + * @tc.type: FUNC + */ +HWTEST_F(EtsRuntimeTest, LoadEtsModule_100, TestSize.Level1) +{ + std::unique_ptr etsRuntime = std::make_unique(); + + std::string moduleName = TEST_MODULE_NAME; + moduleName += "::"; + std::string modulePath = TEST_MODULE_PATH; + std::string hapPath = ""; + std::string srcEntrance = ""; + auto env = etsRuntime->LoadEtsModule(moduleName, modulePath, hapPath, srcEntrance); + EXPECT_NE(env, nullptr); +} +} // namespace AbilityRuntime +} // namespace OHOS \ No newline at end of file From 6a24f3173e23569dd9e7b37998715f41c373a7f0 Mon Sep 17 00:00:00 2001 From: xiehd Date: Mon, 9 Jun 2025 22:22:15 +0800 Subject: [PATCH 19/23] fix uiextension closeFd Signed-off-by: xiehd --- .../ui_extension_record_factory_test.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/test/unittest/ui_extension_record_factory_test/ui_extension_record_factory_test.cpp b/test/unittest/ui_extension_record_factory_test/ui_extension_record_factory_test.cpp index 1b1dc1d176..e66b1b8878 100644 --- a/test/unittest/ui_extension_record_factory_test/ui_extension_record_factory_test.cpp +++ b/test/unittest/ui_extension_record_factory_test/ui_extension_record_factory_test.cpp @@ -144,6 +144,27 @@ HWTEST_F(UIExtensionRecordFactoryTest, NeedReuse_0200, TestSize.Level1) EXPECT_EQ(result, false); } +/** + * @tc.number: NeedReuse_0300 + * @tc.name: UIExtensionRecordFactoryTest + * @tc.desc: Set UIEXTENSION_ABILITY_ID equal INVALID_EXTENSION_RECORD_ID + */ +HWTEST_F(UIExtensionRecordFactoryTest, NeedReuse_0300, TestSize.Level1) +{ + AbilityRuntime::UIExtensionRecordFactory info; + AAFwk::AbilityRequest abilityRequest; + std::string deviceName = "device"; + std::string abilityName = "ServiceAbility"; + std::string appName = "hiservcie"; + std::string bundleName = "com.ix.hiservcie"; + std::string moduleName = "entry"; + abilityRequest = GenerateAbilityRequest(deviceName, abilityName, appName, bundleName, moduleName); + abilityRequest.sessionInfo = nullptr; + int32_t extensionRecordId = 1; + bool result = info.NeedReuse(abilityRequest, extensionRecordId); + EXPECT_EQ(result, false); +} + /** * @tc.number: CreateRecord_0100 * @tc.name: UIExtensionRecordFactoryTest From 891a28ac16f31f4d994d2ef814b05778fbc38960 Mon Sep 17 00:00:00 2001 From: xiehd Date: Mon, 9 Jun 2025 23:24:02 +0800 Subject: [PATCH 20/23] fix uiextension closeFd Signed-off-by: xiehd --- services/abilitymgr/src/ability_manager_stub.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/services/abilitymgr/src/ability_manager_stub.cpp b/services/abilitymgr/src/ability_manager_stub.cpp index c51b8bfd8c..dce240feb8 100644 --- a/services/abilitymgr/src/ability_manager_stub.cpp +++ b/services/abilitymgr/src/ability_manager_stub.cpp @@ -1130,7 +1130,9 @@ int AbilityManagerStub::TerminateUIExtensionAbilityInner(MessageParcel &data, Me int resultCode = data.ReadInt32(); Want *resultWant = data.ReadParcelable(); int32_t result = TerminateUIExtensionAbility(extensionSessionInfo, resultCode, resultWant); - extensionSessionInfo->want.CloseAllFd(); + if(extensionSessionInfo != nullptr){ + extensionSessionInfo->want.CloseAllFd(); + } reply.WriteInt32(result); if (resultWant != nullptr) { delete resultWant; @@ -1184,7 +1186,9 @@ int AbilityManagerStub::MinimizeUIExtensionAbilityInner(MessageParcel &data, Mes } auto fromUser = data.ReadBool(); int32_t result = MinimizeUIExtensionAbility(extensionSessionInfo, fromUser); - extensionSessionInfo->want.CloseAllFd(); + if(extensionSessionInfo != nullptr){ + extensionSessionInfo->want.CloseAllFd(); + } reply.WriteInt32(result); return NO_ERROR; } From 9c6d3a678c8ad2bb6feca5a90791c0635a7a1889 Mon Sep 17 00:00:00 2001 From: xiehd Date: Mon, 9 Jun 2025 23:25:49 +0800 Subject: [PATCH 21/23] fix uiextension closeFd Signed-off-by: xiehd --- services/abilitymgr/src/ability_manager_stub.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/abilitymgr/src/ability_manager_stub.cpp b/services/abilitymgr/src/ability_manager_stub.cpp index dce240feb8..bc0592a655 100644 --- a/services/abilitymgr/src/ability_manager_stub.cpp +++ b/services/abilitymgr/src/ability_manager_stub.cpp @@ -1130,7 +1130,7 @@ int AbilityManagerStub::TerminateUIExtensionAbilityInner(MessageParcel &data, Me int resultCode = data.ReadInt32(); Want *resultWant = data.ReadParcelable(); int32_t result = TerminateUIExtensionAbility(extensionSessionInfo, resultCode, resultWant); - if(extensionSessionInfo != nullptr){ + if (extensionSessionInfo != nullptr) { extensionSessionInfo->want.CloseAllFd(); } reply.WriteInt32(result); @@ -1186,7 +1186,7 @@ int AbilityManagerStub::MinimizeUIExtensionAbilityInner(MessageParcel &data, Mes } auto fromUser = data.ReadBool(); int32_t result = MinimizeUIExtensionAbility(extensionSessionInfo, fromUser); - if(extensionSessionInfo != nullptr){ + if (extensionSessionInfo != nullptr) { extensionSessionInfo->want.CloseAllFd(); } reply.WriteInt32(result); From fd75db550721d4df40ff53ebc37e10caa262f074 Mon Sep 17 00:00:00 2001 From: linjunjie Date: Fri, 6 Jun 2025 09:23:43 +0800 Subject: [PATCH 22/23] =?UTF-8?q?form=E6=96=B0=E5=A2=9E=E5=AD=97=E6=AE=B5?= =?UTF-8?q?=E8=A7=A3=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: linjunjie --- .../extract_insight_intent_profile.h | 8 +++---- .../extract_insight_intent_profile.cpp | 23 +++++++++++++++---- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/services/abilitymgr/include/insight_intent/extract_insight_intent_profile.h b/services/abilitymgr/include/insight_intent/extract_insight_intent_profile.h index 5c849e2a14..a99c28b007 100644 --- a/services/abilitymgr/include/insight_intent/extract_insight_intent_profile.h +++ b/services/abilitymgr/include/insight_intent/extract_insight_intent_profile.h @@ -50,7 +50,6 @@ struct LinkIntentParamMapping { struct InsightIntentLinkInfo { std::string uri; std::vector paramMapping {}; - // std::vector params {}; std::string parameters; InsightIntentLinkInfo() = default; @@ -61,7 +60,6 @@ struct InsightIntentPageInfo { std::string pagePath; std::string navigationId; std::string navDestinationName; - // std::vector params {}; std::string parameters; InsightIntentPageInfo() = default; @@ -70,7 +68,6 @@ struct InsightIntentPageInfo { struct InsightIntentEntryInfo { std::string abilityName; std::vector executeMode {}; - // std::vector params {}; std::string parameters; InsightIntentEntryInfo() = default; @@ -79,14 +76,14 @@ struct InsightIntentEntryInfo { struct InsightIntentFunctionInfo { std::string functionName; std::vector functionParams; - // std::vector params {}; std::string parameters; InsightIntentFunctionInfo() = default; }; struct InsightIntentFormInfo { - // std::vector params {}; + std::string abilityName; + std::string formName; std::string parameters; InsightIntentFormInfo() = default; @@ -216,6 +213,7 @@ struct ExtractInsightIntentProfileInfo { std::vector executeMode {}; std::string functionName; std::vector functionParams; + std::string formName; std::vector entities {}; }; diff --git a/services/abilitymgr/src/insight_intent/extract_insight_intent_profile.cpp b/services/abilitymgr/src/insight_intent/extract_insight_intent_profile.cpp index c1174cb706..a349e73871 100644 --- a/services/abilitymgr/src/insight_intent/extract_insight_intent_profile.cpp +++ b/services/abilitymgr/src/insight_intent/extract_insight_intent_profile.cpp @@ -58,7 +58,7 @@ const std::string INSIGHT_INTENT_PARAM_MAPPING_NAME = "paramMappingName"; const std::string INSIGHT_INTENT_PARAM_CATEGORY = "paramCategory"; const std::string INSIGHT_INTENT_RESULT = "result"; const std::string INSIGHT_INTENT_EXAMPLE = "example"; - +const std::string INSIGHT_INTENT_FORM_NAME = "formName"; const std::string INSIGHT_INTENT_ENTITES = "entities"; const std::string INSIGHT_INTENT_ENTITY_DECORETOR_FILE = "decoratorFile"; const std::string INSIGHT_INTENT_ENTITY_CLASS_NAME = "className"; @@ -130,7 +130,7 @@ void from_json(const nlohmann::json &jsonObject, InsightIntentEntityInfo &entity jsonObjectEnd, INSIGHT_INTENT_ENTITY_DECORETOR_FILE, entityInfo.decoratorFile, - false, + true, g_extraParseResult); AppExecFwk::BMSJsonUtil::GetStrValueIfFindKey(jsonObject, jsonObjectEnd, @@ -165,7 +165,7 @@ void from_json(const nlohmann::json &jsonObject, InsightIntentEntityInfo &entity if (jsonObject.find(INSIGHT_INTENT_ENTITY_PARAMETERS) != jsonObjectEnd) { if (jsonObject.at(INSIGHT_INTENT_ENTITY_PARAMETERS).is_object()) { - entityInfo.parameters = jsonObject[INSIGHT_INTENT_ENTITY_PARAMETERS].dump(); + entityInfo.parameters = jsonObject[INSIGHT_INTENT_ENTITY_PARAMETERS].dump(); } else { TAG_LOGE(AAFwkTag::INTENT, "type error: entity parameters not object"); g_extraParseResult = ERR_INVALID_VALUE; @@ -343,6 +343,12 @@ void from_json(const nlohmann::json &jsonObject, ExtractInsightIntentProfileInfo false, g_extraParseResult, ArrayType::OBJECT); + AppExecFwk::BMSJsonUtil::GetStrValueIfFindKey(jsonObject, + jsonObjectEnd, + INSIGHT_INTENT_FORM_NAME, + insightIntentInfo.formName, + false, + g_extraParseResult); if (jsonObject.find(INSIGHT_INTENT_PARAMETERS) != jsonObjectEnd) { if (jsonObject.at(INSIGHT_INTENT_PARAMETERS).is_object()) { @@ -439,6 +445,7 @@ void to_json(nlohmann::json& jsonObject, const ExtractInsightIntentProfileInfo& {INSIGHT_INTENT_EXECUTE_MODE, info.executeMode}, {INSIGHT_INTENT_FUNCTION_NAME, info.functionName}, {INSIGHT_INTENT_FUNCTION_PARAMS, info.functionParams}, + {INSIGHT_INTENT_FORM_NAME, info.formName}, {INSIGHT_INTENT_ENTITES, info.entities} }; @@ -501,6 +508,11 @@ bool CheckProfileSubIntentInfo(const ExtractInsightIntentProfileInfo &insightInt } break; case DecoratorType::DECORATOR_FORM: + if (insightIntent.formName.empty() || insightIntent.abilityName.empty()) { + TAG_LOGE(AAFwkTag::INTENT, "empty formName or abilityName, intentName: %{public}s, " + "abilityName: %{public}s", insightIntent.intentName.c_str(), insightIntent.abilityName.c_str()); + return false; + } break; default: TAG_LOGE(AAFwkTag::INTENT, "invalid decoratorType: %{public}s", insightIntent.decoratorType.c_str()); @@ -609,6 +621,8 @@ bool TransformToFunctionInfo(const ExtractInsightIntentProfileInfo &insightInten bool TransformToFormInfo(const ExtractInsightIntentProfileInfo &insightIntent, InsightIntentFormInfo &info) { + info.abilityName = insightIntent.abilityName; + info.formName = insightIntent.formName; info.parameters = insightIntent.parameters; TAG_LOGD(AAFwkTag::INTENT, "form parameters: %{public}s", info.parameters.c_str()); return true; @@ -679,8 +693,7 @@ bool ExtractInsightIntentProfile::ProfileInfoFormat(const ExtractInsightIntentPr info.keywords.assign(insightIntent.keywords.begin(), insightIntent.keywords.end()); info.entities = insightIntent.entities; TAG_LOGD(AAFwkTag::INTENT, "entities size: %{public}zu", info.entities.size()); - for (std::vector::const_iterator iter = info.entities.begin(); - iter != info.entities.end(); iter++) { + for (auto iter = info.entities.begin(); iter != info.entities.end(); iter++) { TAG_LOGD(AAFwkTag::INTENT, "entity decoratorFile: %{public}s, className: %{public}s, " "decoratorType: %{public}s, entityId: %{public}s, entityCategory: %{public}s, " "parentClassName: %{public}s, parameters: %{public}s", From bd2244a986f2e860abe12ed092352c4604b514d5 Mon Sep 17 00:00:00 2001 From: zhangzezhong Date: Tue, 10 Jun 2025 00:12:29 +0800 Subject: [PATCH 23/23] modify mainthread Signed-off-by: zhangzezhong --- frameworks/native/ability/native/BUILD.gn | 1 + .../native/ability/native/ability_loader.cpp | 10 +- .../native/extension_ability_thread.cpp | 8 +- .../ability/native/ui_ability_thread.cpp | 6 +- frameworks/native/appkit/BUILD.gn | 4 + .../ability_delegator_registry.cpp | 28 +- .../appkit/app/application_data_manager.cpp | 19 ++ .../native/appkit/app/dump_runtime_helper.cpp | 6 +- frameworks/native/appkit/app/main_thread.cpp | 323 +++++++++++++----- .../native/appkit/app/ohos_application.cpp | 144 ++++++-- frameworks/native/runtime/cj_runtime.cpp | 20 +- frameworks/native/runtime/js_runtime.cpp | 7 + frameworks/native/runtime/runtime.cpp | 42 ++- .../ability_simulator/src/js_runtime.cpp | 3 + interfaces/inner_api/runtime/BUILD.gn | 4 + .../inner_api/runtime/include/cj_runtime.h | 4 +- .../inner_api/runtime/include/js_runtime.h | 3 + .../inner_api/runtime/include/runtime.h | 17 +- .../native/ability/native/ability_loader.h | 9 +- .../ability_delegator_registry.h | 9 +- .../appkit/app/application_data_manager.h | 2 + .../kits/native/appkit/app/main_thread.h | 12 +- .../kits/native/appkit/app/ohos_application.h | 21 +- .../ability_delegator_module_test.cpp | 84 +++-- ...ability_delegator_registry_module_test.cpp | 9 +- .../js_test_runner_module_test.cpp | 12 +- .../ability_service_extension_test/BUILD.gn | 1 + .../app_service_extension_test/BUILD.gn | 1 + .../main_thread_test/main_thread_test.cpp | 2 +- .../ohos_application_test.cpp | 70 ++-- .../cj_ability_delegator_args_test.cpp | 6 +- .../cj_ability_delegator_test.cpp | 3 +- .../cj_ability_stage_object_test/BUILD.gn | 1 + test/unittest/cj_ability_stage_test/BUILD.gn | 1 + test/unittest/cj_ui_ability_test/BUILD.gn | 1 + test/unittest/dfr_test/watchdog_test/BUILD.gn | 1 + .../BUILD.gn | 17 + .../ability_loader_test.cpp | 20 +- .../ability_thread_test.cpp | 12 +- .../extension_ability_thread_test.cpp | 3 +- .../fa_ability_thread_test.cpp | 21 +- .../BUILD.gn | 11 + .../ability_delegator/BUILD.gn | 1 + .../ability_delegator_registry_test.cpp | 6 +- .../ability_delegator_test.cpp | 144 +++++--- .../ability_delegator/js_test_runner_test.cpp | 33 +- .../dump_runtime_helper_second_test.cpp | 19 +- test/unittest/runtime_test/BUILD.gn | 1 + 48 files changed, 868 insertions(+), 314 deletions(-) diff --git a/frameworks/native/ability/native/BUILD.gn b/frameworks/native/ability/native/BUILD.gn index 52d727221b..f250b62c7e 100644 --- a/frameworks/native/ability/native/BUILD.gn +++ b/frameworks/native/ability/native/BUILD.gn @@ -155,6 +155,7 @@ ohos_shared_library("abilitykit_utils") { "${ability_runtime_path}/interfaces/kits/native/ability/native", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/app", "${ability_runtime_innerkits_path}/ability_manager/include", + "${ability_runtime_innerkits_path}/runtime/include", "${ability_runtime_innerkits_path}/wantagent/include", "${ability_runtime_services_path}/abilitymgr/include/utils", "${ability_runtime_services_path}/abilitymgr/include", diff --git a/frameworks/native/ability/native/ability_loader.cpp b/frameworks/native/ability/native/ability_loader.cpp index 1c26bd9c57..1a8f740a1c 100644 --- a/frameworks/native/ability/native/ability_loader.cpp +++ b/frameworks/native/ability/native/ability_loader.cpp @@ -52,21 +52,23 @@ Ability *AbilityLoader::GetAbilityByName(const std::string &abilityName) return nullptr; } -AbilityRuntime::Extension *AbilityLoader::GetExtensionByName(const std::string &abilityName) +AbilityRuntime::Extension *AbilityLoader::GetExtensionByName(const std::string &abilityName, + const std::string &language) { auto it = extensions_.find(abilityName); if (it != extensions_.end()) { - return it->second(); + return it->second(language); } TAG_LOGE(AAFwkTag::ABILITY, "failed:%{public}s", abilityName.c_str()); return nullptr; } -AbilityRuntime::UIAbility *AbilityLoader::GetUIAbilityByName(const std::string &abilityName) +AbilityRuntime::UIAbility *AbilityLoader::GetUIAbilityByName(const std::string &abilityName, + const std::string &language) { auto it = uiAbilities_.find(abilityName); if (it != uiAbilities_.end()) { - return it->second(); + return it->second(language); } TAG_LOGE(AAFwkTag::ABILITY, "failed:%{public}s", abilityName.c_str()); return nullptr; diff --git a/frameworks/native/ability/native/extension_ability_thread.cpp b/frameworks/native/ability/native/extension_ability_thread.cpp index f72fa0f4c2..6a7633b351 100644 --- a/frameworks/native/ability/native/extension_ability_thread.cpp +++ b/frameworks/native/ability/native/extension_ability_thread.cpp @@ -242,7 +242,13 @@ void ExtensionAbilityThread::HandleAttach(const std::shared_ptr abilityInfo = abilityRecord->GetAbilityInfo(); + if (abilityInfo == nullptr) { + TAG_LOGE(AAFwkTag::EXT, "null abilityInfo"); + return; + } + auto extension = AppExecFwk::AbilityLoader::GetInstance().GetExtensionByName(abilityName, + abilityInfo->codeLanguage); if (extension == nullptr) { TAG_LOGE(AAFwkTag::EXT, "null extension"); return; diff --git a/frameworks/native/ability/native/ui_ability_thread.cpp b/frameworks/native/ability/native/ui_ability_thread.cpp index 18d97dee4d..e20643c444 100644 --- a/frameworks/native/ability/native/ui_ability_thread.cpp +++ b/frameworks/native/ability/native/ui_ability_thread.cpp @@ -131,7 +131,8 @@ void UIAbilityThread::Attach(const std::shared_ptr } // 2.new ability - auto ability = AppExecFwk::AbilityLoader::GetInstance().GetUIAbilityByName(abilityName); + auto ability = AppExecFwk::AbilityLoader::GetInstance().GetUIAbilityByName( + abilityName, abilityRecord->GetAbilityInfo()->codeLanguage); if (ability == nullptr) { TAG_LOGE(AAFwkTag::UIABILITY, "null ability"); return; @@ -203,7 +204,8 @@ void UIAbilityThread::Attach(const std::shared_ptr } // 2.new ability - auto ability = AppExecFwk::AbilityLoader::GetInstance().GetUIAbilityByName(abilityName); + auto ability = AppExecFwk::AbilityLoader::GetInstance().GetUIAbilityByName( + abilityName, abilityRecord->GetAbilityInfo()->codeLanguage); if (ability == nullptr) { TAG_LOGE(AAFwkTag::UIABILITY, "null ability"); return; diff --git a/frameworks/native/appkit/BUILD.gn b/frameworks/native/appkit/BUILD.gn index cc0227d2fe..11863d7b8b 100644 --- a/frameworks/native/appkit/BUILD.gn +++ b/frameworks/native/appkit/BUILD.gn @@ -54,6 +54,7 @@ config("appkit_config") { config("appkit_public_config") { visibility = [ ":*" ] include_dirs = [ + "${ability_runtime_path}/ets_environment/interfaces/inner_api", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_delegator", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/app", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_runtime/context", @@ -75,6 +76,7 @@ config("appkit_public_config") { ohos_shared_library("appkit_native") { include_dirs = [ "native", + "${ability_runtime_path}/ets_environment/interfaces/inner_api", "${ability_runtime_path}/interfaces/inner_api/error_utils/include", "${ability_runtime_path}/interfaces/kits/native/appkit", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", @@ -166,6 +168,7 @@ ohos_shared_library("appkit_native") { "${ability_runtime_native_path}/appkit:app_context", "${ability_runtime_native_path}/appkit:app_context_utils", "${ability_runtime_native_path}/appkit:appkit_manager_helper", + "${ability_runtime_path}/ets_environment/frameworks/ets_environment:ets_environment", "${ability_runtime_path}/js_environment/frameworks/js_environment:js_environment", "${ability_runtime_path}/utils/global/freeze:freeze_util", "${ability_runtime_services_path}/common:app_util", @@ -208,6 +211,7 @@ ohos_shared_library("appkit_native") { "napi:ace_napi", "preferences:native_preferences", "resource_management:global_resmgr", + "runtime_core:ani", "safwk:system_ability_fwk", "samgr:samgr_proxy", "storage_service:storage_manager_acl", diff --git a/frameworks/native/appkit/ability_delegator/ability_delegator_registry.cpp b/frameworks/native/appkit/ability_delegator/ability_delegator_registry.cpp index 7187c88382..bfdc3298b9 100644 --- a/frameworks/native/appkit/ability_delegator/ability_delegator_registry.cpp +++ b/frameworks/native/appkit/ability_delegator/ability_delegator_registry.cpp @@ -17,20 +17,30 @@ namespace OHOS { namespace AppExecFwk { -std::shared_ptr AbilityDelegatorRegistry::abilityDelegator_ {}; +std::map> + AbilityDelegatorRegistry::abilityDelegator_ {}; std::shared_ptr AbilityDelegatorRegistry::abilityDelegatorArgs_ {}; -std::shared_ptr AbilityDelegatorRegistry::GetAbilityDelegator() +std::shared_ptr AbilityDelegatorRegistry::GetAbilityDelegator( + const AbilityRuntime::Runtime::Language &language) { - auto p = reinterpret_cast(abilityDelegator_.get()); - return std::shared_ptr(abilityDelegator_, p); + auto it = abilityDelegator_.find(language); + if (it != abilityDelegator_.end()) { + auto p = reinterpret_cast(it->second.get()); + return std::shared_ptr(it->second, p); + } + return nullptr; } #ifdef CJ_FRONTEND std::shared_ptr AbilityDelegatorRegistry::GetCJAbilityDelegator() { - auto p = reinterpret_cast(abilityDelegator_.get()); - return std::shared_ptr(abilityDelegator_, p); + auto it = abilityDelegator_.find(AbilityRuntime::Runtime::Language::CJ); + if (it != abilityDelegator_.end()) { + auto p = reinterpret_cast(it->second.get()); + return std::shared_ptr(it->second, p); + } + return nullptr; } #endif @@ -39,11 +49,11 @@ std::shared_ptr AbilityDelegatorRegistry::GetArguments() return abilityDelegatorArgs_; } -void AbilityDelegatorRegistry::RegisterInstance( - const std::shared_ptr& delegator, const std::shared_ptr& args) +void AbilityDelegatorRegistry::RegisterInstance(const std::shared_ptr &delegator, + const std::shared_ptr &args, const AbilityRuntime::Runtime::Language &language) { - abilityDelegator_ = delegator; abilityDelegatorArgs_ = args; + abilityDelegator_.insert_or_assign(language, delegator); } } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/native/appkit/app/application_data_manager.cpp b/frameworks/native/appkit/app/application_data_manager.cpp index 6dfd3a4493..79c2449ccb 100644 --- a/frameworks/native/appkit/app/application_data_manager.cpp +++ b/frameworks/native/appkit/app/application_data_manager.cpp @@ -59,6 +59,15 @@ bool ApplicationDataManager::NotifyCJUnhandledException(const std::string &errMs return AppRecovery::GetInstance().TryRecoverApp(StateReason::CJ_ERROR); } +bool ApplicationDataManager::NotifyETSUnhandledException(const std::string &errMsg) +{ + if (errorObserver_) { + errorObserver_->OnUnhandledException(errMsg); + return true; + } + return AppRecovery::GetInstance().TryRecoverApp(StateReason::JS_ERROR); +} + void ApplicationDataManager::RemoveErrorObserver() { errorObserver_ = nullptr; @@ -88,5 +97,15 @@ bool ApplicationDataManager::NotifyCJExceptionObject(const AppExecFwk::ErrorObje // and restart as developer wants return AppRecovery::GetInstance().TryRecoverApp(StateReason::CJ_ERROR); } + +bool ApplicationDataManager::NotifyETSExceptionObject(const AppExecFwk::ErrorObject &errorObj) +{ + TAG_LOGD(AAFwkTag::APPKIT, "Notify Exception error observer come"); + if (errorObserver_) { + errorObserver_->OnExceptionObject(errorObj); + return true; + } + return AppRecovery::GetInstance().TryRecoverApp(StateReason::JS_ERROR); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/native/appkit/app/dump_runtime_helper.cpp b/frameworks/native/appkit/app/dump_runtime_helper.cpp index 945867d5b9..052ec4ece7 100644 --- a/frameworks/native/appkit/app/dump_runtime_helper.cpp +++ b/frameworks/native/appkit/app/dump_runtime_helper.cpp @@ -87,7 +87,7 @@ void DumpRuntimeHelper::SetAppFreezeFilterCallback() TAG_LOGE(AAFwkTag::APPKIT, "null application"); return; } - auto& runtime = application_->GetRuntime(); + auto &runtime = application_->GetRuntime(AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); if (runtime == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "null runtime"); return; @@ -205,7 +205,7 @@ void DumpRuntimeHelper::DumpJsHeap(const OHOS::AppExecFwk::JsHeapDumpInfo &info) TAG_LOGE(AAFwkTag::APPKIT, "null application"); return; } - auto& runtime = application_->GetRuntime(); + auto &runtime = application_->GetRuntime(AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); if (runtime == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "null runtime"); return; @@ -235,7 +235,7 @@ void DumpRuntimeHelper::DumpCjHeap(const OHOS::AppExecFwk::CjHeapDumpInfo &info) TAG_LOGE(AAFwkTag::APPKIT, "null application"); return; } - auto& runtime = application_->GetRuntime(); + auto &runtime = application_->GetRuntime(AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); if (runtime == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "null runtime"); return; diff --git a/frameworks/native/appkit/app/main_thread.cpp b/frameworks/native/appkit/app/main_thread.cpp index 0e856912f1..d15795546b 100644 --- a/frameworks/native/appkit/app/main_thread.cpp +++ b/frameworks/native/appkit/app/main_thread.cpp @@ -75,6 +75,7 @@ #include "if_system_ability_manager.h" #include "iservice_registry.h" #include "js_runtime.h" +#include "ets_runtime.h" #ifdef CJ_FRONTEND #include "cj_runtime.h" #endif @@ -183,6 +184,7 @@ const char* PC_LIBRARY_PATH = "/system/lib64/liblayered_parameters_manager.z.so" const char* PC_FUNC_INFO = "DetermineResourceType"; const int32_t TYPE_RESERVE = 1; const int32_t TYPE_OTHERS = 2; +std::unique_ptr RUNTIME_NULL = nullptr; #if defined(NWEB) constexpr int32_t PRELOAD_DELAY_TIME = 2000; //millisecond @@ -1395,6 +1397,59 @@ CJUncaughtExceptionInfo MainThread::CreateCjExceptionInfo(const std::string &bun return uncaughtExceptionInfo; } #endif + +EtsEnv::ETSUncaughtExceptionInfo MainThread::CreateEtsExceptionInfo(const std::string &bundleName, uint32_t versionCode, + const std::string &hapPath, std::string &appRunningId, int32_t pid, std::string &processName) +{ + EtsEnv::ETSUncaughtExceptionInfo uncaughtExceptionInfo; + wptr weak = this; + uncaughtExceptionInfo.uncaughtTask = [weak, bundleName, versionCode, appRunningId = std::move(appRunningId), pid, + processName](std::string summary, const EtsEnv::ETSErrorObject errorObj) { + auto appThread = weak.promote(); + if (appThread == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "null appThread"); + return; + } + time_t timet; + time(&timet); + 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), EVENT_KEY_TYPE, JSCRASH_TYPE, EVENT_KEY_HAPPEN_TIME, timet, EVENT_KEY_REASON, + errorObj.name, EVENT_KEY_JSVM, JSVM_TYPE, EVENT_KEY_SUMMARY, summary, EVENT_KEY_PNAME, processName, + EVENT_KEY_APP_RUNING_UNIQUE_ID, appRunningId); + ErrorObject appExecErrorObj = { .name = errorObj.name, .message = errorObj.message, .stack = errorObj.stack }; + FaultData faultData; + faultData.faultType = FaultDataType::JS_ERROR; + faultData.errorObject = appExecErrorObj; + DelayedSingleton::GetInstance()->NotifyAppFault(faultData); + if (ApplicationDataManager::GetInstance().NotifyETSUnhandledException(summary) && + ApplicationDataManager::GetInstance().NotifyETSExceptionObject(appExecErrorObj)) { + return; + } + TAG_LOGE(AAFwkTag::APPKIT, + "\n%{public}s is about to exit due to RuntimeError\nError " + "type:%{public}s\n%{public}s", + bundleName.c_str(), errorObj.name.c_str(), summary.c_str()); + bool foreground = false; + if (appThread->applicationImpl_ && + appThread->applicationImpl_->GetState() == ApplicationImpl::APP_STATE_FOREGROUND) { + foreground = true; + } + int result = HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::FRAMEWORK, "PROCESS_KILL", + HiviewDFX::HiSysEvent::EventType::FAULT, "PID", pid, "PROCESS_NAME", processName, "MSG", KILL_REASON, + "FOREGROUND", foreground); + TAG_LOGW(AAFwkTag::APPKIT, + "hisysevent write result=%{public}d, send event " + "[FRAMEWORK,PROCESS_KILL]," + " pid=%{public}d, processName=%{public}s, msg=%{public}s, " + "foreground=%{public}d", + result, pid, processName.c_str(), KILL_REASON, foreground); + AAFwk::ExitReason exitReason = { REASON_JS_ERROR, errorObj.name }; + AbilityManagerClient::GetInstance()->RecordAppExitReason(exitReason); + _exit(JS_ERROR_EXIT); + }; + return uncaughtExceptionInfo; +} /** * * @brief Launch the application. @@ -1582,6 +1637,9 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con } else { #endif AbilityRuntime::JsRuntime::SetAppLibPath(appLibPaths, isSystemApp); + if (IsNeedEtsInit(appInfo)) { + AbilityRuntime::ETSRuntime::SetAppLibPath(appLibPaths); + } #ifdef CJ_FRONTEND } #endif @@ -1608,7 +1666,14 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con options.pkgContextInfoJsonStringMap = pkgContextInfoJsonStringMap; options.allowArkTsLargeHeap = appInfo.allowArkTsLargeHeap; #ifdef CJ_FRONTEND - options.lang = isCJApp ? AbilityRuntime::Runtime::Language::CJ : AbilityRuntime::Runtime::Language::JS; + if (isCJApp) { + options.langs.emplace(AbilityRuntime::Runtime::Language::CJ, true); + application_->SetCJApplication(true); + } else { + AddRuntimeLang(appInfo, options); + } +#else + AddRuntimeLang(appInfo, options); #endif if (applicationInfo_->appProvisionType == Constants::APP_PROVISION_TYPE_DEBUG) { TAG_LOGD(AAFwkTag::APPKIT, "multi-thread mode: %{public}d", appLaunchData.GetMultiThread()); @@ -1642,12 +1707,12 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con static_cast(hapModuleInfo.aotCompileStatus); } } - auto runtime = AbilityRuntime::Runtime::Create(options); - if (!runtime) { - TAG_LOGE(AAFwkTag::APPKIT, "null runtime"); + std::vector> runtimes = AbilityRuntime::Runtime::CreateRuntimes(options); + if (runtimes.empty()) { + TAG_LOGE(AAFwkTag::APPKIT, "runtimes empty"); return; } - + auto &runtimeVerOne = GetVerOneRuntime(appInfo, runtimes); if (appInfo.debug && appLaunchData.GetDebugApp()) { wptr weak = this; auto cb = [weak]() { @@ -1658,7 +1723,9 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con } return appThread->NotifyDeviceDisConnect(); }; - runtime->SetDeviceDisconnectCallback(cb); + if (runtimeVerOne != nullptr) { + runtimeVerOne->SetDeviceDisconnectCallback(cb); + } } auto perfCmd = appLaunchData.GetPerfCmd(); @@ -1669,11 +1736,13 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con processName = processInfo_->GetProcessName(); TAG_LOGD(AAFwkTag::APPKIT, "pid is %{public}d, processName is %{public}s", pid, processName.c_str()); } - runtime->SetStopPreloadSoCallback([uid = bundleInfo.applicationInfo.uid, currentPid = pid, - bundleName = appInfo.bundleName]()-> void { - TAG_LOGD(AAFwkTag::APPKIT, "runtime callback and report load abc completed info to rss."); - ResHelper::ReportLoadAbcCompletedInfoToRss(uid, currentPid, bundleName); - }); + if (runtimeVerOne != nullptr) { + runtimeVerOne->SetStopPreloadSoCallback([uid = bundleInfo.applicationInfo.uid, currentPid = pid, + bundleName = appInfo.bundleName]()-> void { + TAG_LOGD(AAFwkTag::APPKIT, "runtime callback and report load abc completed info to rss."); + ResHelper::ReportLoadAbcCompletedInfoToRss(uid, currentPid, bundleName); + }); + } AbilityRuntime::Runtime::DebugOption debugOption; debugOption.isStartWithDebug = appLaunchData.GetDebugApp(); debugOption.processName = processName; @@ -1683,13 +1752,19 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con debugOption.isDebugFromLocal = appLaunchData.GetDebugFromLocal(); debugOption.perfCmd = perfCmd; debugOption.isDeveloperMode = isDeveloperMode_; - runtime->SetDebugOption(debugOption); + if (runtimeVerOne != nullptr) { + runtimeVerOne->SetDebugOption(debugOption); + } if (perfCmd.find(PERFCMD_PROFILE) != std::string::npos || perfCmd.find(PERFCMD_DUMPHEAP) != std::string::npos) { TAG_LOGD(AAFwkTag::APPKIT, "perfCmd is %{public}s", perfCmd.c_str()); - runtime->StartProfiler(debugOption); + if (runtimeVerOne != nullptr) { + runtimeVerOne->StartProfiler(debugOption); + } } else { - runtime->StartDebugMode(debugOption); + if (runtimeVerOne != nullptr) { + runtimeVerOne->StartDebugMode(debugOption); + } } std::vector hqfInfos = appInfo.appQuickFix.deployedAppqfInfo.hqfInfos; @@ -1700,7 +1775,9 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con it->moduleName.c_str(), it->hqfFilePath.c_str()); modulePaths.insert(std::make_pair(it->moduleName, it->hqfFilePath)); } - runtime->RegisterQuickFixQueryFunc(modulePaths); + if (runtimeVerOne != nullptr) { + runtimeVerOne->RegisterQuickFixQueryFunc(modulePaths); + } } auto bundleName = appInfo.bundleName; @@ -1708,18 +1785,37 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con #ifdef CJ_FRONTEND if (!isCJApp) { #endif - JsEnv::UncaughtExceptionInfo uncaughtExceptionInfo; - uncaughtExceptionInfo.hapPath = hapPath; - UncatchableTaskInfo uncatchableTaskInfo = {bundleName, versionCode, appRunningId, pid, processName}; - InitUncatchableTask(uncaughtExceptionInfo.uncaughtTask, uncatchableTaskInfo); - (static_cast(*runtime)).RegisterUncaughtExceptionHandler(uncaughtExceptionInfo); - JsEnv::UncatchableTask uncatchableTask; - InitUncatchableTask(uncatchableTask, uncatchableTaskInfo, true); - (static_cast(*runtime)).RegisterUncatchableExceptionHandler(uncatchableTask); + for (const auto &runtime : runtimes) { + if (appInfo.codeLanguage == AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0 && + runtime->GetLanguage() == AbilityRuntime::Runtime::Language::JS) { + JsEnv::UncaughtExceptionInfo uncaughtExceptionInfo; + uncaughtExceptionInfo.hapPath = hapPath; + UncatchableTaskInfo uncatchableTaskInfo = {bundleName, versionCode, appRunningId, pid, processName}; + InitUncatchableTask(uncaughtExceptionInfo.uncaughtTask, uncatchableTaskInfo); + (static_cast(*runtime)).RegisterUncaughtExceptionHandler( + uncaughtExceptionInfo); + JsEnv::UncatchableTask uncatchableTask; + InitUncatchableTask(uncatchableTask, uncatchableTaskInfo, true); + (static_cast(*runtime)).RegisterUncatchableExceptionHandler( + uncatchableTask); + } + if ((appInfo.codeLanguage == AbilityRuntime::CODE_LANGUAGE_ARKTS_1_2 || + appInfo.codeLanguage == AbilityRuntime::CODE_LANGUAGE_ARKTS_HYBRID) && + runtime->GetLanguage() == AbilityRuntime::Runtime::Language::ETS) { + auto expectionInfo = + CreateEtsExceptionInfo(bundleName, versionCode, hapPath, appRunningId, pid, processName); + runtime->RegisterUncaughtExceptionHandler((void*)&expectionInfo); + } + } #ifdef CJ_FRONTEND } else { - auto expectionInfo = CreateCjExceptionInfo(bundleName, versionCode, hapPath); - (static_cast(*runtime)).RegisterUncaughtExceptionHandler(expectionInfo); + for (const auto &runtime : runtimes) { + if (appInfo.codeLanguage == AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0 && + runtime->GetLanguage() == AbilityRuntime::Runtime::Language::CJ) { + auto expectionInfo = CreateCjExceptionInfo(bundleName, versionCode, hapPath); + runtime->RegisterUncaughtExceptionHandler((void*)&expectionInfo); + } + } } #endif wptr weak = this; @@ -1733,14 +1829,21 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con }; applicationContext->RegisterProcessSecurityExit(callback); - application_->SetRuntime(std::move(runtime)); - + for (auto &runtime : runtimes) { + application_->AddRuntime(std::move(runtime)); + } std::weak_ptr wpApplication = application_; AbilityLoader::GetInstance().RegisterUIAbility("UIAbility", - [wpApplication]() -> AbilityRuntime::UIAbility* { + [wpApplication](const std::string &language) -> AbilityRuntime::UIAbility* { auto app = wpApplication.lock(); if (app != nullptr) { - return AbilityRuntime::UIAbility::Create(app->GetRuntime()); + if (language == AbilityRuntime::CODE_LANGUAGE_ARKTS_1_2) { + return AbilityRuntime::UIAbility::Create(app->GetRuntime( + AbilityRuntime::CODE_LANGUAGE_ARKTS_1_2)); + } else { + return AbilityRuntime::UIAbility::Create(app->GetRuntime( + AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0)); + } } TAG_LOGE(AAFwkTag::APPKIT, "failed"); return nullptr; @@ -1748,33 +1851,18 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con #ifdef CJ_FRONTEND if (!isCJApp) { #endif - auto& jsEngine = (static_cast(*application_->GetRuntime())).GetNativeEngine(); if (application_ != nullptr) { - LoadAllExtensions(jsEngine); + TAG_LOGD(AAFwkTag::APPKIT, "LoadAllExtensions lan:%{public}s", appInfo.codeLanguage.c_str()); + LoadAllExtensions(); } - - IdleTimeCallback callback = [wpApplication](int32_t idleTime) { - auto app = wpApplication.lock(); - if (app == nullptr) { - TAG_LOGE(AAFwkTag::APPKIT, "null app"); - return; - } - auto &runtime = app->GetRuntime(); + if (appInfo.codeLanguage == AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0) { + auto &runtime = application_->GetRuntime(appInfo.codeLanguage); if (runtime == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "null runtime"); return; } - auto& nativeEngine = (static_cast(*runtime)).GetNativeEngine(); - nativeEngine.NotifyIdleTime(idleTime); - }; - idleTime_ = std::make_shared(mainHandler_, callback); - idleTime_->Start(); - - IdleNotifyStatusCallback cb = idleTime_->GetIdleNotifyFunc(); - jsEngine.NotifyIdleStatusControl(cb); - - auto helper = std::make_shared(application_); - helper->SetAppFreezeFilterCallback(); + SetJsIdleCallback(wpApplication, runtime); + } #ifdef CJ_FRONTEND } else { LoadAllExtensions(); @@ -1784,7 +1872,8 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con auto usertestInfo = appLaunchData.GetUserTestInfo(); if (usertestInfo) { - if (!PrepareAbilityDelegator(usertestInfo, isStageBased, entryHapModuleInfo, bundleInfo.targetVersion)) { + if (!PrepareAbilityDelegator(usertestInfo, isStageBased, entryHapModuleInfo, bundleInfo.targetVersion, + appInfo.codeLanguage)) { TAG_LOGE(AAFwkTag::APPKIT, "PrepareAbilityDelegator failed"); return; } @@ -1876,7 +1965,9 @@ void MainThread::HandleLaunchApplication(const AppLaunchData &appLaunchData, con } #endif if (appLaunchData.IsNeedPreloadModule()) { - PreloadModule(entryHapModuleInfo, application_->GetRuntime()); + for (auto &runtime : application_->GetRuntime()) { + PreloadModule(entryHapModuleInfo, runtime); + } } } @@ -1911,7 +2002,8 @@ void MainThread::InitUncatchableTask(JsEnv::UncatchableTask &uncatchableTask, co EVENT_KEY_PROCESS_RSS_MEMINFO, std::to_string(DumpProcessHelper::GetProcRssMemInfo())); ErrorObject appExecErrorObj = { errorObject.name, errorObject.message, errorObject.stack}; - auto napiEnv = (static_cast(*appThread->application_->GetRuntime())).GetNapiEnv(); + auto napiEnv = (static_cast( + *appThread->application_->GetRuntime(AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0))).GetNapiEnv(); AAFwk::ExitReason exitReason = { REASON_JS_ERROR, errorObject.name }; AbilityManagerClient::GetInstance()->RecordAppExitReason(exitReason); if (!isUncatchable && NapiErrorManager::GetInstance()->NotifyUncaughtException(napiEnv, summary, @@ -2054,7 +2146,7 @@ void MainThread::ProcessMainAbility(const AbilityInfo &info, const std::unique_p } void MainThread::PreloadModule(const AppExecFwk::HapModuleInfo &entryHapModuleInfo, - const std::unique_ptr& runtime) + const std::unique_ptr &runtime) { TAG_LOGI(AAFwkTag::APPKIT, "preload module %{public}s", entryHapModuleInfo.moduleName.c_str()); auto callback = []() {}; @@ -2204,7 +2296,7 @@ void MainThread::HandleUpdatePluginInfoInstalled(const ApplicationInfo &pluginAp TAG_LOGE(AAFwkTag::APPKIT, "null application_"); return; } - auto& runtime = application_->GetRuntime(); + auto &runtime = application_->GetRuntime(AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); if (runtime == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "null runtime"); return; @@ -2254,7 +2346,7 @@ void MainThread::HandleUpdateApplicationInfoInstalled(const ApplicationInfo& app } application_->UpdateApplicationInfoInstalled(appInfo); - auto& runtime = application_->GetRuntime(); + auto &runtime = application_->GetRuntime(AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); if (runtime == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "null runtime"); return; @@ -2342,10 +2434,11 @@ void MainThread::LoadAllExtensions() std::string file = item.extensionLibFile; std::weak_ptr wApp = application_; AbilityLoader::GetInstance().RegisterExtension(item.extensionName, - [wApp, file]() -> AbilityRuntime::Extension* { + [wApp, file](const std::string &language) -> AbilityRuntime::Extension* { auto app = wApp.lock(); if (app != nullptr) { - return AbilityRuntime::ExtensionModuleLoader::GetLoader(file.c_str()).Create(app->GetRuntime()); + return AbilityRuntime::ExtensionModuleLoader::GetLoader(file.c_str()) + .Create(app->GetRuntime(language)); } TAG_LOGE(AAFwkTag::APPKIT, "failed"); return nullptr; @@ -2355,7 +2448,8 @@ void MainThread::LoadAllExtensions() } bool MainThread::PrepareAbilityDelegator(const std::shared_ptr &record, bool isStageBased, - const AppExecFwk::HapModuleInfo &entryHapModuleInfo, uint32_t targetVersion) + const AppExecFwk::HapModuleInfo &entryHapModuleInfo, uint32_t targetVersion, + const std::string &applicationCodeLanguage) { TAG_LOGD(AAFwkTag::APPKIT, "enter, isStageBased = %{public}d", isStageBased); if (!record) { @@ -2365,12 +2459,27 @@ bool MainThread::PrepareAbilityDelegator(const std::shared_ptr & auto args = std::make_shared(record->want); if (isStageBased) { // Stage model TAG_LOGD(AAFwkTag::APPKIT, "Stage model"); - auto testRunner = TestRunner::Create(application_->GetRuntime(), args, false); - auto delegator = IAbilityDelegator::Create(application_->GetRuntime(), application_->GetAppContext(), - std::move(testRunner), record->observer); - AbilityDelegatorRegistry::RegisterInstance(delegator, args); - delegator->SetApiTargetVersion(targetVersion); - delegator->Prepare(); + if (applicationCodeLanguage == AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0) { + TAG_LOGI(AAFwkTag::DELEGATOR, "create 1.0 testrunner"); + auto &runtime = application_->GetRuntime(AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); + auto testRunner = TestRunner::Create(runtime, args, false); + auto delegator = IAbilityDelegator::Create(runtime, application_->GetAppContext(), + std::move(testRunner), record->observer); + AbilityDelegatorRegistry::RegisterInstance(delegator, args, runtime->GetLanguage()); + delegator->SetApiTargetVersion(targetVersion); + delegator->Prepare(); + } + + if (applicationCodeLanguage == AbilityRuntime::CODE_LANGUAGE_ARKTS_1_2) { + TAG_LOGI(AAFwkTag::DELEGATOR, "create 1.2 testrunner"); + auto &runtime = application_->GetRuntime(AbilityRuntime::CODE_LANGUAGE_ARKTS_1_2); + auto testRunner = TestRunner::Create(runtime, args, false); + auto delegator = IAbilityDelegator::Create(runtime, application_->GetAppContext(), + std::move(testRunner), record->observer); + AbilityDelegatorRegistry::RegisterInstance(delegator, args, runtime->GetLanguage()); + delegator->SetApiTargetVersion(targetVersion); + delegator->Prepare(); + } } else { // FA model TAG_LOGD(AAFwkTag::APPKIT, "FA model"); AbilityRuntime::Runtime::Options options; @@ -2400,7 +2509,7 @@ bool MainThread::PrepareAbilityDelegator(const std::shared_ptr & } auto delegator = std::make_shared( application_->GetAppContext(), std::move(testRunner), record->observer); - AbilityDelegatorRegistry::RegisterInstance(delegator, args); + AbilityDelegatorRegistry::RegisterInstance(delegator, args, AbilityRuntime::Runtime::Language::JS); delegator->SetApiTargetVersion(targetVersion); delegator->Prepare(); } @@ -2461,7 +2570,7 @@ void MainThread::HandleLaunchAbility(const std::shared_ptr & TAG_LOGE(AAFwkTag::APPKIT, "null application"); return; } - auto& runtime = application->GetRuntime(); + auto &runtime = application->GetRuntime(AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); appThread->UpdateRuntimeModuleChecker(runtime); #ifdef APP_ABILITY_USE_TWO_RUNNER AbilityThread::AbilityThreadMain(application, abilityRecord, stageContext); @@ -2488,7 +2597,7 @@ void MainThread::HandleLaunchAbility(const std::shared_ptr & return; } SetProcessExtensionType(abilityRecord); - auto& runtime = application_->GetRuntime(); + auto &runtime = application_->GetRuntime(AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); UpdateRuntimeModuleChecker(runtime); #ifdef APP_ABILITY_USE_TWO_RUNNER AbilityThread::AbilityThreadMain(application_, abilityRecord, stageContext); @@ -2851,7 +2960,7 @@ void MainThread::HandleDumpHeapPrepare() TAG_LOGE(AAFwkTag::APPKIT, "null app"); return; } - auto &runtime = app->GetRuntime(); + auto &runtime = app->GetRuntime(AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); if (runtime == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "null runtime"); return; @@ -2871,7 +2980,7 @@ void MainThread::HandleDumpHeap(bool isPrivate) TAG_LOGE(AAFwkTag::APPKIT, "null app"); return; } - auto &runtime = app->GetRuntime(); + auto &runtime = app->GetRuntime(AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); if (runtime == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "null runtime"); return; @@ -2924,11 +3033,11 @@ void MainThread::DestroyHeapProfiler() auto task = [] { auto app = applicationForDump_.lock(); - if (app == nullptr || app->GetRuntime() == nullptr) { + if (app == nullptr || app->GetRuntime(AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0) == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "null runtime"); return; } - app->GetRuntime()->DestroyHeapProfiler(); + app->GetRuntime(AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0)->DestroyHeapProfiler(); }; mainHandler_->PostTask(task, "MainThread:DestroyHeapProfiler"); } @@ -2943,11 +3052,11 @@ void MainThread::ForceFullGC() auto task = [] { auto app = applicationForDump_.lock(); - if (app == nullptr || app->GetRuntime() == nullptr) { + if (app == nullptr || app->GetRuntime(AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0) == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "null runtime"); return; } - app->GetRuntime()->ForceFullGC(); + app->GetRuntime(AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0)->ForceFullGC(); }; mainHandler_->PostTask(task, "MainThread:ForceFullGC"); } @@ -3675,7 +3784,7 @@ int32_t MainThread::ChangeAppGcState(int32_t state, uint64_t tid) TAG_LOGE(AAFwkTag::APPKIT, "null application_"); return ERR_INVALID_VALUE; } - auto &runtime = application_->GetRuntime(); + auto &runtime = application_->GetRuntime(AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); if (runtime == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "null runtime"); return ERR_INVALID_VALUE; @@ -3727,7 +3836,7 @@ int32_t MainThread::OnAttachLocalDebug(bool isDebugFromLocal) TAG_LOGE(AAFwkTag::APPKIT, "null application_"); return ERR_INVALID_VALUE; } - auto &runtime = application_->GetRuntime(); + auto &runtime = application_->GetRuntime(AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); if (runtime == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "null runtime"); return ERR_INVALID_VALUE; @@ -3949,7 +4058,7 @@ void MainThread::HandleCacheProcess() // force gc if (application_ != nullptr) { - auto &runtime = application_->GetRuntime(); + auto &runtime = application_->GetRuntime(AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); if (runtime == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "null runtime"); return; @@ -3958,6 +4067,38 @@ void MainThread::HandleCacheProcess() } } +void MainThread::AddRuntimeLang(ApplicationInfo &appInfo, AbilityRuntime::Runtime::Options &options) +{ + if (appInfo.codeLanguage == AbilityRuntime::CODE_LANGUAGE_ARKTS_1_2) { + options.langs.emplace(AbilityRuntime::Runtime::Language::ETS, true); + } else if (appInfo.codeLanguage == AbilityRuntime::CODE_LANGUAGE_ARKTS_HYBRID) { + options.langs.emplace(AbilityRuntime::Runtime::Language::ETS, true); + } else { + options.langs.emplace(AbilityRuntime::Runtime::Language::JS, true); + } +} + +bool MainThread::IsNeedEtsInit(const ApplicationInfo &appInfo) +{ + return appInfo.codeLanguage == AbilityRuntime::CODE_LANGUAGE_ARKTS_1_2 || + appInfo.codeLanguage == AbilityRuntime::CODE_LANGUAGE_ARKTS_HYBRID; +} + +const std::unique_ptr &MainThread::GetVerOneRuntime( + const ApplicationInfo &appInfo, const std::vector> &runtimes) +{ + if (appInfo.codeLanguage != AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0) { + return RUNTIME_NULL; + } + for (auto &runtime : runtimes) { + if (runtime->GetLanguage() == AbilityRuntime::Runtime::Language::JS || + runtime->GetLanguage() == AbilityRuntime::Runtime::Language::CJ) { + return runtime; + } + } + return RUNTIME_NULL; +} + void MainThread::HandleConfigByPlugin(Configuration &config, BundleInfo &bundleInfo) { if (PC_LIBRARY_PATH == nullptr) { @@ -3980,5 +4121,33 @@ void MainThread::HandleConfigByPlugin(Configuration &config, BundleInfo &bundleI entry(config, bundleInfo); } + +void MainThread::SetJsIdleCallback(const std::weak_ptr &wpApplication, + const std::unique_ptr &runtime) +{ + auto &jsEngine = (static_cast(*runtime)).GetNativeEngine(); + IdleTimeCallback callback = [wpApplication](int32_t idleTime) { + auto app = wpApplication.lock(); + if (app == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "null app"); + return; + } + auto &runtime = app->GetRuntime(AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); + if (runtime == nullptr) { + TAG_LOGE(AAFwkTag::APPKIT, "null runtime"); + return; + } + auto &nativeEngine = (static_cast(*runtime)).GetNativeEngine(); + nativeEngine.NotifyIdleTime(idleTime); + }; + idleTime_ = std::make_shared(mainHandler_, callback); + idleTime_->Start(); + + IdleNotifyStatusCallback cb = idleTime_->GetIdleNotifyFunc(); + jsEngine.NotifyIdleStatusControl(cb); + + auto helper = std::make_shared(application_); + helper->SetAppFreezeFilterCallback(); +} } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/native/appkit/app/ohos_application.cpp b/frameworks/native/appkit/app/ohos_application.cpp index 45831ff800..41713dde52 100644 --- a/frameworks/native/appkit/app/ohos_application.cpp +++ b/frameworks/native/appkit/app/ohos_application.cpp @@ -37,6 +37,7 @@ #include "iservice_registry.h" #include "runtime.h" #include "js_runtime.h" +#include "ets_runtime.h" #include "startup_manager.h" #include "system_ability_definition.h" #include "syspara/parameter.h" @@ -51,6 +52,7 @@ namespace OHOS { namespace AppExecFwk { namespace { constexpr const char* PERSIST_DARKMODE_KEY = "persist.ace.darkmode"; + std::unique_ptr RUNTIME_NULL = nullptr; } REGISTER_APPLICATION(OHOSApplication, OHOSApplication) constexpr int32_t APP_ENVIRONMENT_OVERWRITE = 1; @@ -77,11 +79,14 @@ void OHOSApplication::OnForeground() abilityRuntimeContext_->NotifyApplicationForeground(); } - if (runtime_ == nullptr) { - TAG_LOGD(AAFwkTag::APPKIT, "NotifyApplicationState, runtime_ is nullptr"); - return; + for (const auto &runtime : runtimes_) { + if (runtime == nullptr) { + TAG_LOGD(AAFwkTag::APPKIT, "NotifyApplicationState, runtime is nullptr"); + continue; + } + runtime->NotifyApplicationState(false); } - runtime_->NotifyApplicationState(false); + TAG_LOGD(AAFwkTag::APPKIT, "NotifyApplicationState::OnForeground end"); } @@ -97,11 +102,13 @@ void OHOSApplication::OnBackground() abilityRuntimeContext_->NotifyApplicationBackground(); } - if (runtime_ == nullptr) { - TAG_LOGD(AAFwkTag::APPKIT, "runtime_ is nullptr"); - return; + for (const auto &runtime : runtimes_) { + if (runtime == nullptr) { + TAG_LOGD(AAFwkTag::APPKIT, "runtime is nullptr"); + continue; + } + runtime->NotifyApplicationState(true); } - runtime_->NotifyApplicationState(true); } void OHOSApplication::DumpApplication() @@ -149,18 +156,18 @@ void OHOSApplication::DumpApplication() } /** - * @brief Set Runtime + * @brief Add Runtime * * @param runtime Runtime instance. */ -void OHOSApplication::SetRuntime(std::unique_ptr&& runtime) +void OHOSApplication::AddRuntime(std::unique_ptr &&runtime) { TAG_LOGD(AAFwkTag::APPKIT, "begin"); if (runtime == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "null runtime"); return; } - runtime_ = std::move(runtime); + runtimes_.emplace_back(std::move(runtime)); } /** @@ -369,6 +376,25 @@ void OHOSApplication::SetAppEnv(const std::vector& appEnvironmen return; } +void OHOSApplication::PreloadHybridModule(const HapModuleInfo &hapModuleInfo) const +{ + if (hapModuleInfo.codeLanguage != Constants::CODE_LANGUAGE_HYBRID) { + TAG_LOGD(AAFwkTag::APPKIT, "not hybrid runtime"); + return; + } + for (const auto &runtime : runtimes_) { + bool isEsmode = hapModuleInfo.compileMode == CompileMode::ES_MODULE; + bool useCommonTrunk = false; + for (const auto& md : hapModuleInfo.metadata) { + if (md.name == "USE_COMMON_CHUNK") { + useCommonTrunk = md.value == "true"; + break; + } + } + runtime->PreloadModule(hapModuleInfo.moduleName, hapModuleInfo.hapPath, isEsmode, useCommonTrunk); + } +} + std::shared_ptr OHOSApplication::AddAbilityStage( const std::shared_ptr &abilityRecord, const std::function &)> &callback, bool &isAsyncCallback) @@ -413,8 +439,10 @@ std::shared_ptr OHOSApplication::AddAbilityStage( TAG_LOGE(AAFwkTag::APPKIT, "null hapModuleInfo"); return nullptr; } - if (runtime_ && (runtime_->GetLanguage() == AbilityRuntime::Runtime::Language::JS)) { - static_cast(*runtime_).SetPkgContextInfoJson( + PreloadHybridModule(*hapModuleInfo); + auto &runtime = GetRuntime(abilityInfo->codeLanguage); + if (runtime && (runtime->GetLanguage() == AbilityRuntime::Runtime::Language::JS)) { + static_cast(*runtime).SetPkgContextInfoJson( hapModuleInfo->moduleName, hapModuleInfo->hapPath, hapModuleInfo->packageName); } SetAppEnv(hapModuleInfo->appEnvironments); @@ -425,7 +453,8 @@ std::shared_ptr OHOSApplication::AddAbilityStage( stageContext->SetResourceManager(rm); } - abilityStage = AbilityRuntime::AbilityStage::Create(runtime_, *hapModuleInfo); + auto &runtimeStage = GetRuntime(hapModuleInfo->codeLanguage); + abilityStage = AbilityRuntime::AbilityStage::Create(runtimeStage, *hapModuleInfo); if (abilityStage == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "null abilityStage"); return nullptr; @@ -608,8 +637,8 @@ bool OHOSApplication::AddAbilityStage( return false; } - if (runtime_ == nullptr) { - TAG_LOGE(AAFwkTag::APPKIT, "null runtime_"); + if (runtimes_.empty()) { + TAG_LOGE(AAFwkTag::APPKIT, "runtimes empty"); return false; } @@ -633,7 +662,8 @@ bool OHOSApplication::AddAbilityStage( stageContext->SetResourceManager(rm); } - auto abilityStage = AbilityRuntime::AbilityStage::Create(runtime_, *moduleInfo); + auto &runtime = GetRuntime(moduleInfo->codeLanguage); + auto abilityStage = AbilityRuntime::AbilityStage::Create(runtime, *moduleInfo); if (abilityStage == nullptr) { TAG_LOGE(AAFwkTag::APPKIT, "null abilityStage"); return false; @@ -688,9 +718,9 @@ std::shared_ptr OHOSApplication::GetAppContext() const return abilityRuntimeContext_; } -const std::unique_ptr& OHOSApplication::GetRuntime() const +const std::vector> &OHOSApplication::GetRuntime() const { - return runtime_; + return runtimes_; } void OHOSApplication::SetConfiguration(const Configuration &config) @@ -815,32 +845,60 @@ void OHOSApplication::SetExtensionTypeMap(std::map map) bool OHOSApplication::NotifyLoadRepairPatch(const std::string &hqfFile, const std::string &hapPath) { - if (runtime_ == nullptr) { - TAG_LOGD(AAFwkTag::APPKIT, "null runtime"); + if (runtimes_.empty()) { + TAG_LOGD(AAFwkTag::APPKIT, "runtimes empty"); return true; } - return runtime_->LoadRepairPatch(hqfFile, hapPath); + for (const auto &runtime : runtimes_) { + if (runtime == nullptr) { + TAG_LOGD(AAFwkTag::APPKIT, "null runtime"); + continue; + } + if (!runtime->LoadRepairPatch(hqfFile, hapPath)) { + return false; + } + } + return true; } bool OHOSApplication::NotifyHotReloadPage() { - if (runtime_ == nullptr) { - TAG_LOGD(AAFwkTag::APPKIT, "null runtime"); + if (runtimes_.empty()) { + TAG_LOGD(AAFwkTag::APPKIT, "runtimes empty"); return true; } - return runtime_->NotifyHotReloadPage(); + for (const auto &runtime : runtimes_) { + if (runtime == nullptr) { + TAG_LOGD(AAFwkTag::APPKIT, "null runtime"); + continue; + } + if (!runtime->NotifyHotReloadPage()) { + return false; + } + } + return true; } bool OHOSApplication::NotifyUnLoadRepairPatch(const std::string &hqfFile) { - if (runtime_ == nullptr) { - TAG_LOGD(AAFwkTag::APPKIT, "null runtime"); + if (runtimes_.empty()) { + TAG_LOGD(AAFwkTag::APPKIT, "runtimes empty"); return true; } - return runtime_->UnLoadRepairPatch(hqfFile); + for (const auto &runtime : runtimes_) { + if (runtime == nullptr) { + TAG_LOGD(AAFwkTag::APPKIT, "null runtime"); + continue; + } + if (!runtime->UnLoadRepairPatch(hqfFile)) { + return false; + } + } + + return true; } void OHOSApplication::CleanAppTempData(bool isLastProcess) @@ -1080,5 +1138,35 @@ bool OHOSApplication::GetDisplayConfig(uint64_t displayId, float &density, std:: return true; } #endif + +const std::unique_ptr &OHOSApplication::GetRuntime(const std::string &language) const +{ + for (auto &runtime : runtimes_) { + if (runtime->GetLanguage() == ConvertLangToCode(language)) { + return runtime; + } + } + return RUNTIME_NULL; +} + +void OHOSApplication::SetCJApplication(bool isCJApplication) +{ + isCJApplication_ = isCJApplication; +} + +AbilityRuntime::Runtime::Language OHOSApplication::ConvertLangToCode(const std::string &language) const +{ + if (language == AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0) { + if (isCJApplication_) { + return AbilityRuntime::Runtime::Language::CJ; + } else { + return AbilityRuntime::Runtime::Language::JS; + } + } else if (language == AbilityRuntime::CODE_LANGUAGE_ARKTS_1_2) { + return AbilityRuntime::Runtime::Language::ETS; + } else { + return AbilityRuntime::Runtime::Language::UNKNOWN; + } +} } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/native/runtime/cj_runtime.cpp b/frameworks/native/runtime/cj_runtime.cpp index ecf1697834..5ac8d635e2 100644 --- a/frameworks/native/runtime/cj_runtime.cpp +++ b/frameworks/native/runtime/cj_runtime.cpp @@ -118,16 +118,6 @@ bool CJRuntime::Initialize(const Options& options) return true; } -void CJRuntime::RegisterUncaughtExceptionHandler(const CJUncaughtExceptionInfo& uncaughtExceptionInfo) -{ - auto cjEnv = OHOS::CJEnv::LoadInstance(); - if (cjEnv == nullptr) { - TAG_LOGE(AAFwkTag::CJRUNTIME, "null cjEnv"); - return; - } - cjEnv->registerCJUncaughtExceptionHandler(uncaughtExceptionInfo); -} - bool CJRuntime::IsCJAbility(const std::string& info) { // in cj application, the srcEntry format should be packageName.AbilityClassName. @@ -368,4 +358,14 @@ void CJRuntime::ForceFullGC(uint32_t tid) return; } cjEnv->forceFullGC(); +} + +void CJRuntime::RegisterUncaughtExceptionHandler(void* uncaughtExceptionInfo) +{ + auto cjEnv = OHOS::CJEnv::LoadInstance(); + if (cjEnv == nullptr) { + TAG_LOGE(AAFwkTag::CJRUNTIME, "null cjEnv"); + return; + } + cjEnv->registerCJUncaughtExceptionHandler(*static_cast(uncaughtExceptionInfo)); } \ No newline at end of file diff --git a/frameworks/native/runtime/js_runtime.cpp b/frameworks/native/runtime/js_runtime.cpp index 4b04f031c1..cb7c9a217e 100644 --- a/frameworks/native/runtime/js_runtime.cpp +++ b/frameworks/native/runtime/js_runtime.cpp @@ -1765,5 +1765,12 @@ void JsRuntime::StartLocalDebugMode(bool isDebugFromLocal) debugOption_.isDebugFromLocal = isDebugFromLocal; StartDebugMode(debugOption_); } + +void JsRuntime::RegisterUncaughtExceptionHandler(void *uncaughtExceptionInfo) +{ + HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__); + CHECK_POINTER(jsEnv_); + jsEnv_->RegisterUncaughtExceptionHandler(*static_cast(uncaughtExceptionInfo)); +} } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/native/runtime/runtime.cpp b/frameworks/native/runtime/runtime.cpp index 26362dd0db..0beb1b4395 100644 --- a/frameworks/native/runtime/runtime.cpp +++ b/frameworks/native/runtime/runtime.cpp @@ -19,6 +19,7 @@ #include "cj_runtime.h" #endif #include "js_runtime.h" +#include "ets_runtime.h" namespace OHOS { namespace AbilityRuntime { @@ -26,8 +27,45 @@ namespace { std::unique_ptr g_preloadedInstance; } -std::unique_ptr Runtime::Create(const Runtime::Options& options) +std::vector> Runtime::CreateRuntimes(Runtime::Options &options) { + std::vector> runtimes; + for (auto lang : options.langs) { + switch (lang.first) { + case Runtime::Language::JS: + options.lang = Runtime::Language::JS; + runtimes.emplace_back(JsRuntime::Create(options)); + break; +#ifdef CJ_FRONTEND + case Runtime::Language::CJ: + options.lang = Runtime::Language::CJ; + runtimes.emplace_back(CJRuntime::Create(options)); + break; +#endif + case Runtime::Language::ETS: { + options.lang = Runtime::Language::JS; + auto &jsRuntime = runtimes.emplace_back(JsRuntime::Create(options)); + options.lang = Runtime::Language::ETS; + runtimes.emplace_back(ETSRuntime::Create(options, + static_cast(jsRuntime.get()))); + break; + } + default: + runtimes.emplace_back(std::unique_ptr()); + break; + } + } + return runtimes; +} + +std::unique_ptr Runtime::Create(Runtime::Options &options) +{ + std::unique_ptr jsRuntime; + if (options.lang == Runtime::Language::ETS) { + options.lang = Runtime::Language::JS; + jsRuntime = JsRuntime::Create(options); + options.lang = Runtime::Language::ETS; + } switch (options.lang) { case Runtime::Language::JS: return JsRuntime::Create(options); @@ -35,6 +73,8 @@ std::unique_ptr Runtime::Create(const Runtime::Options& options) case Runtime::Language::CJ: return CJRuntime::Create(options); #endif + case Runtime::Language::ETS: + return ETSRuntime::Create(options, jsRuntime.get()); default: return std::unique_ptr(); } diff --git a/frameworks/simulator/ability_simulator/src/js_runtime.cpp b/frameworks/simulator/ability_simulator/src/js_runtime.cpp index 7e173d8a07..3bed249733 100644 --- a/frameworks/simulator/ability_simulator/src/js_runtime.cpp +++ b/frameworks/simulator/ability_simulator/src/js_runtime.cpp @@ -158,5 +158,8 @@ std::unique_ptr JsRuntime::LoadSystemModuleByEngine( napi_create_reference(env, instanceValue, 1, &result); return std::unique_ptr(reinterpret_cast(result)); } + +void JsRuntime::RegisterUncaughtExceptionHandler(void *uncaughtExceptionInfo) +{} } // namespace AbilityRuntime } // namespace OHOS diff --git a/interfaces/inner_api/runtime/BUILD.gn b/interfaces/inner_api/runtime/BUILD.gn index 836d126b83..c642c30ef9 100644 --- a/interfaces/inner_api/runtime/BUILD.gn +++ b/interfaces/inner_api/runtime/BUILD.gn @@ -52,6 +52,7 @@ ohos_shared_library("runtime") { branch_protector_ret = "pac_ret" include_dirs = [ + "${ability_runtime_path}/ets_environment/interfaces/inner_api", "${ability_runtime_path}/services/abilitymgr/include", "${ability_runtime_path}/interfaces/kits/native/appkit/ability_bundle_manager_helper", "${ability_runtime_path}/frameworks/ets/ani/enum_convert", @@ -60,6 +61,7 @@ ohos_shared_library("runtime") { sources = [ "${ability_runtime_native_path}/appkit/ability_bundle_manager_helper/bundle_mgr_helper.cpp", + "${ability_runtime_native_path}/runtime/ets_runtime.cpp", "${ability_runtime_native_path}/runtime/hdc_register.cpp", "${ability_runtime_native_path}/runtime/js_app_process_state.cpp", "${ability_runtime_native_path}/runtime/js_data_struct_converter.cpp", @@ -90,6 +92,7 @@ ohos_shared_library("runtime") { "${ability_runtime_innerkits_path}/connect_server_manager:connect_server_manager", "${ability_runtime_native_path}/ability/native:ability_business_error", "${ability_runtime_native_path}/appkit:appkit_manager_helper", + "${ability_runtime_path}/ets_environment/frameworks/ets_environment:ets_environment", "${ability_runtime_path}/js_environment/frameworks/js_environment:js_environment", "${ability_runtime_services_path}/common:app_util", "${ability_runtime_services_path}/common:record_cost_time_util", @@ -122,6 +125,7 @@ ohos_shared_library("runtime") { "jsoncpp:jsoncpp", "napi:ace_napi", "resource_management:global_resmgr", + "runtime_core:ani", "samgr:samgr_proxy", "zlib:shared_libz", "faultloggerd:libfaultloggerd", diff --git a/interfaces/inner_api/runtime/include/cj_runtime.h b/interfaces/inner_api/runtime/include/cj_runtime.h index 0d406dc6f3..04778b7400 100644 --- a/interfaces/inner_api/runtime/include/cj_runtime.h +++ b/interfaces/inner_api/runtime/include/cj_runtime.h @@ -55,6 +55,8 @@ public: const std::string& hapPath, bool isEsMode, const std::string& srcEntrance) override {} void PreloadModule(const std::string& moduleName, const std::string& srcPath, const std::string& hapPath, bool isEsMode, bool useCommonTrunk) override {} + void PreloadModule(const std::string& moduleName, const std::string& hapPath, + bool isEsMode, bool useCommonTrunk) override {} void FinishPreload() override {} bool LoadRepairPatch(const std::string& patchFile, const std::string& baseFile) override { return false; } bool NotifyHotReloadPage() override { return false; } @@ -72,8 +74,8 @@ public: void DumpCpuProfile() override {}; void AllowCrossThreadExecution() override {}; void GetHeapPrepare() override {}; - void RegisterUncaughtExceptionHandler(const CJUncaughtExceptionInfo& uncaughtExceptionInfo); static bool RegisterCangjieCallback(); + void RegisterUncaughtExceptionHandler(void* uncaughtExceptionInfo) override; private: bool StartDebugger(); diff --git a/interfaces/inner_api/runtime/include/js_runtime.h b/interfaces/inner_api/runtime/include/js_runtime.h index d573886e3c..dcc410a2cf 100644 --- a/interfaces/inner_api/runtime/include/js_runtime.h +++ b/interfaces/inner_api/runtime/include/js_runtime.h @@ -103,6 +103,8 @@ public: const std::string& hapPath, bool isEsMode, const std::string& srcEntrance) override; void PreloadModule(const std::string& moduleName, const std::string& srcPath, const std::string& hapPath, bool isEsMode, bool useCommonTrunk) override; + void PreloadModule(const std::string &moduleName, const std::string &hapPath, + bool isEsMode, bool useCommonTrunk) override {} bool PopPreloadObj(const std::string& key, std::unique_ptr& obj); void StartDebugMode(const DebugOption debugOption) override; void SetDebugOption(const DebugOption debugOption) override; @@ -156,6 +158,7 @@ public: void SetPkgContextInfoJson(std::string moduleName, std::string hapPath, std::string packageName); void UpdatePkgContextInfoJson(const std::string& moduleName, const std::string& hapPath, const std::string& packageName); + void RegisterUncaughtExceptionHandler(void *uncaughtExceptionInfo) override; private: void FinishPreload() override; diff --git a/interfaces/inner_api/runtime/include/runtime.h b/interfaces/inner_api/runtime/include/runtime.h index 5b3312752f..faf6685bbd 100644 --- a/interfaces/inner_api/runtime/include/runtime.h +++ b/interfaces/inner_api/runtime/include/runtime.h @@ -27,14 +27,23 @@ namespace AppExecFwk { class EventRunner; } // namespace AppExecFwk namespace AbilityRuntime { +namespace { +const std::string CODE_LANGUAGE_ARKTS_1_0 = "1.1"; +const std::string CODE_LANGUAGE_ARKTS_1_2 = "1.2"; +const std::string CODE_LANGUAGE_ARKTS_HYBRID = "hybrid"; +} // namespace + class Runtime { public: enum class Language { JS = 0, - CJ + CJ, + ETS, + UNKNOWN, }; struct Options { + std::map langs; Language lang = Language::JS; std::string bundleName; std::string moduleName; @@ -80,7 +89,8 @@ public: bool isDeveloperMode; }; - static std::unique_ptr Create(const Options& options); + static std::vector> CreateRuntimes(Options &options); + static std::unique_ptr Create(Options &options); static void SavePreloaded(std::unique_ptr&& instance); static std::unique_ptr GetPreloaded(); @@ -108,6 +118,8 @@ public: const std::string& hapPath, bool isEsMode, const std::string& srcEntrance) = 0; virtual void PreloadModule(const std::string& moduleName, const std::string& srcPath, const std::string& hapPath, bool isEsMode, bool useCommonTrunk) = 0; + virtual void PreloadModule(const std::string &moduleName, const std::string &hapPath, + bool isEsMode, bool useCommonTrunk) {} virtual void FinishPreload() = 0; virtual bool LoadRepairPatch(const std::string& patchFile, const std::string& baseFile) = 0; virtual bool NotifyHotReloadPage() = 0; @@ -122,6 +134,7 @@ public: Runtime(Runtime&&) = delete; Runtime& operator=(const Runtime&) = delete; Runtime& operator=(Runtime&&) = delete; + virtual void RegisterUncaughtExceptionHandler(void *uncaughtExceptionInfo) {} }; } // namespace AbilityRuntime } // namespace OHOS diff --git a/interfaces/kits/native/ability/native/ability_loader.h b/interfaces/kits/native/ability/native/ability_loader.h index 23947ec898..18fd34818d 100644 --- a/interfaces/kits/native/ability/native/ability_loader.h +++ b/interfaces/kits/native/ability/native/ability_loader.h @@ -28,9 +28,9 @@ namespace OHOS { namespace AppExecFwk { -using CreateExtension = std::function; +using CreateExtension = std::function; using CreateAblity = std::function; -using CreateUIAbility = std::function; +using CreateUIAbility = std::function; #ifdef ABILITY_WINDOW_SUPPORT using CreateSlice = std::function; #endif @@ -90,14 +90,15 @@ public: * * @return return Ability address */ - AbilityRuntime::Extension *GetExtensionByName(const std::string &abilityName); + AbilityRuntime::Extension *GetExtensionByName(const std::string &abilityName, + const std::string &language = AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); /** * @brief Get UIAbility address * @param abilityName UIAbility classname * @return return UIAbility address */ - AbilityRuntime::UIAbility *GetUIAbilityByName(const std::string &abilityName); + AbilityRuntime::UIAbility *GetUIAbilityByName(const std::string &abilityName, const std::string &language); #ifdef ABILITY_WINDOW_SUPPORT void RegisterAbilitySlice(const std::string &sliceName, const CreateSlice &createFunc); diff --git a/interfaces/kits/native/appkit/ability_delegator/ability_delegator_registry.h b/interfaces/kits/native/appkit/ability_delegator/ability_delegator_registry.h index 1fd257b823..57f9c383be 100644 --- a/interfaces/kits/native/appkit/ability_delegator/ability_delegator_registry.h +++ b/interfaces/kits/native/appkit/ability_delegator/ability_delegator_registry.h @@ -24,6 +24,7 @@ #include "cj_ability_delegator_impl.h" #endif #include "iability_delegator.h" +#include "runtime.h" namespace OHOS { namespace AppExecFwk { @@ -34,7 +35,8 @@ public: * * @return the AbilityDelegator object initialized when the application is started. */ - static std::shared_ptr GetAbilityDelegator(); + static std::shared_ptr GetAbilityDelegator( + const AbilityRuntime::Runtime::Language &language = AbilityRuntime::Runtime::Language::JS); #ifdef CJ_FRONTEND /** @@ -60,10 +62,11 @@ public: * @param args, Indicates the AbilityDelegatorArgs object. */ static void RegisterInstance( - const std::shared_ptr& delegator, const std::shared_ptr& args); + const std::shared_ptr &delegator, const std::shared_ptr &args, + const AbilityRuntime::Runtime::Language &language); private: - static std::shared_ptr abilityDelegator_; + static std::map> abilityDelegator_; static std::shared_ptr abilityDelegatorArgs_; }; } // namespace AppExecFwk diff --git a/interfaces/kits/native/appkit/app/application_data_manager.h b/interfaces/kits/native/appkit/app/application_data_manager.h index 3f8bb01b4e..08ddb478a7 100644 --- a/interfaces/kits/native/appkit/app/application_data_manager.h +++ b/interfaces/kits/native/appkit/app/application_data_manager.h @@ -29,9 +29,11 @@ public: void AddErrorObserver(const std::shared_ptr &observer); bool NotifyUnhandledException(const std::string &errMsg); bool NotifyCJUnhandledException(const std::string &errMsg); + bool NotifyETSUnhandledException(const std::string &errMsg); void RemoveErrorObserver(); bool NotifyExceptionObject(const AppExecFwk::ErrorObject &errorObj); bool NotifyCJExceptionObject(const AppExecFwk::ErrorObject &errorObj); + bool NotifyETSExceptionObject(const AppExecFwk::ErrorObject &errorObj); private: ApplicationDataManager(); diff --git a/interfaces/kits/native/appkit/app/main_thread.h b/interfaces/kits/native/appkit/app/main_thread.h index cd5a86a89c..13a4d58604 100644 --- a/interfaces/kits/native/appkit/app/main_thread.h +++ b/interfaces/kits/native/appkit/app/main_thread.h @@ -40,6 +40,7 @@ #include "resource_manager.h" #include "runtime.h" #include "watchdog.h" +#include "ets_exception_callback.h" #ifdef CJ_FRONTEND #include "cj_envsetup.h" @@ -323,6 +324,8 @@ public: CJUncaughtExceptionInfo CreateCjExceptionInfo(const std::string &bundleName, uint32_t versionCode, const std::string &hapPath); #endif + EtsEnv::ETSUncaughtExceptionInfo CreateEtsExceptionInfo(const std::string &bundleName, uint32_t versionCode, + const std::string &hapPath, std::string &appRunningId, int32_t pid, std::string &processName); /** * @brief Notify NativeEngine GC of status change. * @@ -622,7 +625,8 @@ private: * */ bool PrepareAbilityDelegator(const std::shared_ptr &record, bool isStageBased, - const AppExecFwk::HapModuleInfo &entryHapModuleInfo, uint32_t targetVersion); + const AppExecFwk::HapModuleInfo &entryHapModuleInfo, uint32_t targetVersion, + const std::string &applicationCodeLanguage); /** * @brief Set current process extension type @@ -797,6 +801,12 @@ private: void SetAppDebug(uint32_t modeFlag, bool isDebug); void GetPluginNativeLibPath(std::vector &pluginBundleInfos, AppLibPathMap &appLibPaths); + void AddRuntimeLang(ApplicationInfo &appInfo, AbilityRuntime::Runtime::Options &options); + bool IsNeedEtsInit(const ApplicationInfo &appInfo); + const std::unique_ptr &GetVerOneRuntime( + const ApplicationInfo &appInfo, const std::vector> &runtimes); + void SetJsIdleCallback(const std::weak_ptr &wpApplication, + const std::unique_ptr &runtime); std::vector fileEntries_; std::vector nativeFileEntries_; diff --git a/interfaces/kits/native/appkit/app/ohos_application.h b/interfaces/kits/native/appkit/app/ohos_application.h index 783bd60149..3bc1c5697a 100644 --- a/interfaces/kits/native/appkit/app/ohos_application.h +++ b/interfaces/kits/native/appkit/app/ohos_application.h @@ -27,6 +27,7 @@ #include "ability_stage_context.h" #include "application_configuration_manager.h" #include "app_launch_data.h" +#include "runtime.h" namespace OHOS { namespace AbilityRuntime { @@ -49,11 +50,11 @@ public: void DumpApplication(); /** - * @brief Set Runtime + * @brief Add Runtime * * @param runtime Runtime instance. */ - void SetRuntime(std::unique_ptr&& runtime); + void AddRuntime(std::unique_ptr &&runtime); /** * @brief Set ApplicationContext @@ -168,12 +169,19 @@ public: */ std::shared_ptr GetAppContext() const; + /** + * @brief return the application runtimes + * + * @param runtime + */ + const std::vector> &GetRuntime() const; + /** * @brief return the application runtime * * @param runtime */ - const std::unique_ptr& GetRuntime() const; + const std::unique_ptr &GetRuntime(const std::string &language) const; /* * @@ -236,6 +244,8 @@ public: void PreloadAppStartup(const BundleInfo &bundleInfo, const std::string &preloadModuleName, std::shared_ptr startupTaskData); + void SetCJApplication(bool isCJApplication = false); + private: void UpdateAppContextResMgr(const Configuration &config); bool IsUpdateColorNeeded(Configuration &config, AbilityRuntime::SetLevel level); @@ -251,14 +261,17 @@ private: const AppExecFwk::HapModuleInfo &hapModuleInfo, const std::function& callback); bool IsMainProcess(const std::string &bundleName, const std::string &process); + AbilityRuntime::Runtime::Language ConvertLangToCode(const std::string &language) const; + void PreloadHybridModule(const HapModuleInfo &hapModuleInfo) const; private: std::shared_ptr abilityRecordMgr_ = nullptr; std::shared_ptr abilityRuntimeContext_ = nullptr; std::unordered_map> abilityStages_; - std::unique_ptr runtime_; + std::vector> runtimes_; std::shared_ptr configuration_ = nullptr; std::map extensionTypeMap_; + bool isCJApplication_ = false; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/test/moduletest/ability_delegator_test/ability_delegator_module_test.cpp b/test/moduletest/ability_delegator_test/ability_delegator_module_test.cpp index 5e3cda2168..186fa67b1e 100644 --- a/test/moduletest/ability_delegator_test/ability_delegator_module_test.cpp +++ b/test/moduletest/ability_delegator_test/ability_delegator_module_test.cpp @@ -165,7 +165,8 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_0100, Function std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -204,7 +205,8 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_0200, Function std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -239,7 +241,8 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_0300, Function std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -277,7 +280,8 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_0400, Function std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -310,7 +314,8 @@ HWTEST_F(AbilityDelegatorModuleTest2, Ability_Delegator_Args_Test_0500, Function std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub2()); @@ -342,7 +347,8 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_0600, Function std::shared_ptr context = std::make_shared(); EXPECT_TRUE(context != nullptr); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -377,7 +383,8 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_0700, Function std::shared_ptr context = std::make_shared(); EXPECT_TRUE(context != nullptr); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -411,7 +418,8 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_0800, Function std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -443,7 +451,8 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_0900, Function std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -476,7 +485,8 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_1000, Function std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -514,7 +524,8 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_1100, Function std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -551,7 +562,8 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_1200, Function std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -590,7 +602,8 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_1300, Function std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -629,7 +642,8 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_1400, Function std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -662,7 +676,8 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_1500, Function std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -701,7 +716,8 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_1600, Function std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -734,7 +750,8 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_1700, Function std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -773,7 +790,8 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_1800, Function std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -806,7 +824,8 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_1900, Function std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -845,7 +864,8 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_2000, Function std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -884,7 +904,8 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_2100, Function std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -923,7 +944,8 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_2200, Function std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -962,7 +984,8 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_2300, Function std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -1004,13 +1027,15 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_2400, Function std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), abilityArgs, true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub); std::shared_ptr abilityDelegator = std::make_shared(context, std::move(testRunner), iRemoteObj); - AbilityDelegatorRegistry::RegisterInstance(abilityDelegator, abilityArgs); + AbilityDelegatorRegistry::RegisterInstance(abilityDelegator, abilityArgs, + OHOS::AbilityRuntime::Runtime::Language::JS); abilityDelegator->abilityMonitors_.clear(); std::shared_ptr mockMonitor = std::make_shared(ABILITY_NAME); @@ -1049,13 +1074,15 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_2500, Function std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), abilityArgs, true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub2); std::shared_ptr abilityDelegator = std::make_shared(context, std::move(testRunner), iRemoteObj); - AbilityDelegatorRegistry::RegisterInstance(abilityDelegator, abilityArgs); + AbilityDelegatorRegistry::RegisterInstance(abilityDelegator, abilityArgs, + OHOS::AbilityRuntime::Runtime::Language::JS); abilityDelegator->abilityMonitors_.clear(); std::shared_ptr mockMonitor = std::make_shared(ABILITY_NAME); @@ -1091,7 +1118,8 @@ HWTEST_F(AbilityDelegatorModuleTest, Ability_Delegator_Args_Test_2600, Function } std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); diff --git a/test/moduletest/ability_delegator_test/ability_delegator_registry_module_test.cpp b/test/moduletest/ability_delegator_test/ability_delegator_registry_module_test.cpp index 526f8acd5f..d5e7c265d3 100644 --- a/test/moduletest/ability_delegator_test/ability_delegator_registry_module_test.cpp +++ b/test/moduletest/ability_delegator_test/ability_delegator_registry_module_test.cpp @@ -81,13 +81,16 @@ HWTEST_F(AbilityDelegatorRegistryModuleTest, } std::shared_ptr abilityArgs = std::make_shared(want); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), abilityArgs, true); std::shared_ptr abilityDelegator = std::make_shared(nullptr, std::move(testRunner), nullptr); - AbilityDelegatorRegistry::RegisterInstance(abilityDelegator, abilityArgs); + AbilityDelegatorRegistry::RegisterInstance(abilityDelegator, abilityArgs, + OHOS::AbilityRuntime::Runtime::Language::JS); - EXPECT_EQ(AbilityDelegatorRegistry::GetAbilityDelegator(), abilityDelegator); + EXPECT_EQ(AbilityDelegatorRegistry::GetAbilityDelegator(OHOS::AbilityRuntime::Runtime::Language::JS), + abilityDelegator); EXPECT_EQ(AbilityDelegatorRegistry::GetArguments(), abilityArgs); } diff --git a/test/moduletest/ability_delegator_test/js_test_runner_module_test.cpp b/test/moduletest/ability_delegator_test/js_test_runner_module_test.cpp index 52625ddd15..81ab9b9e87 100644 --- a/test/moduletest/ability_delegator_test/js_test_runner_module_test.cpp +++ b/test/moduletest/ability_delegator_test/js_test_runner_module_test.cpp @@ -118,13 +118,15 @@ HWTEST_F(JsTestRunnerModuleTest, Js_Test_Runner_Module_Test_0100, Function | Med std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), abilityArgs, true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub); std::shared_ptr abilityDelegator = std::make_shared(context, std::move(testRunner), iRemoteObj); - AbilityDelegatorRegistry::RegisterInstance(abilityDelegator, abilityArgs); + AbilityDelegatorRegistry::RegisterInstance(abilityDelegator, abilityArgs, + OHOS::AbilityRuntime::Runtime::Language::JS); JsTestRunner* jsRunnerdrive = nullptr; jsRunnerdrive->ReportFinished(REPORT_FINISH_MSG); @@ -157,13 +159,15 @@ HWTEST_F(JsTestRunnerModuleTest, Js_Test_Runner_Module_Test_0200, Function | Med std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), abilityArgs, true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub); std::shared_ptr abilityDelegator = std::make_shared(context, std::move(testRunner), iRemoteObj); - AbilityDelegatorRegistry::RegisterInstance(abilityDelegator, abilityArgs); + AbilityDelegatorRegistry::RegisterInstance(abilityDelegator, abilityArgs, + OHOS::AbilityRuntime::Runtime::Language::JS); sptr shobserver = sptr(new MockTestObserverStub); abilityDelegator->observer_ = shobserver; diff --git a/test/unittest/ability_service_extension_test/BUILD.gn b/test/unittest/ability_service_extension_test/BUILD.gn index 18412fa0cf..398c5223ed 100644 --- a/test/unittest/ability_service_extension_test/BUILD.gn +++ b/test/unittest/ability_service_extension_test/BUILD.gn @@ -75,6 +75,7 @@ ohos_unittest("ability_service_extension_test") { "ipc:ipc_napi", "napi:ace_napi", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { diff --git a/test/unittest/app_service_extension_test/BUILD.gn b/test/unittest/app_service_extension_test/BUILD.gn index 24a5b62347..ddb3ff10c5 100644 --- a/test/unittest/app_service_extension_test/BUILD.gn +++ b/test/unittest/app_service_extension_test/BUILD.gn @@ -75,6 +75,7 @@ ohos_unittest("app_service_extension_test") { "ipc:ipc_napi", "napi:ace_napi", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { diff --git a/test/unittest/appkit/main_thread_test/main_thread_test.cpp b/test/unittest/appkit/main_thread_test/main_thread_test.cpp index fad7eeb63e..ac1a95f76c 100644 --- a/test/unittest/appkit/main_thread_test/main_thread_test.cpp +++ b/test/unittest/appkit/main_thread_test/main_thread_test.cpp @@ -1915,7 +1915,7 @@ HWTEST_F(MainThreadTest, HandleLaunchAbility_0200, TestSize.Level1) abilityRecord3->abilityInfo_ = nullptr; AbilityRuntime::Runtime::Options options; auto runtime = AbilityRuntime::Runtime::Create(options); - mainThread_->application_->SetRuntime(std::move(runtime)); + mainThread_->application_->AddRuntime(std::move(runtime)); auto contextDeal = std::make_shared(); auto appInfo = std::make_shared(); appInfo->debug = true; diff --git a/test/unittest/appkit/ohos_application_test/ohos_application_test.cpp b/test/unittest/appkit/ohos_application_test/ohos_application_test.cpp index 53077a41fc..68a4195205 100644 --- a/test/unittest/appkit/ohos_application_test/ohos_application_test.cpp +++ b/test/unittest/appkit/ohos_application_test/ohos_application_test.cpp @@ -73,7 +73,7 @@ HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_OnForeground_0100, { GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_OnForeground_0100 start."; ohosApplication_->OnForeground(); - EXPECT_TRUE(ohosApplication_->runtime_ == nullptr); + EXPECT_TRUE(ohosApplication_->runtimes_.empty()); GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_OnForeground_0100 end."; } @@ -85,9 +85,9 @@ HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_OnForeground_0100, HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_OnForeground_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_OnForeground_0200 start."; - ohosApplication_->runtime_ = std::make_unique(); + ohosApplication_->runtimes_.push_back(std::make_unique()); ohosApplication_->OnForeground(); - EXPECT_TRUE(ohosApplication_->runtime_ != nullptr); + EXPECT_TRUE(!(ohosApplication_->runtimes_.empty())); GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_OnForeground_0200 end."; } @@ -100,7 +100,7 @@ HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_OnBackground_0100, { GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_OnBackground_0100 start."; ohosApplication_->OnBackground(); - EXPECT_TRUE(ohosApplication_->runtime_ == nullptr); + EXPECT_TRUE(ohosApplication_->runtimes_.empty()); GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_OnBackground_0100 end."; } @@ -112,9 +112,9 @@ HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_OnBackground_0100, HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_OnBackground_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_OnBackground_0200 start."; - ohosApplication_->runtime_ = std::make_unique(); + ohosApplication_->runtimes_.push_back(std::make_unique()); ohosApplication_->OnBackground(); - EXPECT_TRUE(ohosApplication_->runtime_ != nullptr); + EXPECT_TRUE(!(ohosApplication_->runtimes_.empty())); GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_OnBackground_0200 end."; } @@ -174,32 +174,32 @@ HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_DumpApplication_030 } /* -* @tc.number: AppExecFwk_OHOSApplicationTest_SetRuntime_0100 -* @tc.name: SetRuntime -* @tc.desc: Verify function SetRuntime pointer runtime empty +* @tc.number: AppExecFwk_OHOSApplicationTest_AddRuntime_0100 +* @tc.name: AddRuntime +* @tc.desc: Verify function AddRuntime pointer runtime empty */ -HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_SetRuntime_0100, TestSize.Level1) +HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_AddRuntime_0100, TestSize.Level1) { - GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_SetRuntime_0100 start."; + GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_AddRuntime_0100 start."; std::unique_ptr runtime = nullptr; - ohosApplication_->SetRuntime(std::move(runtime)); + ohosApplication_->AddRuntime(std::move(runtime)); EXPECT_TRUE(runtime == nullptr); - GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_SetRuntime_0100 end."; + GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_AddRuntime_0100 end."; } /* -* @tc.number: AppExecFwk_OHOSApplicationTest_SetRuntime_0200 -* @tc.name: SetRuntime -* @tc.desc: Verify function SetRuntime pointer runtime_ not empty +* @tc.number: AppExecFwk_OHOSApplicationTest_AddRuntime_0200 +* @tc.name: AddRuntime +* @tc.desc: Verify function AddRuntime pointer runtime_ not empty */ -HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_SetRuntime_0200, TestSize.Level1) +HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_AddRuntime_0200, TestSize.Level1) { - GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_SetRuntime_0200 start."; + GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_AddRuntime_0200 start."; std::unique_ptr runtime = std::make_unique(); EXPECT_TRUE(runtime != nullptr); - ohosApplication_->SetRuntime(std::move(runtime)); - EXPECT_TRUE(ohosApplication_->runtime_ != nullptr); - GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_SetRuntime_0200 end."; + ohosApplication_->AddRuntime(std::move(runtime)); + EXPECT_TRUE(!(ohosApplication_->runtimes_.empty())); + GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_AddRuntime_0200 end."; } /* @@ -568,7 +568,7 @@ HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_AddAbilityStage_090 bool isAsyncCallback = false; ohosApplication_->abilityRuntimeContext_ = std::make_shared(); ohosApplication_->AddAbilityStage(hapModuleInfo, callback, isAsyncCallback); - EXPECT_TRUE(ohosApplication_->runtime_ == nullptr); + EXPECT_TRUE(ohosApplication_->runtimes_.empty()); EXPECT_FALSE(ohosApplication_->AddAbilityStage(hapModuleInfo, callback, isAsyncCallback)); GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_AddAbilityStage_0900 end."; } @@ -585,7 +585,7 @@ HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_AddAbilityStage_010 auto callback = []() {}; bool isAsyncCallback = false; std::string moduleName = "entry"; - ohosApplication_->runtime_ = std::make_unique(); + ohosApplication_->runtimes_.push_back(std::make_unique()); std::shared_ptr abilityStages = std::make_shared(); ohosApplication_->abilityStages_.emplace(moduleName, abilityStages); ohosApplication_->abilityRuntimeContext_ = std::make_shared(); @@ -606,7 +606,7 @@ HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_AddAbilityStage_011 HapModuleInfo hapModuleInfo; auto callback = []() {}; bool isAsyncCallback = false; - ohosApplication_->runtime_ = std::make_unique(); + ohosApplication_->runtimes_.push_back(std::make_unique()); ohosApplication_->abilityRuntimeContext_ = std::make_shared(); EXPECT_TRUE(ohosApplication_->abilityStages_.empty()); ohosApplication_->abilityRuntimeContext_ = std::make_shared(); @@ -632,7 +632,7 @@ HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_AddAbilityStage_012 HapModuleInfo hapModuleInfo; auto callback = []() {}; bool isAsyncCallback = false; - ohosApplication_->runtime_ = std::make_unique(); + ohosApplication_->runtimes_.push_back(std::make_unique()); ohosApplication_->abilityRuntimeContext_ = std::make_shared(); EXPECT_TRUE(ohosApplication_->abilityStages_.empty()); ohosApplication_->abilityRuntimeContext_ = std::make_shared(); @@ -718,7 +718,7 @@ HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_GetAppContext_0100, HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_GetRuntime_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_GetRuntime_0100 start."; - auto &runtime = ohosApplication_->GetRuntime(); + auto &runtime = ohosApplication_->GetRuntime(OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); EXPECT_TRUE(runtime == nullptr); GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_GetRuntime_0100 end."; } @@ -806,7 +806,7 @@ HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_NotifyLoadRepairPat const std::string hqfFile = "hqfFile"; const std::string hapPat = "hapPat"; EXPECT_TRUE(ohosApplication_->NotifyLoadRepairPatch(hqfFile, hapPat)); - EXPECT_TRUE(ohosApplication_->runtime_ == nullptr); + EXPECT_TRUE(ohosApplication_->runtimes_.empty()); GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_NotifyLoadRepairPatch_0100 end."; } @@ -820,9 +820,9 @@ HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_NotifyLoadRepairPat GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_NotifyLoadRepairPatch_0200 start."; const std::string hqfFile = "hqfFile"; const std::string hapPath = "hapPath"; - ohosApplication_->runtime_ = std::make_unique(); + ohosApplication_->runtimes_.push_back(std::make_unique()); ohosApplication_->NotifyLoadRepairPatch(hqfFile, hapPath); - EXPECT_TRUE(ohosApplication_->runtime_ != nullptr); + EXPECT_TRUE(!(ohosApplication_->runtimes_.empty())); GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_NotifyLoadRepairPatch_0200 end."; } @@ -835,7 +835,7 @@ HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_NotifyHotReloadPage { GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_NotifyHotReloadPage_0100 start."; ohosApplication_->NotifyHotReloadPage(); - EXPECT_TRUE(ohosApplication_->runtime_ == nullptr); + EXPECT_TRUE(ohosApplication_->runtimes_.empty()); GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_NotifyHotReloadPage_0100 end."; } @@ -847,9 +847,9 @@ HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_NotifyHotReloadPage HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_NotifyHotReloadPage_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_NotifyHotReloadPage_0200 start."; - ohosApplication_->runtime_ = std::make_unique(); + ohosApplication_->runtimes_.push_back(std::make_unique()); ohosApplication_->NotifyHotReloadPage(); - EXPECT_TRUE(ohosApplication_->runtime_ != nullptr); + EXPECT_TRUE(!(ohosApplication_->runtimes_.empty())); GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_NotifyHotReloadPage_0200 end."; } @@ -863,7 +863,7 @@ HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_NotifyUnLoadRepairP GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_NotifyUnLoadRepairPatch_0100 start."; std::string hqfFile = "hqfFile"; ohosApplication_->NotifyUnLoadRepairPatch(hqfFile); - EXPECT_TRUE(ohosApplication_->runtime_ == nullptr); + EXPECT_TRUE(ohosApplication_->runtimes_.empty()); GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_NotifyUnLoadRepairPatch_0100 end."; } @@ -875,10 +875,10 @@ HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_NotifyUnLoadRepairP HWTEST_F(OHOSApplicationTest, AppExecFwk_OHOSApplicationTest_NotifyUnLoadRepairPatch_0200, TestSize.Level1) { GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_NotifyUnLoadRepairPatch_0200 start."; - ohosApplication_->runtime_ = std::make_unique(); + ohosApplication_->runtimes_.push_back(std::make_unique()); std::string hqfFile = "entry"; ohosApplication_->NotifyUnLoadRepairPatch(hqfFile); - EXPECT_TRUE(ohosApplication_->runtime_ != nullptr); + EXPECT_TRUE(!(ohosApplication_->runtimes_.empty())); GTEST_LOG_(INFO) << "AppExecFwk_OHOSApplicationTest_NotifyUnLoadRepairPatch_0200 end."; } diff --git a/test/unittest/cj_ability_delegator_args_test/cj_ability_delegator_args_test.cpp b/test/unittest/cj_ability_delegator_args_test/cj_ability_delegator_args_test.cpp index e73ec53dc3..9f5513e7a9 100644 --- a/test/unittest/cj_ability_delegator_args_test/cj_ability_delegator_args_test.cpp +++ b/test/unittest/cj_ability_delegator_args_test/cj_ability_delegator_args_test.cpp @@ -101,7 +101,8 @@ void CjAbilityDelegatorArgsTest::TearDown() HWTEST_F(CjAbilityDelegatorArgsTest, CjAbilityDelegatorArgsTestFfiAbilityDelegatorRegistryGetArguments_001, TestSize.Level1) { - OHOS::AppExecFwk::AbilityDelegatorRegistry::RegisterInstance(nullptr, nullptr); + OHOS::AppExecFwk::AbilityDelegatorRegistry::RegisterInstance(nullptr, nullptr, + OHOS::AbilityRuntime::Runtime::Language::CJ); auto result = FfiAbilityDelegatorRegistryGetArguments(); EXPECT_TRUE(result == INVALID_ARG); } @@ -114,7 +115,8 @@ HWTEST_F(CjAbilityDelegatorArgsTest, HWTEST_F(CjAbilityDelegatorArgsTest, CjAbilityDelegatorArgsTestFfiAbilityDelegatorRegistryGetArguments_002, TestSize.Level1) { - OHOS::AppExecFwk::AbilityDelegatorRegistry::RegisterInstance(abilityDelegator_, abilityDelegatorArgs_); + OHOS::AppExecFwk::AbilityDelegatorRegistry::RegisterInstance(abilityDelegator_, abilityDelegatorArgs_, + OHOS::AbilityRuntime::Runtime::Language::CJ); auto result = FfiAbilityDelegatorRegistryGetArguments(); EXPECT_TRUE(result != INVALID_ARG); } diff --git a/test/unittest/cj_ability_delegator_test/cj_ability_delegator_test.cpp b/test/unittest/cj_ability_delegator_test/cj_ability_delegator_test.cpp index 1bb04bb657..a3ad0e9e26 100644 --- a/test/unittest/cj_ability_delegator_test/cj_ability_delegator_test.cpp +++ b/test/unittest/cj_ability_delegator_test/cj_ability_delegator_test.cpp @@ -125,7 +125,8 @@ void CjAbilityDelegatorTest::TearDown() HWTEST_F(CjAbilityDelegatorTest, CjAbilityDelegatorTestStartAbility_001, TestSize.Level1) { EXPECT_NE(commonDelegator_, nullptr); - AbilityDelegatorRegistry::RegisterInstance(commonDelegator_, delegatorArgs_); + AbilityDelegatorRegistry::RegisterInstance(commonDelegator_, delegatorArgs_, + OHOS::AbilityRuntime::Runtime::Language::CJ); AAFwk::Want want; want.SetElementName(VALUE_TEST_BUNDLE_NAME, ABILITY_NAME); diff --git a/test/unittest/cj_ability_stage_object_test/BUILD.gn b/test/unittest/cj_ability_stage_object_test/BUILD.gn index d81634e4c7..2f3502ed99 100644 --- a/test/unittest/cj_ability_stage_object_test/BUILD.gn +++ b/test/unittest/cj_ability_stage_object_test/BUILD.gn @@ -87,6 +87,7 @@ ohos_unittest("cj_ability_stage_object_test") { "napi:cj_bind_native", "resource_management:global_resmgr", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { diff --git a/test/unittest/cj_ability_stage_test/BUILD.gn b/test/unittest/cj_ability_stage_test/BUILD.gn index b3fdcf676e..65d21dfbae 100644 --- a/test/unittest/cj_ability_stage_test/BUILD.gn +++ b/test/unittest/cj_ability_stage_test/BUILD.gn @@ -92,6 +92,7 @@ ohos_unittest("cj_ability_stage_test") { "napi:cj_bind_native", "resource_management:global_resmgr", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { diff --git a/test/unittest/cj_ui_ability_test/BUILD.gn b/test/unittest/cj_ui_ability_test/BUILD.gn index 397054358b..8cb698f7cd 100644 --- a/test/unittest/cj_ui_ability_test/BUILD.gn +++ b/test/unittest/cj_ui_ability_test/BUILD.gn @@ -95,6 +95,7 @@ ohos_unittest("cj_ui_ability_test") { "samgr:samgr_proxy", "window_manager:cj_window_ffi", "window_manager:scene_session", + "runtime_core:ani", ] if (ability_runtime_graphics) { diff --git a/test/unittest/dfr_test/watchdog_test/BUILD.gn b/test/unittest/dfr_test/watchdog_test/BUILD.gn index 50b69e464d..7d977ca147 100644 --- a/test/unittest/dfr_test/watchdog_test/BUILD.gn +++ b/test/unittest/dfr_test/watchdog_test/BUILD.gn @@ -84,6 +84,7 @@ ohos_unittest("watchdog_test") { "json:nlohmann_json_static", "jsoncpp:jsoncpp", "napi:ace_napi", + "runtime_core:ani", ] defines = [] diff --git a/test/unittest/frameworks_kits_ability_native_test/BUILD.gn b/test/unittest/frameworks_kits_ability_native_test/BUILD.gn index 513d1f172e..475cb31348 100644 --- a/test/unittest/frameworks_kits_ability_native_test/BUILD.gn +++ b/test/unittest/frameworks_kits_ability_native_test/BUILD.gn @@ -123,6 +123,7 @@ ohos_unittest("ability_test") { "relational_store:native_rdb", "resource_management:global_resmgr", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { @@ -696,6 +697,7 @@ ohos_unittest("ability_impl_test") { "relational_store:native_rdb", "resource_management:global_resmgr", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { @@ -764,6 +766,7 @@ ohos_unittest("ui_ability_impl_test") { "i18n:intl_util", "input:libmmi-client", "window_manager:libwm", + "runtime_core:ani", ] } } @@ -839,6 +842,7 @@ ohos_unittest("ability_thread_test") { "relational_store:native_rdb", "resource_management:global_resmgr", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { @@ -923,6 +927,7 @@ ohos_unittest("fa_ability_thread_test") { "relational_store:native_rdb", "resource_management:global_resmgr", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { @@ -1041,6 +1046,7 @@ ohos_unittest("ui_ability_thread_test") { "napi:ace_napi", "resource_management:global_resmgr", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { @@ -1475,6 +1481,7 @@ ohos_unittest("data_ability_impl_test") { "relational_store:rdb_data_share_adapter", "resource_management:global_resmgr", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { @@ -1541,6 +1548,7 @@ ohos_unittest("data_ability_impl_file_secondpart_test") { "relational_store:native_rdb", "resource_management:global_resmgr", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { @@ -1607,6 +1615,7 @@ ohos_unittest("data_ability_impl_file_test") { "relational_store:native_rdb", "resource_management:global_resmgr", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { @@ -1675,6 +1684,7 @@ ohos_unittest("ability_thread_dataability_test") { "relational_store:native_rdb", "resource_management:global_resmgr", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { @@ -1967,6 +1977,7 @@ ohos_unittest("ui_ability_test") { "napi:ace_napi", "resource_management:global_resmgr", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { @@ -2095,6 +2106,7 @@ ohos_unittest("form_host_client_test") { "resource_management:global_resmgr", "samgr:samgr_proxy", "window_manager:libwm", + "runtime_core:ani", ] } } @@ -2149,6 +2161,7 @@ ohos_unittest("continuation_test") { "relational_store:native_rdb", "resource_management:global_resmgr", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { @@ -2415,6 +2428,7 @@ ohos_unittest("ability_window_test") { "window_manager:libwm_lite", "window_manager:libwsutils", "window_manager:scene_session", + "runtime_core:ani", ] if (ability_runtime_graphics) { @@ -2473,6 +2487,7 @@ ohos_unittest("ability_handler_test") { "ipc:ipc_core", "napi:ace_napi", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { @@ -2542,6 +2557,7 @@ ohos_unittest("ability_impl_factory_test") { "relational_store:native_rdb", "relational_store:rdb_data_share_adapter", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { @@ -3425,6 +3441,7 @@ ohos_unittest("ability_second_test") { "relational_store:native_rdb", "resource_management:global_resmgr", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { diff --git a/test/unittest/frameworks_kits_ability_native_test/ability_loader_test.cpp b/test/unittest/frameworks_kits_ability_native_test/ability_loader_test.cpp index 48a66bc11c..c0a65a3feb 100644 --- a/test/unittest/frameworks_kits_ability_native_test/ability_loader_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/ability_loader_test.cpp @@ -27,8 +27,8 @@ using namespace OHOS::AppExecFwk; using namespace testing; using namespace testing::ext; using CreateAblity = std::function; -using CreateExtension = std::function; -using CreateUIAblity = std::function; +using CreateExtension = std::function; +using CreateUIAblity = std::function; class AbilityLoaderTest : public testing::Test { public: @@ -136,13 +136,14 @@ HWTEST_F(AbilityLoaderTest, GetExtensionByName_0100, TestSize.Level2) GTEST_LOG_(INFO) << "AbilityLoaderTest GetExtensionByName_0100 start"; std::string abilityName = "AbilityRuntime::Extension"; CreateExtension createFunc; - auto createExtension = []() -> AbilityRuntime::Extension *{ + auto createExtension = [](const std::string &) -> AbilityRuntime::Extension *{ AbilityRuntime::Extension *callBack = new (std::nothrow) AbilityRuntime::Extension; return callBack; }; AbilityLoader::GetInstance().extensions_.clear(); AbilityLoader::GetInstance().RegisterExtension(abilityName, createExtension); - EXPECT_TRUE(AbilityLoader::GetInstance().GetExtensionByName(abilityName) != nullptr); + EXPECT_TRUE(AbilityLoader::GetInstance().GetExtensionByName(abilityName, + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0) != nullptr); GTEST_LOG_(INFO) << "AbilityLoaderTest GetExtensionByName_0100 end"; } @@ -156,7 +157,8 @@ HWTEST_F(AbilityLoaderTest, GetExtensionByName_0200, TestSize.Level1) GTEST_LOG_(INFO) << "AbilityLoaderTest GetExtensionByName_0200 start"; std::string abilityName = "AbilityRuntime"; AbilityLoader::GetInstance().extensions_.clear(); - EXPECT_FALSE(AbilityLoader::GetInstance().GetExtensionByName(abilityName) != nullptr); + EXPECT_FALSE(AbilityLoader::GetInstance().GetExtensionByName(abilityName, + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0) != nullptr); GTEST_LOG_(INFO) << "AbilityLoaderTest GetExtensionByName_0200 end"; } @@ -191,13 +193,14 @@ HWTEST_F(AbilityLoaderTest, GetUIAbilityByName_0100, TestSize.Level1) GTEST_LOG_(INFO) << "AbilityLoaderTest GetUIAbilityByName_0100 start"; std::string abilityName = "UIAbility"; CreateAblity createFunc; - auto createAblity = []() -> AbilityRuntime::UIAbility *{ + auto createAblity = [](const std::string &) -> AbilityRuntime::UIAbility *{ AbilityRuntime::UIAbility *callBack = new (std::nothrow) AbilityRuntime::UIAbility; return callBack; }; AbilityLoader::GetInstance().uiAbilities_.clear(); AbilityLoader::GetInstance().RegisterUIAbility(abilityName, createAblity); - EXPECT_TRUE(AbilityLoader::GetInstance().GetUIAbilityByName(abilityName) != nullptr); + EXPECT_TRUE(AbilityLoader::GetInstance().GetUIAbilityByName(abilityName, + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0) != nullptr); GTEST_LOG_(INFO) << "AbilityLoaderTest GetUIAbilityByName_0100 end"; } @@ -211,6 +214,7 @@ HWTEST_F(AbilityLoaderTest, GetUIAbilityByName_0200, TestSize.Level1) GTEST_LOG_(INFO) << "AbilityLoaderTest GetAbilityByName_0200 start"; std::string abilityName = "UIAbilityName"; AbilityLoader::GetInstance().abilities_.clear(); - EXPECT_FALSE(AbilityLoader::GetInstance().GetUIAbilityByName(abilityName) != nullptr); + EXPECT_FALSE(AbilityLoader::GetInstance().GetUIAbilityByName(abilityName, + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0) != nullptr); GTEST_LOG_(INFO) << "AbilityLoaderTest GetUIAbilityByName_0200 start"; } \ No newline at end of file diff --git a/test/unittest/frameworks_kits_ability_native_test/ability_thread_test.cpp b/test/unittest/frameworks_kits_ability_native_test/ability_thread_test.cpp index 8217ba8a76..96444807b3 100644 --- a/test/unittest/frameworks_kits_ability_native_test/ability_thread_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/ability_thread_test.cpp @@ -788,7 +788,8 @@ HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_AttachExtension_0100, Function | std::shared_ptr mainRunner = EventRunner::Create(abilityInfo->name); std::string abilityName = abilitythread->CreateAbilityName(abilityRecord, application); - auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); + auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName, + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); EXPECT_EQ(extension, nullptr); abilitythread->AttachExtension(application, abilityRecord, mainRunner); @@ -815,7 +816,8 @@ HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_AttachExtension_0200, Function | auto abilityRecord = std::make_shared(abilityInfo, token, nullptr, 0); std::string abilityName = abilitythread->CreateAbilityName(abilityRecord, application); - auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); + auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName, + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); EXPECT_EQ(extension, nullptr); abilitythread->AttachExtension(application, abilityRecord); @@ -840,7 +842,8 @@ HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_AttachExtension_0201, Function | auto abilityRecord = std::make_shared(abilityInfo, token, nullptr, 0); std::string abilityName = abilitythread->CreateAbilityName(abilityRecord, nullptr); - auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); + auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName, + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); EXPECT_EQ(extension, nullptr); abilitythread->AttachExtension(nullptr, abilityRecord); @@ -860,7 +863,8 @@ HWTEST_F(AbilityThreadTest, AaFwk_AbilityThread_AttachExtension_0202, Function | std::shared_ptr application = std::make_shared(); std::string abilityName = abilitythread->CreateAbilityName(nullptr, application); - auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); + auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName, + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); EXPECT_EQ(extension, nullptr); abilitythread->AttachExtension(application, nullptr); diff --git a/test/unittest/frameworks_kits_ability_native_test/extension_ability_thread_test.cpp b/test/unittest/frameworks_kits_ability_native_test/extension_ability_thread_test.cpp index b7fd594f31..5ece1a597b 100644 --- a/test/unittest/frameworks_kits_ability_native_test/extension_ability_thread_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/extension_ability_thread_test.cpp @@ -1000,7 +1000,8 @@ HWTEST_F( auto abilityRecord = std::make_shared(abilityInfo, token, nullptr, 0); std::shared_ptr mainRunner = EventRunner::Create(abilityInfo->name); std::string abilityName = extensionabilitythread->CreateAbilityName(abilityRecord, application); - auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); + auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName, + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); EXPECT_EQ(extension, nullptr); GTEST_LOG_(INFO) << "ExtensionAbilityThread_CreateAbilityName_0100 end"; } diff --git a/test/unittest/frameworks_kits_ability_native_test/fa_ability_thread_test.cpp b/test/unittest/frameworks_kits_ability_native_test/fa_ability_thread_test.cpp index 6199eaf37b..d8eb82baa2 100644 --- a/test/unittest/frameworks_kits_ability_native_test/fa_ability_thread_test.cpp +++ b/test/unittest/frameworks_kits_ability_native_test/fa_ability_thread_test.cpp @@ -321,7 +321,8 @@ HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_AttachExtension_0300, Function std::shared_ptr mainRunner = EventRunner::Create(abilityInfo->name); std::string abilityName = abilitythread->CreateAbilityName(abilityRecord, nullptr); - auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); + auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName, + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); EXPECT_EQ(extension, nullptr); abilitythread->AttachExtension(nullptr, abilityRecord, mainRunner); @@ -346,7 +347,8 @@ HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_AttachExtension_0400, Function std::shared_ptr mainRunner = EventRunner::Create(abilityInfo->name); std::string abilityName = abilitythread->CreateAbilityName(nullptr, application); - auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); + auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName, + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); EXPECT_EQ(extension, nullptr); abilitythread->AttachExtension(application, nullptr, mainRunner); @@ -373,7 +375,8 @@ HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_AttachExtension_0500, Function auto abilityRecord = std::make_shared(abilityInfo, token, nullptr, 0); std::string abilityName = abilitythread->CreateAbilityName(abilityRecord, application); - auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); + auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName, + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); EXPECT_EQ(extension, nullptr); abilitythread->AttachExtension(application, abilityRecord, nullptr); @@ -401,7 +404,8 @@ HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_CreateAndInitContextDeal_0500, auto abilityRecord = std::make_shared(abilityInfo, token, nullptr, 0); std::string abilityName = abilitythread->CreateAbilityName(abilityRecord, application); - auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); + auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName, + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); EXPECT_EQ(extension, nullptr); auto ret = abilitythread->CreateAndInitContextDeal(application, abilityRecord, nullptr); @@ -428,7 +432,8 @@ HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_CreateAndInitContextDeal_0600, std::shared_ptr abilityObject = std::make_shared(); std::string abilityName = abilitythread->CreateAbilityName(abilityRecord, nullptr); - auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); + auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName, + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); EXPECT_EQ(extension, nullptr); auto ret = abilitythread->CreateAndInitContextDeal(nullptr, abilityRecord, abilityObject); @@ -456,7 +461,8 @@ HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_InitExtensionFlag_0200, Functi auto abilityRecord = std::make_shared(abilityInfo, token, nullptr, 0); std::string abilityName = abilitythread->CreateAbilityName(abilityRecord, application); - auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); + auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName, + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); EXPECT_EQ(extension, nullptr); abilitythread->InitExtensionFlag(abilityRecord); @@ -488,7 +494,8 @@ HWTEST_F(FaAbilityThreadTest, AaFwk_AbilityThread_InitExtensionFlag_0300, Functi auto abilityRecord = std::make_shared(abilityInfo, token, nullptr, 0); std::string abilityName = abilitythread->CreateAbilityName(abilityRecord, application); - auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName); + auto extension = AbilityLoader::GetInstance().GetExtensionByName(abilityName, + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0); EXPECT_EQ(extension, nullptr); abilitythread->InitExtensionFlag(abilityRecord); diff --git a/test/unittest/frameworks_kits_appkit_native_test/BUILD.gn b/test/unittest/frameworks_kits_appkit_native_test/BUILD.gn index 0baadfbaed..0613821abf 100644 --- a/test/unittest/frameworks_kits_appkit_native_test/BUILD.gn +++ b/test/unittest/frameworks_kits_appkit_native_test/BUILD.gn @@ -142,6 +142,7 @@ ohos_unittest("application_test") { "resource_management:global_resmgr", "resource_management:librawfile", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { @@ -207,6 +208,7 @@ ohos_unittest("context_impl_test") { "resource_management:global_resmgr", "resource_management:librawfile", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { @@ -265,6 +267,7 @@ ohos_unittest("context_impl_second_test") { "napi:ace_napi", "resource_management:global_resmgr", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { @@ -325,6 +328,7 @@ ohos_unittest("context_impl_third_test") { "resource_management:global_resmgr", "resource_management:librawfile", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { @@ -375,6 +379,7 @@ ohos_unittest("context_container_test") { "ipc:ipc_core", "napi:ace_napi", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { @@ -576,6 +581,7 @@ ohos_unittest("context_deal_test") { "napi:ace_napi", "resource_management:global_resmgr", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { @@ -631,6 +637,7 @@ ohos_unittest("application_impl_test") { "ipc:ipc_core", "napi:ace_napi", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { @@ -776,6 +783,7 @@ ohos_unittest("form_extension_context_test") { "ipc:ipc_core", "napi:ace_napi", "samgr:samgr_proxy", + "runtime_core:ani", ] if (ability_runtime_graphics) { @@ -908,6 +916,7 @@ ohos_unittest("assert_fault_test") { "init:libbegetutil", "ipc:ipc_core", "napi:ace_napi", + "runtime_core:ani", ] if (ability_runtime_graphics) { @@ -1023,6 +1032,7 @@ ohos_unittest("idle_time_test") { "hilog:libhilog", "ipc:ipc_core", "napi:ace_napi", + "runtime_core:ani", ] } @@ -1061,6 +1071,7 @@ ohos_unittest("dump_runtime_helper_second_test") { "napi:ace_napi", "ffrt:libffrt", "storage_service:storage_manager_acl", + "runtime_core:ani", ] } diff --git a/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/BUILD.gn b/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/BUILD.gn index d23b04bbb7..93ebc7c877 100644 --- a/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/BUILD.gn +++ b/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/BUILD.gn @@ -210,6 +210,7 @@ ohos_unittest("ability_delegator_registry_unittest") { "init:libbegetutil", "ipc:ipc_core", "napi:ace_napi", + "runtime_core:ani", ] } diff --git a/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/ability_delegator_registry_test.cpp b/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/ability_delegator_registry_test.cpp index 46e6d35f18..c6afcd5fba 100644 --- a/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/ability_delegator_registry_test.cpp +++ b/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/ability_delegator_registry_test.cpp @@ -96,8 +96,10 @@ HWTEST_F(AbilityDelegatorRegistryTest, Ability_Delegator_Registry_Test_0100, Fun std::unique_ptr testRunner = TestRunner::Create(nullptr, abilityArgs, true); std::shared_ptr abilityDelegator = std::make_shared(nullptr, std::move(testRunner), nullptr); - AbilityDelegatorRegistry::RegisterInstance(abilityDelegator, abilityArgs); + AbilityDelegatorRegistry::RegisterInstance(abilityDelegator, abilityArgs, + OHOS::AbilityRuntime::Runtime::Language::JS); - EXPECT_EQ(AbilityDelegatorRegistry::GetAbilityDelegator(), abilityDelegator); + EXPECT_EQ(AbilityDelegatorRegistry::GetAbilityDelegator(OHOS::AbilityRuntime::Runtime::Language::JS), + abilityDelegator); EXPECT_EQ(AbilityDelegatorRegistry::GetArguments(), abilityArgs); } diff --git a/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/ability_delegator_test.cpp b/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/ability_delegator_test.cpp index 0be170a4d0..59ed7bb952 100644 --- a/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/ability_delegator_test.cpp +++ b/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/ability_delegator_test.cpp @@ -202,7 +202,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_0100, Function | MediumTes std::shared_ptr abilityArgs = std::make_shared(want); std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), abilityArgs, true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -241,7 +242,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_0200, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -276,7 +278,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_0300, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -306,7 +309,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_0400, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -338,7 +342,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_0500, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -376,7 +381,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_0600, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -409,7 +415,8 @@ HWTEST_F(AbilityDelegatorTest2, Ability_Delegator_Test_070, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub2()); @@ -460,7 +467,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_0800, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -495,7 +503,8 @@ HWTEST_F(AbilityDelegatorTest2, Ability_Delegator_Test_0900, Function | MediumTe std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub2()); @@ -527,7 +536,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_1000, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -557,7 +567,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_1100, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -592,7 +603,8 @@ HWTEST_F(AbilityDelegatorTest2, Ability_Delegator_Test_1200, Function | MediumTe std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub2()); @@ -624,7 +636,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_1300, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -654,7 +667,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_1400, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -684,7 +698,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_1500, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -715,7 +730,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_1600, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -747,7 +763,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_1700, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -780,7 +797,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_1800, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -813,7 +831,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_1900, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -852,7 +871,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_2000, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -890,7 +910,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_2100, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -923,7 +944,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_2200, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -963,7 +985,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_23400, Function | MediumTe std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -996,7 +1019,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_2400, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -1036,7 +1060,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_2500, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -1069,7 +1094,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_2600, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -1109,7 +1135,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_2700, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -1142,7 +1169,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_2800, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -1182,7 +1210,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_2900, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -1215,7 +1244,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_3000, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -1255,7 +1285,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_3100, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -1294,7 +1325,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_3200, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -1334,7 +1366,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_3300, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -1373,7 +1406,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_3400, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -1416,13 +1450,15 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_3500, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), abilityArgs, true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub); std::shared_ptr abilityDelegator = std::make_shared(context, std::move(testRunner), iRemoteObj); - AbilityDelegatorRegistry::RegisterInstance(abilityDelegator, abilityArgs); + AbilityDelegatorRegistry::RegisterInstance(abilityDelegator, abilityArgs, + OHOS::AbilityRuntime::Runtime::Language::JS); abilityDelegator->abilityMonitors_.clear(); std::shared_ptr mockMonitor = std::make_shared(ABILITY_NAME); @@ -1461,13 +1497,15 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_3600, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), abilityArgs, true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub2); std::shared_ptr abilityDelegator = std::make_shared(context, std::move(testRunner), iRemoteObj); - AbilityDelegatorRegistry::RegisterInstance(abilityDelegator, abilityArgs); + AbilityDelegatorRegistry::RegisterInstance(abilityDelegator, abilityArgs, + OHOS::AbilityRuntime::Runtime::Language::JS); abilityDelegator->abilityMonitors_.clear(); std::shared_ptr mockMonitor = std::make_shared(ABILITY_NAME); @@ -1504,7 +1542,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_3700, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new AAFwk::MockTestObserverStub); @@ -1535,7 +1574,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_3800, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new AAFwk::MockTestObserverStub); @@ -1566,7 +1606,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_3900, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new AAFwk::MockTestObserverStub); @@ -1597,7 +1638,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_4000, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new AAFwk::MockTestObserverStub); @@ -1628,7 +1670,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_4100, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new AAFwk::MockTestObserverStub); @@ -1660,7 +1703,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_4200, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new AAFwk::MockTestObserverStub); @@ -1693,7 +1737,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_4300, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new AAFwk::MockTestObserverStub); @@ -1727,7 +1772,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_4400, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new AAFwk::MockTestObserverStub); @@ -1760,7 +1806,8 @@ HWTEST_F(AbilityDelegatorTest, Ability_Delegator_Test_4500, Function | MediumTes std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new AAFwk::MockTestObserverStub); @@ -1903,7 +1950,8 @@ HWTEST_F(AbilityDelegatorTest, StartAbilityTest_0100, TestSize.Level1) { TAG_LOGI(AAFwkTag::TEST, "test start."); ASSERT_NE(commonDelegator_, nullptr); - AbilityDelegatorRegistry::RegisterInstance(commonDelegator_, delegatorArgs_); + AbilityDelegatorRegistry::RegisterInstance(commonDelegator_, delegatorArgs_, + OHOS::AbilityRuntime::Runtime::Language::JS); AAFwk::Want want; want.SetElementName(VALUE_TEST_BUNDLE_NAME, ABILITY_NAME); diff --git a/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/js_test_runner_test.cpp b/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/js_test_runner_test.cpp index 1528289697..f990ee2384 100644 --- a/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/js_test_runner_test.cpp +++ b/test/unittest/frameworks_kits_appkit_native_test/ability_delegator/js_test_runner_test.cpp @@ -111,7 +111,8 @@ HWTEST_F(JsTestRunnerTest, Js_Test_Runner_Test_0100, Function | MediumTest | Lev } std::shared_ptr abilityArgs = std::make_shared(want); - AbilityDelegatorRegistry::RegisterInstance(nullptr, abilityArgs); + AbilityDelegatorRegistry::RegisterInstance(nullptr, abilityArgs, + OHOS::AbilityRuntime::Runtime::Language::JS); JsTestRunner* jsRunnerdrive = nullptr; jsRunnerdrive->ReportFinished(REPORT_FINISH_MSG); @@ -144,14 +145,16 @@ HWTEST_F(JsTestRunnerTest, Js_Test_Runner_Test_0200, Function | MediumTest | Lev std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), abilityArgs, true); EXPECT_TRUE(testRunner->Initialize()); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub); std::shared_ptr abilityDelegator = std::make_shared(context, std::move(testRunner), iRemoteObj); - AbilityDelegatorRegistry::RegisterInstance(abilityDelegator, abilityArgs); + AbilityDelegatorRegistry::RegisterInstance(abilityDelegator, abilityArgs, + OHOS::AbilityRuntime::Runtime::Language::JS); JsTestRunner* jsRunnerdrive = nullptr; jsRunnerdrive->ReportFinished(REPORT_FINISH_MSG); @@ -181,11 +184,13 @@ HWTEST_F(JsTestRunnerTest, Js_Test_Runner_Test_0300, Function | MediumTest | Lev } std::shared_ptr abilityArgs = std::make_shared(want); - AbilityDelegatorRegistry::RegisterInstance(nullptr, abilityArgs); + AbilityDelegatorRegistry::RegisterInstance(nullptr, abilityArgs, + OHOS::AbilityRuntime::Runtime::Language::JS); std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), std::make_shared(want), true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub()); @@ -224,13 +229,15 @@ HWTEST_F(JsTestRunnerTest, Js_Test_Runner_Test_0400, Function | MediumTest | Lev std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), abilityArgs, true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub); std::shared_ptr abilityDelegator = std::make_shared(context, std::move(testRunner), iRemoteObj); - AbilityDelegatorRegistry::RegisterInstance(abilityDelegator, abilityArgs); + AbilityDelegatorRegistry::RegisterInstance(abilityDelegator, abilityArgs, + OHOS::AbilityRuntime::Runtime::Language::JS); sptr shobserver = sptr(new MockTestObserverStub); abilityDelegator->observer_ = shobserver; @@ -266,13 +273,15 @@ HWTEST_F(JsTestRunnerTest, Js_Test_Runner_Test_0500, Function | MediumTest | Lev std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), abilityArgs, true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub); std::shared_ptr abilityDelegator = std::make_shared(context, std::move(testRunner), iRemoteObj); - AbilityDelegatorRegistry::RegisterInstance(abilityDelegator, abilityArgs); + AbilityDelegatorRegistry::RegisterInstance(abilityDelegator, abilityArgs, + OHOS::AbilityRuntime::Runtime::Language::JS); JsTestRunner* pTestRunner = static_cast(static_cast((testRunner.get()))); pTestRunner->ReportFinished(REPORT_FINISH_MSG); @@ -305,13 +314,15 @@ HWTEST_F(JsTestRunnerTest, Js_Test_Runner_Test_0600, Function | MediumTest | Lev std::shared_ptr context = std::make_shared(); std::unique_ptr testRunner = TestRunner::Create( - std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime(), + std::shared_ptr(ApplicationLoader::GetInstance().GetApplicationByName())->GetRuntime( + OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), abilityArgs, true); sptr iRemoteObj = sptr(new MockAbilityDelegatorStub); std::shared_ptr abilityDelegator = std::make_shared(context, std::move(testRunner), iRemoteObj); - AbilityDelegatorRegistry::RegisterInstance(abilityDelegator, abilityArgs); + AbilityDelegatorRegistry::RegisterInstance(abilityDelegator, abilityArgs, + OHOS::AbilityRuntime::Runtime::Language::JS); sptr shobserver = sptr(new MockTestObserverStub); abilityDelegator->observer_ = shobserver; diff --git a/test/unittest/frameworks_kits_appkit_native_test/dump_runtime_helper_second_test.cpp b/test/unittest/frameworks_kits_appkit_native_test/dump_runtime_helper_second_test.cpp index 7be5fffd66..f93adbc173 100644 --- a/test/unittest/frameworks_kits_appkit_native_test/dump_runtime_helper_second_test.cpp +++ b/test/unittest/frameworks_kits_appkit_native_test/dump_runtime_helper_second_test.cpp @@ -79,7 +79,7 @@ HWTEST_F(DumpRuntimeHelperTestSecond, SetAppFreezeFilterCallback_0200, TestSize. AbilityRuntime::Runtime::Options options; auto runtime = AbilityRuntime::Runtime::Create(options); - application->SetRuntime(std::move(runtime)); + application->AddRuntime(std::move(runtime)); helper = std::make_shared(application); helper->SetAppFreezeFilterCallback(); EXPECT_NE(application, nullptr); @@ -117,7 +117,7 @@ HWTEST_F(DumpRuntimeHelperTestSecond, DumpJsHeap_0400, TestSize.Level1) AbilityRuntime::Runtime::Options options; auto runtime = AbilityRuntime::Runtime::Create(options); - application->SetRuntime(std::move(runtime)); + application->AddRuntime(std::move(runtime)); helper = std::make_shared(application); helper->DumpJsHeap(info); EXPECT_NE(application, nullptr); @@ -146,9 +146,10 @@ HWTEST_F(DumpRuntimeHelperTestSecond, GetCheckList_0500, TestSize.Level1) AbilityRuntime::Runtime::Options options; options.lang = AbilityRuntime::Runtime::Language::JS; auto runtime = AbilityRuntime::Runtime::Create(options); - application->SetRuntime(std::move(runtime)); + application->AddRuntime(std::move(runtime)); auto helper = std::make_shared(application); - helper->GetCheckList(helper->application_->GetRuntime(), checkList); + helper->GetCheckList(helper->application_->GetRuntime(OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0), + checkList); EXPECT_NE(checkList, ""); } @@ -164,7 +165,7 @@ HWTEST_F(DumpRuntimeHelperTestSecond, GetJsLeakModule_0600, TestSize.Level1) AbilityRuntime::Runtime::Options options; options.lang = AbilityRuntime::Runtime::Language::JS; auto runtime = AbilityRuntime::Runtime::Create(options); - application->SetRuntime(std::move(runtime)); + application->AddRuntime(std::move(runtime)); auto helper = std::make_shared(application); napi_env env = nullptr; napi_value global = nullptr; @@ -185,10 +186,10 @@ HWTEST_F(DumpRuntimeHelperTestSecond, GetJsLeakModule_0700, TestSize.Level1) AbilityRuntime::Runtime::Options options; options.lang = AbilityRuntime::Runtime::Language::JS; auto runtime = AbilityRuntime::Runtime::Create(options); - application->SetRuntime(std::move(runtime)); + application->AddRuntime(std::move(runtime)); auto helper = std::make_shared(application); AbilityRuntime::JsRuntime &jsruntime = static_cast( - *helper->application_->GetRuntime()); + *helper->application_->GetRuntime(OHOS::AbilityRuntime::CODE_LANGUAGE_ARKTS_1_0)); AbilityRuntime::HandleScope handleScope(jsruntime); auto env = jsruntime.GetNapiEnv(); napi_value global = nullptr; @@ -209,7 +210,7 @@ HWTEST_F(DumpRuntimeHelperTestSecond, GetMethodCheck_0800, TestSize.Level1) AbilityRuntime::Runtime::Options options; options.lang = AbilityRuntime::Runtime::Language::JS; auto runtime = AbilityRuntime::Runtime::Create(options); - application->SetRuntime(std::move(runtime)); + application->AddRuntime(std::move(runtime)); auto helper = std::make_shared(application); napi_env env = nullptr; napi_value global = nullptr; @@ -231,7 +232,7 @@ HWTEST_F(DumpRuntimeHelperTestSecond, WriteCheckList_0900, TestSize.Level1) AbilityRuntime::Runtime::Options options; options.lang = AbilityRuntime::Runtime::Language::JS; auto runtime = AbilityRuntime::Runtime::Create(options); - application->SetRuntime(std::move(runtime)); + application->AddRuntime(std::move(runtime)); auto helper = std::make_shared(application); std::string checkList = "test"; helper->WriteCheckList(checkList); diff --git a/test/unittest/runtime_test/BUILD.gn b/test/unittest/runtime_test/BUILD.gn index 98e40c9dfd..0d058bc38e 100644 --- a/test/unittest/runtime_test/BUILD.gn +++ b/test/unittest/runtime_test/BUILD.gn @@ -287,6 +287,7 @@ group("unittest") { deps = [ ":hdc_register_test", + ":ets_runtime_test", ":js_runtime_first_test", ":js_runtime_test", ":js_worker_test",