diff --git a/bundle.json b/bundle.json index 62ba325842fb1112358b41ab8f2120e937061ed9..6c50a6466a83114a34106826e02535537930d3dc 100644 --- a/bundle.json +++ b/bundle.json @@ -179,7 +179,8 @@ "//foundation/aafwk/standard/frameworks/kits/content/cpp/test:unittest", "//foundation/aafwk/standard/frameworks/kits/ability/native/test:unittest", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/dataShare/test:unittest", - "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test:moduletest", + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/moduletest:moduletest", + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/unittest:unittest", "//foundation/aafwk/standard/frameworks/kits/test:moduletest", "//foundation/aafwk/standard/services/test:moduletest", "//foundation/aafwk/standard/services:unittest", diff --git a/frameworks/kits/ability/ability_runtime/src/ability_context_impl.cpp b/frameworks/kits/ability/ability_runtime/src/ability_context_impl.cpp index 7fe1a471cf048580712914dd8722c15a8e2e1c87..57c8cf1fc139a9d85761f193c8e46f794db03059 100644 --- a/frameworks/kits/ability/ability_runtime/src/ability_context_impl.cpp +++ b/frameworks/kits/ability/ability_runtime/src/ability_context_impl.cpp @@ -353,11 +353,12 @@ ErrCode AbilityContextImpl::StartAbility( ErrCode AbilityContextImpl::ReleaseAbility(const std::shared_ptr &callback) { + HILOG_DEBUG("AbilityContextImpl::Release begain."); if (!localCallContainer_) { HILOG_ERROR("%{public}s false.", __func__); return ERR_INVALID_VALUE; } - + HILOG_DEBUG("AbilityContextImpl::Release end."); return localCallContainer_->Release(callback); } diff --git a/frameworks/kits/ability/ability_runtime/src/local_call_container.cpp b/frameworks/kits/ability/ability_runtime/src/local_call_container.cpp index a1ac33cca6d94ae58deb8a6d71aec1aeed5011fa..a1cf18bde7dcea12b57de5a2bf6b413715748346 100644 --- a/frameworks/kits/ability/ability_runtime/src/local_call_container.cpp +++ b/frameworks/kits/ability/ability_runtime/src/local_call_container.cpp @@ -63,9 +63,9 @@ int LocalCallContainer::StartAbilityInner( HILOG_ERROR("LocalCallContainer::Resolve abilityClient is nullptr"); return ERR_INVALID_VALUE; } - sptr connect = iface_cast(this); + sptr connect = iface_cast(this->AsObject()); HILOG_DEBUG("start ability by call, abilityClient->StartAbilityByCall call"); - return abilityClient->StartAbilityByCall(want, this, callerToken); + return abilityClient->StartAbilityByCall(want, connect, callerToken); } // already finish call request. HILOG_DEBUG("start ability by call, callback->InvokeCallBack(remote) begin"); @@ -77,7 +77,9 @@ int LocalCallContainer::StartAbilityInner( int LocalCallContainer::Release(const std::shared_ptr& callback) { + HILOG_DEBUG("LocalCallContainer::Release begain."); auto isExist = [&callback](auto &record) { + HILOG_DEBUG("LocalCallContainer::Release begain1."); return record.second->RemoveCaller(callback); }; @@ -95,6 +97,7 @@ int LocalCallContainer::Release(const std::shared_ptr& callback) if (record->IsExistCallBack()) { // just release callback. + HILOG_DEBUG("LocalCallContainer::Release begain2."); return ERR_OK; } @@ -105,14 +108,14 @@ int LocalCallContainer::Release(const std::shared_ptr& callback) HILOG_ERROR("LocalCallContainer::Resolve abilityClient is nullptr"); return ERR_INVALID_VALUE; } - sptr connect = iface_cast(this); + sptr connect = iface_cast(this->AsObject()); if (abilityClient->ReleaseAbility(connect, elementName) != ERR_OK) { HILOG_ERROR("ReleaseAbility failed."); return ERR_INVALID_VALUE; } callProxyRecords_.erase(iter); - + HILOG_DEBUG("LocalCallContainer::Release end."); return ERR_OK; } @@ -180,7 +183,6 @@ bool LocalCallContainer::GetCallLocalreocrd( localCallRecord = iter->second; return true; } - return false; } diff --git a/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_ability_manager_client.cpp b/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_ability_manager_client.cpp index 284df7e225e4b63fccdde2add4d7ba972b9985b1..7423927c815093c48ef6721d56a80bb6a4019440 100644 --- a/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_ability_manager_client.cpp +++ b/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_ability_manager_client.cpp @@ -130,9 +130,11 @@ ErrCode AbilityManagerClient::StartAbilityByCall( HILOG_INFO("AbilityManagerClient::StartAbilityByCall start"); if (remoteObject_ == nullptr) { HILOG_INFO("AbilityManagerClient::StartAbilityByCall fail because remoteobject is null"); - return ABILITY_SERVICE_NOT_CONNECTED; + remoteObject_ = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID); } sptr abms = iface_cast(remoteObject_); + HILOG_INFO("AbilityManagerClient::StartAbilityByCall end"); return abms->StartAbilityByCall(want, connect, callerToken); } @@ -142,10 +144,11 @@ ErrCode AbilityManagerClient::ReleaseAbility( HILOG_INFO("AbilityManagerClient::ReleaseAbility start"); if (remoteObject_ == nullptr) { HILOG_INFO("AbilityManagerClient::ReleaseAbility fail because remoteobject is null"); - return ABILITY_SERVICE_NOT_CONNECTED; + remoteObject_ = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID); } - HILOG_INFO("AbilityManagerClient::StartAbility start2"); sptr abms = iface_cast(remoteObject_); + HILOG_INFO("AbilityManagerClient::ReleaseAbility end"); return abms->ReleaseAbility(connect, element); } diff --git a/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_serviceability_manager_service.cpp b/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_serviceability_manager_service.cpp index 2e1125b34861be734b6ac5ded468b519469b756d..01e0d174911733771f21a9c2e47a5d23012634bc 100644 --- a/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_serviceability_manager_service.cpp +++ b/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_serviceability_manager_service.cpp @@ -45,11 +45,12 @@ int MockServiceAbilityManagerService::StartAbility( int MockServiceAbilityManagerService::StartAbilityByCall( const Want &want, const sptr &connect, const sptr &callerToken) { - GTEST_LOG_(INFO) << "MockServiceAbilityManagerService::StartAbilityByCall"; + GTEST_LOG_(INFO) << "MockServiceAbilityManagerService::StartAbilityByCall begain"; if (!connect) { GTEST_LOG_(INFO) << "MockAbilityManagerService::StartAbilityByCall connect is null"; return -1; } + GTEST_LOG_(INFO) << "MockServiceAbilityManagerService::StartAbilityByCall end"; return 0; } @@ -69,7 +70,7 @@ int MockServiceAbilityManagerService::TerminateAbility( int MockServiceAbilityManagerService::ConnectAbility( const Want &want, const sptr &connect, const sptr &callerToken, int32_t userId) { - return -1; + return 0; } int MockServiceAbilityManagerService::DisconnectAbility(const sptr &connect) diff --git a/frameworks/kits/ability/ability_runtime/test/BUILD.gn b/frameworks/kits/ability/ability_runtime/test/moduletest/BUILD.gn similarity index 83% rename from frameworks/kits/ability/ability_runtime/test/BUILD.gn rename to frameworks/kits/ability/ability_runtime/test/moduletest/BUILD.gn index cbdb9dc5c4082132a98ac705fed220ba48ffe38e..8e960d4eac4fc026f083d8d56d4b029bbd902217 100644 --- a/frameworks/kits/ability/ability_runtime/test/BUILD.gn +++ b/frameworks/kits/ability/ability_runtime/test/moduletest/BUILD.gn @@ -26,10 +26,7 @@ config("module_private_config") { } include_dirs = [ "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/mock/AMS", - "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/mock/Ability/include", - "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/mock/BMS/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr/", - "//foundation/distributedschedule/safwk/services/safwk/include", + #"//foundation/distributedschedule/safwk/services/safwk/include", ] } @@ -39,7 +36,7 @@ ohos_moduletest("ability_caller_fw_module_test") { "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_ability_manager_client.cpp", "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_serviceability_manager_service.cpp", "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include/sys_mgr_client_mock.cpp", - "moduletest/ability_caller_fw_module_test.cpp", + "ability_caller_fw_module_test.cpp", ] configs = [ ":module_private_config" ] @@ -74,9 +71,6 @@ group("moduletest") { testonly = true deps = [] - deps += [ ":ability_caller_fw_module_test" ] - - # if (is_phone_product) { - # deps += [ ":ability_caller_fw_module_test" ] - # } + deps += + [ ":ability_caller_fw_module_test"] } diff --git a/frameworks/kits/ability/ability_runtime/test/moduletest/ability_caller_fw_module_test.cpp b/frameworks/kits/ability/ability_runtime/test/moduletest/ability_caller_fw_module_test.cpp index 19505858ba2fa86482470f3695197ce38ed3565f..79bf37ab2f6628148820e5685695e516ca99b3f8 100644 --- a/frameworks/kits/ability/ability_runtime/test/moduletest/ability_caller_fw_module_test.cpp +++ b/frameworks/kits/ability/ability_runtime/test/moduletest/ability_caller_fw_module_test.cpp @@ -61,10 +61,6 @@ void AbilityCallerTest::SetUpTestCase(void) } sysMgr->RegisterSystemAbility(OHOS::ABILITY_MGR_SERVICE_ID, abilityObject); - - auto task = []()->Ability* { return new (std::nothrow) Ability; }; - - AbilityLoader::GetInstance().RegisterAbility(ACE_SERVICE_ABILITY_NAME, task); } void AbilityCallerTest::TearDownTestCase(void) @@ -85,20 +81,8 @@ void AbilityCallerTest::TearDown(void) */ HWTEST_F(AbilityCallerTest, AaFwk_Ability_StartAbility_0100, Function | MediumTest | Level1) { - std::shared_ptr application = std::make_shared(); - sptr abilityToken = sptr(new AbilityThread()); - std::shared_ptr abilityInfo = std::make_shared(); - abilityInfo->type = AppExecFwk::AbilityType::SERVICE; - abilityInfo->name = "DemoAbilityNameA"; - abilityInfo->bundleName = "DemoBundleNameA"; - abilityInfo->deviceId = "DemoDeviceIdA"; - std::shared_ptr abilityRecord = - std::make_shared(abilityInfo, abilityToken); - - AbilityThread::AbilityThreadMain(application, abilityRecord, nullptr); - Want want; - want.SetElementName("DemoDeviceIdB", "DemoBundleNameB", "DemoAbilityNameB"); + want.SetElementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); std::shared_ptr callback = std::make_shared(); callback->SetCallBack([](const sptr &) {}); @@ -107,10 +91,14 @@ HWTEST_F(AbilityCallerTest, AaFwk_Ability_StartAbility_0100, Function | MediumTe ErrCode ret = context_->StartAbility(want, callback); EXPECT_TRUE(ret == 0); - AppExecFwk::ElementName element("DemoDeviceIdB", "DemoBundleNameB", "DemoAbilityNameB"); + AppExecFwk::ElementName element("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); sptr callRemoteObject = OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID); context_->localCallContainer_->OnAbilityConnectDone(element, callRemoteObject, ERR_OK); + std::vector info; + EXPECT_TRUE(info.size() == 0); + context_->localCallContainer_->DumpCalls(info); + EXPECT_TRUE(info.size() != 0); EXPECT_TRUE(callback->IsCallBack()); } @@ -122,7 +110,7 @@ HWTEST_F(AbilityCallerTest, AaFwk_Ability_StartAbility_0100, Function | MediumTe HWTEST_F(AbilityCallerTest, AaFwk_Ability_StartAbility_0200, Function | MediumTest | Level1) { Want want; - want.SetElementName("DemoDeviceIdB", "DemoBundleNameB", "DemoAbilityNameB"); + want.SetElementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); ErrCode ret = context_->StartAbility(want, nullptr); EXPECT_FALSE(ret == 0); @@ -151,18 +139,6 @@ HWTEST_F(AbilityCallerTest, AaFwk_Ability_StartAbility_0300, Function | MediumTe */ HWTEST_F(AbilityCallerTest, AaFwk_Ability_ReleaseAbility_0100, Function | MediumTest | Level1) { - std::shared_ptr application = std::make_shared(); - sptr abilityToken = sptr(new AbilityThread()); - std::shared_ptr abilityInfo = std::make_shared(); - abilityInfo->type = AppExecFwk::AbilityType::SERVICE; - abilityInfo->name = "DemoAbilityNameA"; - abilityInfo->bundleName = "DemoBundleNameA"; - abilityInfo->deviceId = "DemoDeviceIdA"; - std::shared_ptr abilityRecord = - std::make_shared(abilityInfo, abilityToken); - - AbilityThread::AbilityThreadMain(application, abilityRecord, nullptr); - Want want; want.SetElementName("DemoDeviceIdB", "DemoBundleNameB", "DemoAbilityNameB"); @@ -197,20 +173,8 @@ HWTEST_F(AbilityCallerTest, AaFwk_Ability_ReleaseAbility_0200, Function | Medium */ HWTEST_F(AbilityCallerTest, AaFwk_Ability_OnCallStubDied_0100, Function | MediumTest | Level1) { - std::shared_ptr application = std::make_shared(); - sptr abilityToken = sptr(new AbilityThread()); - std::shared_ptr abilityInfo = std::make_shared(); - abilityInfo->type = AppExecFwk::AbilityType::SERVICE; - abilityInfo->name = "DemoAbilityNameA"; - abilityInfo->bundleName = "DemoBundleNameA"; - abilityInfo->deviceId = "DemoDeviceIdA"; - std::shared_ptr abilityRecord = - std::make_shared(abilityInfo, abilityToken); - - AbilityThread::AbilityThreadMain(application, abilityRecord, nullptr); - Want want; - want.SetElementName("DemoDeviceIdB", "DemoBundleNameB", "DemoAbilityNameB"); + want.SetElementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); std::shared_ptr callback = std::make_shared(); bool isSetOnReleaseCalled = false; @@ -225,7 +189,7 @@ HWTEST_F(AbilityCallerTest, AaFwk_Ability_OnCallStubDied_0100, Function | Medium EXPECT_TRUE(ret == 0); std::shared_ptr localCallRecord; - AppExecFwk::ElementName elementName("DemoDeviceIdB", "DemoBundleNameB", "DemoAbilityNameB"); + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); context_->localCallContainer_->GetCallLocalreocrd(elementName, localCallRecord); sptr callRemoteObject = diff --git a/frameworks/kits/ability/ability_runtime/test/unittest/BUILD.gn b/frameworks/kits/ability/ability_runtime/test/unittest/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..fc57e2ec4f9dce569be7a955b43d29239f29d8bb --- /dev/null +++ b/frameworks/kits/ability/ability_runtime/test/unittest/BUILD.gn @@ -0,0 +1,126 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") + +module_out_path = "ability_runtime/ability_call_test" + +############################################################################### + +config("module_private_config") { + visibility = [ ":*" ] +} + +ohos_unittest("ability_context_impl_ut_test") { + module_out_path = module_out_path + + include_dirs = [ "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/mock/AMS" ] + + sources = [ + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_ability_manager_client.cpp", + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_serviceability_manager_service.cpp", + "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include/sys_mgr_client_mock.cpp", + "ability_context_impl_ut_test.cpp", + ] + + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_native", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] +} + +ohos_unittest("caller_call_back_ut_test") { + module_out_path = module_out_path + sources = [ + "caller_call_back_ut_test.cpp", + ] + + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_native", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//third_party/googletest:gtest_main", + ] +} + +ohos_unittest("local_call_container_ut_test") { + module_out_path = module_out_path + + include_dirs = [ "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/mock/AMS" ] + + sources = [ + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_ability_manager_client.cpp", + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_serviceability_manager_service.cpp", + "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include/sys_mgr_client_mock.cpp", + "local_call_container_ut_test.cpp", + ] + + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_native", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] +} + +ohos_unittest("local_call_record_ut_test") { + module_out_path = module_out_path + + include_dirs = [ "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/mock/AMS" ] + + sources = [ + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_ability_manager_client.cpp", + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_serviceability_manager_service.cpp", + "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include/sys_mgr_client_mock.cpp", + "local_call_record_ut_test.cpp", + ] + + deps = [ + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_native", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] +} + +################################################################################ +group("unittest") { + testonly = true + deps = [] + + deps += [ + ":ability_context_impl_ut_test", + ":caller_call_back_ut_test", + ":local_call_container_ut_test", + ":local_call_record_ut_test", + ] +} diff --git a/frameworks/kits/ability/ability_runtime/test/unittest/ability_context_impl_ut_test.cpp b/frameworks/kits/ability/ability_runtime/test/unittest/ability_context_impl_ut_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fc0014c519079a80dd7446651a06ec351db05e4a --- /dev/null +++ b/frameworks/kits/ability/ability_runtime/test/unittest/ability_context_impl_ut_test.cpp @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#define private public +#include "ability_context_impl.h" +#define protected public +#include "ability_loader.h" +#include "ability_thread.h" +#include "mock_serviceability_manager_service.h" +#include "system_ability_definition.h" +#include "sys_mgr_client.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS::AbilityRuntime; +class AbilityContextImplTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +public: + std::unique_ptr context_ = nullptr; +}; + +void AbilityContextImplTest::SetUpTestCase(void) +{ + OHOS::sptr abilityObject = new (std::nothrow) MockServiceAbilityManagerService(); + + auto sysMgr = OHOS::DelayedSingleton::GetInstance(); + if (sysMgr == NULL) { + GTEST_LOG_(ERROR) << "fail to get ISystemAbilityManager"; + return; + } + sysMgr->RegisterSystemAbility(OHOS::ABILITY_MGR_SERVICE_ID, abilityObject); +} + +void AbilityContextImplTest::TearDownTestCase(void) +{} + +void AbilityContextImplTest::SetUp(void) +{ + context_ = std::make_unique(); +} + +void AbilityContextImplTest::TearDown(void) +{} + +/** + * @tc.number: Ability_Context_Impl_StartAbility_0100 + * @tc.name: StartAbility + * @tc.desc: Ability context to process StartAbility, and the result is success(localCallContainer_ is null). + */ +HWTEST_F(AbilityContextImplTest, Ability_Context_Impl_StartAbility_0100, Function | MediumTest | Level1) +{ + Want want; + want.SetElementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + + std::shared_ptr callback = std::make_shared(); + callback->SetCallBack([](const sptr &) {}); + + ErrCode ret = context_->StartAbility(want, callback); + EXPECT_TRUE(ret == ERR_OK); +} + +/** + * @tc.number: Ability_Context_Impl_StartAbility_0200 + * @tc.name: StartAbility + * @tc.desc: Ability context to process StartAbility, and the result is success(localCallContainer_ is not null). + */ +HWTEST_F(AbilityContextImplTest, Ability_Context_Impl_StartAbility_0200, Function | MediumTest | Level1) +{ + Want want; + want.SetElementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + + std::shared_ptr callback = std::make_shared(); + callback->SetCallBack([](const sptr &) {}); + + context_->localCallContainer_ = new (std::nothrow)LocalCallContainer(); + EXPECT_NE(context_->localCallContainer_, nullptr); + + ErrCode ret = context_->StartAbility(want, callback); + EXPECT_TRUE(ret == ERR_OK); +} + +/** + * @tc.number: Ability_Context_Impl_ReleaseAbility_0100 + * @tc.name: StartAbility + * @tc.desc: Ability context to process ReleaseAbility, and the result is success. + */ +HWTEST_F(AbilityContextImplTest, Ability_Context_Impl_ReleaseAbility_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "========Ability_Context_Impl_ReleaseAbility_0100beagin==============."; + + std::shared_ptr callback = std::make_shared(); + callback->SetCallBack([](const sptr &) {}); + + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + std::shared_ptr localCallRecord = std::make_shared(elementName); + localCallRecord->AddCaller(callback); + + context_->localCallContainer_ = new (std::nothrow) LocalCallContainer(); + EXPECT_NE(context_->localCallContainer_, nullptr); + + std::string uri = elementName.GetURI(); + context_->localCallContainer_->callProxyRecords_.emplace(uri, localCallRecord); + + ErrCode ret = context_->ReleaseAbility(callback); + EXPECT_TRUE(ret == ERR_OK); + GTEST_LOG_(INFO) << "========Ability_Context_Impl_ReleaseAbility_0100end==============."; +} + +/** + * @tc.number: Ability_Context_Impl_ReleaseAbility_0200 + * @tc.name: StartAbility + * @tc.desc: Ability context to process ReleaseAbility, and the result is fail because localCallContainer is null. + */ +HWTEST_F(AbilityContextImplTest, Ability_Context_Impl_ReleaseAbility_0200, Function | MediumTest | Level1) +{ + std::shared_ptr callback = std::make_shared(); + ErrCode ret = context_->ReleaseAbility(callback); + EXPECT_TRUE(ret == ERR_INVALID_VALUE); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/ability_runtime/test/unittest/caller_call_back_ut_test.cpp b/frameworks/kits/ability/ability_runtime/test/unittest/caller_call_back_ut_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..909f105e4adada7cb80838b02c5c201b2140bfe4 --- /dev/null +++ b/frameworks/kits/ability/ability_runtime/test/unittest/caller_call_back_ut_test.cpp @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#define private public +#define protected public +#include "caller_callback.h" +#undef private +#undef protected + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS::AbilityRuntime; + +class CallerCallBackTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void CallerCallBackTest::SetUpTestCase(void) +{} + +void CallerCallBackTest::TearDownTestCase(void) +{} + +void CallerCallBackTest::SetUp(void) +{} + +void CallerCallBackTest::TearDown(void) +{} + +/** + * @tc.number: Caller_Call_Back_SetCallBack_0100 + * @tc.name: StartAbility + * @tc.desc: Caller call back to process SetCallBack success. + */ +HWTEST_F(CallerCallBackTest, Caller_Call_Back_SetCallBack_0100, Function | MediumTest | Level1) +{ + CallerCallBack callerCallBack; + EXPECT_TRUE(callerCallBack.callback_ == nullptr); + + callerCallBack.SetCallBack([](const sptr &) {}); + + EXPECT_TRUE(callerCallBack.callback_ != nullptr); +} + +/** + * @tc.number: Caller_Call_Back_SetOnRelease_0100 + * @tc.name: SetOnRelease + * @tc.desc: Caller call back to process SetOnRelease success. + */ +HWTEST_F(CallerCallBackTest, Caller_Call_Back_SetOnRelease_0100, Function | MediumTest | Level1) +{ + CallerCallBack callerCallBack; + EXPECT_TRUE(callerCallBack.onRelease_ == nullptr); + + callerCallBack.SetOnRelease([](const std::string &result) { + }); + + EXPECT_TRUE(callerCallBack.onRelease_ != nullptr); +} + +/** + * @tc.number: Caller_Call_Back_InvokeCallBack_0100 + * @tc.name: InvokeCallBack + * @tc.desc: Caller call back to process InvokeCallBack success. + */ +HWTEST_F(CallerCallBackTest, Caller_Call_Back_InvokeCallBack_0100, Function | MediumTest | Level1) +{ + CallerCallBack callerCallBack; + EXPECT_EQ(callerCallBack.isCallBack_, false); + + callerCallBack.SetCallBack([](const sptr &) {}); + + callerCallBack.InvokeCallBack(nullptr); + + EXPECT_EQ(callerCallBack.isCallBack_, true); +} + +/** + * @tc.number: Caller_Call_Back_InvokeCallBack_0200 + * @tc.name: InvokeCallBack + * @tc.desc: Caller call back to process InvokeCallBack fail because call back is null. + */ +HWTEST_F(CallerCallBackTest, Caller_Call_Back_InvokeCallBack_0200, Function | MediumTest | Level1) +{ + CallerCallBack callerCallBack; + EXPECT_EQ(callerCallBack.isCallBack_, false); + + callerCallBack.InvokeCallBack(nullptr); + + EXPECT_EQ(callerCallBack.isCallBack_, false); +} + +/** + * @tc.number: Caller_Call_Back_InvokeOnRelease_0100 + * @tc.name: InvokeOnRelease + * @tc.desc: Caller call back to process InvokeOnRelease success. + */ +HWTEST_F(CallerCallBackTest, Caller_Call_Back_InvokeOnRelease_0100, Function | MediumTest | Level1) +{ + CallerCallBack callerCallBack; + + callerCallBack.SetOnRelease([](const std::string &result) { + EXPECT_TRUE("result" == result); + }); + + std::string key = "result"; + callerCallBack.InvokeOnRelease(key); +} + +/** + * @tc.number: Caller_Call_Back_InvokeOnRelease_0200 + * @tc.name: InvokeOnRelease + * @tc.desc: Caller call back to process InvokeOnRelease fail because onRelease is null. + */ +HWTEST_F(CallerCallBackTest, Caller_Call_Back_InvokeOnRelease_0200, Function | MediumTest | Level1) +{ + CallerCallBack callerCallBack; + + std::string key(""); + callerCallBack.InvokeOnRelease(key); + + EXPECT_TRUE("" == key); +} + +/** + * @tc.number: Caller_Call_Back_IsCallBack_0100 + * @tc.name: IsCallBack + * @tc.desc: Caller call back to process IsCallBack success. + */ +HWTEST_F(CallerCallBackTest, Caller_Call_Back_IsCallBack_0100, Function | MediumTest | Level1) +{ + CallerCallBack callerCallBack; + callerCallBack.isCallBack_ = true; + + bool ret = callerCallBack.IsCallBack(); + + EXPECT_EQ(ret, true); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/ability_runtime/test/unittest/local_call_container_ut_test.cpp b/frameworks/kits/ability/ability_runtime/test/unittest/local_call_container_ut_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..894e3bc784097b4de99b70e7e4b600b2776df536 --- /dev/null +++ b/frameworks/kits/ability/ability_runtime/test/unittest/local_call_container_ut_test.cpp @@ -0,0 +1,417 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#define private public +#include "local_call_container.h" +#define protected public +#include "ability_loader.h" +#include "ability_thread.h" +#include "mock_serviceability_manager_service.h" +#include "system_ability_definition.h" +#include "sys_mgr_client.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS::AbilityRuntime; + +namespace { +} +class LocalCallContainerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void LocalCallContainerTest::SetUpTestCase(void) +{ + OHOS::sptr abilityObject = new (std::nothrow) MockServiceAbilityManagerService(); + + auto sysMgr = OHOS::DelayedSingleton::GetInstance(); + if (sysMgr == NULL) { + GTEST_LOG_(ERROR) << "fail to get ISystemAbilityManager"; + return; + } + + sysMgr->RegisterSystemAbility(OHOS::ABILITY_MGR_SERVICE_ID, abilityObject); +} + +void LocalCallContainerTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "LocalCallContainerTest::TearDownTestCase end"; +} + +void LocalCallContainerTest::SetUp(void) +{} + +void LocalCallContainerTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "LocalCallContainerTest::TearDown end"; +} + +/** + * @tc.number: Local_Call_Container_StartAbilityInner_0100 + * @tc.name: StartAbility + * @tc.desc: Local Call Container to process StartAbilityInner, and the result is success. + */ +HWTEST_F(LocalCallContainerTest, Local_Call_Container_StartAbilityInner_0100, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "Local_Call_Container_StartAbilityInner_0100::" << + "Local_Call_Container_StartAbilityInner_0100 begain"; + + sptr localCallContainer = new (std::nothrow)LocalCallContainer(); + + Want want; + want.SetElementName("DemoDeviceIdB", "DemoBundleNameB", "DemoAbilityNameB"); + + std::shared_ptr callback = std::make_shared(); + callback->SetCallBack([](const sptr &) {}); + GTEST_LOG_(INFO) << "Local_Call_Container_StartAbilityInner_0100::" << + "Local_Call_Container_StartAbilityInner_0100 begain1"; + ErrCode ret = localCallContainer->StartAbilityInner(want, callback, nullptr); + GTEST_LOG_(INFO) << "Local_Call_Container_StartAbilityInner_0100::" << + "Local_Call_Container_StartAbilityInner_0100 begain2"; + EXPECT_TRUE(ret == ERR_OK); + GTEST_LOG_(INFO) << "Local_Call_Container_StartAbilityInner_0100::" << + "Local_Call_Container_StartAbilityInner_0100 end"; +} + +/** + * @tc.number: Local_Call_Container_StartAbilityInner_0200 + * @tc.name: StartAbility + * @tc.desc: Local Call Container to process StartAbilityInner, and the result is fail because callback is null. + */ +HWTEST_F(LocalCallContainerTest, Local_Call_Container_StartAbilityInner_0200, Function | MediumTest | Level1) +{ + LocalCallContainer localCallContainer; + + Want want; + want.SetElementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + + sptr callRemoteObject = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + + ErrCode ret = localCallContainer.StartAbilityInner(want, nullptr, callRemoteObject); + EXPECT_TRUE(ret == ERR_INVALID_VALUE); +} + +/** + * @tc.number: Local_Call_Container_StartAbilityInner_0300 + * @tc.name: StartAbility + * @tc.desc: Local Call Container to process StartAbilityInner, and the result is fail because bundle name is null. + */ +HWTEST_F(LocalCallContainerTest, Local_Call_Container_StartAbilityInner_0300, Function | MediumTest | Level1) +{ + LocalCallContainer localCallContainer; + + Want want; + want.SetElementName("DemoDeviceId", "", "DemoAbilityName"); + + sptr callRemoteObject = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + + ErrCode ret = localCallContainer.StartAbilityInner(want, nullptr, callRemoteObject); + EXPECT_TRUE(ret == ERR_INVALID_VALUE); +} + +/** + * @tc.number: Local_Call_Container_StartAbilityInner_0400 + * @tc.name: StartAbility + * @tc.desc: Local Call Container to process StartAbilityInner, and the result is fail because ability name is null. + */ +HWTEST_F(LocalCallContainerTest, Local_Call_Container_StartAbilityInner_0400, Function | MediumTest | Level1) +{ + LocalCallContainer localCallContainer; + + Want want; + want.SetElementName("DemoDeviceId", "DemoBundleName", ""); + + sptr callRemoteObject = + OHOS::DelayedSingleton::GetInstance()->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + + ErrCode ret = localCallContainer.StartAbilityInner(want, nullptr, callRemoteObject); + EXPECT_TRUE(ret == ERR_INVALID_VALUE); +} + +/** + * @tc.number: Local_Call_Container_Release_0100 + * @tc.name: Release + * @tc.desc: Local Call Container to process Release, and the result is success. + */ +HWTEST_F(LocalCallContainerTest, Local_Call_Container_Release_0100, Function | MediumTest | Level1) +{ + sptr localCallContainer = new (std::nothrow)LocalCallContainer(); + + Want want; + want.SetElementName("DemoDeviceId", "DemoBundleName", ""); + + std::shared_ptr callback = std::make_shared(); + + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + std::shared_ptr localCallRecord = std::make_shared(elementName); + localCallRecord->AddCaller(callback); + + callback->SetCallBack([](const sptr &) {}); + + std::string uri = elementName.GetURI(); + localCallContainer->callProxyRecords_.emplace(uri, localCallRecord); + + ErrCode ret = localCallContainer->Release(callback); + EXPECT_TRUE(ret == ERR_OK); +} + +/** + * @tc.number: Local_Call_Container_Release_0200 + * @tc.name: Release + * @tc.desc: Local Call Container to process Release, and the result is fail bacause callProxyRecords_ is null. + */ +HWTEST_F(LocalCallContainerTest, Local_Call_Container_Release_0200, Function | MediumTest | Level1) +{ + sptr localCallContainer = new (std::nothrow)LocalCallContainer(); + + Want want; + want.SetElementName("DemoDeviceId", "DemoBundleName", ""); + + std::shared_ptr callback = std::make_shared(); + + callback->SetCallBack([](const sptr &) {}); + + ErrCode ret = localCallContainer->Release(callback); + EXPECT_TRUE(ret == ERR_INVALID_VALUE); +} + +/** + * @tc.number: Local_Call_Container_DumpCalls_0100 + * @tc.name: DumpCalls + * @tc.desc: Local Call Container to process DumpCalls, and the result is success(call back is called). + */ +HWTEST_F(LocalCallContainerTest, Local_Call_Container_DumpCalls_0100, Function | MediumTest | Level1) +{ + LocalCallContainer localCallContainer; + + std::shared_ptr callback = std::make_shared(); + callback->isCallBack_ = true; + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + std::shared_ptr localCallRecord = std::make_shared(elementName); + localCallRecord->AddCaller(callback); + + std::string uri = elementName.GetURI(); + localCallContainer.callProxyRecords_.emplace(uri, localCallRecord); + + std::vector info; + std::string resultReceiver = ""; + EXPECT_TRUE(resultReceiver == ""); + localCallContainer.DumpCalls(info); + + for (auto it : info) { + GTEST_LOG_(ERROR) << it; + resultReceiver += it + "\n"; + } + string::size_type idx; + idx = resultReceiver.find("REQUESTEND"); + EXPECT_TRUE(idx != string::npos); +} + +/** + * @tc.number: Local_Call_Container_DumpCalls_0200 + * @tc.name: DumpCalls + * @tc.desc: Local Call Container to process DumpCalls, and the result is success(call back is not called). + */ +HWTEST_F(LocalCallContainerTest, Local_Call_Container_DumpCalls_0200, Function | MediumTest | Level1) +{ + LocalCallContainer localCallContainer; + + std::shared_ptr callback = std::make_shared(); + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + std::shared_ptr localCallRecord = std::make_shared(elementName); + localCallRecord->AddCaller(callback); + + std::string uri = elementName.GetURI(); + localCallContainer.callProxyRecords_.emplace(uri, localCallRecord); + + std::vector info; + std::string resultReceiver = ""; + std::string::size_type idx; + idx = resultReceiver.find("REQUESTING"); + EXPECT_FALSE(idx != string::npos); + localCallContainer.DumpCalls(info); + + for (auto it : info) { + resultReceiver += it + "\n"; + } + idx = resultReceiver.find("REQUESTING"); + EXPECT_TRUE(idx != string::npos); +} + +/** + * @tc.number: Local_Call_Container_DumpCalls_0300 + * @tc.name: DumpCalls + * @tc.desc: Local Call Container to process DumpCalls, and the result is success(no caller). + */ +HWTEST_F(LocalCallContainerTest, Local_Call_Container_DumpCalls_0300, Function | MediumTest | Level1) +{ + LocalCallContainer localCallContainer; + + std::shared_ptr callback = std::make_shared(); + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + std::shared_ptr localCallRecord = std::make_shared(elementName); + + std::string uri = elementName.GetURI(); + localCallContainer.callProxyRecords_.emplace(uri, localCallRecord); + + std::vector info; + std::string resultReceiver = ""; + std::string::size_type idx; + idx = resultReceiver.find("REQUESTEND"); + EXPECT_FALSE(idx != string::npos); + localCallContainer.DumpCalls(info); + + for (auto it : info) { + resultReceiver += it + "\n"; + } + + idx = resultReceiver.find("REQUESTEND"); + EXPECT_TRUE(idx != string::npos); +} + +/** + * @tc.number: Local_Call_Container_DumpCalls_0400 + * @tc.name: DumpCalls + * @tc.desc: Local Call Container to process DumpCalls, and the result is success(callProxyRecords_ is empty). + */ +HWTEST_F(LocalCallContainerTest, Local_Call_Container_DumpCalls_0400, Function | MediumTest | Level1) +{ + LocalCallContainer localCallContainer; + + std::vector info; + std::string resultReceiver = ""; + EXPECT_TRUE(resultReceiver == ""); + localCallContainer.DumpCalls(info); + EXPECT_TRUE(resultReceiver == ""); +} + +/** + * @tc.number: Local_Call_Container_OnAbilityConnectDone_0100 + * @tc.name: OnAbilityConnectDone + * @tc.desc: Local Call Container to process OnAbilityConnectDone, and the result is success resultCode == ERR_OK. + */ +HWTEST_F(LocalCallContainerTest, Local_Call_Container_OnAbilityConnectDone_0100, Function | MediumTest | Level1) +{ + LocalCallContainer localCallContainer; + + std::shared_ptr callback = std::make_shared(); + callback->SetCallBack([](const sptr &) {}); + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + std::shared_ptr localCallRecord = std::make_shared(elementName); + localCallRecord->AddCaller(callback); + localCallRecord->callers_.emplace_back(callback); + + std::string uri = elementName.GetURI(); + localCallContainer.callProxyRecords_.emplace(uri, localCallRecord); + + OHOS::sptr remoteObject = new (std::nothrow) MockServiceAbilityManagerService(); + + localCallContainer.OnAbilityConnectDone(elementName, remoteObject, 0); + EXPECT_EQ(callback->isCallBack_, true); +} + +/** + * @tc.number: Local_Call_Container_OnAbilityConnectDone_0200 + * @tc.name: OnAbilityConnectDone + * @tc.desc: Local Call Container to process OnAbilityConnectDone success when resultCode != ERR_OK. + */ +HWTEST_F(LocalCallContainerTest, Local_Call_Container_OnAbilityConnectDone_0200, Function | MediumTest | Level1) +{ + LocalCallContainer localCallContainer; + + std::shared_ptr callback = std::make_shared(); + callback->SetCallBack([](const sptr &) {}); + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + std::shared_ptr localCallRecord = std::make_shared(elementName); + localCallRecord->AddCaller(callback); + localCallRecord->callers_.emplace_back(callback); + + std::string uri = elementName.GetURI(); + localCallContainer.callProxyRecords_.emplace(uri, localCallRecord); + + OHOS::sptr remoteObject = new (std::nothrow) MockServiceAbilityManagerService(); + + localCallContainer.OnAbilityConnectDone(elementName, remoteObject, -1); + EXPECT_EQ(callback->isCallBack_, true); +} + +/** + * @tc.number: Local_Call_Container_OnAbilityConnectDone_0300 + * @tc.name: OnAbilityConnectDone + * @tc.desc: Local Call Container to process OnAbilityConnectDone fail because localCallRecord is null. + */ +HWTEST_F(LocalCallContainerTest, Local_Call_Container_OnAbilityConnectDone_0300, Function | MediumTest | Level1) +{ + LocalCallContainer localCallContainer; + + std::shared_ptr callback = std::make_shared(); + EXPECT_EQ(callback->isCallBack_, false); + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + std::shared_ptr localCallRecord = std::make_shared(elementName); + localCallRecord->AddCaller(callback); + + OHOS::sptr remoteObject = new (std::nothrow) MockServiceAbilityManagerService(); + + localCallContainer.OnAbilityConnectDone(elementName, remoteObject, 0); + EXPECT_EQ(callback->isCallBack_, false); +} + +/** + * @tc.number: Local_Call_Container_GetCallLocalreocrd_0100 + * @tc.name: GetCallLocalreocrd + * @tc.desc: Local Call Container to process GetCallLocalreocrd, and the result is success. + */ +HWTEST_F(LocalCallContainerTest, Local_Call_Container_GetCallLocalreocrd_0100, Function | MediumTest | Level1) +{ + LocalCallContainer localCallContainer; + + std::shared_ptr callback = std::make_shared(); + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + std::shared_ptr localCallRecord = std::make_shared(elementName); + localCallRecord->AddCaller(callback); + + std::string uri = elementName.GetURI(); + localCallContainer.callProxyRecords_.emplace(uri, localCallRecord); + + bool ret = localCallContainer.GetCallLocalreocrd(elementName, localCallRecord); + EXPECT_TRUE(ret == true); +} + +/** + * @tc.number: Local_Call_Container_GetCallLocalreocrd_0100 + * @tc.name: GetCallLocalreocrd + * @tc.desc: Local Call Container to process GetCallLocalreocrd, and the result is fail + * because call proxy records is empty. + */ +HWTEST_F(LocalCallContainerTest, Local_Call_Container_GetCallLocalreocrd_0200, Function | MediumTest | Level1) +{ + LocalCallContainer localCallContainer; + + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + std::shared_ptr localCallRecord = std::make_shared(elementName); + + bool ret = localCallContainer.GetCallLocalreocrd(elementName, localCallRecord); + EXPECT_TRUE(ret == false); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/ability_runtime/test/unittest/local_call_record_ut_test.cpp b/frameworks/kits/ability/ability_runtime/test/unittest/local_call_record_ut_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a31e072f5d72bd4cd8953b1316042bae1c997dd6 --- /dev/null +++ b/frameworks/kits/ability/ability_runtime/test/unittest/local_call_record_ut_test.cpp @@ -0,0 +1,315 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "ability_loader.h" +#include "ability_thread.h" +#include "mock_serviceability_manager_service.h" +#define private public +#include "local_call_record.h" +#define protected public +#include "system_ability_definition.h" +#include "sys_mgr_client.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS::AbilityRuntime; + +namespace { +} + +class LocalCallRecordTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +public: + std::unique_ptr context_ = nullptr; +}; + +void LocalCallRecordTest::SetUpTestCase(void) +{ + OHOS::sptr abilityObject = new (std::nothrow) MockServiceAbilityManagerService(); + + auto sysMgr = OHOS::DelayedSingleton::GetInstance(); + if (sysMgr == NULL) { + GTEST_LOG_(ERROR) << "fail to get ISystemAbilityManager"; + return; + } + sysMgr->RegisterSystemAbility(OHOS::ABILITY_MGR_SERVICE_ID, abilityObject); +} + +void LocalCallRecordTest::TearDownTestCase(void) +{} + +void LocalCallRecordTest::SetUp(void) +{} + +void LocalCallRecordTest::TearDown(void) +{} + +/** + * @tc.number: Local_Call_Record_SetRemoteObject_0100 + * @tc.name: SetRemoteObject + * @tc.desc: LocalCallRecord to process SetRemoteObject success. + */ +HWTEST_F(LocalCallRecordTest, Local_Call_Record_SetRemoteObject_0100, Function | MediumTest | Level1) +{ + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + LocalCallRecord localCallRecord(elementName); + EXPECT_TRUE(localCallRecord.callRecipient_ == nullptr); + sptr call = new (std::nothrow) MockServiceAbilityManagerService(); + EXPECT_TRUE(call != nullptr); + localCallRecord.SetRemoteObject(call); + EXPECT_TRUE(localCallRecord.callRecipient_ != nullptr); + EXPECT_TRUE(localCallRecord.remoteObject_ != nullptr); +} + +/** + * @tc.number: Local_Call_Record_SetRemoteObject_0200 + * @tc.name: SetRemoteObject + * @tc.desc: LocalCallRecord to process SetRemoteObject fail because call back is null. + */ +HWTEST_F(LocalCallRecordTest, Local_Call_Record_SetRemoteObject_0200, Function | MediumTest | Level1) +{ + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + LocalCallRecord localCallRecord(elementName); + EXPECT_TRUE(localCallRecord.callRecipient_ == nullptr); + localCallRecord.SetRemoteObject(nullptr); + EXPECT_TRUE(localCallRecord.callRecipient_ == nullptr); + EXPECT_TRUE(localCallRecord.remoteObject_ == nullptr); +} + +/** + * @tc.number: Local_Call_Record_AddCaller_0100 + * @tc.name: AddCaller + * @tc.desc: LocalCallRecord to process AddCaller success. + */ +HWTEST_F(LocalCallRecordTest, Local_Call_Record_AddCaller_0100, Function | MediumTest | Level1) +{ + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + LocalCallRecord localCallRecord(elementName); + EXPECT_TRUE(localCallRecord.callers_.size() == 0); + std::shared_ptr callback = std::make_shared(); + localCallRecord.AddCaller(callback); + EXPECT_TRUE(localCallRecord.callers_.size() != 0); +} + +/** + * @tc.number: Local_Call_Record_RemoveCaller_0100 + * @tc.name: RemoveCaller + * @tc.desc: LocalCallRecord to process RemoveCaller success. + */ +HWTEST_F(LocalCallRecordTest, Local_Call_Record_RemoveCaller_0100, Function | MediumTest | Level1) +{ + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + LocalCallRecord localCallRecord(elementName); + std::shared_ptr callback = std::make_shared(); + localCallRecord.callers_.emplace_back(callback); + bool ret = localCallRecord.RemoveCaller(callback); + EXPECT_EQ(ret, true); +} + +/** + * @tc.number: Local_Call_Record_RemoveCaller_0200 + * @tc.name: RemoveCaller + * @tc.desc: LocalCallRecord to process RemoveCaller fail because callers_ is empty. + */ +HWTEST_F(LocalCallRecordTest, Local_Call_Record_RemoveCaller_0200, Function | MediumTest | Level1) +{ + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + LocalCallRecord localCallRecord(elementName); + std::shared_ptr callback = std::make_shared(); + bool ret = localCallRecord.RemoveCaller(callback); + EXPECT_EQ(ret, false); +} + + /** + * @tc.number: Local_Call_Record_RemoveCaller_0300 + * @tc.name: RemoveCaller + * @tc.desc: LocalCallRecord to process RemoveCaller fail because not find call back. + */ +HWTEST_F(LocalCallRecordTest, Local_Call_Record_RemoveCaller_0300, Function | MediumTest | Level1) +{ + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + LocalCallRecord localCallRecord(elementName); + std::shared_ptr callback = std::make_shared(); + localCallRecord.callers_.emplace_back(callback); + std::shared_ptr callback1 = std::make_shared(); + bool ret = localCallRecord.RemoveCaller(callback1); + EXPECT_EQ(ret, false); +} + + /** + * @tc.number: Local_Call_Record_OnCallStubDied_0100 + * @tc.name: OnCallStubDied + * @tc.desc: LocalCallRecord to process OnCallStubDied success. + */ +HWTEST_F(LocalCallRecordTest, Local_Call_Record_OnCallStubDied_0100, Function | MediumTest | Level1) +{ + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + LocalCallRecord localCallRecord(elementName); + std::shared_ptr callback = std::make_shared(); + callback->SetOnRelease([](const std::string &result) { + GTEST_LOG_(ERROR) << "OnRelease-----------" << result; + EXPECT_TRUE(result == "died"); + }); + localCallRecord.callers_.emplace_back(callback); + localCallRecord.OnCallStubDied(nullptr); +} + + /** + * @tc.number: Local_Call_Record_OnCallStubDied_0200 + * @tc.name: OnCallStubDied + * @tc.desc: LocalCallRecord to process OnCallStubDied fail because callers_ is empty. + */ +HWTEST_F(LocalCallRecordTest, Local_Call_Record_OnCallStubDied_0200, Function | MediumTest | Level1) +{ + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + LocalCallRecord localCallRecord(elementName); + std::shared_ptr callback = std::make_shared(); + callback->SetOnRelease([](const std::string &result) { + GTEST_LOG_(ERROR) << "OnRelease-----------" << result; + EXPECT_TRUE(result != "died"); + }); + localCallRecord.OnCallStubDied(nullptr); +} + + /** + * @tc.number: Local_Call_Record_OnCallStubDied_0300 + * @tc.name: OnCallStubDied + * @tc.desc: LocalCallRecord to process OnCallStubDied fail because callback is null. + */ +HWTEST_F(LocalCallRecordTest, Local_Call_Record_OnCallStubDied_0300, Function | MediumTest | Level1) +{ + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + LocalCallRecord localCallRecord(elementName); + std::shared_ptr callback = std::make_shared(); + callback->SetOnRelease([](const std::string &result) { + GTEST_LOG_(ERROR) << "OnRelease-----------" << result; + EXPECT_TRUE(result != "died"); + }); + localCallRecord.callers_.emplace_back(nullptr); + localCallRecord.OnCallStubDied(nullptr); +} + + /** + * @tc.number: Local_Call_Record_InvokeCallBack_0100 + * @tc.name: InvokeCallBack + * @tc.desc: LocalCallRecord to process InvokeCallBack success. + */ +HWTEST_F(LocalCallRecordTest, Local_Call_Record_InvokeCallBack_0100, Function | MediumTest | Level1) +{ + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + LocalCallRecord localCallRecord(elementName); + localCallRecord.remoteObject_ = new (std::nothrow) MockServiceAbilityManagerService(); + std::shared_ptr callback = std::make_shared(); + callback->SetCallBack([](const sptr &) {}); + EXPECT_TRUE(callback->IsCallBack() == false); + localCallRecord.callers_.emplace_back(callback); + localCallRecord.InvokeCallBack(); + EXPECT_TRUE(callback->IsCallBack() == true); +} + + /** + * @tc.number: Local_Call_Record_InvokeCallBack_0200 + * @tc.name: InvokeCallBack + * @tc.desc: LocalCallRecord to process InvokeCallBack fail because remote is null. + */ +HWTEST_F(LocalCallRecordTest, Local_Call_Record_InvokeCallBack_0200, Function | MediumTest | Level1) +{ + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + LocalCallRecord localCallRecord(elementName); + std::shared_ptr callback = std::make_shared(); + EXPECT_TRUE(callback->IsCallBack() == false); + localCallRecord.InvokeCallBack(); + EXPECT_TRUE(callback->IsCallBack() == false); +} + + /** + * @tc.number: Local_Call_Record_InvokeCallBack_0300 + * @tc.name: InvokeCallBack + * @tc.desc: LocalCallRecord to process InvokeCallBack fail because callers_ is empty. + */ +HWTEST_F(LocalCallRecordTest, Local_Call_Record_InvokeCallBack_0300, Function | MediumTest | Level1) +{ + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + LocalCallRecord localCallRecord(elementName); + localCallRecord.remoteObject_ = new (std::nothrow) MockServiceAbilityManagerService(); + std::shared_ptr callback = std::make_shared(); + EXPECT_TRUE(callback->IsCallBack() == false); + localCallRecord.InvokeCallBack(); + EXPECT_TRUE(callback->IsCallBack() == false); +} + + /** + * @tc.number: Local_Call_Record_InvokeCallBack_0400 + * @tc.name: InvokeCallBack + * @tc.desc: LocalCallRecord to process InvokeCallBack fail because call back is null. + */ +HWTEST_F(LocalCallRecordTest, Local_Call_Record_InvokeCallBack_0400, Function | MediumTest | Level1) +{ + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + LocalCallRecord localCallRecord(elementName); + localCallRecord.remoteObject_ = new (std::nothrow) MockServiceAbilityManagerService(); + std::shared_ptr callback = std::make_shared(); + EXPECT_TRUE(callback->IsCallBack() == false); + localCallRecord.callers_.emplace_back(nullptr); + localCallRecord.InvokeCallBack(); + EXPECT_TRUE(callback->IsCallBack() == false); +} + + /** + * @tc.number: Local_Call_Record_GetRemoteObject_0100 + * @tc.name: GetRemoteObject + * @tc.desc: LocalCallRecord to process GetRemoteObject success. + */ +HWTEST_F(LocalCallRecordTest, Local_Call_Record_GetRemoteObject_0100, Function | MediumTest | Level1) +{ + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + LocalCallRecord localCallRecord(elementName); + localCallRecord.remoteObject_ = new (std::nothrow) MockServiceAbilityManagerService(); + EXPECT_TRUE(localCallRecord.GetRemoteObject() != nullptr); +} + + /** + * @tc.number: Local_Call_Record_GetElementName_0100 + * @tc.name: GetElementName + * @tc.desc: LocalCallRecord to process GetElementName success. + */ +HWTEST_F(LocalCallRecordTest, Local_Call_Record_GetElementName_0100, Function | MediumTest | Level1) +{ + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + LocalCallRecord localCallRecord(elementName); + EXPECT_TRUE(localCallRecord.GetElementName().GetBundleName() == "DemoBundleName"); +} + + /** + * @tc.number: Local_Call_Record_IsExistCallBack_0100 + * @tc.name: IsExistCallBack + * @tc.desc: LocalCallRecord to process success. + */ +HWTEST_F(LocalCallRecordTest, Local_Call_Record_IsExistCallBack_0100, Function | MediumTest | Level1) +{ + AppExecFwk::ElementName elementName("DemoDeviceId", "DemoBundleName", "DemoAbilityName"); + LocalCallRecord localCallRecord(elementName); + std::shared_ptr callback = std::make_shared(); + localCallRecord.AddCaller(callback); + EXPECT_TRUE(localCallRecord.IsExistCallBack() == true); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/ability/native/include/ability_runtime/js_ability.h b/frameworks/kits/ability/native/include/ability_runtime/js_ability.h index 989495a67579ef4c723e0fcb4f6e5ca04309ef37..3b740e5726fd51c0ae598fb5dfa64fff6cbb87d1 100755 --- a/frameworks/kits/ability/native/include/ability_runtime/js_ability.h +++ b/frameworks/kits/ability/native/include/ability_runtime/js_ability.h @@ -77,6 +77,7 @@ private: JsRuntime &jsRuntime_; std::shared_ptr shellContextRef_; std::unique_ptr jsAbilityObj_; + sptr remoteCallee_; }; } // namespace AbilityRuntime } // namespace OHOS diff --git a/frameworks/kits/ability/native/src/ability_runtime/js_ability.cpp b/frameworks/kits/ability/native/src/ability_runtime/js_ability.cpp index 5e6d332fa6309d805aa0c84d5f0bfb7e387fe9c9..484d2f1855196b694f47d714441ea0ea84f7e522 100755 --- a/frameworks/kits/ability/native/src/ability_runtime/js_ability.cpp +++ b/frameworks/kits/ability/native/src/ability_runtime/js_ability.cpp @@ -370,6 +370,12 @@ sptr JsAbility::CallRequest() HILOG_WARN("JsAbility::CallRequest Obj is nullptr"); return nullptr; } + + if (remoteCallee_ != nullptr) { + HILOG_INFO("JsAbility::CallRequest get Callee remoteObj."); + return remoteCallee_; + } + HandleScope handleScope(jsRuntime_); HILOG_DEBUG("JsAbility::CallRequest set runtime scope."); auto& nativeEngine = jsRuntime_.GetNativeEngine(); @@ -403,8 +409,9 @@ sptr JsAbility::CallRequest() HILOG_ERROR("JsAbility::CallRequest obj is nullptr"); } + remoteCallee_ = remoteObj; HILOG_INFO("JsAbility::CallRequest end."); - return remoteObj; + return remoteCallee_; } void JsAbility::OnRequestPermissionsFromUserResult( diff --git a/frameworks/kits/ability/native/src/ability_runtime/js_caller_complex.cpp b/frameworks/kits/ability/native/src/ability_runtime/js_caller_complex.cpp index 76b16908e1db9803802758bc4062d9a01ce0a494..699329cb22fc730619d579427c8eb6b14a5b3505 100644 --- a/frameworks/kits/ability/native/src/ability_runtime/js_caller_complex.cpp +++ b/frameworks/kits/ability/native/src/ability_runtime/js_caller_complex.cpp @@ -58,6 +58,7 @@ public: return; } std::unique_ptr(static_cast(data)); + HILOG_ERROR("JsCallerComplex::%{public}s is called.", __func__); } static NativeValue* JsRelease(NativeEngine* engine, NativeCallbackInfo* info) @@ -112,7 +113,7 @@ private: } auto task = [notify = this, &str] () { notify->OnReleaseNotifyTask(str); }; - handler_->PostTask(task, "OnReleaseNotify"); + handler_->PostSyncTask(task, "OnReleaseNotify"); HILOG_DEBUG("OnReleaseNotify end"); } diff --git a/frameworks/kits/ability/native/src/new_ability_impl.cpp b/frameworks/kits/ability/native/src/new_ability_impl.cpp index 78f08b58884b401cc5fee58db5dc66810965056e..0fc4d7d53fddade706c7ccbfaa0aa7ad9c16f4c7 100644 --- a/frameworks/kits/ability/native/src/new_ability_impl.cpp +++ b/frameworks/kits/ability/native/src/new_ability_impl.cpp @@ -95,8 +95,10 @@ bool NewAbilityImpl::AbilityTransaction(const Want &want, const AAFwk::LifeCycle break; } case AAFwk::ABILITY_STATE_BACKGROUND_NEW: { + if (lifecycleState_ != ABILITY_STATE_STARTED_NEW) { + ret = false; + } Background(); - ret = false; break; } default: { diff --git a/frameworks/kits/ability/native/test/BUILD.gn b/frameworks/kits/ability/native/test/BUILD.gn index 3191a85b5a0650330884de957a42548725e94c87..17ad88af3b175a0f008c8534511d82a658602694 100644 --- a/frameworks/kits/ability/native/test/BUILD.gn +++ b/frameworks/kits/ability/native/test/BUILD.gn @@ -197,7 +197,9 @@ ohos_unittest("ability_lifecycle_executor_test") { ohos_unittest("ability_context_for_task_dispacher_test") { module_out_path = module_output_path - sources = [ "unittest/ability_context_for_task_dispacher_test.cpp" ] + sources = [ + "unittest/ability_context_for_task_dispacher_test.cpp", + ] include_dirs = [ "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include" ] @@ -372,7 +374,9 @@ ohos_unittest("scene_created_test") { configs = [ ":module_ability_context_config" ] - sources = [ "unittest/scene_created_test.cpp" ] + sources = [ + "unittest/scene_created_test.cpp", + ] deps = [ "${INNERKITS_PATH}/want:want", @@ -401,7 +405,9 @@ ohos_unittest("data_ability_helper_test") { module_out_path = module_output_path include_dirs = [ "//foundation/aafwk/standard/services/abilitymgr/include" ] - sources = [ "unittest/data_ability_helper_test.cpp" ] + sources = [ + "unittest/data_ability_helper_test.cpp", + ] configs = [ ":module_ability_context_config" ] @@ -431,7 +437,9 @@ ohos_unittest("data_ability_helper_test") { ohos_unittest("data_ability_operation_test") { module_out_path = module_output_path - sources = [ "unittest/data_ability_operation_test.cpp" ] + sources = [ + "unittest/data_ability_operation_test.cpp", + ] configs = [ ":module_private_config" ] @@ -593,6 +601,33 @@ ohos_unittest("ability_thread_test") { ] } +ohos_unittest("ability_thread_call_request_test") { + module_out_path = module_output_path + sources = [ + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/context_container.cpp", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/src/appmgr/configuration.cpp", + "unittest/ability_thread_call_request_test.cpp", + ] + + configs = [ ":module_private_config" ] + + deps = [ + "${INNERKITS_PATH}/want:want", + "//foundation/aafwk/standard/common/task_dispatcher:task_dispatcher", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ "ability_runtime:runtime" ] +} + ohos_unittest("form_provider_client_test") { module_out_path = module_output_path include_dirs = [ @@ -871,7 +906,9 @@ ohos_unittest("data_uri_utils_test") { ohos_unittest("pac_map_test") { module_out_path = module_output_path - sources = [ "//foundation/aafwk/standard/frameworks/kits/ability/native/test/unittest/pac_map_test.cpp" ] + sources = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native/test/unittest/pac_map_test.cpp", + ] configs = [ ":module_private_config" ] @@ -927,7 +964,9 @@ ohos_unittest("ability_permission_test") { ohos_unittest("task_handler_client_test") { module_out_path = module_output_path - sources = [ "//foundation/aafwk/standard/frameworks/kits/ability/native/test/unittest/task_handler_client_test.cpp" ] + sources = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native/test/unittest/task_handler_client_test.cpp", + ] configs = [ ":module_private_config" ] @@ -949,7 +988,9 @@ ohos_unittest("task_handler_client_test") { ohos_unittest("ability_thread_for_ability_on_configuration_update") { module_out_path = module_output_path - sources = [ "//foundation/aafwk/standard/frameworks/kits/ability/native/test/unittest/ability_thread_for_ability_on_configuration_update.cpp" ] + sources = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native/test/unittest/ability_thread_for_ability_on_configuration_update.cpp", + ] configs = [ ":module_private_config" ] @@ -974,7 +1015,9 @@ ohos_unittest("ability_thread_for_ability_on_configuration_update") { ohos_unittest("data_ability_result_test") { module_out_path = module_output_path - sources = [ "//foundation/aafwk/standard/frameworks/kits/ability/native/test/unittest/data_ability_result_test.cpp" ] + sources = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native/test/unittest/data_ability_result_test.cpp", + ] configs = [ ":module_private_config" ] @@ -1094,6 +1137,7 @@ group("unittest") { # ":ability_test", ":ability_thread_dataability_test", ":ability_thread_test", + ":ability_thread_call_request_test", ":continuation_test", # ":data_ability_helper_test", diff --git a/frameworks/kits/ability/native/test/unittest/ability_thread_call_request_test.cpp b/frameworks/kits/ability/native/test/unittest/ability_thread_call_request_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..07ca9b8f1baf1b176c7a395c2a7c0cffc38dc2ba --- /dev/null +++ b/frameworks/kits/ability/native/test/unittest/ability_thread_call_request_test.cpp @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#define private public +#include "ability_thread.h" +#define protected public +#include "system_ability_definition.h" +#include "sys_mgr_client.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +class CurrentAbilityTest : public Ability { +public: + sptr CallRequest() + { + sptr remoteObject = + OHOS::DelayedSingleton::GetInstance() + ->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + return remoteObject; + } +}; + +class AbilityThreadCallRequestTest : public testing::Test { +public: + AbilityThreadCallRequestTest() : abilitythread_(nullptr) + {} + ~AbilityThreadCallRequestTest() + { + abilitythread_ = nullptr; + } + AbilityThread *abilitythread_; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void AbilityThreadCallRequestTest::SetUpTestCase(void) +{} + +void AbilityThreadCallRequestTest::TearDownTestCase(void) +{} + +void AbilityThreadCallRequestTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "AbilityThreadCallRequestTest SetUp"; +} + +void AbilityThreadCallRequestTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "AbilityThreadCallRequestTest TearDown"; +} + + +/** + * @tc.number: AaFwk_AbilityThread_CallRequest_0100 + * @tc.name: CallRequest + * @tc.desc: CallRequest success + */ +HWTEST_F(AbilityThreadCallRequestTest, AaFwk_AbilityThread_CallRequest_0100, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CallRequest_0100 start"; + + AbilityThread *abilitythread = new (std::nothrow) AbilityThread(); + EXPECT_NE(abilitythread, nullptr); + if (abilitythread != nullptr) { + abilitythread->currentAbility_ = std::make_shared(); + EXPECT_NE(abilitythread->currentAbility_, nullptr); + auto runner = EventRunner::Create(true); + abilitythread->abilityHandler_ = std::make_shared(runner, abilitythread); + EXPECT_NE(abilitythread->abilityHandler_, nullptr); + sptr retval = nullptr; + retval = abilitythread->CallRequest(); + EXPECT_TRUE(retval != nullptr); + } + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CallRequest_0100 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_CallRequest_0200 + * @tc.name: CallRequest + * @tc.desc: CallRequest success fail because currentAbility_ is null + */ +HWTEST_F(AbilityThreadCallRequestTest, AaFwk_AbilityThread_CallRequest_0200, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CallRequest_0200 start"; + AbilityThread *abilitythread = new (std::nothrow) AbilityThread(); + sptr retval = abilitythread->CallRequest(); + EXPECT_TRUE(retval == nullptr); + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CallRequest_0200 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_CallRequest_0300 + * @tc.name: CallRequest + * @tc.desc: CallRequest success fail because abilityHandler_ is null + */ +HWTEST_F(AbilityThreadCallRequestTest, AaFwk_AbilityThread_CallRequest_0300, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CallRequest_0300 start"; + + AbilityThread *abilitythread = new (std::nothrow) AbilityThread(); + EXPECT_NE(abilitythread, nullptr); + if (abilitythread != nullptr) { + abilitythread->currentAbility_ = std::make_shared(); + EXPECT_NE(abilitythread->currentAbility_, nullptr); + sptr retval = abilitythread->CallRequest(); + EXPECT_TRUE(retval == nullptr); + } + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CallRequest_0300 end"; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/kits/appkit/native/app/src/context_deal.cpp b/frameworks/kits/appkit/native/app/src/context_deal.cpp index e5afdfc045c25694acda1e016726fc752e15d3f3..4f0f3835a549b1e299e1b260169d2defa8ae5316 100644 --- a/frameworks/kits/appkit/native/app/src/context_deal.cpp +++ b/frameworks/kits/appkit/native/app/src/context_deal.cpp @@ -47,7 +47,7 @@ const std::string ContextDeal::CONTEXT_DISTRIBUTED_BASE_BEFORE("/mnt/hmdfs/"); const std::string ContextDeal::CONTEXT_DISTRIBUTED_BASE_MIDDLE("/device_view/local/data/"); const std::string ContextDeal::CONTEXT_DISTRIBUTED("distributedfiles"); const std::string ContextDeal::CONTEXT_DATA_STORAGE("/data/storage/"); -const std::string ContextDeal::CONTEXT_ELS[] = {"el1", "el2"}; +const std::string ContextDeal::CONTEXT_ELS[] = {"el1", "el2", "el3", "el4"}; ContextDeal::ContextDeal(bool isCreateBySystemApp) : isCreateBySystemApp_(isCreateBySystemApp) {} diff --git a/frameworks/kits/runtime/native/js_runtime.cpp b/frameworks/kits/runtime/native/js_runtime.cpp index 41c5383a47251b18fdfcf8070ef92bfae0a100c7..5bc2ed8f4306e96ce5a519b7638f5795bec6ec1b 100644 --- a/frameworks/kits/runtime/native/js_runtime.cpp +++ b/frameworks/kits/runtime/native/js_runtime.cpp @@ -66,12 +66,6 @@ public: } } - bool RunScript(const std::string& path) override - { - static const char PANDA_MAIN_FUNCTION[] = "_GLOBAL::func_main_0"; - return vm_ != nullptr ? panda::JSNApi::Execute(vm_, path.c_str(), PANDA_MAIN_FUNCTION) : false; - } - private: static int32_t PrintVmLog(int32_t id, int32_t level, const char* tag, const char* fmt, const char* message) { @@ -353,9 +347,9 @@ std::unique_ptr JsRuntime::LoadModule(const std::string& module if (it != modules_.end()) { classValue = it->second->Get(); } else { - std::string fileName; - if (!MakeFilePath(codePath_, modulePath, fileName)) { - HILOG_ERROR("Failed to make module file path: %{private}s", modulePath.c_str()); + std::vector content; + if (!LoadModuleFile(moduleName, modulePath, content)) { + HILOG_ERROR("Failed to load module file: %{public}s", modulePath.c_str()); return std::unique_ptr(); } @@ -363,10 +357,7 @@ std::unique_ptr JsRuntime::LoadModule(const std::string& module NativeValue* exports = nativeEngine_->CreateObject(); globalObj->SetProperty("exports", exports); - if (!RunScript(fileName)) { - HILOG_ERROR("Failed to run script: %{public}s", fileName.c_str()); - return std::unique_ptr(); - } + nativeEngine_->RunBufferScript(content); NativeObject* exportsObj = ConvertNativeValueTo(globalObj->GetProperty("exports")); if (exportsObj == nullptr) { @@ -411,9 +402,29 @@ std::unique_ptr JsRuntime::LoadSystemModule( return std::unique_ptr(nativeEngine_->CreateReference(instanceValue, 1)); } -bool JsRuntime::RunScript(const std::string& path) +bool JsRuntime::LoadModuleFile( + const std::string& moduleName, const std::string& modulePath, std::vector& content) { - return nativeEngine_->RunScript(path.c_str()) != nullptr; + std::string fileName; + if (!MakeFilePath(codePath_, modulePath, fileName)) { + HILOG_ERROR("Failed to make module file path: %{private}s", modulePath.c_str()); + return false; + } + + HILOG_DEBUG("Try to open module file: %{public}s", fileName.c_str()); + + std::ifstream stream(fileName, std::ios_base::binary | std::ios_base::in | std::ios_base::ate); + if (!stream.is_open()) { + HILOG_ERROR("Failed to open module file: %{private}s", fileName.c_str()); + return false; + } + + size_t fileLength = stream.tellg(); + content.resize(fileLength); + + stream.seekg(0, std::ios_base::beg); + stream.read(reinterpret_cast(content.data()), fileLength); + return true; } using OHOS::Ace::ContainerScope; diff --git a/frameworks/kits/test/BUILD.gn b/frameworks/kits/test/BUILD.gn index e1129fb323667b18948a2e9c00d120618c9816a2..0f8c0c42bfeb1ac823b3a453ec9fb66b2d12a503 100644 --- a/frameworks/kits/test/BUILD.gn +++ b/frameworks/kits/test/BUILD.gn @@ -181,6 +181,33 @@ ohos_moduletest("ability_conetxt_test") { ] } +ohos_moduletest("ability_thread_call_request_module_test") { + module_out_path = module_output_path + sources = [ + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/src/context_container.cpp", + "//foundation/aafwk/standard/frameworks/kits/test/moduletest/cpp/abilitytest/ability_thread_call_request_module_test.cpp", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/src/appmgr/configuration.cpp", + ] + + configs = [ ":module_private_config" ] + + deps = [ + "//foundation/aafwk/standard/common/task_dispatcher:task_dispatcher", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/common:libappexecfwk_common", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ "ability_runtime:runtime" ] +} + ohos_moduletest("data_ability_operation_moduletest") { module_out_path = module_output_path sources = [ @@ -307,7 +334,7 @@ group("moduletest") { if (is_phone_product) { deps += [ ":ability_conetxt_test", - + ":ability_thread_call_request_module_test", # ":ability_moduletest", ":data_ability_helper_module_test", ":data_ability_operation_moduletest", diff --git a/frameworks/kits/test/moduletest/cpp/abilitytest/ability_thread_call_request_module_test.cpp b/frameworks/kits/test/moduletest/cpp/abilitytest/ability_thread_call_request_module_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..07ca9b8f1baf1b176c7a395c2a7c0cffc38dc2ba --- /dev/null +++ b/frameworks/kits/test/moduletest/cpp/abilitytest/ability_thread_call_request_module_test.cpp @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#define private public +#include "ability_thread.h" +#define protected public +#include "system_ability_definition.h" +#include "sys_mgr_client.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::AppExecFwk; +class CurrentAbilityTest : public Ability { +public: + sptr CallRequest() + { + sptr remoteObject = + OHOS::DelayedSingleton::GetInstance() + ->GetSystemAbility(ABILITY_MGR_SERVICE_ID); + return remoteObject; + } +}; + +class AbilityThreadCallRequestTest : public testing::Test { +public: + AbilityThreadCallRequestTest() : abilitythread_(nullptr) + {} + ~AbilityThreadCallRequestTest() + { + abilitythread_ = nullptr; + } + AbilityThread *abilitythread_; + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void AbilityThreadCallRequestTest::SetUpTestCase(void) +{} + +void AbilityThreadCallRequestTest::TearDownTestCase(void) +{} + +void AbilityThreadCallRequestTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "AbilityThreadCallRequestTest SetUp"; +} + +void AbilityThreadCallRequestTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "AbilityThreadCallRequestTest TearDown"; +} + + +/** + * @tc.number: AaFwk_AbilityThread_CallRequest_0100 + * @tc.name: CallRequest + * @tc.desc: CallRequest success + */ +HWTEST_F(AbilityThreadCallRequestTest, AaFwk_AbilityThread_CallRequest_0100, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CallRequest_0100 start"; + + AbilityThread *abilitythread = new (std::nothrow) AbilityThread(); + EXPECT_NE(abilitythread, nullptr); + if (abilitythread != nullptr) { + abilitythread->currentAbility_ = std::make_shared(); + EXPECT_NE(abilitythread->currentAbility_, nullptr); + auto runner = EventRunner::Create(true); + abilitythread->abilityHandler_ = std::make_shared(runner, abilitythread); + EXPECT_NE(abilitythread->abilityHandler_, nullptr); + sptr retval = nullptr; + retval = abilitythread->CallRequest(); + EXPECT_TRUE(retval != nullptr); + } + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CallRequest_0100 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_CallRequest_0200 + * @tc.name: CallRequest + * @tc.desc: CallRequest success fail because currentAbility_ is null + */ +HWTEST_F(AbilityThreadCallRequestTest, AaFwk_AbilityThread_CallRequest_0200, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CallRequest_0200 start"; + AbilityThread *abilitythread = new (std::nothrow) AbilityThread(); + sptr retval = abilitythread->CallRequest(); + EXPECT_TRUE(retval == nullptr); + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CallRequest_0200 end"; +} + +/** + * @tc.number: AaFwk_AbilityThread_CallRequest_0300 + * @tc.name: CallRequest + * @tc.desc: CallRequest success fail because abilityHandler_ is null + */ +HWTEST_F(AbilityThreadCallRequestTest, AaFwk_AbilityThread_CallRequest_0300, Function | MediumTest | Level3) +{ + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CallRequest_0300 start"; + + AbilityThread *abilitythread = new (std::nothrow) AbilityThread(); + EXPECT_NE(abilitythread, nullptr); + if (abilitythread != nullptr) { + abilitythread->currentAbility_ = std::make_shared(); + EXPECT_NE(abilitythread->currentAbility_, nullptr); + sptr retval = abilitythread->CallRequest(); + EXPECT_TRUE(retval == nullptr); + } + GTEST_LOG_(INFO) << "AaFwk_AbilityThread_CallRequest_0300 end"; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/runtime/include/js_runtime.h b/interfaces/innerkits/runtime/include/js_runtime.h index 0888ae2ebacf9b760060f69f9811433281ce9007..0cd7570177cab01c4aa06fa0b666caa967f11900 100644 --- a/interfaces/innerkits/runtime/include/js_runtime.h +++ b/interfaces/innerkits/runtime/include/js_runtime.h @@ -58,13 +58,12 @@ public: NativeValue* ClearCallbackTimer(NativeEngine& engine, NativeCallbackInfo& info); std::string BuildNativeAndJsBackStackTrace(); - virtual bool RunScript(const std::string& path); - protected: JsRuntime() = default; virtual bool Initialize(const Options& options); void Deinitialize(); + bool LoadModuleFile(const std::string& moduleName, const std::string& modulePath, std::vector& content); bool isArkEngine_ = false; bool debugMode_ = false; diff --git a/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.cpp b/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.cpp index c030fac89c17012429e7db4e970d614ca50a67e1..782927ff8fd2591f89a67869a9571dd13a7c2ac8 100644 --- a/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.cpp +++ b/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.cpp @@ -2243,10 +2243,6 @@ napi_value NAPI_GetSystemMemoryAttr(napi_env env, napi_callback_info info) static void GetAppMemorySizeExecute(napi_env env, void *data) { CallbackInfo *cb = static_cast(data); - if (cb == nullptr) { - HILOG_ERROR("%{public}s, create cd failed.", __func__); - return; - } cb->result = GetAbilityManagerInstance()->GetAppMemorySize(); HILOG_INFO("%{public}s, result = %{public}d", __func__, cb->result); } @@ -2256,7 +2252,7 @@ static void GetAppMemorySizePromiseComplete(napi_env env, napi_status status, vo HILOG_INFO("%{public}s, main event thread complete.", __func__); CallbackInfo *cb = static_cast(data); if (cb == nullptr) { - HILOG_ERROR("%{public}s, create cd failed.", __func__); + HILOG_ERROR("%{public}s, main event thread complete end.", __func__); return; } napi_value result = nullptr; @@ -2275,7 +2271,7 @@ static void GetAppMemorySizeAsyncComplete(napi_env env, napi_status status, void HILOG_INFO("%{public}s, main event thread complete.", __func__); CallbackInfo *cb = static_cast(data); if (cb == nullptr) { - HILOG_ERROR("%{public}s, create cd failed.", __func__); + HILOG_ERROR("%{public}s, main event thread complete end.", __func__); return; } const int errorCodeFailed = -1; @@ -2314,7 +2310,7 @@ static napi_value GetAppMemorySizePromise(napi_env env) napi_value retPromise = nullptr; CallbackInfo *cb = new (std::nothrow) CallbackInfo; if (cb == nullptr) { - HILOG_ERROR("%{public}s, create cd failed", __func__); + HILOG_INFO("%{public}s, promise cb new failed", __func__); NAPI_CALL(env, napi_get_null(env, &retPromise)); return retPromise; } @@ -2334,7 +2330,7 @@ static napi_value GetAppMemorySizeAsync(napi_env env, napi_value args) napi_valuetype valuetype = napi_undefined; CallbackInfo *cb = new (std::nothrow) CallbackInfo; if (cb == nullptr) { - HILOG_ERROR("%{public}s, create cd failed", __func__); + HILOG_ERROR("%{public}s, async cb new failed", __func__); NAPI_CALL(env, napi_get_null(env, &retAsync)); return retAsync; } @@ -2377,11 +2373,12 @@ napi_value NAPI_GetAppMemorySize(napi_env env, napi_callback_info info) static void IsRamConstrainedDeviceExecute(napi_env env, void *data) { CallbackInfo *cb = static_cast(data); - if (cb == nullptr) { - HILOG_ERROR("%{public}s, create cb failed.", __func__); - return; - } cb->isRamConstrainedDevice = GetAbilityManagerInstance()->IsRamConstrainedDevice(); + if (cb->isRamConstrainedDevice) { + HILOG_ERROR("%{public}s, true", __func__); + } else { + HILOG_ERROR("%{public}s, false", __func__); + } } static void IsRamConstrainedDevicePromiseComplete(napi_env env, napi_status status, void *data) @@ -2389,7 +2386,7 @@ static void IsRamConstrainedDevicePromiseComplete(napi_env env, napi_status stat HILOG_INFO("%{public}s, main event thread complete.", __func__); CallbackInfo *cb = static_cast(data); if (cb == nullptr) { - HILOG_ERROR("%{public}s, create cb failed.", __func__); + HILOG_ERROR("%{public}s, main event thread complete end.", __func__); return; } napi_value result = nullptr; @@ -2409,7 +2406,7 @@ static napi_value IsRamConstrainedDevicePromise(napi_env env) napi_value retPromise = nullptr; CallbackInfo *cb = new (std::nothrow) CallbackInfo; if (cb == nullptr) { - HILOG_ERROR("%{public}s, create cb failed.", __func__); + HILOG_INFO("%{public}s, promise cb new failed", __func__); NAPI_CALL(env, napi_get_null(env, &retPromise)); return retPromise; } @@ -2427,16 +2424,22 @@ static void IsRamConstrainedDeviceAsyncComplete(napi_env env, napi_status status HILOG_INFO("%{public}s, main event thread complete.", __func__); CallbackInfo *cb = static_cast(data); if (cb == nullptr) { - HILOG_ERROR("%{public}s, create cd failed.", __func__); + HILOG_ERROR("%{public}s, main event thread complete end.", __func__); return; } + const int errorCodeFailed = 1; const int errorCodeSuccess = 0; const unsigned int argsCount = 2; const unsigned int paramFirst = 0; const unsigned int paramSecond = 1; napi_value result[argsCount] = {nullptr}; - napi_create_int32(env, errorCodeSuccess, &result[paramFirst]); - napi_get_boolean(env, cb->isRamConstrainedDevice, &result[paramSecond]); + if (cb->isRamConstrainedDevice) { + napi_create_int32(env, errorCodeSuccess, &result[paramFirst]); + napi_get_boolean(env, cb->isRamConstrainedDevice, &result[paramSecond]); + } else { + napi_create_int32(env, errorCodeFailed, &result[paramFirst]); + napi_get_boolean(env, cb->isRamConstrainedDevice, &result[paramSecond]); + } napi_value undefined = nullptr; NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); napi_value callback = nullptr; @@ -2461,7 +2464,7 @@ static napi_value IsRamConstrainedDeviceAsync(napi_env env, napi_value args) napi_valuetype valuetype = napi_undefined; CallbackInfo *cb = new (std::nothrow) CallbackInfo; if (cb == nullptr) { - HILOG_ERROR("%{public}s, create cd failed", __func__); + HILOG_ERROR("%{public}s, async cb new failed", __func__); NAPI_CALL(env, napi_get_null(env, &retAsync)); return retAsync; } @@ -2469,8 +2472,6 @@ static napi_value IsRamConstrainedDeviceAsync(napi_env env, napi_value args) NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); NAPI_CALL(env, napi_typeof(env, args, &valuetype)); if (valuetype != napi_function) { - HILOG_ERROR("%{public}s, value type failed", __func__); - NAPI_CALL(env, napi_get_null(env, &retAsync)); return retAsync; } NAPI_CALL(env, napi_create_reference(env, args, 1, &cb->callback)); diff --git a/interfaces/kits/napi/aafwk/caller/caller.js b/interfaces/kits/napi/aafwk/caller/caller.js index 92cc5af9100711e2dac4cbf78bc94697f1113ee3..4ec2764a9e6bea46d5f8c20283bfda000252b336 100644 --- a/interfaces/kits/napi/aafwk/caller/caller.js +++ b/interfaces/kits/napi/aafwk/caller/caller.js @@ -58,6 +58,8 @@ class Caller { let status = await this.__call_obj__.callee.sendRequest(EVENT_CALL_NOTIFY, msgData, msgReply, option); if (!status) { + msgData.reclaim(); + msgReply.reclaim(); console.log("Caller call return status " + status); throw new Error("Function execution exception"); return ; @@ -67,6 +69,8 @@ class Caller { let str = msgReply.readString(); if (retval === REQUEST_SUCCESS && str === 'object') { console.log("Caller call return str " + str); + msgData.reclaim(); + msgReply.reclaim(); } else { console.log("Caller call retval is [" + retval + "], str [" + str + "]"); msgData.reclaim(); @@ -109,6 +113,8 @@ class Caller { let status = await this.__call_obj__.callee.sendRequest(EVENT_CALL_NOTIFY, msgData, msgReply, option); if (!status) { console.log("Caller callWithResult return data " + status); + msgData.reclaim(); + msgReply.reclaim(); return reply; } @@ -117,6 +123,7 @@ class Caller { if (retval === REQUEST_SUCCESS && str === 'object') { reply = msgReply; console.log("Caller callWithResult return data " + str); + msgData.reclaim(); } else { console.log("Caller callWithResult retval is [" + retval + "], str [" + str + "]"); msgData.reclaim(); diff --git a/interfaces/kits/napi/aafwk/featureAbility/feature_ability_constant.cpp b/interfaces/kits/napi/aafwk/featureAbility/feature_ability_constant.cpp index e9a4928fe5a2cded514bf249983ced8e937daa6e..be59c1411845b6540c92f062f2b6c4913f446c4f 100644 --- a/interfaces/kits/napi/aafwk/featureAbility/feature_ability_constant.cpp +++ b/interfaces/kits/napi/aafwk/featureAbility/feature_ability_constant.cpp @@ -35,17 +35,11 @@ napi_value FAConstantInit(napi_env env, napi_value exports) const int Window_Configuration_Zero = 100; const int Window_Configuration_One = 101; const int Window_Configuration_Two = 102; - const int NO_ERROR = 0; - const int INVALID_PARAMETER = -1; - const int ABILITY_NOT_FOUND = -2; - const int PERMISSION_DENY = -3; HILOG_INFO("%{public}s,called", __func__); napi_value abilityStartSetting = nullptr; napi_value abilityWindowConfiguration = nullptr; - napi_value errorCode = nullptr; napi_create_object(env, &abilityStartSetting); napi_create_object(env, &abilityWindowConfiguration); - napi_create_object(env, &errorCode); SetNamedProperty(env, abilityStartSetting, "abilityBounds", "BOUNDS_KEY"); SetNamedProperty(env, abilityStartSetting, "windowMode", "WINDOW_MODE_KEY"); @@ -57,15 +51,9 @@ napi_value FAConstantInit(napi_env env, napi_value exports) SetNamedProperty(env, abilityWindowConfiguration, Window_Configuration_One, "WINDOW_MODE_SPLIT_SECONDARY"); SetNamedProperty(env, abilityWindowConfiguration, Window_Configuration_Two, "WINDOW_MODE_FLOATING"); - SetNamedProperty(env, errorCode, NO_ERROR, "NO_ERROR"); - SetNamedProperty(env, errorCode, INVALID_PARAMETER, "INVALID_PARAMETER"); - SetNamedProperty(env, errorCode, ABILITY_NOT_FOUND, "ABILITY_NOT_FOUND"); - SetNamedProperty(env, errorCode, PERMISSION_DENY, "PERMISSION_DENY"); - napi_property_descriptor exportFuncs[] = { DECLARE_NAPI_PROPERTY("AbilityStartSetting", abilityStartSetting), DECLARE_NAPI_PROPERTY("AbilityWindowConfiguration", abilityWindowConfiguration), - DECLARE_NAPI_PROPERTY("ErrorCode", errorCode), }; napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); diff --git a/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp b/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp index 980cb62a4f8d10a9355ea086a7b7d24fb2de8396..2ae57a00d06a098a26a9d46dc0fd0c9245c7c54a 100644 --- a/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp +++ b/interfaces/kits/napi/aafwk/featureAbility/napi_context.cpp @@ -539,6 +539,20 @@ napi_value NAPI_GetCacheDir(napi_env env, napi_callback_info info) return NAPI_GetCacheDirCommon(env, info, AbilityType::PAGE); } +/** + * @brief Get ExternalCache Dir. + * + * @param env The environment that the Node-API call is invoked under. + * @param info The callback info passed into the callback function. + * + * @return The return value from NAPI C++ to JS for the module. + */ +napi_value NAPI_GetExternalCacheDir(napi_env env, napi_callback_info info) +{ + HILOG_INFO("%{public}s called", __func__); + return NAPI_GetExternalCacheDirCommon(env, info, AbilityType::PAGE); +} + /** * @brief Obtains the type of this application. * @@ -3085,6 +3099,7 @@ napi_value ContextPermissionInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("getDatabaseDirSync", NAPI_GetDatabaseDirSync), DECLARE_NAPI_FUNCTION("getPreferencesDirSync", NAPI_GetPreferencesDirSync), DECLARE_NAPI_FUNCTION("getCacheDir", NAPI_GetCacheDir), + DECLARE_NAPI_FUNCTION("getExternalCacheDir", NAPI_GetExternalCacheDir), DECLARE_NAPI_FUNCTION("getAppType", NAPI_GetCtxAppType), DECLARE_NAPI_FUNCTION("getHapModuleInfo", NAPI_GetCtxHapModuleInfo), DECLARE_NAPI_FUNCTION("getAppVersionInfo", NAPI_GetAppVersionInfo), diff --git a/interfaces/kits/napi/aafwk/featureAbility/napi_context.h b/interfaces/kits/napi/aafwk/featureAbility/napi_context.h index ff440a1d1446bdcc5ec6c06a12613c654f38ac59..5f40eb0520523126f74762ab829f7b89e6e88031 100644 --- a/interfaces/kits/napi/aafwk/featureAbility/napi_context.h +++ b/interfaces/kits/napi/aafwk/featureAbility/napi_context.h @@ -119,6 +119,8 @@ napi_value NAPI_GetFilesDir(napi_env env, napi_callback_info info); napi_value NAPI_GetCacheDir(napi_env env, napi_callback_info info); +napi_value NAPI_GetExternalCacheDir(napi_env env, napi_callback_info info); + /** * @brief Obtains the type of this application. * diff --git a/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp b/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp index 520ab24ec73c4c48d41b79a13dba055c16c54580..d6dcde5a74ee448218b2571821cd6500dc1da210 100644 --- a/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp +++ b/interfaces/kits/napi/aafwk/featureAbility/napi_data_ability_helper.cpp @@ -24,7 +24,6 @@ #include "uri.h" #include "../inner/napi_common/napi_common_ability.h" -#include "../inner/napi_common/napi_common_call_util.h" #include "data_ability_operation.h" #include "data_ability_result.h" #include "hilog_wrapper.h" @@ -35,6 +34,7 @@ #include "napi_rdb_predicates.h" #include "napi_result_set.h" #include "securec.h" +#include "json.h" using namespace OHOS::AAFwk; using namespace OHOS::AppExecFwk; @@ -2452,6 +2452,324 @@ void UpdatePromiseCompleteCB(napi_env env, napi_status status, void *data) HILOG_INFO("NAPI_Update, main event thread complete end."); } +void Stringsplit(const string &str, const string &splits, std::vector &res) +{ + if (str == "") { + return; + } + string strs = str + splits; + size_t pos = strs.find(splits); + int step = splits.size(); + + while (pos != strs.npos) { + string temp = strs.substr(0, pos); + HILOG_INFO("Stringsplit temp:%{public}s", temp.c_str()); + res.push_back(temp); + strs = strs.substr(pos + step, strs.size()); + pos = strs.find(splits); + } +} + +void SetPacMapObject(AppExecFwk::PacMap &pacMap, const napi_env &env, std::string keyStr, napi_value value) +{ + napi_valuetype valueType = napi_undefined; + napi_typeof(env, value, &valueType); + HILOG_INFO("ValueObject--------> type:%{public}d", valueType); + if (valueType == napi_string) { + std::string valueString = UnwrapStringFromJS(env, value); + HILOG_INFO("ValueObject type:%{public}d, key:%{public}s, value:%{private}s", valueType, keyStr.c_str(), + valueString.c_str()); + pacMap.PutStringValue(keyStr, valueString); + } else if (valueType == napi_number) { + double valueNumber = 0; + napi_get_value_double(env, value, &valueNumber); + pacMap.PutDoubleValue(keyStr, valueNumber); + HILOG_INFO( + "ValueObject type:%{public}d, key:%{public}s, value:%{private}lf", valueType, keyStr.c_str(), valueNumber); + } else if (valueType == napi_boolean) { + bool valueBool = false; + napi_get_value_bool(env, value, &valueBool); + HILOG_INFO( + "ValueObject type:%{public}d, key:%{public}s, value:%{private}d", valueType, keyStr.c_str(), valueBool); + pacMap.PutBooleanValue(keyStr, valueBool); + } else if (valueType == napi_null) { + pacMap.PutObject(keyStr, nullptr); + HILOG_INFO("ValueObject type:%{public}d, key:%{public}s, value:null", valueType, keyStr.c_str()); + } else if (valueType == napi_object) { + HILOG_INFO("ValueObject type:%{public}d, key:%{public}s, value:Uint8Array", valueType, keyStr.c_str()); + pacMap.PutStringValueArray(keyStr, ConvertStringVector(env, value)); + } else { + HILOG_ERROR("pacMap error"); + } +} + +void AnalysisPacMap(AppExecFwk::PacMap &pacMap, const napi_env &env, const napi_value &arg) +{ + napi_value keys = 0; + napi_get_property_names(env, arg, &keys); + uint32_t arrLen = 0; + napi_status status = napi_get_array_length(env, keys, &arrLen); + if (status != napi_ok) { + HILOG_ERROR("PacMap errr"); + return; + } + HILOG_INFO("PacMap num:%{public}d ", arrLen); + for (size_t i = 0; i < arrLen; ++i) { + napi_value key = 0; + status = napi_get_element(env, keys, i, &key); + std::string keyStr = UnwrapStringFromJS(env, key); + HILOG_INFO("PacMap keyStr:%{public}s ", keyStr.c_str()); + napi_value value = 0; + napi_get_property(env, arg, key, &value); + + SetPacMapObject(pacMap, env, keyStr, value); + } +} + +void ParseEqualTo(AppExecFwk::PacMap &pacMap, std::string &value_str, NativeRdb::DataAbilityPredicates &predicates) +{ + std::string equalValue = pacMap.GetStringValue(value_str, ""); + HILOG_INFO("ParseJsonKey equalTo equalValue1:%{private}s ", equalValue.c_str()); + if (equalValue != "") { + if (equalValue.find(",") == string::npos) { + predicates.EqualTo(value_str, equalValue); + pacMap.Remove(value_str); + } else { + std::vector value_vec; + Stringsplit(equalValue, ",", value_vec); + predicates.EqualTo(value_str, value_vec[0]); + pacMap.Remove(value_str); + pacMap.PutStringValue(value_str, equalValue.substr(value_vec[0].length() + 1, equalValue.length())); + HILOG_INFO("ParseJsonKey notEqualTo equalValue2:%{private}s ", + equalValue.substr(value_vec[0].length() + 1, equalValue.length()).c_str()); + } + } else { + double equalDoubleValue = pacMap.GetDoubleValue(value_str, DBL_MIN); + predicates.EqualTo(value_str, std::to_string(equalDoubleValue)); + HILOG_INFO("ParseJsonKey notEqualTo equalValue3:%{private}s ", + std::to_string(pacMap.GetDoubleValue(value_str, DBL_MIN)).c_str()); + pacMap.Remove(value_str); + } +} + +void ParseNotEqualTo(AppExecFwk::PacMap &pacMap, std::string &value_str, NativeRdb::DataAbilityPredicates &predicates) +{ + std::string equalValue = pacMap.GetStringValue(value_str, "123##*##abc"); + HILOG_INFO("ParseJsonKey notEqualTo equalValue1:%{private}s ", equalValue.c_str()); + if (equalValue != "123##*##abc") { + if (equalValue.find(",") == string::npos) { + predicates.NotEqualTo(value_str, equalValue); + pacMap.Remove(value_str); + } else { + std::vector value_vec; + Stringsplit(equalValue, ",", value_vec); + predicates.NotEqualTo(value_str, value_vec[0]); + pacMap.Remove(value_str); + pacMap.PutStringValue(value_str, equalValue.substr(value_vec[0].length() + 1, equalValue.length())); + HILOG_INFO("ParseJsonKey notEqualTo equalValue2:%{private}s ", + equalValue.substr(value_vec[0].length() + 1, equalValue.length()).c_str()); + } + } else { + predicates.NotEqualTo(value_str, std::to_string(pacMap.GetDoubleValue(value_str, DBL_MIN))); + HILOG_INFO("ParseJsonKey notEqualTo equalValue3:%{private}s ", + std::to_string(pacMap.GetDoubleValue(value_str, DBL_MIN)).c_str()); + pacMap.Remove(value_str); + } +} + +void ParseBetween(AppExecFwk::PacMap &pacMap, std::string &value_str, NativeRdb::DataAbilityPredicates &predicates) +{ + std::string betweenValue = pacMap.GetStringValue(value_str, ""); + HILOG_INFO("ParseJsonKey between betweenValue1:%{private}s ", betweenValue.c_str()); + std::vector value_vec; + Stringsplit(betweenValue, ",", value_vec); + predicates.Between(value_str, value_vec[0], value_vec[1]); + int tempLength = value_vec[0].length() + 1 + value_vec[1].length() + 1; + value_vec.erase(value_vec.begin(), value_vec.begin() + 1); + pacMap.Remove(value_str); + if (value_vec.size() == 1) { + pacMap.PutDoubleValue(value_str, stod(value_vec[0])); + HILOG_INFO("ParseJsonKey between betweenValue2:%{private}s ", value_vec[0].c_str()); + } else if (value_vec.size() > 1) { + pacMap.PutStringValue(value_str, betweenValue.substr(tempLength, betweenValue.length())); + HILOG_INFO("ParseJsonKey between betweenValue3:%{private}s ", + betweenValue.substr(tempLength, betweenValue.length()).c_str()); + } +} + +void ParseNotBetween(AppExecFwk::PacMap &pacMap, std::string &value_str, NativeRdb::DataAbilityPredicates &predicates) +{ + std::string betweenValue = pacMap.GetStringValue(value_str, ""); + HILOG_INFO("ParseJsonKey notBetween betweenValue1:%{private}s ", betweenValue.c_str()); + std::vector value_vec; + Stringsplit(betweenValue, ",", value_vec); + predicates.NotBetween(value_str, value_vec[0], value_vec[1]); + int tempLength = value_vec[0].length() + 1 + value_vec[1].length() + 1; + value_vec.erase(value_vec.begin(), value_vec.begin() + 1); + pacMap.Remove(value_str); + if (value_vec.size() == 1) { + pacMap.PutDoubleValue(value_str, stod(value_vec[0])); + HILOG_INFO("ParseJsonKey notBetween betweenValue2:%{private}s ", value_vec[0].c_str()); + } else if (value_vec.size() > 1) { + pacMap.PutStringValue(value_str, betweenValue.substr(tempLength, betweenValue.length())); + HILOG_INFO("ParseJsonKey notBetween betweenValue3:%{private}s ", + betweenValue.substr(tempLength, betweenValue.length()).c_str()); + } +} + +void ParseIn(AppExecFwk::PacMap &pacMap, std::string &value_str, NativeRdb::DataAbilityPredicates &predicates) +{ + std::string inValue = pacMap.GetStringValue(value_str, ""); + HILOG_INFO("ParseJsonKey in value_str1:%{private}s ", inValue.c_str()); + std::vector value_vec; + Stringsplit(inValue, ",", value_vec); + if (value_vec.size() >= ARGS_TWO) { + std::vector in_vec; + in_vec.push_back(value_vec[0]); + in_vec.push_back(value_vec[1]); + predicates.In(value_str, in_vec); + int tempLength = value_vec[0].length() + 1 + value_vec[1].length() + 1; + value_vec.erase(value_vec.begin(), value_vec.begin() + 1); + pacMap.Remove(value_str); + if (value_vec.size() == 1) { + pacMap.PutDoubleValue(value_str, stod(value_vec[0])); + HILOG_INFO("ParseJsonKey in value_str2:%{private}s ", value_vec[0].c_str()); + } else if (value_vec.size() > 1) { + pacMap.PutStringValue(value_str, inValue.substr(tempLength, inValue.length())); + HILOG_INFO("ParseJsonKey in value_str3:%{private}s ", inValue.substr(tempLength, inValue.length()).c_str()); + } + } else { + pacMap.Remove(value_str); + } +} + +void ParseNotIn(AppExecFwk::PacMap &pacMap, std::string &value_str, NativeRdb::DataAbilityPredicates &predicates) +{ + std::string inValue = pacMap.GetStringValue(value_str, ""); + HILOG_INFO("ParseJsonKey notIn value_str1:%{private}s ", inValue.c_str()); + std::vector value_vec; + Stringsplit(inValue, ",", value_vec); + if (value_vec.size() >= ARGS_TWO) { + std::vector in_vec; + in_vec.push_back(value_vec[0]); + in_vec.push_back(value_vec[1]); + predicates.NotIn(value_str, in_vec); + int tempLength = value_vec[0].length() + 1 + value_vec[1].length() + 1; + value_vec.erase(value_vec.begin(), value_vec.begin() + 1); + pacMap.Remove(value_str); + if (value_vec.size() == 1) { + pacMap.PutDoubleValue(value_str, stod(value_vec[0])); + HILOG_INFO("ParseJsonKey notIn value_str2:%{private}s ", value_vec[0].c_str()); + } else if (value_vec.size() > 1) { + pacMap.PutStringValue(value_str, inValue.substr(tempLength, inValue.length())); + HILOG_INFO( + "ParseJsonKey notIn value_str3:%{private}s ", inValue.substr(tempLength, inValue.length()).c_str()); + } + } else { + pacMap.Remove(value_str); + } +} + +void ParseNormal(AppExecFwk::PacMap &pacMap, std::string &value_str, NativeRdb::DataAbilityPredicates &predicates, + std::string key_str) +{ + if (key_str == "equalTo") { + ParseEqualTo(pacMap, value_str, predicates); + } else if (key_str == "notEqualTo") { + ParseNotEqualTo(pacMap, value_str, predicates); + } else if (key_str == "contains") { + predicates.Contains(value_str, pacMap.GetStringValue(value_str, "")); + HILOG_INFO("ParseJsonKey contains :%{private}s ", pacMap.GetStringValue(value_str, "").c_str()); + pacMap.Remove(value_str); + } else if (key_str == "beginsWith") { + predicates.BeginsWith(value_str, pacMap.GetStringValue(value_str, "")); + HILOG_INFO("ParseJsonKey beginsWith :%{private}s ", pacMap.GetStringValue(value_str, "").c_str()); + pacMap.Remove(value_str); + } else if (key_str == "endsWith") { + predicates.EndsWith(value_str, pacMap.GetStringValue(value_str, "")); + HILOG_INFO("ParseJsonKey endsWithValue1:%{private}s ", pacMap.GetStringValue(value_str, "").c_str()); + pacMap.Remove(value_str); + } else if (key_str == "greaterThan") { + double greateValue = pacMap.GetDoubleValue(value_str, DBL_MIN); + predicates.GreaterThan(value_str, std::to_string(greateValue)); + pacMap.Remove(value_str); + } else if (key_str == "lessThan") { + double lessValue = pacMap.GetDoubleValue(value_str, DBL_MAX); + predicates.LessThan(value_str, std::to_string(lessValue)); + pacMap.Remove(value_str); + } else if (key_str == "greaterThanOrEqualTo") { + double greateValue = pacMap.GetDoubleValue(value_str, DBL_MIN); + predicates.GreaterThanOrEqualTo(value_str, std::to_string(greateValue)); + pacMap.Remove(value_str); + } else if (key_str == "lessThanOrEqualTo") { + double lessValue = pacMap.GetDoubleValue(value_str, DBL_MAX); + predicates.LessThanOrEqualTo(value_str, std::to_string(lessValue)); + pacMap.Remove(value_str); + } +} + +void ParseUnNormal(AppExecFwk::PacMap &pacMap, std::string &value_str, NativeRdb::DataAbilityPredicates &predicates, + std::string key_str) +{ + if (key_str == "beginWrap") { + predicates.BeginWrap(); + } else if (key_str == "endWrap") { + predicates.EndWrap(); + } else if (key_str == "or") { + predicates.Or(); + } else if (key_str == "and") { + predicates.And(); + } else if (key_str == "orderByAsc") { + predicates.OrderByAsc(value_str); + } else if (key_str == "orderByDesc") { + predicates.OrderByDesc(value_str); + } else if (key_str == "distinct") { + predicates.Distinct(); + } else if (key_str == "limitAs") { + predicates.Limit(pacMap.GetIntValue(value_str, 0)); + } else if (key_str == "offsetAs") { + predicates.Offset(pacMap.GetIntValue(value_str, 0)); + } else if (key_str == "groupBy") { + std::string groupByValue = pacMap.GetStringValue(value_str, ""); + HILOG_INFO("ParseJsonKey groupBy groupByValue:%{private}s ", groupByValue.c_str()); + std::vector res; + Stringsplit(groupByValue, ",", res); + predicates.GroupBy(res); + } else if (key_str == "indexedBy") { + predicates.IndexedBy(value_str); + } else if (key_str == "in") { + ParseIn(pacMap, value_str, predicates); + } else if (key_str == "notIn") { + ParseNotIn(pacMap, value_str, predicates); + } +} + +void ParseJsonKey(std::string &jsonStr, AppExecFwk::PacMap &pacMap, NativeRdb::DataAbilityPredicates &predicates) +{ + HILOG_INFO("%{public}s, called.", __func__); + Json::Reader reader; + Json::Value devJson; + Json::Value::iterator iter; + Json::Value::Members members; + bool parseSuc = reader.parse(jsonStr, devJson); + if (parseSuc) { + members = devJson.getMemberNames(); + for (Json::Value::Members::iterator it = members.begin(); it != members.end(); ++it) { + std::string key_str = *it; + std::string value_str = devJson[key_str].asString(); + HILOG_INFO("%{public}s, called,value_str = %{private}s", __func__, value_str.c_str()); + if (key_str == "equalTo" || key_str == "notEqualTo" || key_str == "contains" || key_str == "beginsWith" || + key_str == "endsWith" || key_str == "greaterThan" || key_str == "lessThan" || + key_str == "greaterThanOrEqualTo" || key_str == "lessThanOrEqualTo") { + ParseNormal(pacMap, value_str, predicates, key_str); + } else { + ParseUnNormal(pacMap, value_str, predicates, key_str); + } + } + } + HILOG_INFO("%{public}s, called end.", __func__); +} + napi_value GetCallbackPacmapValue(napi_env env, int index) { HILOG_INFO("GetCallbackPacmapValue is called."); @@ -2468,17 +2786,18 @@ void CallInsertExecuteCB(napi_env env, void *data) { HILOG_INFO("NAPI_Insert, worker pool thread execute."); DAHelperInsertCB *insertCB = static_cast(data); - if (insertCB != nullptr && insertCB->dataAbilityHelper != nullptr) { + if (insertCB->dataAbilityHelper != nullptr) { insertCB->execResult = INVALID_PARAMETER; if (!insertCB->uri.empty()) { OHOS::Uri uri(insertCB->uri); insertCB->result = insertCB->dataAbilityHelper->Insert(uri, insertCB->valueBucket); + HILOG_INFO("NAPI_Insert, result = %{public}d", insertCB->result); if (insertCB->result > 0) { insertCB->execResult = NO_ERROR; } } } else { - HILOG_ERROR("NAPI_Insert, insertCB or dataAbilityHelper is null."); + HILOG_ERROR("NAPI_Insert, dataAbilityHelper == nullptr."); } HILOG_INFO("NAPI_Insert, worker pool thread execute end."); } @@ -2487,23 +2806,21 @@ void CallInsertAsyncCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_Insert, main event thread complete."); DAHelperInsertCB *insertCB = static_cast(data); - if (insertCB != nullptr) { - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, insertCB->cbBase.cbInfo.callback, &callback)); - - napi_create_int32(env, insertCB->execResult, &result[PARAM0]); - result[PARAM1] = GetCallbackPacmapValue(env, insertCB->result); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, result, &callResult)); - - if (insertCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, insertCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, insertCB->cbBase.asyncWork)); + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, insertCB->cbBase.cbInfo.callback, &callback)); + + napi_create_int32(env, insertCB->execResult, &result[PARAM0]); + result[PARAM1] = GetCallbackPacmapValue(env, insertCB->result); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, result, &callResult)); + + if (insertCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, insertCB->cbBase.cbInfo.callback)); } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, insertCB->cbBase.asyncWork)); delete insertCB; insertCB = nullptr; HILOG_INFO("NAPI_Insert, main event thread complete end."); @@ -2513,11 +2830,9 @@ void CallInsertPromiseCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_Insert, main event thread complete."); DAHelperInsertCB *insertCB = static_cast(data); - if (insertCB != nullptr) { - napi_value result = GetCallbackPacmapValue(env, insertCB->result); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, insertCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, insertCB->cbBase.asyncWork)); - } + napi_value result = GetCallbackPacmapValue(env, insertCB->result); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, insertCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, insertCB->cbBase.asyncWork)); delete insertCB; insertCB = nullptr; HILOG_INFO("NAPI_Insert, main event thread complete end."); @@ -2527,7 +2842,7 @@ napi_value CallInsertAsync(napi_env env, napi_value *args, const size_t argCallb { HILOG_INFO("%{public}s, asyncCallback.", __func__); if (args == nullptr || insertCB == nullptr) { - HILOG_ERROR("%{public}s, param is null.", __func__); + HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName = 0; @@ -2552,7 +2867,7 @@ napi_value CallInsertPromise(napi_env env, DAHelperInsertCB *insertCB) { HILOG_INFO("%{public}s, promise.", __func__); if (insertCB == nullptr) { - HILOG_ERROR("%{public}s, param is null.", __func__); + HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName; @@ -2569,12 +2884,13 @@ napi_value CallInsertPromise(napi_env env, DAHelperInsertCB *insertCB) return promise; } -napi_value CallInsertWrap(napi_env env, napi_value thisVar, napi_callback_info info, napi_value *args, bool isPromise) +napi_value CallInsertWrap(napi_env env, napi_value thisVar, napi_callback_info info, napi_value *args, size_t argcAsync, + const size_t argcPromise) { HILOG_INFO("%{public}s,called", __func__); DAHelperInsertCB *insertCB = new (std::nothrow) DAHelperInsertCB; if (insertCB == nullptr) { - HILOG_ERROR("%{public}s, insertCB is null.", __func__); + HILOG_ERROR("%{public}s, insertCB == nullptr.", __func__); return WrapVoidToJS(env); } insertCB->cbBase.cbInfo.env = env; @@ -2598,13 +2914,13 @@ napi_value CallInsertWrap(napi_env env, napi_value thisVar, napi_callback_info i insertCB->dataAbilityHelper = objectInfo; napi_value ret = nullptr; - if (!isPromise) { + if (argcAsync > argcPromise) { ret = CallInsertAsync(env, args, ARGS_FOUR, insertCB); } else { ret = CallInsertPromise(env, insertCB); } if (ret == nullptr) { - HILOG_ERROR("%{public}s, ret is null.", __func__); + HILOG_ERROR("%{public}s, ret == nullptr.", __func__); if (insertCB != nullptr) { delete insertCB; insertCB = nullptr; @@ -2630,7 +2946,7 @@ void CallDeleteExecuteCB(napi_env env, void *data) HILOG_ERROR("NAPI_Delete, dataAbilityHelper uri is empty"); } } else { - HILOG_ERROR("NAPI_Delete, dataAbilityHelper is null"); + HILOG_ERROR("NAPI_Delete, dataAbilityHelper == nullptr"); } HILOG_INFO("NAPI_Delete, worker pool thread execute end."); } @@ -2638,38 +2954,38 @@ void CallDeleteExecuteCB(napi_env env, void *data) void CallDeleteAsyncCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_Delete, main event thread complete."); - DAHelperDeleteCB *deleteCB = static_cast(data); + DAHelperDeleteCB *DeleteCB = static_cast(data); napi_value callback = nullptr; napi_value undefined = nullptr; napi_value result[ARGS_TWO] = {nullptr}; napi_value callResult = nullptr; NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, deleteCB->cbBase.cbInfo.callback, &callback)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, DeleteCB->cbBase.cbInfo.callback, &callback)); - napi_create_int32(env, deleteCB->execResult, &result[PARAM0]); - result[PARAM1] = GetCallbackPacmapValue(env, deleteCB->result); + napi_create_int32(env, DeleteCB->execResult, &result[PARAM0]); + result[PARAM1] = GetCallbackPacmapValue(env, DeleteCB->result); NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, result, &callResult)); - if (deleteCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, deleteCB->cbBase.cbInfo.callback)); + if (DeleteCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, DeleteCB->cbBase.cbInfo.callback)); } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, deleteCB->cbBase.asyncWork)); - delete deleteCB; - deleteCB = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, DeleteCB->cbBase.asyncWork)); + delete DeleteCB; + DeleteCB = nullptr; HILOG_INFO("NAPI_Delete, main event thread complete end."); } void CallDeletePromiseCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_Delete, main event thread complete."); - DAHelperDeleteCB *deleteCB = static_cast(data); + DAHelperDeleteCB *DeleteCB = static_cast(data); - napi_value result = GetCallbackPacmapValue(env, deleteCB->result); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, deleteCB->cbBase.deferred, result)); + napi_value result = GetCallbackPacmapValue(env, DeleteCB->result); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, DeleteCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, deleteCB->cbBase.asyncWork)); - delete deleteCB; - deleteCB = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, DeleteCB->cbBase.asyncWork)); + delete DeleteCB; + DeleteCB = nullptr; HILOG_INFO("NAPI_Delete, main event thread complete end."); } @@ -2677,7 +2993,7 @@ napi_value CallDeleteAsync(napi_env env, napi_value *args, const size_t argCallb { HILOG_INFO("%{public}s, asyncCallback.", __func__); if (args == nullptr || deleteCB == nullptr) { - HILOG_ERROR("%{public}s, param is null.", __func__); + HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName = 0; @@ -2702,7 +3018,7 @@ napi_value CallDeletePromise(napi_env env, DAHelperDeleteCB *deleteCB) { HILOG_INFO("%{public}s, promise.", __func__); if (deleteCB == nullptr) { - HILOG_ERROR("%{public}s, param is null.", __func__); + HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName; @@ -2719,12 +3035,13 @@ napi_value CallDeletePromise(napi_env env, DAHelperDeleteCB *deleteCB) return promise; } -napi_value CallDeleteWrap(napi_env env, napi_value thisVar, napi_callback_info info, napi_value *args, bool isPromise) +napi_value CallDeleteWrap(napi_env env, napi_value thisVar, napi_callback_info info, napi_value *args, size_t argcAsync, + const size_t argcPromise) { HILOG_INFO("%{public}s,called", __func__); DAHelperDeleteCB *deleteCB = new (std::nothrow) DAHelperDeleteCB; if (deleteCB == nullptr) { - HILOG_ERROR("%{public}s, deleteCB is null.", __func__); + HILOG_ERROR("%{public}s, deleteCB == nullptr.", __func__); return WrapVoidToJS(env); } deleteCB->cbBase.cbInfo.env = env; @@ -2736,30 +3053,35 @@ napi_value CallDeleteWrap(napi_env env, napi_value thisVar, napi_callback_info i NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); if (valuetype == napi_string) { deleteCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,uri=%{public}s", __func__, deleteCB->uri.c_str()); } valuetype = napi_undefined; std::string predicateArg; NAPI_CALL(env, napi_typeof(env, args[PARAM2], &valuetype)); if (valuetype == napi_string) { predicateArg = NapiValueToStringUtf8(env, args[PARAM2]); + HILOG_INFO("%{public}s,predicateArg=%{public}s", __func__, predicateArg.c_str()); } deleteCB->pacMap.Clear(); + HILOG_INFO("%{public}s,AnalysisPacMap start", __func__); AnalysisPacMap(deleteCB->pacMap, env, args[PARAM3]); + HILOG_INFO("%{public}s, AnalysisPacMap end", __func__); ParseJsonKey(predicateArg, deleteCB->pacMap, deleteCB->predicates); DataAbilityHelper *objectInfo = nullptr; napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("%{public}s,DataAbilityHelper objectInfo = %{public}p", __func__, objectInfo); deleteCB->dataAbilityHelper = objectInfo; napi_value ret = nullptr; - if (!isPromise) { + if (argcAsync > argcPromise) { ret = CallDeleteAsync(env, args, ARGS_FOUR, deleteCB); } else { ret = CallDeletePromise(env, deleteCB); } if (ret == nullptr) { - HILOG_ERROR("%{public}s,ret is null", __func__); + HILOG_ERROR("%{public}s,ret == nullptr", __func__); if (deleteCB != nullptr) { delete deleteCB; deleteCB = nullptr; @@ -2774,7 +3096,7 @@ void CallUpdateExecuteCB(napi_env env, void *data) { HILOG_INFO("NAPI_Update, worker pool thread execute."); DAHelperUpdateCB *updateCB = static_cast(data); - if (updateCB != nullptr && updateCB->dataAbilityHelper != nullptr) { + if (updateCB->dataAbilityHelper != nullptr) { updateCB->execResult = INVALID_PARAMETER; if (!updateCB->uri.empty()) { OHOS::Uri uri(updateCB->uri); @@ -2786,7 +3108,7 @@ void CallUpdateExecuteCB(napi_env env, void *data) HILOG_ERROR("NAPI_Update, dataAbilityHelper uri is empty"); } } else { - HILOG_ERROR("NAPI_Update, updateCB or dataAbilityHelper is null"); + HILOG_ERROR("NAPI_Update, dataAbilityHelper == nullptr"); } HILOG_INFO("NAPI_Update, worker pool thread execute end."); } @@ -2795,23 +3117,21 @@ void CallUpdateAsyncCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_Update, main event thread complete."); DAHelperUpdateCB *updateCB = static_cast(data); - if (updateCB != nullptr) { - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, updateCB->cbBase.cbInfo.callback, &callback)); - - napi_create_int32(env, updateCB->execResult, &result[PARAM0]); - result[PARAM1] = GetCallbackPacmapValue(env, updateCB->result); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, result, &callResult)); - - if (updateCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, updateCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, updateCB->cbBase.asyncWork)); + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, updateCB->cbBase.cbInfo.callback, &callback)); + + napi_create_int32(env, updateCB->execResult, &result[PARAM0]); + result[PARAM1] = GetCallbackPacmapValue(env, updateCB->result); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, result, &callResult)); + + if (updateCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, updateCB->cbBase.cbInfo.callback)); } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, updateCB->cbBase.asyncWork)); delete updateCB; updateCB = nullptr; HILOG_INFO("NAPI_Update, main event thread complete end."); @@ -2821,12 +3141,11 @@ void CallUpdatePromiseCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_Update, main event thread complete."); DAHelperUpdateCB *updateCB = static_cast(data); - if (updateCB != nullptr) { - napi_value result = GetCallbackPacmapValue(env, updateCB->result); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, updateCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, updateCB->cbBase.asyncWork)); - } + napi_value result = GetCallbackPacmapValue(env, updateCB->result); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, updateCB->cbBase.deferred, result)); + + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, updateCB->cbBase.asyncWork)); delete updateCB; updateCB = nullptr; HILOG_INFO("NAPI_Update, main event thread complete end."); @@ -2836,7 +3155,7 @@ napi_value CallUpdateAsync(napi_env env, napi_value *args, const size_t argCallb { HILOG_INFO("%{public}s, asyncCallback.", __func__); if (args == nullptr || updateCB == nullptr) { - HILOG_ERROR("%{public}s, param is null.", __func__); + HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName = 0; @@ -2861,7 +3180,7 @@ napi_value CallUpdatePromise(napi_env env, DAHelperUpdateCB *updateCB) { HILOG_INFO("%{public}s, promise.", __func__); if (updateCB == nullptr) { - HILOG_ERROR("%{public}s, param is null.", __func__); + HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName; @@ -2878,12 +3197,13 @@ napi_value CallUpdatePromise(napi_env env, DAHelperUpdateCB *updateCB) return promise; } -napi_value CallUpdateWrap(napi_env env, napi_value thisVar, napi_callback_info info, napi_value *args, bool isPromise) +napi_value CallUpdateWrap(napi_env env, napi_value thisVar, napi_callback_info info, napi_value *args, size_t argcAsync, + const size_t argcPromise) { HILOG_INFO("%{public}s,called", __func__); DAHelperUpdateCB *updateCB = new (std::nothrow) DAHelperUpdateCB; if (updateCB == nullptr) { - HILOG_ERROR("%{public}s, updateCB is null.", __func__); + HILOG_ERROR("%{public}s, updateCB == nullptr.", __func__); return WrapVoidToJS(env); } updateCB->cbBase.cbInfo.env = env; @@ -2894,12 +3214,14 @@ napi_value CallUpdateWrap(napi_env env, napi_value thisVar, napi_callback_info i NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); if (valuetype == napi_string) { updateCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,uri=%{public}s", __func__, updateCB->uri.c_str()); } valuetype = napi_undefined; std::string predicateArg; NAPI_CALL(env, napi_typeof(env, args[PARAM2], &valuetype)); if (valuetype == napi_string) { predicateArg = NapiValueToStringUtf8(env, args[PARAM2]); + HILOG_INFO("%{public}s,predicateArg=%{public}s", __func__, predicateArg.c_str()); } updateCB->pacMap.Clear(); AnalysisPacMap(updateCB->pacMap, env, args[PARAM3]); @@ -2917,9 +3239,10 @@ napi_value CallUpdateWrap(napi_env env, napi_value thisVar, napi_callback_info i } DataAbilityHelper *objectInfo = nullptr; napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("%{public}s,DataAbilityHelper objectInfo = %{public}p", __func__, objectInfo); updateCB->dataAbilityHelper = objectInfo; napi_value ret = nullptr; - if (!isPromise) { + if (argcAsync > argcPromise) { ret = CallUpdateAsync(env, args, ARGS_FOUR, updateCB); } else { ret = CallUpdatePromise(env, updateCB); @@ -2928,6 +3251,56 @@ napi_value CallUpdateWrap(napi_env env, napi_value thisVar, napi_callback_info i return ret; } +void GetValue(std::vector &columnNames, int &index, Json::Value &data, + std::shared_ptr &resultSet) +{ + std::string typeValue = columnNames[index]; + int columnIndex; + resultSet->GetColumnIndex(typeValue, columnIndex); + OHOS::NativeRdb::ColumnType columnType; + resultSet->GetColumnType(columnIndex, columnType); + if (columnType == OHOS::NativeRdb::ColumnType::TYPE_INTEGER) { + int intValue; + resultSet->GetInt(columnIndex, intValue); + data[typeValue] = intValue; + } else if (columnType == OHOS::NativeRdb::ColumnType::TYPE_FLOAT) { + double doubleValue; + resultSet->GetDouble(columnIndex, doubleValue); + data[typeValue] = doubleValue; + } else if (columnType == OHOS::NativeRdb::ColumnType::TYPE_STRING) { + std::string stringValue; + resultSet->GetString(columnIndex, stringValue); + if (!stringValue.empty()) { + data[typeValue] = stringValue; + } + } +} + +void ConvertResultSet(Json::Value &arrayValue, std::shared_ptr &resultSet) +{ + int resultSetNum = resultSet->GoToFirstRow(); + std::vector columnNames; + resultSet->GetAllColumnNames(columnNames); + while (resultSetNum == NO_ERROR) { + Json::Value data; + int size = columnNames.size(); + for (int i = 0; i < size; i++) { + GetValue(columnNames, i, data, resultSet); + } + arrayValue.append(data); + resultSetNum = resultSet->GoToNextRow(); + } +} + +std::string GetResultData(std::shared_ptr &resultSet) +{ + Json::Value arrayValue; + ConvertResultSet(arrayValue, resultSet); + Json::StreamWriterBuilder builder; + const std::string personal_ringtone = Json::writeString(builder, arrayValue); + return personal_ringtone; +} + napi_value GetQueryCallbackPacmapValue(napi_env env, std::shared_ptr &resultSet) { HILOG_INFO("GetQueryCallbackPacmapValue is called."); @@ -2946,23 +3319,21 @@ void CallQueryAsyncCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_Query, main event thread complete."); DAHelperQueryCB *queryCB = static_cast(data); - if (queryCB != nullptr) { - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, queryCB->cbBase.cbInfo.callback, &callback)); - - napi_create_int32(env, queryCB->execResult, &result[PARAM0]); - result[PARAM1] = GetQueryCallbackPacmapValue(env, queryCB->result); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, result, &callResult)); - - if (queryCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, queryCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, queryCB->cbBase.asyncWork)); + napi_value callback = nullptr; + napi_value undefined = nullptr; + napi_value result[ARGS_TWO] = {nullptr}; + napi_value callResult = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, queryCB->cbBase.cbInfo.callback, &callback)); + + napi_create_int32(env, queryCB->execResult, &result[PARAM0]); + result[PARAM1] = GetQueryCallbackPacmapValue(env, queryCB->result); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, result, &callResult)); + + if (queryCB->cbBase.cbInfo.callback != nullptr) { + NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, queryCB->cbBase.cbInfo.callback)); } + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, queryCB->cbBase.asyncWork)); delete queryCB; queryCB = nullptr; HILOG_INFO("NAPI_Query, main event thread complete end."); @@ -2971,14 +3342,12 @@ void CallQueryAsyncCompleteCB(napi_env env, napi_status status, void *data) void CallQueryPromiseCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_DAHelperQueryCB, main event thread complete."); - DAHelperQueryCB *queryCB = static_cast(data); - if (queryCB != nullptr) { - napi_value result = GetQueryCallbackPacmapValue(env, queryCB->result); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, queryCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, queryCB->cbBase.asyncWork)); - } - delete queryCB; - queryCB = nullptr; + DAHelperQueryCB *QueryCB = static_cast(data); + napi_value result = GetQueryCallbackPacmapValue(env, QueryCB->result); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, QueryCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, QueryCB->cbBase.asyncWork)); + delete QueryCB; + QueryCB = nullptr; HILOG_INFO("NAPI_DAHelperQueryCB, main event thread complete end."); } @@ -2986,7 +3355,7 @@ void CallQueryExecuteCB(napi_env env, void *data) { HILOG_INFO("NAPI_Query, worker pool thread execute."); DAHelperQueryCB *queryCB = static_cast(data); - if (queryCB != nullptr && queryCB->dataAbilityHelper != nullptr) { + if (queryCB->dataAbilityHelper != nullptr) { queryCB->execResult = INVALID_PARAMETER; if (!queryCB->uri.empty()) { OHOS::Uri uri(queryCB->uri); @@ -2995,13 +3364,13 @@ void CallQueryExecuteCB(napi_env env, void *data) queryCB->result = resultset; queryCB->execResult = NO_ERROR; } else { - HILOG_ERROR("NAPI_Query, resultset is null."); + HILOG_INFO("NAPI_Query, resultset == nullptr."); } } else { HILOG_ERROR("NAPI_Query, dataAbilityHelper uri is empty"); } } else { - HILOG_ERROR("NAPI_Query, queryCB or dataAbilityHelper is null"); + HILOG_ERROR("NAPI_Query, dataAbilityHelper == nullptr"); } HILOG_INFO("NAPI_Query, worker pool thread execute end."); } @@ -3010,7 +3379,7 @@ napi_value CallQueryAsync(napi_env env, napi_value *args, const size_t argCallba { HILOG_INFO("%{public}s, asyncCallback.", __func__); if (args == nullptr || queryCB == nullptr) { - HILOG_ERROR("%{public}s, param or queryCB is null.", __func__); + HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName = 0; @@ -3035,7 +3404,7 @@ napi_value CallQueryPromise(napi_env env, DAHelperQueryCB *queryCB) { HILOG_INFO("%{public}s, promise.", __func__); if (queryCB == nullptr) { - HILOG_ERROR("%{public}s, param is null.", __func__); + HILOG_ERROR("%{public}s, param == nullptr.", __func__); return nullptr; } napi_value resourceName; @@ -3052,12 +3421,13 @@ napi_value CallQueryPromise(napi_env env, DAHelperQueryCB *queryCB) return promise; } -napi_value CallQueryWrap(napi_env env, napi_value thisVar, napi_callback_info info, napi_value *args, bool isPromise) +napi_value CallQueryWrap(napi_env env, napi_value thisVar, napi_callback_info info, napi_value *args, size_t argcAsync, + const size_t argcPromise) { HILOG_INFO("%{public}s,called", __func__); DAHelperQueryCB *queryCB = new (std::nothrow) DAHelperQueryCB; if (queryCB == nullptr) { - HILOG_ERROR("%{public}s, queryCB is null.", __func__); + HILOG_ERROR("%{public}s, QueryCB == nullptr.", __func__); return WrapVoidToJS(env); } queryCB->cbBase.cbInfo.env = env; @@ -3069,27 +3439,35 @@ napi_value CallQueryWrap(napi_env env, napi_value thisVar, napi_callback_info in NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); if (valuetype == napi_string) { queryCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); + HILOG_INFO("%{public}s,uri=%{public}s", __func__, queryCB->uri.c_str()); } valuetype = napi_undefined; std::string predicateArg; NAPI_CALL(env, napi_typeof(env, args[PARAM2], &valuetype)); if (valuetype == napi_string) { predicateArg = NapiValueToStringUtf8(env, args[PARAM2]); + HILOG_INFO("%{public}s,predicateArg=%{public}s", __func__, predicateArg.c_str()); } queryCB->pacMap.Clear(); AnalysisPacMap(queryCB->pacMap, env, args[PARAM3]); std::string columns = queryCB->pacMap.GetStringValue("columns", ""); - StringSplit(columns, ",", queryCB->columns); + HILOG_INFO("%{public}s,columns=%{public}s", __func__, columns.c_str()); + Stringsplit(columns, ",", queryCB->columns); + HILOG_INFO("%{public}s,columns.size=%{public}d", __func__, queryCB->columns.size()); queryCB->pacMap.Remove("columns"); + for (size_t i = 0; i < queryCB->columns.size(); i++) { + HILOG_INFO("%{public}s,columns=%{public}s", __func__, queryCB->columns.at(i).c_str()); + } ParseJsonKey(predicateArg, queryCB->pacMap, queryCB->predicates); DataAbilityHelper *objectInfo = nullptr; napi_unwrap(env, thisVar, (void **)&objectInfo); + HILOG_INFO("%{public}s,DataAbilityHelper objectInfo = %{public}p", __func__, objectInfo); queryCB->dataAbilityHelper = objectInfo; napi_value ret = nullptr; - if (!isPromise) { + if (argcAsync > argcPromise) { ret = CallQueryAsync(env, args, ARGS_FOUR, queryCB); } else { ret = CallQueryPromise(env, queryCB); @@ -3127,21 +3505,19 @@ napi_value CallWrap(napi_env env, napi_callback_info info) NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); if (valuetype == napi_string) { method = NapiValueToStringUtf8(env, args[PARAM1]); + HILOG_INFO("%{public}s,method=%{public}s", __func__, method.c_str()); } else { HILOG_ERROR("%{public}s, Wrong argument type.", __func__); return nullptr; } - bool isPromise = argcAsync > argcPromise ? false : true; if (method == "insert") { - ret = CallInsertWrap(env, thisVar, info, args, isPromise); + ret = CallInsertWrap(env, thisVar, info, args, argcAsync, argcPromise); } else if (method == "delete") { - ret = CallDeleteWrap(env, thisVar, info, args, isPromise); + ret = CallDeleteWrap(env, thisVar, info, args, argcAsync, argcPromise); } else if (method == "update") { - ret = CallUpdateWrap(env, thisVar, info, args, isPromise); + ret = CallUpdateWrap(env, thisVar, info, args, argcAsync, argcPromise); } else if (method == "query") { - ret = CallQueryWrap(env, thisVar, info, args, isPromise); - } else { - ret = WrapVoidToJS(env); + ret = CallQueryWrap(env, thisVar, info, args, argcAsync, argcPromise); } HILOG_INFO("%{public}s,end", __func__); return ret; @@ -3610,22 +3986,22 @@ void BatchInsertPromiseCompleteCB(napi_env env, napi_status status, void *data) napi_value NAPI_Query(napi_env env, napi_callback_info info) { HILOG_INFO("%{public}s,called", __func__); - DAHelperQueryCB *queryCB = new (std::nothrow) DAHelperQueryCB; - if (queryCB == nullptr) { - HILOG_ERROR("%{public}s, queryCB == nullptr.", __func__); + DAHelperQueryCB *QueryCB = new (std::nothrow) DAHelperQueryCB; + if (QueryCB == nullptr) { + HILOG_ERROR("%{public}s, QueryCB == nullptr.", __func__); return WrapVoidToJS(env); } - queryCB->cbBase.cbInfo.env = env; - queryCB->cbBase.asyncWork = nullptr; - queryCB->cbBase.deferred = nullptr; - queryCB->cbBase.ability = nullptr; + QueryCB->cbBase.cbInfo.env = env; + QueryCB->cbBase.asyncWork = nullptr; + QueryCB->cbBase.deferred = nullptr; + QueryCB->cbBase.ability = nullptr; - napi_value ret = QueryWrap(env, info, queryCB); + napi_value ret = QueryWrap(env, info, QueryCB); if (ret == nullptr) { HILOG_ERROR("%{public}s,ret == nullptr", __func__); - if (queryCB != nullptr) { - delete queryCB; - queryCB = nullptr; + if (QueryCB != nullptr) { + delete QueryCB; + QueryCB = nullptr; } ret = WrapVoidToJS(env); } @@ -3751,13 +4127,13 @@ napi_value QueryPromise(napi_env env, DAHelperQueryCB *queryCB) void QueryPromiseCompleteCB(napi_env env, napi_status status, void *data) { HILOG_INFO("NAPI_DAHelperQueryCB, main event thread complete."); - DAHelperQueryCB *queryCB = static_cast(data); + DAHelperQueryCB *QueryCB = static_cast(data); napi_value result = nullptr; - result = WrapResultSet(env, queryCB->result); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, queryCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, queryCB->cbBase.asyncWork)); - delete queryCB; - queryCB = nullptr; + result = WrapResultSet(env, QueryCB->result); + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, QueryCB->cbBase.deferred, result)); + NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, QueryCB->cbBase.asyncWork)); + delete QueryCB; + QueryCB = nullptr; HILOG_INFO("NAPI_DAHelperQueryCB, main event thread complete end."); } diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/BUILD.gn b/interfaces/kits/napi/aafwk/inner/napi_common/BUILD.gn index ca350fbabe62be75e82449d30196fb2db61a1a53..dd4f40fdbc273bb4fdb48a9cc6335cfc821e5c3f 100644 --- a/interfaces/kits/napi/aafwk/inner/napi_common/BUILD.gn +++ b/interfaces/kits/napi/aafwk/inner/napi_common/BUILD.gn @@ -19,13 +19,10 @@ ohos_shared_library("napi_common") { "//third_party/node/src", "//third_party/libuv/include", "//foundation/aafwk/standard/frameworks/kits/ability/native/include", - "//third_party/jsoncpp", - "//third_party/jsoncpp/include/json", ] sources = [ "napi_common_ability.cpp", - "napi_common_call_util.cpp", "napi_common_configuration.cpp", "napi_common_start_options.cpp", "napi_common_util.cpp", @@ -37,7 +34,6 @@ ohos_shared_library("napi_common") { "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/ace/napi:ace_napi", - "//third_party/jsoncpp:jsoncpp", "//third_party/libuv:uv_static", "//utils/native/base:utils", ] diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp index 43b100181448284d27f428d64f55f3bca03adf1e..8f5ce8b92ab9fe4ff5928cfdf4c0cb78d5e4860b 100644 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp @@ -2052,6 +2052,12 @@ void GetAppVersionInfoExecuteCB(napi_env env, void *data) std::shared_ptr abilityInfoPtr = appVersionInfoCB->cbBase.ability->GetAbilityInfo(); std::shared_ptr appInfoPtr = appVersionInfoCB->cbBase.ability->GetApplicationInfo(); if (abilityInfoPtr != nullptr && appInfoPtr != nullptr) { + HILOG_ERROR("NAPI_GetAppVersionInfo, bundleName = %{public}s", abilityInfoPtr->bundleName.c_str()); + HILOG_ERROR("NAPI_GetAppVersionInfo, appName = %{public}s", abilityInfoPtr->appName.c_str()); + HILOG_ERROR("NAPI_GetAppVersionInfo, versionName1 = %{public}s", abilityInfoPtr->versionName.c_str()); + HILOG_ERROR("NAPI_GetAppVersionInfo, name = %{public}s", appInfoPtr->name.c_str()); + HILOG_ERROR("NAPI_GetAppVersionInfo, versionCode = %{public}d", appInfoPtr->versionCode); + HILOG_ERROR("NAPI_GetAppVersionInfo, versionName2 = %{public}s", appInfoPtr->versionName.c_str()); SaveAppVersionInfo(appVersionInfoCB->appVersionInfo, abilityInfoPtr->appName, appInfoPtr->versionName, appInfoPtr->versionCode); } else { diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_call_util.cpp b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_call_util.cpp deleted file mode 100644 index caa12559d022fbe973f13e0f21c2c9b7b62c2c95..0000000000000000000000000000000000000000 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_call_util.cpp +++ /dev/null @@ -1,364 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "napi_common_call_util.h" - -#include - -#include "napi_common_util.h" -#include "hilog_wrapper.h" -#include "napi_common_data.h" -#include "napi_common_error.h" - -namespace OHOS { -namespace AppExecFwk { -void StringSplit(const string &str, const string &splits, std::vector &res) -{ - if (str == "") { - return; - } - string strs = str + splits; - size_t pos = strs.find(splits); - int step = splits.size(); - - while (pos != strs.npos) { - string temp = strs.substr(0, pos); - res.push_back(temp); - strs = strs.substr(pos + step, strs.size()); - pos = strs.find(splits); - } -} - -void SetPacMapObject(AppExecFwk::PacMap &pacMap, const napi_env &env, std::string keyStr, napi_value value) -{ - napi_valuetype valueType = napi_undefined; - napi_typeof(env, value, &valueType); - if (valueType == napi_string) { - std::string valueString = UnwrapStringFromJS(env, value); - pacMap.PutStringValue(keyStr, valueString); - } else if (valueType == napi_number) { - double valueNumber = 0; - napi_get_value_double(env, value, &valueNumber); - pacMap.PutDoubleValue(keyStr, valueNumber); - } else if (valueType == napi_boolean) { - bool valueBool = false; - napi_get_value_bool(env, value, &valueBool); - pacMap.PutBooleanValue(keyStr, valueBool); - } else if (valueType == napi_null) { - pacMap.PutObject(keyStr, nullptr); - } else if (valueType == napi_object) { - pacMap.PutStringValueArray(keyStr, ConvertStringVector(env, value)); - } else { - HILOG_ERROR("pacMap error"); - } -} - -void AnalysisPacMap(AppExecFwk::PacMap &pacMap, const napi_env &env, const napi_value &arg) -{ - napi_value keys = 0; - napi_get_property_names(env, arg, &keys); - uint32_t arrLen = 0; - napi_status status = napi_get_array_length(env, keys, &arrLen); - if (status != napi_ok) { - HILOG_ERROR("PacMap errr"); - return; - } - for (size_t i = 0; i < arrLen; ++i) { - napi_value key = 0; - status = napi_get_element(env, keys, i, &key); - std::string keyStr = UnwrapStringFromJS(env, key); - napi_value value = 0; - napi_get_property(env, arg, key, &value); - - SetPacMapObject(pacMap, env, keyStr, value); - } -} - -void ParseEqualTo(AppExecFwk::PacMap &pacMap, std::string &value_str, NativeRdb::DataAbilityPredicates &predicates) -{ - std::string equalValue = pacMap.GetStringValue(value_str, ""); - if (equalValue != "") { - if (equalValue.find(",") == string::npos) { - predicates.EqualTo(value_str, equalValue); - pacMap.Remove(value_str); - } else { - std::vector value_vec; - StringSplit(equalValue, ",", value_vec); - predicates.EqualTo(value_str, value_vec[0]); - pacMap.Remove(value_str); - pacMap.PutStringValue(value_str, equalValue.substr(value_vec[0].length() + 1, equalValue.length())); - } - } else { - double equalDoubleValue = pacMap.GetDoubleValue(value_str, DBL_MIN); - predicates.EqualTo(value_str, std::to_string(equalDoubleValue)); - pacMap.Remove(value_str); - } -} - -void ParseNotEqualTo(AppExecFwk::PacMap &pacMap, std::string &value_str, NativeRdb::DataAbilityPredicates &predicates) -{ - std::string equalValue = pacMap.GetStringValue(value_str, ""); - if (equalValue != "") { - if (equalValue.find(",") == string::npos) { - predicates.NotEqualTo(value_str, equalValue); - pacMap.Remove(value_str); - } else { - std::vector value_vec; - StringSplit(equalValue, ",", value_vec); - predicates.NotEqualTo(value_str, value_vec[0]); - pacMap.Remove(value_str); - pacMap.PutStringValue(value_str, equalValue.substr(value_vec[0].length() + 1, equalValue.length())); - } - } else { - predicates.NotEqualTo(value_str, std::to_string(pacMap.GetDoubleValue(value_str, DBL_MIN))); - pacMap.Remove(value_str); - } -} - -void ParseBetween(AppExecFwk::PacMap &pacMap, std::string &value_str, NativeRdb::DataAbilityPredicates &predicates) -{ - std::string betweenValue = pacMap.GetStringValue(value_str, ""); - std::vector value_vec; - StringSplit(betweenValue, ",", value_vec); - predicates.Between(value_str, value_vec[0], value_vec[1]); - int tempLength = value_vec[0].length() + 1 + value_vec[1].length() + 1; - value_vec.erase(value_vec.begin(), value_vec.begin() + 1); - pacMap.Remove(value_str); - if (value_vec.size() == 1) { - pacMap.PutDoubleValue(value_str, stod(value_vec[0])); - } else if (value_vec.size() > 1) { - pacMap.PutStringValue(value_str, betweenValue.substr(tempLength, betweenValue.length())); - } -} - -void ParseNotBetween(AppExecFwk::PacMap &pacMap, std::string &value_str, NativeRdb::DataAbilityPredicates &predicates) -{ - std::string betweenValue = pacMap.GetStringValue(value_str, ""); - std::vector value_vec; - StringSplit(betweenValue, ",", value_vec); - predicates.NotBetween(value_str, value_vec[0], value_vec[1]); - int tempLength = value_vec[0].length() + 1 + value_vec[1].length() + 1; - value_vec.erase(value_vec.begin(), value_vec.begin() + 1); - pacMap.Remove(value_str); - if (value_vec.size() == 1) { - pacMap.PutDoubleValue(value_str, stod(value_vec[0])); - } else if (value_vec.size() > 1) { - pacMap.PutStringValue(value_str, betweenValue.substr(tempLength, betweenValue.length())); - } -} - -void ParseIn(AppExecFwk::PacMap &pacMap, std::string &value_str, NativeRdb::DataAbilityPredicates &predicates) -{ - std::string inValue = pacMap.GetStringValue(value_str, ""); - std::vector value_vec; - StringSplit(inValue, ",", value_vec); - if (value_vec.size() >= ARGS_TWO) { - std::vector in_vec; - in_vec.push_back(value_vec[0]); - in_vec.push_back(value_vec[1]); - predicates.In(value_str, in_vec); - int tempLength = value_vec[0].length() + 1 + value_vec[1].length() + 1; - value_vec.erase(value_vec.begin(), value_vec.begin() + 1); - pacMap.Remove(value_str); - if (value_vec.size() == 1) { - pacMap.PutDoubleValue(value_str, stod(value_vec[0])); - } else if (value_vec.size() > 1) { - pacMap.PutStringValue(value_str, inValue.substr(tempLength, inValue.length())); - } - } else { - pacMap.Remove(value_str); - } -} - -void ParseNotIn(AppExecFwk::PacMap &pacMap, std::string &value_str, NativeRdb::DataAbilityPredicates &predicates) -{ - std::string inValue = pacMap.GetStringValue(value_str, ""); - std::vector value_vec; - StringSplit(inValue, ",", value_vec); - if (value_vec.size() >= ARGS_TWO) { - std::vector in_vec; - in_vec.push_back(value_vec[0]); - in_vec.push_back(value_vec[1]); - predicates.NotIn(value_str, in_vec); - int tempLength = value_vec[0].length() + 1 + value_vec[1].length() + 1; - value_vec.erase(value_vec.begin(), value_vec.begin() + 1); - pacMap.Remove(value_str); - if (value_vec.size() == 1) { - pacMap.PutDoubleValue(value_str, stod(value_vec[0])); - } else if (value_vec.size() > 1) { - pacMap.PutStringValue(value_str, inValue.substr(tempLength, inValue.length())); - } - } else { - pacMap.Remove(value_str); - } -} - -void ParseNormal(AppExecFwk::PacMap &pacMap, std::string &value_str, NativeRdb::DataAbilityPredicates &predicates, - std::string key_str) -{ - if (key_str == "equalTo") { - ParseEqualTo(pacMap, value_str, predicates); - } else if (key_str == "notEqualTo") { - ParseNotEqualTo(pacMap, value_str, predicates); - } else if (key_str == "contains") { - predicates.Contains(value_str, pacMap.GetStringValue(value_str, "")); - pacMap.Remove(value_str); - } else if (key_str == "beginsWith") { - predicates.BeginsWith(value_str, pacMap.GetStringValue(value_str, "")); - pacMap.Remove(value_str); - } else if (key_str == "endsWith") { - predicates.EndsWith(value_str, pacMap.GetStringValue(value_str, "")); - pacMap.Remove(value_str); - } else if (key_str == "greaterThan") { - double greateValue = pacMap.GetDoubleValue(value_str, DBL_MIN); - predicates.GreaterThan(value_str, std::to_string(greateValue)); - pacMap.Remove(value_str); - } else if (key_str == "lessThan") { - double lessValue = pacMap.GetDoubleValue(value_str, DBL_MAX); - predicates.LessThan(value_str, std::to_string(lessValue)); - pacMap.Remove(value_str); - } else if (key_str == "greaterThanOrEqualTo") { - double greateValue = pacMap.GetDoubleValue(value_str, DBL_MIN); - predicates.GreaterThanOrEqualTo(value_str, std::to_string(greateValue)); - pacMap.Remove(value_str); - } else if (key_str == "lessThanOrEqualTo") { - double lessValue = pacMap.GetDoubleValue(value_str, DBL_MAX); - predicates.LessThanOrEqualTo(value_str, std::to_string(lessValue)); - pacMap.Remove(value_str); - } -} - -void ParseUnNormal(AppExecFwk::PacMap &pacMap, std::string &value_str, NativeRdb::DataAbilityPredicates &predicates, - std::string key_str) -{ - if (key_str == "beginWrap") { - predicates.BeginWrap(); - } else if (key_str == "endWrap") { - predicates.EndWrap(); - } else if (key_str == "or") { - predicates.Or(); - } else if (key_str == "and") { - predicates.And(); - } else if (key_str == "orderByAsc") { - predicates.OrderByAsc(value_str); - } else if (key_str == "orderByDesc") { - predicates.OrderByDesc(value_str); - } else if (key_str == "distinct") { - predicates.Distinct(); - } else if (key_str == "limitAs") { - predicates.Limit(pacMap.GetIntValue(value_str, 0)); - } else if (key_str == "offsetAs") { - predicates.Offset(pacMap.GetIntValue(value_str, 0)); - } else if (key_str == "groupBy") { - std::string groupByValue = pacMap.GetStringValue(value_str, ""); - std::vector res; - StringSplit(groupByValue, ",", res); - predicates.GroupBy(res); - } else if (key_str == "indexedBy") { - predicates.IndexedBy(value_str); - } else if (key_str == "in") { - ParseIn(pacMap, value_str, predicates); - } else if (key_str == "notIn") { - ParseNotIn(pacMap, value_str, predicates); - } -} - -bool KeyInValue(std::string &key_str) -{ - if (key_str == "equalTo" || key_str == "notEqualTo" || key_str == "contains" || key_str == "beginsWith" || - key_str == "endsWith" || key_str == "greaterThan" || key_str == "lessThan" || - key_str == "greaterThanOrEqualTo" || key_str == "lessThanOrEqualTo") { - return true; - } else { - return false; - } -} - -void ParseJsonKey(std::string &jsonStr, AppExecFwk::PacMap &pacMap, NativeRdb::DataAbilityPredicates &predicates) -{ - HILOG_INFO("%{public}s called.", __func__); - Json::Reader reader; - Json::Value devJson; - Json::Value::iterator iter; - Json::Value::Members members; - bool parseSuc = reader.parse(jsonStr, devJson); - if (parseSuc) { - members = devJson.getMemberNames(); - for (Json::Value::Members::iterator it = members.begin(); it != members.end(); ++it) { - std::string key_str = *it; - std::string value_str = devJson[key_str].asString(); - if (KeyInValue(key_str)) { - ParseNormal(pacMap, value_str, predicates, key_str); - } else { - ParseUnNormal(pacMap, value_str, predicates, key_str); - } - } - } - HILOG_INFO("%{public}s called end.", __func__); -} - -void GetValue(std::vector &columnNames, int &index, Json::Value &data, - std::shared_ptr &resultSet) -{ - std::string typeValue = columnNames[index]; - int columnIndex; - resultSet->GetColumnIndex(typeValue, columnIndex); - OHOS::NativeRdb::ColumnType columnType; - resultSet->GetColumnType(columnIndex, columnType); - if (columnType == OHOS::NativeRdb::ColumnType::TYPE_INTEGER) { - int intValue; - resultSet->GetInt(columnIndex, intValue); - data[typeValue] = intValue; - } else if (columnType == OHOS::NativeRdb::ColumnType::TYPE_FLOAT) { - double doubleValue; - resultSet->GetDouble(columnIndex, doubleValue); - data[typeValue] = doubleValue; - } else if (columnType == OHOS::NativeRdb::ColumnType::TYPE_STRING) { - std::string stringValue; - resultSet->GetString(columnIndex, stringValue); - if (!stringValue.empty()) { - data[typeValue] = stringValue; - } - } -} - -void ConvertResultSet(Json::Value &arrayValue, std::shared_ptr &resultSet) -{ - int resultSetNum = resultSet->GoToFirstRow(); - std::vector columnNames; - resultSet->GetAllColumnNames(columnNames); - while (resultSetNum == NO_ERROR) { - Json::Value data; - int size = columnNames.size(); - for (int i = 0; i < size; i++) { - GetValue(columnNames, i, data, resultSet); - } - arrayValue.append(data); - resultSetNum = resultSet->GoToNextRow(); - } -} - -std::string GetResultData(std::shared_ptr &resultSet) -{ - if (resultSet == nullptr) { - return ""; - } - Json::Value arrayValue; - ConvertResultSet(arrayValue, resultSet); - Json::StreamWriterBuilder builder; - const std::string personal_ringtone = Json::writeString(builder, arrayValue); - return personal_ringtone; -} -} // namespace AppExecFwk -} // namespace OHOS diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_call_util.h b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_call_util.h deleted file mode 100644 index 8680dd8bbe7554d6f080cef250bd313d677851fe..0000000000000000000000000000000000000000 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_call_util.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_APPEXECFWK_NAPI_COMMON_CALL_UTIL_H -#define OHOS_APPEXECFWK_NAPI_COMMON_CALL_UTIL_H - -#include -#include - -#include "napi/native_api.h" -#include "abs_shared_result_set.h" -#include "data_ability_predicates.h" -#include "pac_map.h" -#include "json.h" - -namespace OHOS { -namespace AppExecFwk { -void StringSplit(const std::string &str, const std::string &splits, std::vector &res); - -void SetPacMapObject(AppExecFwk::PacMap &pacMap, const napi_env &env, std::string keyStr, napi_value value); - -void AnalysisPacMap(AppExecFwk::PacMap &pacMap, const napi_env &env, const napi_value &arg); - -void ParseNotEqualTo(AppExecFwk::PacMap &pacMap, std::string &value_str, NativeRdb::DataAbilityPredicates &predicates); - -void ParseNotEqualTo(AppExecFwk::PacMap &pacMap, std::string &value_str, NativeRdb::DataAbilityPredicates &predicates); - -void ParseBetween(AppExecFwk::PacMap &pacMap, std::string &value_str, NativeRdb::DataAbilityPredicates &predicates); - -void ParseNotBetween(AppExecFwk::PacMap &pacMap, std::string &value_str, NativeRdb::DataAbilityPredicates &predicates); - -void ParseIn(AppExecFwk::PacMap &pacMap, std::string &value_str, NativeRdb::DataAbilityPredicates &predicates); - -void ParseNotIn(AppExecFwk::PacMap &pacMap, std::string &value_str, NativeRdb::DataAbilityPredicates &predicates); - -void ParseNormal(AppExecFwk::PacMap &pacMap, std::string &value_str, NativeRdb::DataAbilityPredicates &predicates, - std::string key_str); - -void ParseUnNormal(AppExecFwk::PacMap &pacMap, std::string &value_str, NativeRdb::DataAbilityPredicates &predicates, - std::string key_str); - -bool KeyInValue(std::string &key_str); - -void ParseJsonKey(std::string &jsonStr, AppExecFwk::PacMap &pacMap, NativeRdb::DataAbilityPredicates &predicates); - -void GetValue(std::vector &columnNames, int &index, Json::Value &data, - std::shared_ptr &resultSet); - -void ConvertResultSet(Json::Value &arrayValue, std::shared_ptr &resultSet); - -std::string GetResultData(std::shared_ptr &resultSet); -} // namespace AppExecFwk -} // namespace OHOS -#endif // OHOS_APPEXECFWK_NAPI_COMMON_CALL_UTIL_H diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.cpp b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.cpp index 903cd9e6a953081d669ccb570d2460d2d60975a0..f1a5de4aaa5337e4a55128cb9b599600fba36a5a 100644 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.cpp +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_util.cpp @@ -1077,11 +1077,7 @@ void CompleteAsyncVoidCallbackWork(napi_env env, napi_status status, void *data) napi_get_undefined(env, &undefined); napi_value callResult = 0; napi_value result[ARGS_TWO] = {nullptr}; - - if (asyncCallbackInfo->error_code) { - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, asyncCallbackInfo->error_code, &result[PARAM0])); - } - + result[PARAM0] = GetCallbackErrorValue(env, asyncCallbackInfo->error_code); if (asyncCallbackInfo->error_code == NAPI_ERR_NO_ERROR) { result[PARAM1] = WrapVoidToJS(env); } else { @@ -1178,7 +1174,7 @@ std::vector ConvertStringVector(napi_env env, napi_value jsValue) bool isTypedArray = false; napi_status status = napi_is_typedarray(env, jsValue, &isTypedArray); if (status != napi_ok || !isTypedArray) { - HILOG_ERROR("%{public}s called, napi_is_typedarray error", __func__); + HILOG_INFO("%{public}s called, napi_is_typedarray error", __func__); return {}; } @@ -1196,10 +1192,7 @@ std::vector ConvertStringVector(napi_env env, napi_value jsValue) NAPI_CALL_BASE(env, napi_get_arraybuffer_info(env, buffer, reinterpret_cast(&data), &total), {}); length = std::min(length, total - offset); std::vector result(sizeof(std::string) + length); - int retCode = memcpy_s(result.data(), result.size(), &data[offset], length); - if (retCode != 0) { - return {}; - } + memcpy_s(result.data(), result.size(), &data[offset], length); return result; } } // namespace AppExecFwk diff --git a/ohos.build b/ohos.build index 7dd1884617d45bc23bb582abc48578ef4e5dcaa3..05bcbb7bf511defd0b3fcc1655c29418cc88fe39 100644 --- a/ohos.build +++ b/ohos.build @@ -118,7 +118,8 @@ "test_list": [ "//foundation/aafwk/standard/frameworks/kits/content/cpp/test:unittest", "//foundation/aafwk/standard/frameworks/kits/ability/native/test:unittest", - "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test:moduletest", + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/moduletest:moduletest", + "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime/test/unittest:unittest", "//foundation/aafwk/standard/frameworks/kits/test:moduletest", "//foundation/aafwk/standard/services/test:moduletest", "//foundation/aafwk/standard/services:unittest", diff --git a/services/abilitymgr/include/ability_record.h b/services/abilitymgr/include/ability_record.h index a6384c46dff1b82cec6b234a5d4aa5cf030bd460..cf1c6732134fefdbb5b5a7d0157e4d88721f60ba 100644 --- a/services/abilitymgr/include/ability_record.h +++ b/services/abilitymgr/include/ability_record.h @@ -885,6 +885,7 @@ private: int32_t restartCount_ = -1; int32_t restratMax_ = -1; std::string specifiedFlag_; + std::mutex lock_; }; class AbilityRecordNew : public AbilityRecord { diff --git a/services/abilitymgr/include/inner_mission_info.h b/services/abilitymgr/include/inner_mission_info.h index faec076413295cd66f39b6c6a45b0f129c191040..af13a48e3507e0f7dc6aa8e64eb9e79781889cf6 100644 --- a/services/abilitymgr/include/inner_mission_info.h +++ b/services/abilitymgr/include/inner_mission_info.h @@ -31,6 +31,10 @@ enum class JsonType { ARRAY, STRING, }; +enum class StartMethod { + START_NORMAL, + START_CALL, +}; /** * @struct InnerMissionInfo @@ -40,6 +44,7 @@ struct InnerMissionInfo { MissionInfo missionInfo; std::string missionName; bool isSingletonMode; + int32_t startMethod; std::string ToJsonStr() const; bool FromJsonStr(const std::string &jsonStr); diff --git a/services/abilitymgr/include/mission.h b/services/abilitymgr/include/mission.h index 899311b5a2747359fe1bc15df881b7e01bda4da9..161ab18e7cbd8caaba1bf92e0e2e2d42ef1f42ca 100644 --- a/services/abilitymgr/include/mission.h +++ b/services/abilitymgr/include/mission.h @@ -29,7 +29,8 @@ namespace AAFwk { */ class Mission : public std::enable_shared_from_this { public: - Mission(int32_t id, const std::shared_ptr abilityRecord, const std::string &missionName = ""); + Mission(int32_t id, const std::shared_ptr abilityRecord, const std::string &missionName = "", + int32_t startMethod = 0); Mission(const std::shared_ptr &mission); virtual ~Mission(); @@ -120,8 +121,25 @@ public: */ void Dump(std::vector &info); + /** + * @brief whether it is a form ByCall start-up + * + * @return true form BaCall start-up, false other + */ + bool IsStartByCall(); + + /** + * @brief update mission id + * + * @param id mission id. + * @param method start method. + * @return Returns true on success, false on failure + */ + bool UpdateMissionId(int32_t id, int32_t method); + private: int32_t missionId_; + int32_t startMethod_; std::shared_ptr abilityRecord_; std::string missionName_; std::weak_ptr ownerMissionList_; diff --git a/services/abilitymgr/src/ability_manager_service.cpp b/services/abilitymgr/src/ability_manager_service.cpp index 4c7cf21c3858fbbc692d634fa2669d7f423c0c3d..efa9380595929fa81f37d5e995e7d3b212474e87 100644 --- a/services/abilitymgr/src/ability_manager_service.cpp +++ b/services/abilitymgr/src/ability_manager_service.cpp @@ -2859,10 +2859,12 @@ bool AbilityManagerService::VerificationToken(const sptr &token) } if (dataAbilityManager_->GetAbilityRecordByToken(token)) { + HILOG_INFO("Verification token4."); return true; } if (connectManager_->GetServiceRecordByToken(token)) { + HILOG_INFO("Verification token5."); return true; } @@ -3475,6 +3477,18 @@ int AbilityManagerService::StartAbilityByCall( return RESOLVE_CALL_NO_PERMISSIONS; } + HILOG_DEBUG("abilityInfo.applicationInfo.singleUser is %{public}s", + abilityRequest.abilityInfo.applicationInfo.singleUser ? "true" : "false"); + if (abilityRequest.abilityInfo.applicationInfo.singleUser) { + auto missionListManager = GetListManagerByUserId(U0_USER_ID); + if (missionListManager == nullptr) { + HILOG_ERROR("missionListManager is Null. userId=%{public}d", U0_USER_ID); + return ERR_INVALID_VALUE; + } + + return missionListManager->ResolveLocked(abilityRequest); + } + return currentMissionListManager_->ResolveLocked(abilityRequest); } diff --git a/services/abilitymgr/src/ability_record.cpp b/services/abilitymgr/src/ability_record.cpp index 2e556f359b9e00a9a0bae2b7d5a101ecd3c4bc30..03a20a15aaa462806fd5322a69877ccefab4bf2f 100644 --- a/services/abilitymgr/src/ability_record.cpp +++ b/services/abilitymgr/src/ability_record.cpp @@ -694,6 +694,7 @@ std::shared_ptr AbilityRecord::GetResult() const void AbilityRecord::SendResult() { HILOG_INFO("Send result."); + std::lock_guard guard(lock_); CHECK_POINTER(scheduler_); CHECK_POINTER(result_); scheduler_->SendResult(result_->requestCode_, result_->resultCode_, result_->resultWant_); @@ -705,6 +706,10 @@ void AbilityRecord::SendResult() void AbilityRecord::SendResultToCallers() { for (auto caller : GetCallerRecordList()) { + if (caller == nullptr) { + HILOG_WARN("Caller record is nullptr."); + continue; + } std::shared_ptr callerAbilityRecord = caller->GetCaller(); if (callerAbilityRecord != nullptr && callerAbilityRecord->GetResult() != nullptr) { callerAbilityRecord->SendResult(); @@ -715,6 +720,10 @@ void AbilityRecord::SendResultToCallers() void AbilityRecord::SaveResultToCallers(const int resultCode, const Want *resultWant) { for (auto caller : GetCallerRecordList()) { + if (caller == nullptr) { + HILOG_WARN("Caller record is nullptr."); + continue; + } std::shared_ptr callerAbilityRecord = caller->GetCaller(); if (callerAbilityRecord != nullptr) { callerAbilityRecord->SetResult( @@ -1062,6 +1071,7 @@ void AbilityRecord::OnSchedulerDied(const wptr &remote) if (mission) { HILOG_WARN("On scheduler died. Is app not response Reason:%{public}d", mission->IsANRState()); } + std::lock_guard guard(lock_); CHECK_POINTER(scheduler_); auto object = remote.promote(); diff --git a/services/abilitymgr/src/ability_scheduler_proxy.cpp b/services/abilitymgr/src/ability_scheduler_proxy.cpp index 557d9c42a522b16d0c59541443ef2f3fd02792c3..17fcd71a727c675107cb6a1fa056f7c5a0087d8c 100755 --- a/services/abilitymgr/src/ability_scheduler_proxy.cpp +++ b/services/abilitymgr/src/ability_scheduler_proxy.cpp @@ -1032,10 +1032,9 @@ sptr AbilitySchedulerProxy::CallRequest() HILOG_ERROR("CallRequest failed, err %{public}d", result); return nullptr; } - - auto call = reply.ReadParcelable(); - if (!call) { - HILOG_ERROR("CallRequest error"); + auto call = reply.ReadRemoteObject(); + if (call == nullptr) { + HILOG_ERROR("CallRequest failed, err remoteObject is nullptr"); return nullptr; } diff --git a/services/abilitymgr/src/ability_scheduler_stub.cpp b/services/abilitymgr/src/ability_scheduler_stub.cpp index 89e19940414d40019d3d127e4c5bf403428909a0..1b8057897fe52cc40f902fa1523757e356fbdd18 100644 --- a/services/abilitymgr/src/ability_scheduler_stub.cpp +++ b/services/abilitymgr/src/ability_scheduler_stub.cpp @@ -614,8 +614,8 @@ int AbilitySchedulerStub::CallRequestInner(MessageParcel &data, MessageParcel &r return ERR_INVALID_VALUE; } - if (!reply.WriteParcelable(call)) { - HILOG_ERROR("call request write failed."); + if (!reply.WriteRemoteObject(call)) { + HILOG_ERROR("Connect done remote object error."); return ERR_INVALID_VALUE; } diff --git a/services/abilitymgr/src/call_record.cpp b/services/abilitymgr/src/call_record.cpp index c4f7ca30979b8d42eb3b681569b1469f7274be91..934e4194bc5a8762a2496b6bd94a2f81cc542abf 100644 --- a/services/abilitymgr/src/call_record.cpp +++ b/services/abilitymgr/src/call_record.cpp @@ -140,8 +140,6 @@ bool CallRecord::SchedulerDisConnectDone() void CallRecord::OnCallStubDied(const wptr & remote) { HILOG_WARN("callstub is died. id:%{public}d", recordId_); - auto object = remote.promote(); - CHECK_POINTER(object); auto abilityManagerService = DelayedSingleton::GetInstance(); CHECK_POINTER(abilityManagerService); diff --git a/services/abilitymgr/src/inner_mission_info.cpp b/services/abilitymgr/src/inner_mission_info.cpp index 6231b346fce388e389a010501dfaa0ac76402157..2198f0df7ed3b311e87ef5494c2b2e88ea14512e 100644 --- a/services/abilitymgr/src/inner_mission_info.cpp +++ b/services/abilitymgr/src/inner_mission_info.cpp @@ -25,6 +25,7 @@ std::string InnerMissionInfo::ToJsonStr() const nlohmann::json value; value["MissionName"] = missionName; value["IsSingleton"] = isSingletonMode; + value["StartMethod"] = startMethod; value["MissionId"] = missionInfo.id; value["RunningState"] = missionInfo.runningState; value["LockedState"] = missionInfo.lockedState; @@ -71,6 +72,10 @@ bool InnerMissionInfo::FromJsonStr(const std::string &jsonStr) return false; } isSingletonMode = value["IsSingleton"].get(); + if (!CheckJsonNode("StartMethod", JsonType::NUMBER)) { + return false; + } + startMethod = value["StartMethod"].get(); if (!CheckJsonNode("MissionId", JsonType::NUMBER)) { return false; } diff --git a/services/abilitymgr/src/mission.cpp b/services/abilitymgr/src/mission.cpp index 7113b70418a0b8dec6fcd8163ceccf0b09dab28e..20fdda11f1c2a716db269ff25210602b89c5a99a 100644 --- a/services/abilitymgr/src/mission.cpp +++ b/services/abilitymgr/src/mission.cpp @@ -17,8 +17,9 @@ namespace OHOS { namespace AAFwk { -Mission::Mission(int32_t id, const std::shared_ptr abilityRecord, const std::string &missionName) - : missionId_(id), abilityRecord_(abilityRecord), missionName_(missionName) +Mission::Mission(int32_t id, const std::shared_ptr abilityRecord, const std::string &missionName, + int32_t startMethod) + : missionId_(id), startMethod_(startMethod), abilityRecord_(abilityRecord), missionName_(missionName) { } @@ -29,6 +30,7 @@ Mission::Mission(const std::shared_ptr &mission) } missionId_ = mission->missionId_; + startMethod_ = mission->startMethod_; abilityRecord_ = mission->abilityRecord_; missionName_ = mission->missionName_; ownerMissionList_ = mission->ownerMissionList_; @@ -115,5 +117,21 @@ void Mission::Dump(std::vector &info) } } +bool Mission::IsStartByCall() +{ + return static_cast(StartMethod::START_CALL) == startMethod_; +} + +bool Mission::UpdateMissionId(int32_t id, int32_t method) +{ + if (method == startMethod_ && id > 0) { + return false; + } + + startMethod_ = method; + missionId_ = id; + return true; +} + } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/mission_info_mgr.cpp b/services/abilitymgr/src/mission_info_mgr.cpp index 5dbb0d3d63b06bbd12c3ef3101e008614d01b0c0..224364b1b2cf0976000d8ff0b896816fdc12c328 100644 --- a/services/abilitymgr/src/mission_info_mgr.cpp +++ b/services/abilitymgr/src/mission_info_mgr.cpp @@ -179,6 +179,16 @@ bool MissionInfoMgr::DeleteAllMissionInfos(const std::shared_ptr(startMethod)) { + case StartMethod::START_CALL: + return true; + default: + return false; + } +} + int MissionInfoMgr::GetMissionInfos(int32_t numMax, std::vector &missionInfos) { HILOG_INFO("GetMissionInfos, numMax:%{public}d", numMax); @@ -190,6 +200,11 @@ int MissionInfoMgr::GetMissionInfos(int32_t numMax, std::vector &mi if (static_cast(missionInfos.size()) >= numMax) { break; } + + if (DoesNotShowInTheMissionList(mission.startMethod)) { + HILOG_INFO("MissionId[%{public}d] don't show in mission list", mission.missionInfo.id); + continue; + } MissionInfo info = mission.missionInfo; missionInfos.emplace_back(info); } @@ -215,6 +230,12 @@ int MissionInfoMgr::GetMissionInfoById(int32_t missionId, MissionInfo &missionIn HILOG_ERROR("no such mission:%{public}d", missionId); return -1; } + + if (DoesNotShowInTheMissionList((*it).startMethod)) { + HILOG_INFO("MissionId[%{public}d] don't show in mission list", (*it).missionInfo.id); + return -1; + } + HILOG_INFO("GetMissionInfoById, find missionId missionId:%{public}d", missionId); missionInfo = (*it).missionInfo; return 0; diff --git a/services/abilitymgr/src/mission_list_manager.cpp b/services/abilitymgr/src/mission_list_manager.cpp index 7f27af14e24704375f28ee8f4462c6f296897b3a..b220cab98686632df52908b8ae4dcc420d3293f9 100644 --- a/services/abilitymgr/src/mission_list_manager.cpp +++ b/services/abilitymgr/src/mission_list_manager.cpp @@ -286,10 +286,36 @@ int MissionListManager::StartAbilityLocked(const std::shared_ptr } } +static int32_t CallType2StartMethod(int32_t callType) +{ + switch (callType) { + case AbilityCallType::INVALID_TYPE: + return static_cast(StartMethod::START_NORMAL); + case AbilityCallType::CALL_REQUEST_TYPE: + return static_cast(StartMethod::START_CALL); + default: + break; + } + return -1; +} + +static bool CallTypeFilter(int32_t callType) +{ + switch (callType) { + case AbilityCallType::CALL_REQUEST_TYPE: + return true; + default: + break; + } + return false; +} + void MissionListManager::GetTargetMissionAndAbility(const AbilityRequest &abilityRequest, std::shared_ptr &targetMission, std::shared_ptr &targetRecord) { + auto startMethod = CallType2StartMethod(abilityRequest.callType); + HILOG_DEBUG("GetTargetMissionAndAbility called startMethod is %{public}d.", startMethod); auto reUsedMission = GetReusedMission(abilityRequest); if (reUsedMission) { HILOG_DEBUG("find reused mission in running list."); @@ -299,7 +325,13 @@ void MissionListManager::GetTargetMissionAndAbility(const AbilityRequest &abilit targetRecord->SetWant(abilityRequest.want); targetRecord->SetIsNewWant(true); } - return; + + if (!(targetMission->IsStartByCall() + && !CallTypeFilter(startMethod))) { + HILOG_DEBUG("mission exists. No update required"); + return; + } + HILOG_DEBUG("mission exists. need to be updated"); } // no reused mission, create a new one. @@ -319,6 +351,7 @@ void MissionListManager::GetTargetMissionAndAbility(const AbilityRequest &abilit info.missionName = missionName; info.isSingletonMode = isSingleton; + info.startMethod = startMethod; info.missionInfo.runningState = 0; info.missionInfo.continuable = abilityRequest.abilityInfo.continuable; info.missionInfo.time = Time2str(time(0)); @@ -332,10 +365,22 @@ void MissionListManager::GetTargetMissionAndAbility(const AbilityRequest &abilit return; } } - targetRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); - targetMission = std::make_shared(info.missionInfo.id, targetRecord, missionName); - targetRecord->SetUseNewMission(); - targetRecord->SetMission(targetMission); + + if (targetMission == nullptr) { + HILOG_DEBUG("Make new mission data."); + targetRecord = AbilityRecord::CreateAbilityRecord(abilityRequest); + targetMission = std::make_shared(info.missionInfo.id, targetRecord, missionName, startMethod); + targetRecord->SetUseNewMission(); + targetRecord->SetMission(targetMission); + } else { + HILOG_DEBUG("Update old mission data."); + auto state = targetMission->UpdateMissionId(info.missionInfo.id, startMethod); + if (!state) { + HILOG_INFO("targetMission UpdateMissionId(%{public}d, %{public}d) failed", info.missionInfo.id, + startMethod); + } + HILOG_DEBUG("Update MissionId UpdateMissionId(%{public}d, %{public}d) end", info.missionInfo.id, startMethod); + } if (abilityRequest.abilityInfo.launchMode == AppExecFwk::LaunchMode::SPECIFIED) { targetRecord->SetSpecifiedFlag(abilityRequest.specifiedFlag); diff --git a/services/abilitymgr/test/BUILD.gn b/services/abilitymgr/test/BUILD.gn index 471faea2ff7bf0a044ac11bf2e800693bb8ae772..9be84eef1fc1df9774f9970403f6540b32d5f702 100644 --- a/services/abilitymgr/test/BUILD.gn +++ b/services/abilitymgr/test/BUILD.gn @@ -168,6 +168,7 @@ group("unittest") { "unittest/phone/ability_connect_callback_stub_test:unittest", "unittest/phone/ability_connect_manage_test:unittest", "unittest/phone/ability_dump_test:unittest", + "unittest/phone/ability_manager_client_test:unittest", "unittest/phone/ability_manager_proxy_test:unittest", "unittest/phone/ability_manager_service_test:unittest", "unittest/phone/ability_manager_stub_test:unittest", @@ -181,6 +182,8 @@ group("unittest") { "unittest/phone/ability_with_applications_test:unittest", "unittest/phone/abilityms_appms_test:unittest", "unittest/phone/app_scheduler_test:unittest", + "unittest/phone/call_container_test:unittest", + "unittest/phone/call_record_test:unittest", "unittest/phone/configuration_test:unittest", "unittest/phone/connection_record_test:unittest", "unittest/phone/data_ability_manager_test:unittest", @@ -189,6 +192,8 @@ group("unittest") { "unittest/phone/lifecycle_deal_test:unittest", "unittest/phone/lifecycle_test:unittest", "unittest/phone/lock_screen_white_list_test:unittest", + "unittest/phone/mission_list_manager_ut_test:unittest", + "unittest/phone/mission_list_test:unittest", "unittest/phone/mission_record_test:unittest", "unittest/phone/mission_stack_test:unittest", "unittest/phone/pending_want_key_test:unittest", diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/mock_bundle_manager.h b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/mock_bundle_manager.h index 9f26de661771c5f56c1dd80f737cdceb9412281d..1fb11478dc88e48648b615114d613553d56e1435 100644 --- a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/mock_bundle_manager.h +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/mock_bundle_manager.h @@ -48,6 +48,7 @@ auto HiWordInfo = [](std::string bundleName, AbilityInfo &abilityInfo, ElementNa abilityInfo.applicationInfo.name = "Helloworld"; abilityInfo.type = AbilityType::PAGE; abilityInfo.applicationInfo.isLauncherApp = true; + abilityInfo.applicationInfo.apiCompatibleVersion = 8; return true; }; diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_client_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_manager_client_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..7577602c81845e337669d27b1bb6a9cada996521 --- /dev/null +++ b/services/abilitymgr/test/unittest/phone/ability_manager_client_test/BUILD.gn @@ -0,0 +1,70 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +ohos_unittest("ability_manager_client_test") { + module_out_path = "ability_runtime/ability_call_test" + + include_dirs = [ + "${services_path}/abilitymgr/test/mock/libs/system_ability_mock", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include", + ] + + sources = [ + "${services_path}/abilitymgr/src/ability_manager_client.cpp", + "ability_manager_client_test.cpp", + ] + + configs = [ "${services_path}/abilitymgr:abilityms_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${innerkits_path}/want:want", + "${services_path}/abilitymgr/test:abilityms_test_source", + "${services_path}/abilitymgr/test/mock/libs/aakit:aakit_mock", + "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_appmgr_mock", + "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_bundlemgr_mock", + "${services_path}/common:perm_verification", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", + "//utils/native/base:utils", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "device_manager_base:devicemanagersdk", + "dsoftbus_standard:softbus_client", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + deps = [ ":ability_manager_client_test" ] +} diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_client_test/ability_manager_client_test.cpp b/services/abilitymgr/test/unittest/phone/ability_manager_client_test/ability_manager_client_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a00b287d89c68eb162fe4008427c8538a9db673a --- /dev/null +++ b/services/abilitymgr/test/unittest/phone/ability_manager_client_test/ability_manager_client_test.cpp @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#define private public +#define protected public +#include "ability_manager_client.h" +#undef private +#undef protected +#include "ability_manager_stub_mock_test.h" + +using namespace testing::ext; +using namespace testing; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace AAFwk { +class AbilityManagerClientTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + std::shared_ptr client_ {nullptr}; + sptr mock_ {nullptr}; +}; + +void AbilityManagerClientTest::SetUpTestCase(void) +{} +void AbilityManagerClientTest::TearDownTestCase(void) +{} +void AbilityManagerClientTest::TearDown() +{} + +void AbilityManagerClientTest::SetUp() +{ + client_ = std::make_shared(); + mock_ = new AbilityManagerStubTestMock(); + client_->remoteObject_ = mock_; +} + +/* + * Feature: AbilityManagerClient + * Function: StartAbilityByCall + * SubFunction: NA + * FunctionPoints: AbilityManagerClient StartAbility + * EnvConditions: NA + * CaseDescription: Verify the StartAbilityByCall call normal + */ +HWTEST_F(AbilityManagerClientTest, StartAbilityByCall_001, TestSize.Level1) +{ + Want want; + EXPECT_EQ(client_->StartAbilityByCall(want, nullptr, nullptr), 0); +} + +/* + * Feature: AbilityManagerClient + * Function: StartAbilityByCall + * SubFunction: NA + * FunctionPoints: AbilityManagerClient StartAbility + * EnvConditions: NA + * CaseDescription: Verify the ReleaseAbility call normal + */ +HWTEST_F(AbilityManagerClientTest, ReleaseAbility_001, TestSize.Level1) +{ + ElementName element; + sptr connect = nullptr; + EXPECT_EQ(client_->ReleaseAbility(connect, element), 0); +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_client_test/ability_manager_stub_mock_test.h b/services/abilitymgr/test/unittest/phone/ability_manager_client_test/ability_manager_stub_mock_test.h new file mode 100644 index 0000000000000000000000000000000000000000..2d4167321eee6daa818f23e6f5a054a5621d1373 --- /dev/null +++ b/services/abilitymgr/test/unittest/phone/ability_manager_client_test/ability_manager_stub_mock_test.h @@ -0,0 +1,472 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ABILITY_UNITTEST_ABILITY_MANAGER_STUB_MOCK_H +#define ABILITY_UNITTEST_ABILITY_MANAGER_STUB_MOCK_H +#include +#include +#include +#include "ability_manager_interface.h" + +namespace OHOS { +namespace AAFwk { +class AbilityManagerStubTestMock : public IRemoteStub { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"IAbilityManagerMock"); + + AbilityManagerStubTestMock() : code_(0) + {} + virtual ~AbilityManagerStubTestMock() + {} + + MOCK_METHOD4(SendRequest, int(uint32_t, MessageParcel &, MessageParcel &, MessageOption &)); + + int InvokeSendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) + { + code_ = code; + + if (GET_RECENT_MISSION == code) { + std::vector missionInfos; + AbilityMissionInfo info; + info.id = 1; + const Want want; + info.baseWant = want; + AppExecFwk::ElementName baseEle("baseDevice", "baseBundle", "baseAbility"); + info.baseAbility = baseEle; + AppExecFwk::ElementName topEle("topDevice", "topBundle", "topAbility"); + info.topAbility = topEle; + missionInfos.emplace_back(info); + + reply.WriteInt32(missionInfos.size()); + for (auto &it : missionInfos) { + if (!reply.WriteParcelable(&it)) { + return ERR_INVALID_VALUE; + } + } + + int res = 1; + if (!reply.WriteInt32(res)) { + return ERR_INVALID_VALUE; + } + } + + return 0; + } + + int InvokeErrorSendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) + { + code_ = code; + return UNKNOWN_ERROR; + } + + int code_ = 0; + + virtual int StartAbility(const Want &want, int32_t userId = DEFAULT_INVAL_VALUE, int requestCode = -1) + { + return 0; + } + + virtual int StartAbility(const Want &want, + const AbilityStartSetting &abilityStartSetting, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) + { + return 0; + } + + virtual int StartAbility( + const Want &want, + const StartOptions &startOptions, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE, + int requestCode = DEFAULT_INVAL_VALUE) + { + return 0; + } + + virtual int TerminateAbility(const sptr &token, int resultCode, const Want *resultWant = nullptr) + { + return 0; + } + virtual int CloseAbility(const sptr &token, int resultCode = DEFAULT_INVAL_VALUE, + const Want *resultWant = nullptr) override + { + return 0; + } + virtual int MinimizeAbility(const sptr &token, bool fromUser) override + { + return 0; + } + + virtual int ConnectAbility( + const Want &want, + const sptr &connect, + const sptr &callerToken, + int32_t userId = DEFAULT_INVAL_VALUE) + { + return 0; + } + + virtual sptr AcquireDataAbility( + const Uri &uri, bool tryBind, const sptr &callerToken) override + { + return nullptr; + } + + virtual int ReleaseDataAbility(sptr dataAbilityScheduler, const sptr &callerToken) + { + return 0; + } + + virtual int DisconnectAbility(const sptr &connect) + { + return 0; + } + + virtual void AddWindowInfo(const sptr &token, int32_t windowToken) + {} + + virtual int AttachAbilityThread(const sptr &scheduler, const sptr &token) + { + return 0; + } + + virtual int AbilityTransitionDone(const sptr &token, int state, const PacMap &saveData) + { + return 0; + } + + virtual int ScheduleConnectAbilityDone(const sptr &token, const sptr &remoteObject) + { + return 0; + } + + virtual int ScheduleDisconnectAbilityDone(const sptr &token) + { + return 0; + } + + virtual int ScheduleCommandAbilityDone(const sptr &token) + { + return 0; + } + + virtual void DumpState(const std::string &args, std::vector &state) + {} + + virtual void DumpSysState( + const std::string& args, std::vector& info, bool isClient, bool isUserID, int UserID) + {} + + virtual int TerminateAbilityResult(const sptr &token, int startId) + { + return 0; + } + + virtual int StopServiceAbility(const Want &want, int32_t userId = DEFAULT_INVAL_VALUE) + { + return 0; + } + + virtual int GetAllStackInfo(StackInfo &stackInfo) + { + return 0; + } + + virtual int GetRecentMissions( + const int32_t numMax, const int32_t flags, std::vector &recentList) + { + return 0; + } + + int GetMissionSnapshot(const int32_t missionId, MissionPixelMap &missionPixelMap) + { + return 0; + } + + virtual int RemoveMission(int id) + { + return 0; + } + + virtual int RemoveStack(int id) + { + return 0; + } + + virtual int KillProcess(const std::string &bundleName) + { + return 0; + } + + virtual int UninstallApp(const std::string &bundleName) + { + return 0; + } + + virtual int MoveMissionToTop(int32_t missionId) + { + return 0; + } + + bool IsFirstInMission(const sptr &token) override + { + return true; + } + + int CompelVerifyPermission(const std::string &permission, int pid, int uid, std::string &message) override + { + return 0; + } + + int MoveMissionToEnd(const sptr &token, const bool nonFirst) override + { + return 0; + } + + int PowerOff() override + { + return 0; + } + + int PowerOn() override + { + return 0; + } + + int LockMission(int missionId) override + { + return 0; + } + int UnlockMission(int missionId) override + { + return 0; + } + + int SetMissionDescriptionInfo( + const sptr &token, const MissionDescriptionInfo &missionDescriptionInfo) override + { + return 0; + } + + int GetMissionLockModeState() + { + return 0; + } + + int MoveMissionToFloatingStack(const MissionOption &missionOption) + { + return 0; + } + + int UpdateConfiguration(const AppExecFwk::Configuration &config) + + { + return 0; + } + + int MoveMissionToSplitScreenStack(const MissionOption &primary, const MissionOption &secondary) + { + return 0; + } + + int ChangeFocusAbility(const sptr &lostFocusToken, const sptr &getFocusToken) + { + return 0; + } + + int MinimizeMultiWindow(int missionId) + { + return 0; + } + + int MaximizeMultiWindow(int missionId) + { + return 0; + } + + int GetFloatingMissions(std::vector &list) + { + return 0; + } + + int CloseMultiWindow(int missionId) + { + return 0; + } + + int SetMissionStackSetting(const StackSetting &stackSetting) + { + return 0; + } + + virtual int SetShowOnLockScreen(bool isAllow) override + { + return 0; + } + + virtual int ClearUpApplicationData(const std::string &bundleName) override + { + return 0; + } + + virtual int StartUser(int userId) override + { + return 0; + } + + virtual int StopUser(int userId, const sptr &callback) override + { + return 0; + } + virtual int StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag) override + { + return 0; + } + virtual int StopSyncRemoteMissions(const std::string& devId) override + { + return 0; + } + virtual int RegisterMissionListener(const std::string &deviceId, + const sptr &listener) override + { + return 0; + } + virtual int UnRegisterMissionListener(const std::string &deviceId, + const sptr &listener) override + { + return 0; + } + virtual int ReleaseAbility(const sptr &connect, + const AppExecFwk::ElementName &element) override + { + return 0; + } + virtual int GetMissionSnapshot(const std::string& deviceId, int32_t missionId, MissionSnapshot& snapshot) + { + return 0; + } + virtual int RegisterSnapshotHandler(const sptr& handler) + { + return 0; + } + + virtual int SetAbilityController(const sptr &abilityController, + bool imAStabilityTest) override + { + return 0; + } + + virtual bool IsRunningInStabilityTest() override + { + return true; + } + + virtual int SendANRProcessID(int pid) override + { + return 0; + } + + MOCK_METHOD2(TerminateAbilityByCaller, int(const sptr &callerToken, int requestCode)); + MOCK_METHOD4(StartAbility, int(const Want &want, const sptr &callerToken, + int32_t userId, int requestCode)); + MOCK_METHOD2( + GetWantSender, sptr(const WantSenderInfo &wantSenderInfo, const sptr &callerToken)); + MOCK_METHOD2(SendWantSender, int(const sptr &target, const SenderInfo &senderInfo)); + MOCK_METHOD1(CancelWantSender, void(const sptr &sender)); + MOCK_METHOD1(GetPendingWantUid, int(const sptr &target)); + MOCK_METHOD1(GetPendingWantUserId, int(const sptr &target)); + MOCK_METHOD1(GetPendingWantBundleName, std::string(const sptr &target)); + MOCK_METHOD1(GetPendingWantCode, int(const sptr &target)); + MOCK_METHOD1(GetPendingWantType, int(const sptr &target)); + MOCK_METHOD2(RegisterCancelListener, void(const sptr &sender, const sptr &receiver)); + MOCK_METHOD2(UnregisterCancelListener, void(const sptr &sender, const sptr &receiver)); + MOCK_METHOD2(GetPendingRequestWant, int(const sptr &target, std::shared_ptr &want)); + MOCK_METHOD1(GetSystemMemoryAttr, void(AppExecFwk::SystemMemoryAttr &memoryInfo)); + MOCK_METHOD3(StartContinuation, int(const Want &want, const sptr &abilityToken, int32_t status)); + MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, int32_t result)); + MOCK_METHOD5(ContinueMission, int(const std::string &srcDeviceId, const std::string &dstDeviceId, + int32_t missionId, const sptr &callBack, AAFwk::WantParams &wantParams)); + MOCK_METHOD2(ContinueAbility, int(const std::string &deviceId, int32_t missionId)); + MOCK_METHOD3(NotifyCompleteContinuation, void(const std::string &deviceId, int32_t sessionId, bool isSuccess)); + + MOCK_METHOD1(LockMissionForCleanup, int(int32_t missionId)); + MOCK_METHOD1(UnlockMissionForCleanup, int(int32_t missionId)); + MOCK_METHOD1(RegisterMissionListener, int(const sptr &listener)); + MOCK_METHOD1(UnRegisterMissionListener, int(const sptr &listener)); + MOCK_METHOD3( + GetMissionInfos, int(const std::string& deviceId, int32_t numMax, std::vector &missionInfos)); + MOCK_METHOD3(GetMissionInfo, int(const std::string& deviceId, int32_t missionId, MissionInfo &missionInfo)); + MOCK_METHOD1(CleanMission, int(int32_t missionId)); + MOCK_METHOD0(CleanAllMissions, int()); + MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); + MOCK_METHOD2(MoveMissionToFront, int(int32_t missionId, const StartOptions &startOptions)); + MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); + MOCK_METHOD2(GetWantSenderInfo, int(const sptr &target, std::shared_ptr &info)); + MOCK_METHOD1(GetAbilityRunningInfos, int(std::vector &info)); + MOCK_METHOD2(GetExtensionRunningInfos, int(int upperLimit, std::vector &info)); + MOCK_METHOD1(GetProcessRunningInfos, int(std::vector &info)); + + virtual int StartAbilityByCall( + const Want &want, const sptr &connect, const sptr &callerToken) override + { + return 0; + } + + virtual int StartUserTest(const Want &want, const sptr &observer) override + { + return 0; + } + + virtual int FinishUserTest(const std::string &msg, const int &resultCode, const std::string &bundleName) override + { + return 0; + } + + virtual int GetCurrentTopAbility(sptr &token) override + { + return 0; + } + + virtual int DelegatorDoAbilityForeground(const sptr &token) override + { + return 0; + } + + virtual int DelegatorDoAbilityBackground(const sptr &token) override + { + return 0; + } + + virtual int DoAbilityForeground(const sptr &token, uint32_t flag) override + { + return 0; + } + + virtual int DoAbilityBackground(const sptr &token, uint32_t flag) override + { + return 0; + } + + virtual int ForceTimeoutForTest(const std::string &abilityName, const std::string &state) override + { + return 0; + } +}; +} // namespace AAFwk +} // namespace OHOS + +#endif diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/ability_manager_proxy_test.cpp b/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/ability_manager_proxy_test.cpp index 68a16ff107800c771ea7611a6f402533b4c09d03..05d4d8704df3a1fcace89283caefa611e3b4ada5 100644 --- a/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/ability_manager_proxy_test.cpp +++ b/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/ability_manager_proxy_test.cpp @@ -786,5 +786,75 @@ HWTEST_F(AbilityManagerProxyTest, AbilityManagerProxy_ReleaseDataAbility_004, Te EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(TRANSACTION_ERR)); EXPECT_EQ(proxy_->ReleaseDataAbility(scheduler, abilityRecord->GetToken()), TRANSACTION_ERR); } + +/* + * Feature: AbilityManagerService + * Function: StartAbilityByCall + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartAbilityByCall + * EnvConditions: NA + * CaseDescription: Verify the function StartAbilityByCall connect is nullptr. + */ +HWTEST_F(AbilityManagerProxyTest, AbilityManagerProxy_StartAbilityByCall_001, TestSize.Level1) +{ + Want want; + sptr callerToken = nullptr; + sptr connect = nullptr; + EXPECT_EQ(proxy_->StartAbilityByCall(want, connect, callerToken), ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: StartAbilityByCall + * SubFunction: NA + * FunctionPoints: AbilityManagerService StartAbilityByCall + * EnvConditions: NA + * CaseDescription: Verify the function StartAbilityByCall is normal flow. + */ +HWTEST_F(AbilityManagerProxyTest, AbilityManagerProxy_StartAbilityByCall_002, TestSize.Level1) +{ + Want want; + sptr callerToken = nullptr; + sptr connect = new AbilityConnectCallback(); + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) + .Times(1) + .WillOnce(Invoke(mock_.GetRefPtr(), &AbilityManagerStubMock::InvokeSendRequest)); + EXPECT_EQ(proxy_->StartAbilityByCall(want, connect, callerToken), ERR_OK); + EXPECT_EQ(IAbilityManager::START_CALL_ABILITY, mock_->code_); +} + +/* + * Feature: AbilityManagerService + * Function: ReleaseAbility + * SubFunction: NA + * FunctionPoints: AbilityManagerService ReleaseAbility + * EnvConditions: NA + * CaseDescription: Verify the function ReleaseAbility connect is nullptr. + */ +HWTEST_F(AbilityManagerProxyTest, AbilityManagerProxy_ReleaseAbility_001, TestSize.Level1) +{ + AppExecFwk::ElementName element; + sptr connect = nullptr; + EXPECT_EQ(proxy_->ReleaseAbility(connect, element), ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: ReleaseAbility + * SubFunction: NA + * FunctionPoints: AbilityManagerService ReleaseAbility + * EnvConditions: NA + * CaseDescription: Verify the function ReleaseAbility is normal flow. + */ +HWTEST_F(AbilityManagerProxyTest, AbilityManagerProxy_ReleaseAbility_002, TestSize.Level1) +{ + AppExecFwk::ElementName element; + sptr connect = new AbilityConnectCallback(); + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) + .Times(1) + .WillOnce(Invoke(mock_.GetRefPtr(), &AbilityManagerStubMock::InvokeSendRequest)); + EXPECT_EQ(proxy_->ReleaseAbility(connect, element), ERR_OK); + EXPECT_EQ(IAbilityManager::RELEASE_CALL_ABILITY, mock_->code_); +} } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_service_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_manager_service_test/BUILD.gn index 97a773591ca332c1e0500533bd76e134a8760bb7..859322b11bed6b2d0139443378fe6e6043fb5f0e 100644 --- a/services/abilitymgr/test/unittest/phone/ability_manager_service_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_manager_service_test/BUILD.gn @@ -67,7 +67,59 @@ ohos_unittest("ability_manager_service_test") { ] } +ohos_unittest("ability_manager_service_test_call") { + module_out_path = "ability_runtime/ability_call_test" + + include_dirs = [ + "${services_path}/abilitymgr/test/mock/libs/system_ability_mock", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include", + ] + + sources = [ + # add mock file + "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp", + "ability_manager_service_test_call.cpp", + ] + + configs = [ "${services_path}/abilitymgr:abilityms_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${innerkits_path}/want:want", + "${services_path}/abilitymgr/test:abilityms_test_source", + "${services_path}/abilitymgr/test/mock/libs/aakit:aakit_mock", + "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_appmgr_mock", + "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_bundlemgr_mock", + "${services_path}/common:perm_verification", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", + "//utils/native/base:utils", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "device_manager_base:devicemanagersdk", + "dsoftbus_standard:softbus_client", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + group("unittest") { testonly = true # deps = [ ":ability_manager_service_test" ] + deps = [ ":ability_manager_service_test_call" ] } diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_service_test/ability_manager_service_test_call.cpp b/services/abilitymgr/test/unittest/phone/ability_manager_service_test/ability_manager_service_test_call.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b965aa1a17739fb86c3183a02a586b8a6b525ba3 --- /dev/null +++ b/services/abilitymgr/test/unittest/phone/ability_manager_service_test/ability_manager_service_test_call.cpp @@ -0,0 +1,321 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#define private public +#define protected public +#include "ability_manager_service.h" +#include "ability_event_handler.h" +#undef private +#undef protected + +#include "app_process_data.h" +#include "system_ability_definition.h" +#include "ability_manager_errors.h" +#include "ability_scheduler.h" +#include "bundlemgr/mock_bundle_manager.h" +#include "sa_mgr_client.h" +#include "mock_ability_connect_callback.h" +#include "mock_ability_token.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" + +using namespace testing; +using namespace testing::ext; +using namespace OHOS::AppExecFwk; + +namespace { + const std::string DEVICE_ID = "15010038475446345206a332922cb765"; + const std::string BUNDLE_NAME = "testBundle"; + const std::string NAME = ".testMainAbility"; +} + +namespace OHOS { +namespace AAFwk { +static void WaitUntilTaskFinished() +{ + const uint32_t maxRetryCount = 1000; + const uint32_t sleepTime = 1000; + uint32_t count = 0; + auto handler = OHOS::DelayedSingleton::GetInstance()->GetEventHandler(); + std::atomic taskCalled(false); + auto f = [&taskCalled]() { taskCalled.store(true); }; + if (handler->PostTask(f)) { + while (!taskCalled.load()) { + ++count; + if (count >= maxRetryCount) { + break; + } + usleep(sleepTime); + } + } +} + +#define SLEEP(milli) std::this_thread::sleep_for(std::chrono::seconds(milli)) + +namespace { +const std::string WaitUntilTaskFinishedByTimer = "BundleMgrService"; +} // namespace + +class AbilityManagerServiceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + void OnStartAms(); + void OnStopAms(); + int StartAbility(const Want &want); + static constexpr int TEST_WAIT_TIME = 100000; + +public: + AbilityRequest abilityRequest_; + std::shared_ptr abilityRecord_ {nullptr}; + std::shared_ptr abilityMs_ = DelayedSingleton::GetInstance(); +}; + +int AbilityManagerServiceTest::StartAbility(const Want &want) +{ + int ref = -1; + auto topAbility = abilityMs_->GetStackManager()->GetCurrentTopAbility(); + if (topAbility) { + topAbility->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); + } + ref = abilityMs_->StartAbility(want); + WaitUntilTaskFinished(); + return ref; +} + +void AbilityManagerServiceTest::OnStartAms() +{ + if (abilityMs_) { + if (abilityMs_->state_ == ServiceRunningState::STATE_RUNNING) { + return; + } + + abilityMs_->state_ = ServiceRunningState::STATE_RUNNING; + + abilityMs_->eventLoop_ = AppExecFwk::EventRunner::Create(AbilityConfig::NAME_ABILITY_MGR_SERVICE); + EXPECT_TRUE(abilityMs_->eventLoop_); + + abilityMs_->handler_ = std::make_shared(abilityMs_->eventLoop_, abilityMs_); + abilityMs_->connectManager_ = std::make_shared(); + abilityMs_->connectManagers_.emplace(0, abilityMs_->connectManager_); + EXPECT_TRUE(abilityMs_->handler_); + EXPECT_TRUE(abilityMs_->connectManager_); + + abilityMs_->dataAbilityManager_ = std::make_shared(); + abilityMs_->dataAbilityManagers_.emplace(0, abilityMs_->dataAbilityManager_); + EXPECT_TRUE(abilityMs_->dataAbilityManager_); + + abilityMs_->amsConfigResolver_ = std::make_shared(); + EXPECT_TRUE(abilityMs_->amsConfigResolver_); + abilityMs_->amsConfigResolver_->Parse(); + + abilityMs_->pendingWantManager_ = std::make_shared(); + EXPECT_TRUE(abilityMs_->pendingWantManager_); + + abilityMs_->currentMissionListManager_ = std::make_shared(0); + abilityMs_->currentMissionListManager_->Init(); + int userId = abilityMs_->GetUserId(); + abilityMs_->SetStackManager(userId, true); + EXPECT_TRUE(abilityMs_->GetStackManager()); + abilityMs_->stackManagers_.emplace(0, abilityMs_->GetStackManager()); + abilityMs_->eventLoop_->Run(); + return; + } + + GTEST_LOG_(INFO) << "OnStart fail"; +} + +void AbilityManagerServiceTest::OnStopAms() +{ + abilityMs_->OnStop(); +} + +void AbilityManagerServiceTest::SetUpTestCase() +{ + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility( + OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, new BundleMgrService()); +} + +void AbilityManagerServiceTest::TearDownTestCase() +{ + OHOS::DelayedSingleton::DestroyInstance(); +} + +void AbilityManagerServiceTest::SetUp() +{ + OnStartAms(); + WaitUntilTaskFinished(); + if (abilityRecord_ == nullptr) { + abilityRequest_.appInfo.bundleName = "data.client.bundle"; + abilityRequest_.abilityInfo.name = "ClientAbility"; + abilityRequest_.abilityInfo.type = AbilityType::DATA; + abilityRecord_ = AbilityRecord::CreateAbilityRecord(abilityRequest_); + } +} + +void AbilityManagerServiceTest::TearDown() +{ + OnStopAms(); +} + +/** + * @tc.name: CheckCallPermissions_001 + * @tc.desc: Verify function CheckCallPermissions return RESOLVE_CALL_NO_PERMISSIONS + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AbilityManagerServiceTest, CheckCallPermissions_001, TestSize.Level1) +{ + abilityRequest_.callerUid = 0; + EXPECT_EQ(RESOLVE_CALL_NO_PERMISSIONS, abilityMs_->CheckCallPermissions(abilityRequest_)); +} + +/** + * @tc.name: CheckCallPermissions_002 + * @tc.desc: Verify function CheckCallPermissions return ERR_OK + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AbilityManagerServiceTest, CheckCallPermissions_002, TestSize.Level1) +{ + abilityRequest_.callerUid = 1000; + abilityRequest_.abilityInfo.type = AppExecFwk::AbilityType::PAGE; + abilityRequest_.abilityInfo.launchMode = AppExecFwk::LaunchMode::SINGLETON; + EXPECT_EQ(ERR_OK, abilityMs_->CheckCallPermissions(abilityRequest_)); +} + +/** + * @tc.name: StartAbilityByCall_001 + * @tc.desc: Verify function StartAbilityByCall return RESOLVE_ABILITY_ERR + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AbilityManagerServiceTest, StartAbilityByCall_001, TestSize.Level1) +{ + Want want; + sptr connect = new AbilityConnectCallback(); + EXPECT_EQ(RESOLVE_ABILITY_ERR, abilityMs_->StartAbilityByCall(want, connect, nullptr)); +} + +/** + * @tc.name: StartAbilityByCall_002 + * @tc.desc: Verify function StartAbilityByCall return RESOLVE_CALL_ABILITY_VERSION_ERR + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AbilityManagerServiceTest, StartAbilityByCall_002, TestSize.Level1) +{ + std::string localDeviceId; + bool getLocalDeviceId = abilityMs_->GetLocalDeviceId(localDeviceId); + EXPECT_EQ(true, getLocalDeviceId); + Want want; + ElementName element(localDeviceId, "com.ix.hiMusic", "MusicAbility"); + want.SetElement(element); + sptr connect = new AbilityConnectCallback(); + EXPECT_EQ(RESOLVE_CALL_ABILITY_VERSION_ERR, abilityMs_->StartAbilityByCall(want, connect, nullptr)); +} + +/** + * @tc.name: StartAbilityByCall_003 + * @tc.desc: Verify function StartAbilityByCall return RESOLVE_CALL_NO_PERMISSIONS + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AbilityManagerServiceTest, StartAbilityByCall_003, TestSize.Level1) +{ + std::string localDeviceId; + bool getLocalDeviceId = abilityMs_->GetLocalDeviceId(localDeviceId); + EXPECT_EQ(true, getLocalDeviceId); + Want want; + ElementName element(localDeviceId, "com.ix.hiworld", "MusicAbility"); + want.SetElement(element); + sptr connect = new AbilityConnectCallback(); + EXPECT_EQ(RESOLVE_CALL_NO_PERMISSIONS, abilityMs_->StartAbilityByCall(want, connect, nullptr)); +} + +/** + * @tc.name: ReleaseAbility_001 + * @tc.desc: Verify function ReleaseAbility return ERR_INVALID_VALUE + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AbilityManagerServiceTest, ReleaseAbility_001, TestSize.Level1) +{ + std::string localDeviceId; + bool getLocalDeviceId = abilityMs_->GetLocalDeviceId(localDeviceId); + EXPECT_EQ(true, getLocalDeviceId); + Want want; + ElementName element(localDeviceId, "com.ix.hiworld", "MusicAbility"); + want.SetElement(element); + EXPECT_EQ(ERR_INVALID_VALUE, abilityMs_->ReleaseAbility(nullptr, element)); +} + +/** + * @tc.name: ReleaseAbility_002 + * @tc.desc: Verify function ReleaseAbility return RELEASE_CALL_ABILITY_INNER_ERR + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AbilityManagerServiceTest, ReleaseAbility_002, TestSize.Level1) +{ + std::string localDeviceId; + bool getLocalDeviceId = abilityMs_->GetLocalDeviceId(localDeviceId); + EXPECT_EQ(true, getLocalDeviceId); + Want want; + ElementName element(localDeviceId, "com.ix.hiworld", "MusicAbility"); + want.SetElement(element); + sptr connect = new AbilityConnectCallback(); + EXPECT_EQ(RELEASE_CALL_ABILITY_INNER_ERR, abilityMs_->ReleaseAbility(connect, element)); +} + +/** + * @tc.name: OnCallConnectDied_001 + * @tc.desc: Verify function OnCallConnectDied call success + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AbilityManagerServiceTest, OnCallConnectDied_001, TestSize.Level1) +{ + std::shared_ptr callContainer = std::make_shared(); + EXPECT_EQ(callContainer->callRecordMap_.size(), 0); + + AbilityRequest abilityRequest; + abilityRequest.callerUid = 1; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + abilityRequest.connect = new AbilityConnectCallback(); + std::shared_ptr callRecord = CallRecord::CreateCallRecord( + abilityRequest.callerUid, abilityRecord_->shared_from_this(), + abilityRequest.connect, abilityRequest.callerToken); + callRecord->SetCallState(CallState::REQUESTED); + callContainer->AddCallRecord(abilityRequest.connect, callRecord); + EXPECT_EQ(callContainer->callRecordMap_.size(), 1); + + auto mission = std::make_shared(0, abilityRecord_, "launcher"); + auto missionList = std::make_shared(); + missionList->AddMissionToTop(mission); + abilityRecord_->callContainer_ = callContainer; + + std::shared_ptr missionListMgr = std::make_shared(0); + missionListMgr->currentMissionLists_.push_front(missionList); + + abilityMs_->currentMissionListManager_ = missionListMgr; + abilityMs_->OnCallConnectDied(callRecord); + EXPECT_EQ(callContainer->callRecordMap_.size(), 0); +} +} +} \ No newline at end of file diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/ability_manager_stub_test.cpp b/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/ability_manager_stub_test.cpp index b95f55bd057af129ca98f181e7d49b2c55b63f76..37fcbccc43874cd130124bcec662786c9d9fbbcd 100644 --- a/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/ability_manager_stub_test.cpp +++ b/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/ability_manager_stub_test.cpp @@ -449,5 +449,88 @@ HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_017, TestSize.Level1) EXPECT_EQ(res, NO_ERROR); } + +/* + * Feature: AbilityManagerService + * Function: OnRemoteRequest + * SubFunction: NA + * FunctionPoints: AbilityManagerService OnRemoteRequest + * EnvConditions: code is START_CALL_ABILITY + * CaseDescription: Verify that on remote request is normal + */ +HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_018, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + Want want; + WriteInterfaceToken(data); + want.SetFlags(10); + data.WriteParcelable(&want); + int res = stub_->OnRemoteRequest(IAbilityManager::START_CALL_ABILITY, data, reply, option); + + EXPECT_EQ(res, NO_ERROR); +} + +/* + * Feature: AbilityManagerService + * Function: OnRemoteRequest + * SubFunction: NA + * FunctionPoints: AbilityManagerService OnRemoteRequest + * EnvConditions: code is START_CALL_ABILITY + * CaseDescription: Verify that on remote request is ERR_INVALID_VALUE + */ +HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_019, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + WriteInterfaceToken(data); + int res = stub_->OnRemoteRequest(IAbilityManager::START_CALL_ABILITY, data, reply, option); + + EXPECT_EQ(res, ERR_INVALID_VALUE); +} + +/* + * Feature: AbilityManagerService + * Function: OnRemoteRequest + * SubFunction: NA + * FunctionPoints: AbilityManagerService OnRemoteRequest + * EnvConditions: code is START_CALL_ABILITY + * CaseDescription: Verify that on remote request is normal + */ +HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_020, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + WriteInterfaceToken(data); + AppExecFwk::ElementName element; + sptr connect = new AbilityConnectCallback(); + data.WriteParcelable(connect->AsObject()); + data.WriteParcelable(&element); + int res = stub_->OnRemoteRequest(IAbilityManager::RELEASE_CALL_ABILITY, data, reply, option); + + EXPECT_EQ(res, NO_ERROR); +} + +/* + * Feature: AbilityManagerService + * Function: OnRemoteRequest + * SubFunction: NA + * FunctionPoints: AbilityManagerService OnRemoteRequest + * EnvConditions: code is START_CALL_ABILITY + * CaseDescription: Verify that on remote request is ERR_INVALID_VALUE + */ +HWTEST_F(AbilityManagerStubTest, AbilityManagerStub_021, TestSize.Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + WriteInterfaceToken(data); + int res = stub_->OnRemoteRequest(IAbilityManager::RELEASE_CALL_ABILITY, data, reply, option); + + EXPECT_EQ(res, ERR_INVALID_VALUE); +} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/test/unittest/phone/ability_record_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/ability_record_test/BUILD.gn index 0cc1d4c91e0967b588a2da298a7e04bcbb77f5a1..872fd7506c15bac29e1fd27057dfacd284d3a326 100644 --- a/services/abilitymgr/test/unittest/phone/ability_record_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/ability_record_test/BUILD.gn @@ -63,7 +63,57 @@ ohos_unittest("ability_record_test") { ] } +ohos_unittest("ability_record_test_call") { + module_out_path = "ability_runtime/ability_call_test" + + include_dirs = [ + "${services_path}/abilitymgr/test/mock/libs/system_ability_mock", + "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/ability_scheduler_mock", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + ] + + sources = [ + "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp", + "ability_record_test_call.cpp", # add mock file + ] + + configs = [ + "${services_path}/abilitymgr:abilityms_config", + "${services_path}/abilitymgr/test/mock:aafwk_mock_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${innerkits_path}/want:want", + "${services_path}/abilitymgr/test:abilityms_test_source", + "${services_path}/abilitymgr/test/mock/libs/aakit:aakit_mock", + "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_appmgr_mock", + "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_bundlemgr_mock", + "${services_path}/common:perm_verification", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", + "//utils/native/base:utils", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "device_manager_base:devicemanagersdk", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + group("unittest") { testonly = true # deps = [ ":ability_record_test" ] + deps = [ ":ability_record_test_call" ] } diff --git a/services/abilitymgr/test/unittest/phone/ability_record_test/ability_record_test_call.cpp b/services/abilitymgr/test/unittest/phone/ability_record_test/ability_record_test_call.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cc73de74d50756c0fd5f7460cf606aa5e4fef13a --- /dev/null +++ b/services/abilitymgr/test/unittest/phone/ability_record_test/ability_record_test_call.cpp @@ -0,0 +1,430 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#define private public +#define protected public +#include "ability_record.h" +#undef private +#undef protected + +#include "ability_manager_service.h" +#include "ability_scheduler.h" +#include "connection_record.h" +#include "mission_record.h" +#include "mock_ability_connect_callback.h" +#include "ability_scheduler_mock.h" +#include "ability_connect_callback_stub.h" + +using namespace testing::ext; + +namespace OHOS { +namespace AAFwk { +class AbilityRecordTest : public testing::TestWithParam { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + + std::shared_ptr abilityRecord_ {nullptr}; + std::shared_ptr abilityResult_ {nullptr}; + std::shared_ptr abilityRequest_ {nullptr}; + static constexpr unsigned int CHANGE_CONFIG_LOCALE = 0x00000001; +}; + +void AbilityRecordTest::SetUpTestCase(void) +{ + OHOS::DelayedSingleton::GetInstance()->OnStart(); +} +void AbilityRecordTest::TearDownTestCase(void) +{ + OHOS::DelayedSingleton::GetInstance()->OnStop(); +} + +void AbilityRecordTest::SetUp(void) +{ + OHOS::AppExecFwk::AbilityInfo abilityInfo; + OHOS::AppExecFwk::ApplicationInfo applicationInfo; + Want want; + abilityRecord_ = std::make_shared(want, abilityInfo, applicationInfo); + abilityResult_ = std::make_shared(-1, -1, want); + abilityRequest_ = std::make_shared(); + abilityRecord_->Init(); +} + +void AbilityRecordTest::TearDown(void) +{ + abilityRecord_.reset(); + abilityResult_.reset(); + abilityRequest_.reset(); +} + +bool IsTestAbilityExist(const std::string &data) +{ + return std::string::npos != data.find("previous ability app name [NULL]"); +} + +bool IsTestAbilityExist1(const std::string &data) +{ + return std::string::npos != data.find("test_pre_app"); +} + +bool IsTestAbilityExist2(const std::string &data) +{ + return std::string::npos != data.find("test_next_app"); +} + +/* + * Feature: AbilityRecord + * Function: IsCallType + * SubFunction: IsCallType + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: Verify create one abilityRequest could through IsCallType INVALID_TYPE + */ +HWTEST_F(AbilityRecordTest, AaFwk_AbilityMS_IsCallType_001, TestSize.Level1) +{ + EXPECT_EQ(abilityRequest_->IsCallType(AbilityCallType::INVALID_TYPE), true); +} + +/* + * Feature: AbilityRecord + * Function: IsCallType + * SubFunction: IsCallType + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: Verify create one abilityRequest could through IsCallType CALL_REQUEST_TYPE + */ +HWTEST_F(AbilityRecordTest, AaFwk_AbilityMS_IsCallType_002, TestSize.Level1) +{ + abilityRequest_->callType = AbilityCallType::CALL_REQUEST_TYPE; + EXPECT_EQ(abilityRequest_->IsCallType(AbilityCallType::CALL_REQUEST_TYPE), true); +} + +/* + * Feature: AbilityRecord + * Function: Resolve + * SubFunction: Resolve + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: Verify create one abilityRecord could through Resolve + * ResolveResultType::NG_INNER_ERROR + */ +HWTEST_F(AbilityRecordTest, AaFwk_AbilityMS_Resolve_001, TestSize.Level1) +{ + AbilityRequest abilityRequest; + EXPECT_EQ(abilityRecord_->Resolve(abilityRequest), ResolveResultType::NG_INNER_ERROR); +} + +/* + * Feature: AbilityRecord + * Function: Resolve + * SubFunction: Resolve + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: Verify create one abilityRequest could through Resolve + * ResolveResultType::NG_INNER_ERROR + */ +HWTEST_F(AbilityRecordTest, AaFwk_AbilityMS_Resolve_002, TestSize.Level1) +{ + AbilityRequest abilityRequest; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + EXPECT_EQ(abilityRecord_->Resolve(abilityRequest), ResolveResultType::NG_INNER_ERROR); +} + +/* + * Feature: AbilityRecord + * Function: Resolve + * SubFunction: Resolve + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: Verify create one abilityRequest could through Resolve + * ResolveResultType::NG_INNER_ERROR + */ +HWTEST_F(AbilityRecordTest, AaFwk_AbilityMS_Resolve_003, TestSize.Level1) +{ + AbilityRequest abilityRequest; + abilityRequest.connect = new AbilityConnectCallback(); + EXPECT_EQ(abilityRecord_->Resolve(abilityRequest), ResolveResultType::NG_INNER_ERROR); +} + +/* + * Feature: AbilityRecord + * Function: Resolve + * SubFunction: Resolve + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: Verify create one abilityRequest could through Resolve + * ResolveResultType::OK_HAS_REMOTE_OBJ + */ +HWTEST_F(AbilityRecordTest, AaFwk_AbilityMS_Resolve_004, TestSize.Level1) +{ + AbilityRequest abilityRequest; + abilityRequest.callerUid = 1; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + abilityRequest.connect = new AbilityConnectCallback(); + std::shared_ptr callRecord = CallRecord::CreateCallRecord( + abilityRequest.callerUid, abilityRecord_->shared_from_this(), + abilityRequest.connect, abilityRequest.callerToken); + callRecord->SetCallState(CallState::REQUESTING); + abilityRecord_->callContainer_ = std::make_shared(); + abilityRecord_->callContainer_->AddCallRecord(abilityRequest.connect, callRecord); + class AbilitySchedulerMockFunction : public AbilitySchedulerMock + { + public: + virtual sptr CallRequest() override + { + return sptr(this); + } + }; + + OHOS::sptr scheduler = new AbilitySchedulerMockFunction(); + sptr object = scheduler->CallRequest(); + abilityRecord_->callContainer_->CallRequestDone(object); + callRecord->SetCallState(CallState::REQUESTED); + EXPECT_EQ(abilityRecord_->Resolve(abilityRequest), ResolveResultType::OK_HAS_REMOTE_OBJ); +} + +/* + * Feature: AbilityRecord + * Function: Resolve + * SubFunction: Resolve + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: Verify create one abilityRequest could through Resolve + * ResolveResultType::OK_NO_REMOTE_OBJ + */ +HWTEST_F(AbilityRecordTest, AaFwk_AbilityMS_Resolve_005, TestSize.Level1) +{ + AbilityRequest abilityRequest; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + abilityRequest.connect = new AbilityConnectCallback(); + EXPECT_EQ(abilityRecord_->Resolve(abilityRequest), ResolveResultType::OK_NO_REMOTE_OBJ); +} + +/* + * Feature: AbilityRecord + * Function: Release + * SubFunction: Release + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: Verify create one abilityRecord could through Release false + */ +HWTEST_F(AbilityRecordTest, AaFwk_AbilityMS_Release_001, TestSize.Level1) +{ + sptr connect = new AbilityConnectCallback(); + EXPECT_EQ(abilityRecord_->Release(connect), false); +} + +/* + * Feature: AbilityRecord + * Function: Release + * SubFunction: Release + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: Verify create one abilityRecord could through Release false + */ +HWTEST_F(AbilityRecordTest, AaFwk_AbilityMS_Release_002, TestSize.Level1) +{ + sptr connect = new AbilityConnectCallback(); + AbilityRequest abilityRequest; + abilityRequest.callerUid = 1; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + abilityRequest.connect = connect; + std::shared_ptr callRecord = CallRecord::CreateCallRecord( + abilityRequest.callerUid, abilityRecord_->shared_from_this(), + abilityRequest.connect, abilityRequest.callerToken); + abilityRecord_->callContainer_ = std::make_shared(); + abilityRecord_->callContainer_->AddCallRecord(abilityRequest.connect, callRecord); + EXPECT_EQ(abilityRecord_->Release(connect), true); +} + +/* + * Feature: AbilityRecord + * Function: IsStartedByCall + * SubFunction: IsStartedByCall + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: Verify create one abilityRecord could through IsStartedByCall false + */ +HWTEST_F(AbilityRecordTest, AaFwk_AbilityMS_IsStartedByCall_001, TestSize.Level1) +{ + EXPECT_EQ(abilityRecord_->IsStartedByCall(), false); +} + +/* + * Feature: AbilityRecord + * Function: SetStartedByCall + * SubFunction: SetStartedByCall + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: Verify create one abilityRecord could through IsStartedByCall true + */ +HWTEST_F(AbilityRecordTest, AaFwk_AbilityMS_SetStartedByCall_001, TestSize.Level1) +{ + abilityRecord_->SetStartedByCall(true); + EXPECT_EQ(abilityRecord_->IsStartedByCall(), true); +} + +/* + * Feature: AbilityRecord + * Function: CallRequest + * SubFunction: CallRequest + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: Verify create one abilityRecord could through Release success + */ +HWTEST_F(AbilityRecordTest, AaFwk_AbilityMS_CallRequest_001, TestSize.Level1) +{ + class AbilitySchedulerMockFunction : public AbilitySchedulerMock + { + virtual sptr CallRequest() override + { + return sptr(this); + } + }; + + OHOS::sptr scheduler = new AbilitySchedulerMockFunction(); + abilityRecord_->lifecycleDeal_ = std::make_unique(); + EXPECT_EQ(false, abilityRecord_->IsReady()); + abilityRecord_->SetScheduler(scheduler); + + AbilityRequest abilityRequest; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + abilityRequest.connect = new AbilityConnectCallback(); + EXPECT_EQ(abilityRecord_->Resolve(abilityRequest), ResolveResultType::OK_NO_REMOTE_OBJ); + EXPECT_EQ(abilityRecord_->CallRequest(), true); +} + +/* + * Feature: AbilityRecord + * Function: CallRequest + * SubFunction: CallRequest + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: Verify create one abilityRecord could through Release success + */ +HWTEST_F(AbilityRecordTest, AaFwk_AbilityMS_CallRequest_002, TestSize.Level1) +{ + OHOS::sptr scheduler = new AbilitySchedulerMock(); + abilityRecord_->lifecycleDeal_ = std::make_unique(); + EXPECT_EQ(false, abilityRecord_->IsReady()); + abilityRecord_->SetScheduler(scheduler); + + AbilityRequest abilityRequest; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + abilityRequest.connect = new AbilityConnectCallback(); + EXPECT_EQ(abilityRecord_->Resolve(abilityRequest), ResolveResultType::OK_NO_REMOTE_OBJ); + EXPECT_EQ(abilityRecord_->CallRequest(), false); +} + +/* + * Feature: AbilityRecord + * Function: IsStartToBackground + * SubFunction: IsStartToBackground + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: Verify create one abilityRecord could through IsStartToBackground false + */ +HWTEST_F(AbilityRecordTest, AaFwk_AbilityMS_IsStartToBackground_001, TestSize.Level1) +{ + EXPECT_EQ(abilityRecord_->IsStartToBackground(), false); +} + +/* + * Feature: AbilityRecord + * Function: SetStartToBackground + * SubFunction: SetStartToBackground + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: Verify create one abilityRecord could through SetStartToBackground success + */ +HWTEST_F(AbilityRecordTest, AaFwk_AbilityMS_SetStartToBackground_002, TestSize.Level1) +{ + abilityRecord_->SetStartToBackground(true); + EXPECT_EQ(abilityRecord_->IsStartToBackground(), true); + abilityRecord_->SetStartToBackground(false); + EXPECT_EQ(abilityRecord_->IsStartToBackground(), false); +} + +/* + * Feature: AbilityRecord + * Function: SetSpecifiedFlag + * SubFunction: SetSpecifiedFlag + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: Verify create one abilityRecord could through SetSpecifiedFlag success + */ +HWTEST_F(AbilityRecordTest, AaFwk_AbilityMS_SetSpecifiedFlag_001, TestSize.Level1) +{ + const std::string specifiedFlag= "flag"; + abilityRecord_->SetSpecifiedFlag(specifiedFlag); + EXPECT_EQ(specifiedFlag, abilityRecord_->GetSpecifiedFlag()); +} + +/* + * Feature: AbilityRecord + * Function: GetSpecifiedFlag + * SubFunction: GetSpecifiedFlag + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: Verify create one abilityRecord could through GetSpecifiedFlag success + */ +HWTEST_F(AbilityRecordTest, AaFwk_AbilityMS_GetSpecifiedFlag_002, TestSize.Level1) +{ + EXPECT_EQ(std::string(), abilityRecord_->GetSpecifiedFlag()); +} + +/* + * Feature: AbilityRecord + * Function: IsNeedToCallRequest + * SubFunction: IsNeedToCallRequest + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: Verify create one abilityRecord could through SetSpecifiedFlag false + */ +HWTEST_F(AbilityRecordTest, AaFwk_AbilityMS_IsNeedToCallRequest_001, TestSize.Level1) +{ + EXPECT_EQ(false, abilityRecord_->IsNeedToCallRequest()); +} + +/* + * Feature: AbilityRecord + * Function: IsNeedToCallRequest + * SubFunction: IsNeedToCallRequest + * FunctionPoints: NA + * EnvConditions: NA + * CaseDescription: Verify create one abilityRecord could through GetSpecifiedFlag success + */ +HWTEST_F(AbilityRecordTest, AaFwk_AbilityMS_IsNeedToCallRequest_002, TestSize.Level1) +{ + AbilityRequest abilityRequest; + abilityRequest.callerUid = 1; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + abilityRequest.connect = new AbilityConnectCallback(); + std::shared_ptr callRecord = CallRecord::CreateCallRecord( + abilityRequest.callerUid, abilityRecord_->shared_from_this(), + abilityRequest.connect, abilityRequest.callerToken); + callRecord->SetCallState(CallState::INIT); + + abilityRecord_->callContainer_ = std::make_shared(); + abilityRecord_->callContainer_->AddCallRecord(abilityRequest.connect, callRecord); + + EXPECT_EQ(true, abilityRecord_->IsNeedToCallRequest()); +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/test/unittest/phone/ability_scheduler_proxy_test/ability_scheduler_proxy_test.cpp b/services/abilitymgr/test/unittest/phone/ability_scheduler_proxy_test/ability_scheduler_proxy_test.cpp index 574bf41a41752ca787f6ac6dc8b7af0865647cbf..63b4f252406db32a04a1dd9a3cd7fcdebbff9ab0 100644 --- a/services/abilitymgr/test/unittest/phone/ability_scheduler_proxy_test/ability_scheduler_proxy_test.cpp +++ b/services/abilitymgr/test/unittest/phone/ability_scheduler_proxy_test/ability_scheduler_proxy_test.cpp @@ -294,5 +294,37 @@ HWTEST_F(AbilitySchedulerProxyTest, ability_scheduler_proxy_operating_013, TestS EXPECT_EQ(IAbilityScheduler::NOTIFY_CONTINUATION_RESULT, mock_->code_); } + +/** + * @tc.name: ability_scheduler_proxy_operating_014 + * @tc.desc: test CallRequest + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AbilitySchedulerProxyTest, ability_scheduler_proxy_operating_014, TestSize.Level0) +{ + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) + .Times(1) + .WillOnce(Invoke(mock_.GetRefPtr(), &AbilitySchedulerMock::InvokeSendRequest)); + abilitySchedulerProxy_->CallRequest(); + + EXPECT_EQ(IAbilityScheduler::REQUEST_CALL_REMOTE, mock_->code_); +} + +/** + * @tc.name: ability_scheduler_proxy_operating_015 + * @tc.desc: test CallRequest + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AbilitySchedulerProxyTest, ability_scheduler_proxy_operating_015, TestSize.Level0) +{ + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) + .Times(1) + .WillOnce(Invoke(mock_.GetRefPtr(), &AbilitySchedulerMock::InvokeErrorSendRequest)); + abilitySchedulerProxy_->CallRequest(); + + EXPECT_EQ(IAbilityScheduler::REQUEST_CALL_REMOTE, mock_->code_); +} } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/ability_schedule_stub_mock.h b/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/ability_schedule_stub_mock.h index ce061009455fb9542e134f5bd19a36c0883b36d4..2ef828793c70d7b8a2f10379d8eada21ac73329c 100755 --- a/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/ability_schedule_stub_mock.h +++ b/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/ability_schedule_stub_mock.h @@ -137,7 +137,7 @@ public: {} virtual sptr CallRequest() override { - return sptr(nullptr); + return sptr(this); } }; } // namespace AAFwk diff --git a/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/ability_scheduler_stub_test.cpp b/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/ability_scheduler_stub_test.cpp index 2481809453e0bb0c0cbeacfb01734b8773395b9c..1e4cf5613a0430114847813218ddb4a73fbef939 100644 --- a/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/ability_scheduler_stub_test.cpp +++ b/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/ability_scheduler_stub_test.cpp @@ -234,5 +234,23 @@ HWTEST_F(AbilitySchedulerStubTest, AbilitySchedulerStub_009, TestSize.Level0) auto res = stub_->OnRemoteRequest(IAbilityScheduler::NOTIFY_CONTINUATION_RESULT, data, reply, option); EXPECT_EQ(res, NO_ERROR); } + +/** + * @tc.name: AbilitySchedulerStub_0010 + * @tc.desc: test NotifyContinuationResult + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AbilitySchedulerStubTest, AbilitySchedulerStub_0010, TestSize.Level0) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + WriteInterfaceToken(data); + int32_t result = 0; + data.WriteInt32(result); + auto res = stub_->OnRemoteRequest(IAbilityScheduler::REQUEST_CALL_REMOTE, data, reply, option); + EXPECT_EQ(res, NO_ERROR); +} } // namespace AAFwk } // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/test/unittest/phone/call_container_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/call_container_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0aaecc1c3534970d163563076a1e9b64873c35c9 --- /dev/null +++ b/services/abilitymgr/test/unittest/phone/call_container_test/BUILD.gn @@ -0,0 +1,65 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/ability_call_test" + +ohos_unittest("call_container_test") { + module_out_path = module_output_path + + include_dirs = [ + "${services_path}/abilitymgr/test/mock/libs/system_ability_mock", + "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/ability_scheduler_mock", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + ] + + sources = [ + "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp", + "call_container_test.cpp", + ] + + configs = [ + "${services_path}/abilitymgr:abilityms_config", + "${services_path}/abilitymgr/test/mock:aafwk_mock_config", + ] + + deps = [ + "${innerkits_path}/want:want", + "${services_path}/abilitymgr/test:abilityms_test_source", + "${services_path}/abilitymgr/test/mock/libs/aakit:aakit_mock", + "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_appmgr_mock", + "${services_path}/common:perm_verification", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":call_container_test" ] +} diff --git a/services/abilitymgr/test/unittest/phone/call_container_test/call_container_test.cpp b/services/abilitymgr/test/unittest/phone/call_container_test/call_container_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1f17623ce7b45ab8eac971b981b8b200cfed1d8a --- /dev/null +++ b/services/abilitymgr/test/unittest/phone/call_container_test/call_container_test.cpp @@ -0,0 +1,459 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#define private public +#define protected public +#include "call_container.h" +#include "ability_record.h" +#include "ability_manager_service.h" +#undef private +#undef protected +#include "ability_event_handler.h" +#include "ability_scheduler_mock.h" +#include "mock_ability_connect_callback.h" + +using namespace testing::ext; + + +static void WaitUntilTaskFinished() +{ + const uint32_t maxRetryCount = 1000; + const uint32_t sleepTime = 1000; + uint32_t count = 0; + auto handler = OHOS::DelayedSingleton::GetInstance()->GetEventHandler(); + std::atomic taskCalled(false); + auto f = [&taskCalled]() { taskCalled.store(true); }; + if (handler->PostTask(f)) { + while (!taskCalled.load()) { + ++count; + if (count >= maxRetryCount) { + std::cout << "max count\n"; + break; + } + usleep(sleepTime); + } + } +} + +namespace OHOS { +namespace AAFwk { +class CallContainerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + void OnStartAms(); + std::shared_ptr get() const; + std::shared_ptr abilityRecord_ {nullptr}; +private: + std::shared_ptr callContainer_ {nullptr}; + std::shared_ptr abilityMgrServ_ {nullptr}; + int MOCK_MAIN_USER_ID = 100; +}; + +void CallContainerTest::SetUpTestCase(void) +{ +} +void CallContainerTest::TearDownTestCase(void) +{ + DelayedSingleton::DestroyInstance(); +} +void CallContainerTest::TearDown() +{ + DelayedSingleton::DestroyInstance(); +} + +void CallContainerTest::SetUp() +{ + callContainer_ = std::make_shared(); + OHOS::AppExecFwk::AbilityInfo abilityInfo; + OHOS::AppExecFwk::ApplicationInfo applicationInfo; + Want want; + abilityRecord_ = std::make_shared(want, abilityInfo, applicationInfo); + abilityMgrServ_ = DelayedSingleton::GetInstance(); + OnStartAms(); +} + +void CallContainerTest::OnStartAms() +{ + if (abilityMgrServ_) { + if (abilityMgrServ_->state_ == ServiceRunningState::STATE_RUNNING) { + return; + } + + abilityMgrServ_->state_ = ServiceRunningState::STATE_RUNNING; + abilityMgrServ_->useNewMission_ = true; + + abilityMgrServ_->eventLoop_ = AppExecFwk::EventRunner::Create(AbilityConfig::NAME_ABILITY_MGR_SERVICE); + EXPECT_TRUE(abilityMgrServ_->eventLoop_); + + abilityMgrServ_->handler_ = std::make_shared(abilityMgrServ_->eventLoop_, abilityMgrServ_); + EXPECT_TRUE(abilityMgrServ_->handler_); + + // init user controller. + abilityMgrServ_->userController_ = std::make_shared(); + EXPECT_TRUE(abilityMgrServ_->userController_); + abilityMgrServ_->userController_->Init(); + int userId = MOCK_MAIN_USER_ID; + abilityMgrServ_->userController_->SetCurrentUserId(userId); + abilityMgrServ_->InitConnectManager(userId, true); + abilityMgrServ_->InitDataAbilityManager(userId, true); + abilityMgrServ_->InitPendWantManager(userId, true); + abilityMgrServ_->systemDataAbilityManager_ = std::make_shared(); + EXPECT_TRUE(abilityMgrServ_->systemDataAbilityManager_); + + abilityMgrServ_->amsConfigResolver_ = std::make_shared(); + EXPECT_TRUE(abilityMgrServ_->amsConfigResolver_); + abilityMgrServ_->amsConfigResolver_->Parse(); + abilityMgrServ_->useNewMission_ = abilityMgrServ_->amsConfigResolver_->IsUseNewMission(); + + abilityMgrServ_->SetStackManager(userId, true); + abilityMgrServ_->InitMissionListManager(userId, true); + abilityMgrServ_->connectManager_->SetEventHandler(abilityMgrServ_->handler_); + abilityMgrServ_->eventLoop_->Run(); + auto topAbility = abilityMgrServ_->GetListManagerByUserId(MOCK_MAIN_USER_ID)->GetCurrentTopAbilityLocked(); + if (topAbility) { + topAbility->SetAbilityState(AAFwk::AbilityState::FOREGROUND_NEW); + } + WaitUntilTaskFinished(); + return; + } + + GTEST_LOG_(INFO) << "OnStart fail"; +} + + +std::shared_ptr CallContainerTest::get() const +{ + return callContainer_; +} + +/* + * Feature: CallContainer + * Function: AddCallRecord + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions:NA + * CaseDescription: Verify funtion call called + */ +HWTEST_F(CallContainerTest, Call_Container_Add_Call_Record_001, TestSize.Level1) +{ + std::shared_ptr callContainer = get(); + AbilityRequest abilityRequest; + abilityRequest.callerUid = 1; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + abilityRequest.connect = new AbilityConnectCallback(); + std::shared_ptr callRecord = CallRecord::CreateCallRecord( + abilityRequest.callerUid, abilityRecord_->shared_from_this(), + abilityRequest.connect, abilityRequest.callerToken); + callContainer->AddCallRecord(abilityRequest.connect, callRecord); + + std::shared_ptr getCallRecord = callContainer->GetCallRecord(abilityRequest.connect); + EXPECT_EQ(callRecord, getCallRecord); +} + +/* + * Feature: CallContainer + * Function: GetCallRecord + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions:NA + * CaseDescription: Verify funtion call called + */ +HWTEST_F(CallContainerTest, Call_Container_Get_Call_Record_001, TestSize.Level1) +{ + sptr connect = new AbilityConnectCallback(); + std::shared_ptr callContainer = get(); + std::shared_ptr getCallRecord = callContainer->GetCallRecord(connect); + EXPECT_EQ(nullptr, getCallRecord); +} + +/* + * Feature: CallContainer + * Function: RemoveCallRecord + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions:NA + * CaseDescription: Verify funtion call called + */ +HWTEST_F(CallContainerTest, Call_Container_Remove_Call_Record_001, TestSize.Level1) +{ + sptr connect = new AbilityConnectCallback(); + std::shared_ptr callContainer = get(); + bool result = callContainer->RemoveCallRecord(connect); + EXPECT_EQ(result, false); +} + +/* + * Feature: CallContainer + * Function: RemoveCallRecord + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions:NA + * CaseDescription: Verify funtion call called + */ +HWTEST_F(CallContainerTest, Call_Container_Remove_Call_Record_002, TestSize.Level1) +{ + std::shared_ptr callContainer = get(); + AbilityRequest abilityRequest; + abilityRequest.callerUid = 1; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + abilityRequest.connect = new AbilityConnectCallback(); + std::shared_ptr callRecord = CallRecord::CreateCallRecord( + abilityRequest.callerUid, abilityRecord_->shared_from_this(), + abilityRequest.connect, abilityRequest.callerToken); + callContainer->AddCallRecord(abilityRequest.connect, callRecord); + + bool result = callContainer->RemoveCallRecord(abilityRequest.connect); + EXPECT_EQ(result, true); +} + +/* + * Feature: CallContainer + * Function: CallRequestDone + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions:NA + * CaseDescription: Verify funtion call called + */ +HWTEST_F(CallContainerTest, Call_Container_Call_Request_Done_001, TestSize.Level1) +{ + std::shared_ptr callContainer = get(); + OHOS::sptr scheduler = new AbilitySchedulerMock(); + abilityRecord_->SetScheduler(scheduler); + sptr object = scheduler->CallRequest(); + bool result = callContainer->CallRequestDone(object); + EXPECT_EQ(result, false); +} + +/* + * Feature: CallContainer + * Function: CallRequestDone + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions:NA + * CaseDescription: Verify funtion call called + */ +HWTEST_F(CallContainerTest, Call_Container_Call_Request_Done_002, TestSize.Level1) +{ + class AbilitySchedulerMockFunction : public AbilitySchedulerMock { + virtual sptr CallRequest() { return this; } + }; + + std::shared_ptr callContainer = get(); + OHOS::sptr scheduler = new AbilitySchedulerMockFunction(); + sptr object = scheduler->CallRequest(); + bool result = callContainer->CallRequestDone(object); + EXPECT_EQ(result, true); +} + +/* + * Feature: CallContainer + * Function: Dump + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions:NA + * CaseDescription: Verify funtion call called + */ +HWTEST_F(CallContainerTest, Call_Container_Dump_001, TestSize.Level1) +{ + std::shared_ptr callContainer = get(); + std::vector dumpInfo; + callContainer->Dump(dumpInfo); + EXPECT_EQ(dumpInfo.size(), 0); +} + +/* + * Feature: CallContainer + * Function: Dump + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions:NA + * CaseDescription: Verify funtion call called + */ +HWTEST_F(CallContainerTest, Call_Container_Dump_002, TestSize.Level1) +{ + std::shared_ptr callContainer = get(); + AbilityRequest abilityRequest; + abilityRequest.callerUid = 1; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + abilityRequest.connect = new AbilityConnectCallback(); + std::shared_ptr callRecord = CallRecord::CreateCallRecord( + abilityRequest.callerUid, abilityRecord_->shared_from_this(), + abilityRequest.connect, abilityRequest.callerToken); + callContainer->AddCallRecord(abilityRequest.connect, callRecord); + + std::vector dumpInfo; + callContainer->Dump(dumpInfo); + EXPECT_NE(dumpInfo.size(), 0); +} + +/* + * Feature: CallContainer + * Function: IsNeedToCallRequest + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions:NA + * CaseDescription: Verify funtion call called + */ +HWTEST_F(CallContainerTest, Call_Container_Is_Need_To_Call_Request_001, TestSize.Level1) +{ + std::shared_ptr callContainer = get(); + EXPECT_EQ(callContainer->IsNeedToCallRequest(), false); +} + +/* + * Feature: CallContainer + * Function: IsNeedToCallRequest + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions:NA + * CaseDescription: Verify funtion call called + */ +HWTEST_F(CallContainerTest, Call_Container_Is_Need_To_Call_Request_002, TestSize.Level1) +{ + std::shared_ptr callContainer = get(); + AbilityRequest abilityRequest; + abilityRequest.callerUid = 1; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + abilityRequest.connect = new AbilityConnectCallback(); + std::shared_ptr callRecord = CallRecord::CreateCallRecord( + abilityRequest.callerUid, abilityRecord_->shared_from_this(), + abilityRequest.connect, abilityRequest.callerToken); + callRecord->SetCallState(CallState::INIT); + callContainer->AddCallRecord(abilityRequest.connect, callRecord); + EXPECT_EQ(callContainer->IsNeedToCallRequest(), true); +} + +/* + * Feature: CallContainer + * Function: IsNeedToCallRequest + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions:NA + * CaseDescription: Verify funtion call called + */ +HWTEST_F(CallContainerTest, Call_Container_Is_Need_To_Call_Request_003, TestSize.Level1) +{ + std::shared_ptr callContainer = get(); + AbilityRequest abilityRequest; + abilityRequest.callerUid = 1; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + abilityRequest.connect = new AbilityConnectCallback(); + std::shared_ptr callRecord = CallRecord::CreateCallRecord( + abilityRequest.callerUid, abilityRecord_->shared_from_this(), + abilityRequest.connect, abilityRequest.callerToken); + callRecord->SetCallState(CallState::REQUESTING); + callContainer->AddCallRecord(abilityRequest.connect, callRecord); + EXPECT_EQ(callContainer->IsNeedToCallRequest(), true); +} + +/* + * Feature: CallContainer + * Function: IsNeedToCallRequest + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions:NA + * CaseDescription: Verify funtion call called + */ +HWTEST_F(CallContainerTest, Call_Container_Is_Need_To_Call_Request_004, TestSize.Level1) +{ + std::shared_ptr callContainer = get(); + AbilityRequest abilityRequest; + abilityRequest.callerUid = 1; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + abilityRequest.connect = new AbilityConnectCallback(); + std::shared_ptr callRecord = CallRecord::CreateCallRecord( + abilityRequest.callerUid, abilityRecord_->shared_from_this(), + abilityRequest.connect, abilityRequest.callerToken); + callRecord->SetCallState(CallState::REQUESTED); + callContainer->AddCallRecord(abilityRequest.connect, callRecord); + EXPECT_EQ(callContainer->IsNeedToCallRequest(), false); +} + +/* + * Feature: CallContainer + * Function: AddConnectDeathRecipient + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions:NA + * CaseDescription: Verify funtion call called + */ +HWTEST_F(CallContainerTest, Call_Container_Add_Connect_Death_Recipient_001, TestSize.Level1) +{ + std::shared_ptr callContainer = get(); + sptr connect = new AbilityConnectCallback(); + callContainer->AddConnectDeathRecipient(connect); + EXPECT_EQ(callContainer->deathRecipientMap_.size(), 1); +} + +/* + * Feature: CallContainer + * Function: RemoveConnectDeathRecipient + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions:NA + * CaseDescription: Verify funtion call called + */ +HWTEST_F(CallContainerTest, Call_Container_Remove_Connect_Death_Recipient_001, TestSize.Level1) +{ + std::shared_ptr callContainer = get(); + sptr connect = new AbilityConnectCallback(); + callContainer->AddConnectDeathRecipient(connect); + callContainer->RemoveConnectDeathRecipient(connect); + EXPECT_EQ(callContainer->deathRecipientMap_.size(), 0); +} + +/* + * Feature: CallContainer + * Function: OnConnectionDied + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions:NA + * CaseDescription: Verify funtion call called + */ +HWTEST_F(CallContainerTest, Call_Container_On_Connect_Died_001, TestSize.Level1) +{ + std::shared_ptr callContainer = get(); + EXPECT_EQ(callContainer->callRecordMap_.size(), 0); + + AbilityRequest abilityRequest; + abilityRequest.callerUid = 1; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + abilityRequest.connect = new AbilityConnectCallback(); + std::shared_ptr callRecord = CallRecord::CreateCallRecord( + abilityRequest.callerUid, abilityRecord_->shared_from_this(), + abilityRequest.connect, abilityRequest.callerToken); + callRecord->SetCallState(CallState::REQUESTED); + callContainer->AddCallRecord(abilityRequest.connect, callRecord); + EXPECT_EQ(callContainer->callRecordMap_.size(), 1); + + auto mission = std::make_shared(0, abilityRecord_, "launcher"); + auto missionList = std::make_shared(); + missionList->AddMissionToTop(mission); + abilityRecord_->callContainer_ = callContainer; + + std::shared_ptr missionListMgr = std::make_shared(0); + missionListMgr->currentMissionLists_.push_front(missionList); + DelayedSingleton::GetInstance()->currentMissionListManager_ = missionListMgr; + callContainer->OnConnectionDied(abilityRequest.connect->AsObject()); + WaitUntilTaskFinished(); + + EXPECT_EQ(callContainer->callRecordMap_.size(), 0); +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/test/unittest/phone/call_record_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/call_record_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0b38683cc116baab467122b3882448c4853abe78 --- /dev/null +++ b/services/abilitymgr/test/unittest/phone/call_record_test/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/ability_call_test" + +ohos_unittest("call_record_test") { + module_out_path = module_output_path + + include_dirs = [ + "${services_path}/abilitymgr/test/mock/libs/system_ability_mock", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + ] + + sources = [ + "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp", + "call_record_test.cpp", + ] + + configs = [ "${services_path}/abilitymgr:abilityms_config" ] + + deps = [ + "${innerkits_path}/want:want", + "${services_path}/abilitymgr/test:abilityms_test_source", + "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_appmgr_mock", + "${services_path}/common:perm_verification", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":call_record_test" ] +} diff --git a/services/abilitymgr/test/unittest/phone/call_record_test/call_record_test.cpp b/services/abilitymgr/test/unittest/phone/call_record_test/call_record_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c855068afac404d5876d5e10570abb71d62c8348 --- /dev/null +++ b/services/abilitymgr/test/unittest/phone/call_record_test/call_record_test.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "call_record.h" + +using namespace testing::ext; +using OHOS::sptr; + +namespace OHOS { +namespace AAFwk { +class CallRecordTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void CallRecordTest::SetUpTestCase(void) +{} +void CallRecordTest::TearDownTestCase(void) +{} +void CallRecordTest::TearDown() +{} + +void CallRecordTest::SetUp() +{} + +/* + * Feature: WindowInfo + * Function: OnRemoteDied + * SubFunction: NA + * FunctionPoints: NA + * EnvConditions:NA + * CaseDescription: Verify funtion call called + */ +HWTEST_F(CallRecordTest, AAFWK_Call_Record, TestSize.Level1) +{ + static bool value = false; + + auto function = [] (const wptr &) { value = true;}; + AbilityCallRecipient abilityCallRecipient(function); + + wptr object = nullptr; + abilityCallRecipient.OnRemoteDied(object); + EXPECT_EQ(value, true); +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/test/unittest/phone/mission_list_manager_ut_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/mission_list_manager_ut_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..fda9a0da7cdf294c1a550587b07cfcd51cdd3bf5 --- /dev/null +++ b/services/abilitymgr/test/unittest/phone/mission_list_manager_ut_test/BUILD.gn @@ -0,0 +1,73 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/abilitymgr" + +ohos_unittest("mission_list_manager_ut_test") { + module_out_path = module_output_path + + include_dirs = [ + "${services_path}/abilitymgr/test/mock/libs/system_ability_mock", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + ] + + sources = [ + "./mission_list_manager_ut_test.cpp", # add mock file + ] + + configs = [ + "${services_path}/abilitymgr:abilityms_config", + "${services_path}/abilitymgr/test/mock:aafwk_mock_config", + ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${innerkits_path}/want:want", + "${services_path}/abilitymgr/test:abilityms_test_source", + "${services_path}/abilitymgr/test/mock/libs/aakit:aakit_mock", + "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_appmgr_mock", + "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_bundlemgr_mock", + "${services_path}/common:perm_verification", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", + "//utils/native/base:utils", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "device_manager_base:devicemanagersdk", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "native_appdatamgr:native_appdatafwk", + "native_appdatamgr:native_dataability", + "native_appdatamgr:native_rdb", + ] +} + +group("unittest") { + testonly = true + + deps = [ ":mission_list_manager_ut_test" ] +} diff --git a/services/abilitymgr/test/unittest/phone/mission_list_manager_ut_test/mission_list_manager_ut_test.cpp b/services/abilitymgr/test/unittest/phone/mission_list_manager_ut_test/mission_list_manager_ut_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..017f5172a6b729da86647d097509d4dd60840d7e --- /dev/null +++ b/services/abilitymgr/test/unittest/phone/mission_list_manager_ut_test/mission_list_manager_ut_test.cpp @@ -0,0 +1,580 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include + +#include +#include + +#include "ability_connect_callback_interface.h" +#include "ability_loader.h" +#include "ability_thread.h" +#define private public +#define protected public +#include "ability_record.h" +#include "call_record.h" +#include "mission_list.h" +#include "mission.h" +#include "mission_info_mgr.h" +#include "mission_list_manager.h" + +namespace OHOS { +namespace AAFwk { +using namespace testing::ext; +using namespace OHOS::AbilityRuntime; + +namespace { +} + +class MissionListManagerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +public: + std::unique_ptr missionListMgr_ = nullptr; +}; + +void MissionListManagerTest::SetUpTestCase(void) +{} + +void MissionListManagerTest::TearDownTestCase(void) +{} + +void MissionListManagerTest::SetUp(void) +{} + +void MissionListManagerTest::TearDown(void) +{} + +class MissionListManagerTestStub : public IRemoteStub { +public: + MissionListManagerTestStub() {}; + virtual ~MissionListManagerTestStub() {}; + + 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) {}; +}; + +class MissionListManagerTestAbilityThreadStub : public AppExecFwk::AbilityThread { +public: + MissionListManagerTestAbilityThreadStub() {}; + ~MissionListManagerTestAbilityThreadStub() {}; + + sptr CallRequest() + { + sptr remote = new (std::nothrow) MissionListManagerTestStub(); + return remote->AsObject(); + } +}; + +/** + * @tc.number: MissionListManager_001 + * @tc.name: OnCallConnectDied + * @tc.desc: MissionListManager to process OnCallConnectDied success. + */ +HWTEST_F(MissionListManagerTest, MissionListManager_001, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "MissionListManager_001 begin"; + Want want; + AppExecFwk::AbilityInfo abilityInfo; + AppExecFwk::ApplicationInfo applicationInfo; + + int32_t callerUid; + sptr connCallback = new (std::nothrow) MissionListManagerTestStub(); + sptr callToken = nullptr; + AppExecFwk::ElementName element; + + std::shared_ptr missionListMgr = std::make_shared(0); + std::shared_ptr abilityRecord = + std::make_shared(want, abilityInfo, applicationInfo); + std::shared_ptr callRecord = + std::make_shared(callerUid, abilityRecord, connCallback, callToken); + std::shared_ptr missionList = std::make_shared(); + std::shared_ptr mission = std::make_shared(0, abilityRecord, ""); + std::shared_ptr callContainer = std::make_shared(); + + callContainer->AddCallRecord(connCallback, callRecord); + abilityRecord->callContainer_ = callContainer; + missionList->AddMissionToTop(mission); + missionListMgr->currentMissionLists_.push_front(missionList); + + auto testValue = static_cast(callContainer->callRecordMap_.size()); + EXPECT_EQ(1, testValue); + missionListMgr->OnCallConnectDied(callRecord); + + testValue = static_cast(callContainer->callRecordMap_.size()); + EXPECT_EQ(0, testValue); + GTEST_LOG_(INFO) << "MissionListManager_001 end"; +} + +/** + * @tc.number: MissionListManager_002 + * @tc.name: OnCallConnectDied + * @tc.desc: MissionListManager to process OnCallConnectDied success. + */ +HWTEST_F(MissionListManagerTest, MissionListManager_002, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "MissionListManager_002 begin"; + Want want; + AppExecFwk::AbilityInfo abilityInfo; + AppExecFwk::ApplicationInfo applicationInfo; + + int32_t callerUid; + sptr connCallback = new (std::nothrow) MissionListManagerTestStub(); + sptr callToken = nullptr; + AppExecFwk::ElementName element; + + std::shared_ptr missionListMgr = std::make_shared(0); + std::shared_ptr abilityRecord = + std::make_shared(want, abilityInfo, applicationInfo); + std::shared_ptr callRecord = + std::make_shared(callerUid, abilityRecord, connCallback, callToken); + std::shared_ptr missionList = std::make_shared(); + std::shared_ptr mission = std::make_shared(0, abilityRecord, ""); + std::shared_ptr callContainer = std::make_shared(); + + callContainer->AddCallRecord(connCallback, callRecord); + abilityRecord->callContainer_ = callContainer; + missionList->AddMissionToTop(mission); + missionListMgr->currentMissionLists_.push_front(missionList); + + auto testValue = static_cast(callContainer->callRecordMap_.size()); + EXPECT_EQ(1, testValue); + missionListMgr->OnCallConnectDied(nullptr); + + testValue = static_cast(callContainer->callRecordMap_.size()); + EXPECT_EQ(1, testValue); + GTEST_LOG_(INFO) << "MissionListManager_002 end"; +} + +/** + * @tc.number: MissionListManager_003 + * @tc.name: OnCallConnectDied + * @tc.desc: MissionListManager to process OnCallConnectDied success. + */ +HWTEST_F(MissionListManagerTest, MissionListManager_003, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "MissionListManager_003 begin"; + Want want; + AppExecFwk::AbilityInfo abilityInfo; + AppExecFwk::ApplicationInfo applicationInfo; + + sptr connCallback = new (std::nothrow) MissionListManagerTestStub(); + sptr connCallback1 = new (std::nothrow) MissionListManagerTestStub(); + sptr callToken = nullptr; + AppExecFwk::ElementName element; + + std::shared_ptr missionListMgr = std::make_shared(0); + std::shared_ptr abilityRecord = + std::make_shared(want, abilityInfo, applicationInfo); + std::shared_ptr callRecord = + std::make_shared(1, abilityRecord, connCallback, callToken); + std::shared_ptr callRecord1 = + std::make_shared(2, abilityRecord, connCallback1, callToken); + std::shared_ptr missionList = std::make_shared(); + std::shared_ptr mission = std::make_shared(0, abilityRecord, ""); + std::shared_ptr callContainer = std::make_shared(); + + callContainer->AddCallRecord(connCallback1, callRecord1); + abilityRecord->callContainer_ = callContainer; + missionList->AddMissionToTop(mission); + missionListMgr->currentMissionLists_.push_front(missionList); + + auto testValue = static_cast(callContainer->callRecordMap_.size()); + EXPECT_EQ(1, testValue); + missionListMgr->OnCallConnectDied(callRecord); + + testValue = static_cast(callContainer->callRecordMap_.size()); + EXPECT_EQ(1, testValue); + GTEST_LOG_(INFO) << "MissionListManager_003 end"; +} + +/** + * @tc.number: MissionListManager_004 + * @tc.name: CallAbilityLocked + * @tc.desc: MissionListManager to process CallAbilityLocked success. + */ +HWTEST_F(MissionListManagerTest, MissionListManager_004, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "MissionListManager_004 begin"; + + AbilityRequest abilityRequest; + std::shared_ptr missionListMgr = std::make_shared(0); + + int testRet = missionListMgr->CallAbilityLocked(abilityRequest); + + EXPECT_EQ(ERR_INVALID_VALUE, testRet); + GTEST_LOG_(INFO) << "MissionListManager_004 end"; +} + +/** + * @tc.number: MissionListManager_005 + * @tc.name: CallAbilityLocked + * @tc.desc: MissionListManager to process CallAbilityLocked success. + */ +HWTEST_F(MissionListManagerTest, MissionListManager_005, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "MissionListManager_005 begin"; + + AbilityRequest abilityRequest; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + abilityRequest.abilityInfo.bundleName = "test_bundle"; + abilityRequest.abilityInfo.name = "test_name"; + abilityRequest.abilityInfo.launchMode = AppExecFwk::LaunchMode::SINGLETON; + + Want want; + AppExecFwk::AbilityInfo abilityInfo = abilityRequest.abilityInfo; + AppExecFwk::ApplicationInfo applicationInfo; + int32_t id; + std::string missionName = "#" + abilityRequest.abilityInfo.bundleName + ":" + abilityRequest.abilityInfo.name; + + std::shared_ptr missionListMgr = std::make_shared(0); + std::shared_ptr abilityRecord = + std::make_shared(want, abilityInfo, applicationInfo); + std::shared_ptr missionList = std::make_shared(); + std::shared_ptr mission = std::make_shared(id, abilityRecord, missionName); + std::shared_ptr callContainer = std::make_shared(); + sptr connCallback = new (std::nothrow) MissionListManagerTestStub(); + std::shared_ptr callRecord = std::make_shared(0, abilityRecord, connCallback, nullptr); + + callRecord->connCallback_ = connCallback; + callRecord->callRemoteObject_ = connCallback->AsObject(); + callRecord->SetCallState(CallState::INIT); + callContainer->AddCallRecord(connCallback, callRecord); + abilityRecord->callContainer_ = callContainer; + missionList->AddMissionToTop(mission); + missionListMgr->currentMissionLists_.push_front(missionList); + + int testRet = missionListMgr->CallAbilityLocked(abilityRequest); + + EXPECT_EQ(RESOLVE_CALL_ABILITY_INNER_ERR, testRet); + GTEST_LOG_(INFO) << "MissionListManager_005 end"; +} + +/** + * @tc.number: MissionListManager_006 + * @tc.name: CallAbilityLocked + * @tc.desc: MissionListManager to process CallAbilityLocked success. + */ +HWTEST_F(MissionListManagerTest, MissionListManager_006, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "MissionListManager_006 begin"; + + sptr connCallback = new (std::nothrow) MissionListManagerTestStub(); + AbilityRequest abilityRequest; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + abilityRequest.abilityInfo.bundleName = "test_bundle"; + abilityRequest.abilityInfo.name = "test_name"; + abilityRequest.abilityInfo.launchMode = AppExecFwk::LaunchMode::SINGLETON; + abilityRequest.connect = connCallback; + Want want; + AppExecFwk::AbilityInfo abilityInfo = abilityRequest.abilityInfo; + AppExecFwk::ApplicationInfo applicationInfo; + int32_t id; + std::string missionName = "#" + abilityRequest.abilityInfo.bundleName + ":" + abilityRequest.abilityInfo.name; + + std::shared_ptr missionListMgr = std::make_shared(0); + std::shared_ptr abilityRecord = + std::make_shared(want, abilityInfo, applicationInfo); + std::shared_ptr missionList = std::make_shared(); + std::shared_ptr mission = std::make_shared(id, abilityRecord, missionName); + std::shared_ptr callContainer = std::make_shared(); + std::shared_ptr callRecord = std::make_shared(0, abilityRecord, connCallback, nullptr); + callRecord->connCallback_ = connCallback; + callRecord->callRemoteObject_ = connCallback->AsObject(); + callRecord->SetCallState(CallState::REQUESTED); + callContainer->AddCallRecord(connCallback, callRecord); + abilityRecord->callContainer_ = callContainer; + missionList->AddMissionToTop(mission); + missionListMgr->currentMissionLists_.push_front(missionList); + + int testRet = missionListMgr->CallAbilityLocked(abilityRequest); + + EXPECT_EQ(ERR_OK, testRet); + GTEST_LOG_(INFO) << "MissionListManager_006 end"; +} + +/** + * @tc.number: MissionListManager_007 + * @tc.name: ResolveAbility + * @tc.desc: MissionListManager to process ResolveAbility success. + */ +HWTEST_F(MissionListManagerTest, MissionListManager_007, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "MissionListManager_007 begin"; + + AbilityRequest abilityRequest; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + Want want; + AppExecFwk::AbilityInfo abilityInfo; + AppExecFwk::ApplicationInfo applicationInfo; + + std::shared_ptr missionListMgr = std::make_shared(0); + std::shared_ptr abilityRecord = + std::make_shared(want, abilityInfo, applicationInfo); + + int testRet = missionListMgr->ResolveAbility(abilityRecord, abilityRequest); + + EXPECT_EQ(ResolveResultType::NG_INNER_ERROR, testRet); + GTEST_LOG_(INFO) << "MissionListManager_007 end"; +} + + +/** + * @tc.number: MissionListManager_008 + * @tc.name: GetAbilityRecordByName + * @tc.desc: MissionListManager to process GetAbilityRecordByName success. + */ +HWTEST_F(MissionListManagerTest, MissionListManager_008, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "MissionListManager_008 begin"; + + AbilityRequest abilityRequest; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + AppExecFwk::ElementName element; + + std::shared_ptr missionListMgr = std::make_shared(0); + std::shared_ptr missionList = std::make_shared(); + + missionListMgr->currentMissionLists_.push_front(missionList); + missionListMgr->launcherList_ = missionList; + missionListMgr->defaultSingleList_ = missionList; + + auto testRet = missionListMgr->GetAbilityRecordByName(element); + + EXPECT_TRUE(nullptr == testRet); + GTEST_LOG_(INFO) << "MissionListManager_008 end"; +} + +/** + * @tc.number: MissionListManager_009 + * @tc.name: GetAbilityRecordByName + * @tc.desc: MissionListManager to process GetAbilityRecordByName success. + */ +HWTEST_F(MissionListManagerTest, MissionListManager_009, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "MissionListManager_009 begin"; + + AbilityRequest abilityRequest; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + Want want; + AppExecFwk::AbilityInfo abilityInfo; + AppExecFwk::ApplicationInfo applicationInfo; + AppExecFwk::ElementName element; + + std::shared_ptr missionListMgr = std::make_shared(0); + std::shared_ptr abilityRecord = + std::make_shared(want, abilityInfo, applicationInfo); + std::shared_ptr missionList = std::make_shared(); + std::shared_ptr mission = std::make_shared(0, abilityRecord, ""); + + missionList->AddMissionToTop(mission); + missionListMgr->currentMissionLists_.push_front(missionList); + + auto testRet = missionListMgr->GetAbilityRecordByName(element); + + EXPECT_TRUE(nullptr != testRet); + GTEST_LOG_(INFO) << "MissionListManager_009 end"; +} + +/** + * @tc.number: MissionListManager_010 + * @tc.name: ResolveAbility + * @tc.desc: MissionListManager to process ResolveAbility success. + */ +HWTEST_F(MissionListManagerTest, MissionListManager_010, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "MissionListManager_010 begin"; + + sptr connCallback = new (std::nothrow) MissionListManagerTestStub(); + AbilityRequest abilityRequest; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + abilityRequest.connect = connCallback; + Want want; + AppExecFwk::AbilityInfo abilityInfo; + AppExecFwk::ApplicationInfo applicationInfo; + + std::shared_ptr missionListMgr = std::make_shared(0); + std::shared_ptr abilityRecord = + std::make_shared(want, abilityInfo, applicationInfo); + std::shared_ptr callRecord = std::make_shared(0, abilityRecord, connCallback, nullptr); + std::shared_ptr callContainer = std::make_shared(); + + callRecord->connCallback_ = connCallback; + callRecord->callRemoteObject_ = connCallback->AsObject(); + callRecord->SetCallState(CallState::REQUESTED); + callContainer->AddCallRecord(connCallback, callRecord); + abilityRecord->callContainer_ = callContainer; + + int testRet = missionListMgr->ResolveAbility(abilityRecord, abilityRequest); + + EXPECT_EQ(ResolveResultType::OK_HAS_REMOTE_OBJ, testRet); + GTEST_LOG_(INFO) << "MissionListManager_010 end"; +} + +/** + * @tc.number: MissionListManager_011 + * @tc.name: ResolveAbility + * @tc.desc: MissionListManager to process ResolveAbility success. + */ +HWTEST_F(MissionListManagerTest, MissionListManager_011, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "MissionListManager_011 begin"; + + sptr connCallback = new (std::nothrow) MissionListManagerTestStub(); + AbilityRequest abilityRequest; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + abilityRequest.connect = connCallback; + Want want; + AppExecFwk::AbilityInfo abilityInfo; + AppExecFwk::ApplicationInfo applicationInfo; + + std::shared_ptr missionListMgr = std::make_shared(0); + std::shared_ptr abilityRecord = + std::make_shared(want, abilityInfo, applicationInfo); + std::shared_ptr callRecord = std::make_shared(0, abilityRecord, connCallback, nullptr); + std::shared_ptr callContainer = std::make_shared(); + + callRecord->connCallback_ = connCallback; + callRecord->callRemoteObject_ = connCallback->AsObject(); + callRecord->SetCallState(CallState::INIT); + callContainer->AddCallRecord(connCallback, callRecord); + abilityRecord->callContainer_ = callContainer; + abilityRecord->isReady_ = true; + abilityRecord->scheduler_ = new (std::nothrow) MissionListManagerTestAbilityThreadStub(); + + int testRet = missionListMgr->ResolveAbility(abilityRecord, abilityRequest); + + EXPECT_EQ(ResolveResultType::OK_HAS_REMOTE_OBJ, testRet); + GTEST_LOG_(INFO) << "MissionListManager_011 end"; +} + +/** + * @tc.number: MissionListManager_012 + * @tc.name: ResolveAbility + * @tc.desc: MissionListManager to process ResolveAbility success. + */ +HWTEST_F(MissionListManagerTest, MissionListManager_012, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "MissionListManager_012 begin"; + + sptr connCallback = new (std::nothrow) MissionListManagerTestStub(); + AbilityRequest abilityRequest; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + abilityRequest.connect = connCallback; + Want want; + AppExecFwk::AbilityInfo abilityInfo; + AppExecFwk::ApplicationInfo applicationInfo; + + std::shared_ptr missionListMgr = std::make_shared(0); + std::shared_ptr abilityRecord = + std::make_shared(want, abilityInfo, applicationInfo); + std::shared_ptr callRecord = std::make_shared(0, abilityRecord, connCallback, nullptr); + std::shared_ptr callContainer = std::make_shared(); + + callRecord->connCallback_ = connCallback; + callRecord->callRemoteObject_ = connCallback->AsObject(); + callRecord->SetCallState(CallState::INIT); + callContainer->AddCallRecord(connCallback, callRecord); + abilityRecord->callContainer_ = callContainer; + abilityRecord->isReady_ = false; + + int testRet = missionListMgr->ResolveAbility(abilityRecord, abilityRequest); + + EXPECT_EQ(ResolveResultType::OK_NO_REMOTE_OBJ, testRet); + GTEST_LOG_(INFO) << "MissionListManager_012 end"; +} + +/** + * @tc.number: MissionListManager_013 + * @tc.name: ResolveLocked + * @tc.desc: MissionListManager to process ResolveLocked success. + */ +HWTEST_F(MissionListManagerTest, MissionListManager_013, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "MissionListManager_013 begin"; + AbilityRequest abilityRequest; + abilityRequest.callType = AbilityCallType::INVALID_TYPE; + + std::shared_ptr missionListMgr = std::make_shared(0); + + int testRet = missionListMgr->ResolveLocked(abilityRequest); + + EXPECT_EQ(RESOLVE_CALL_ABILITY_INNER_ERR, testRet); + GTEST_LOG_(INFO) << "MissionListManager_013 end"; +} + + +/** + * @tc.number: MissionListManager_014 + * @tc.name: ResolveLocked + * @tc.desc: MissionListManager to process ResolveLocked success. + */ +HWTEST_F(MissionListManagerTest, MissionListManager_014, Function | MediumTest | Level1) +{ + GTEST_LOG_(INFO) << "MissionListManager_014 begin"; + + + sptr connCallback = new (std::nothrow) MissionListManagerTestStub(); + AbilityRequest abilityRequest; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + abilityRequest.abilityInfo.bundleName = "test_bundle"; + abilityRequest.abilityInfo.name = "test_name"; + abilityRequest.abilityInfo.launchMode = AppExecFwk::LaunchMode::SINGLETON; + abilityRequest.connect = connCallback; + Want want; + AppExecFwk::AbilityInfo abilityInfo = abilityRequest.abilityInfo; + AppExecFwk::ApplicationInfo applicationInfo; + int32_t id; + std::string missionName = "#" + abilityRequest.abilityInfo.bundleName + ":" + abilityRequest.abilityInfo.name; + + std::shared_ptr missionListMgr = std::make_shared(0); + std::shared_ptr abilityRecord = + std::make_shared(want, abilityInfo, applicationInfo); + std::shared_ptr missionList = std::make_shared(); + std::shared_ptr mission = std::make_shared(id, abilityRecord, missionName); + std::shared_ptr callContainer = std::make_shared(); + std::shared_ptr callRecord = std::make_shared(0, abilityRecord, connCallback, nullptr); + callRecord->connCallback_ = connCallback; + callRecord->callRemoteObject_ = connCallback->AsObject(); + callRecord->SetCallState(CallState::REQUESTED); + callContainer->AddCallRecord(connCallback, callRecord); + abilityRecord->callContainer_ = callContainer; + missionList->AddMissionToTop(mission); + missionListMgr->currentMissionLists_.push_front(missionList); + + int testRet = missionListMgr->ResolveLocked(abilityRequest); + + EXPECT_EQ(ERR_OK, testRet); + GTEST_LOG_(INFO) << "MissionListManager_014 end"; +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/test/unittest/phone/mission_list_test/BUILD.gn b/services/abilitymgr/test/unittest/phone/mission_list_test/BUILD.gn index d2f8baf9eb0c03f0c7183e40a07c03f8d7531f2d..0611c386a63ae1b3587ca102923da09750980251 100644 --- a/services/abilitymgr/test/unittest/phone/mission_list_test/BUILD.gn +++ b/services/abilitymgr/test/unittest/phone/mission_list_test/BUILD.gn @@ -14,7 +14,7 @@ import("//build/test.gni") import("//foundation/aafwk/standard/aafwk.gni") -module_output_path = "ability_runtime/abilitymgr" +module_output_path = "ability_runtime/ability_call_test" ohos_unittest("mission_list_test") { module_out_path = module_output_path @@ -63,8 +63,36 @@ ohos_unittest("mission_list_test") { ] } +ohos_unittest("mission_list_test_call") { + module_out_path = module_output_path + + sources = [ + "mission_list_test_call.cpp", # add mock file + ] + + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${innerkits_path}/want:want", + "${services_path}/abilitymgr/test:abilityms_test_source", + "${services_path}/common:perm_verification", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] +} + group("unittest") { testonly = true - deps = [ ":mission_list_test" ] + deps = [ ":mission_list_test_call" ] } diff --git a/services/abilitymgr/test/unittest/phone/mission_list_test/mission_list_test_call.cpp b/services/abilitymgr/test/unittest/phone/mission_list_test/mission_list_test_call.cpp new file mode 100644 index 0000000000000000000000000000000000000000..830ac9a10287a58eaa41fc9a4ea0b71a1cb895df --- /dev/null +++ b/services/abilitymgr/test/unittest/phone/mission_list_test/mission_list_test_call.cpp @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "ability_info.h" +#include "mission.h" +#include "mission_list.h" + +using namespace testing::ext; +using namespace OHOS::AppExecFwk; + +namespace { + const std::string DEVICE_ID = "15010038475446345206a332922cb765"; + const std::string INVALID_DEVICE_ID = "88880038475446345206a332922c8888"; + const std::string BUNDLE_NAME = "testBundle"; + const std::string INVALID_BUNDLE_NAME = "invalidBundle"; + const std::string NAME = ".testMainAbility"; + const std::string INVALID_NAME = "invalid.testMainAbility"; +} + +namespace OHOS { +namespace AAFwk { +class MissionListTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void MissionListTest::SetUpTestCase(void) +{} +void MissionListTest::TearDownTestCase(void) +{} +void MissionListTest::SetUp(void) +{} +void MissionListTest::TearDown(void) +{} + +/* + * Feature: MissionList + * Function: GetAbilityRecordByName + * SubFunction: NA + * FunctionPoints: MissionList GetAbilityRecordByName + * EnvConditions: NA + * CaseDescription: Verify GetAbilityRecordByName + */ +HWTEST_F(MissionListTest, mission_list_get_ability_record_by_name_001, TestSize.Level1) +{ + AppExecFwk::AbilityInfo abilityInfo; + abilityInfo.deviceId = DEVICE_ID; + abilityInfo.bundleName = BUNDLE_NAME; + abilityInfo.name = NAME; + Want want; + AppExecFwk::ApplicationInfo applicationInfo; + std::shared_ptr abilityRecord = std::make_shared(want, abilityInfo, applicationInfo); + + auto mission = std::make_shared(0, abilityRecord, "launcher"); + auto missionList = std::make_shared(); + missionList->AddMissionToTop(mission); + + AppExecFwk::ElementName localElement(DEVICE_ID, BUNDLE_NAME, NAME); + EXPECT_EQ(abilityRecord, missionList->GetAbilityRecordByName(localElement)); +} + +/* + * Feature: MissionList + * Function: GetAbilityRecordByName + * SubFunction: NA + * FunctionPoints: MissionList GetAbilityRecordByName + * EnvConditions: NA + * CaseDescription: Verify GetAbilityRecordByName + */ +HWTEST_F(MissionListTest, mission_list_get_ability_record_by_name_002, TestSize.Level1) +{ + AppExecFwk::AbilityInfo abilityInfo; + abilityInfo.deviceId = DEVICE_ID; + abilityInfo.bundleName = BUNDLE_NAME; + abilityInfo.name = NAME; + Want want; + AppExecFwk::ApplicationInfo applicationInfo; + std::shared_ptr abilityRecord = std::make_shared(want, abilityInfo, applicationInfo); + + auto mission = std::make_shared(0, abilityRecord, "launcher"); + auto missionList = std::make_shared(); + missionList->AddMissionToTop(mission); + + AppExecFwk::ElementName localElement(INVALID_DEVICE_ID, BUNDLE_NAME, NAME); + EXPECT_EQ(nullptr, missionList->GetAbilityRecordByName(localElement)); +} + +/* + * Feature: MissionList + * Function: GetAbilityRecordByName + * SubFunction: NA + * FunctionPoints: MissionList GetAbilityRecordByName + * EnvConditions: NA + * CaseDescription: Verify GetAbilityRecordByName + */ +HWTEST_F(MissionListTest, mission_list_get_ability_record_by_name_003, TestSize.Level1) +{ + AppExecFwk::AbilityInfo abilityInfo; + abilityInfo.deviceId = DEVICE_ID; + abilityInfo.bundleName = BUNDLE_NAME; + abilityInfo.name = NAME; + Want want; + AppExecFwk::ApplicationInfo applicationInfo; + std::shared_ptr abilityRecord = std::make_shared(want, abilityInfo, applicationInfo); + + auto mission = std::make_shared(0, abilityRecord, "launcher"); + auto missionList = std::make_shared(); + missionList->AddMissionToTop(mission); + + AppExecFwk::ElementName localElement(DEVICE_ID, INVALID_BUNDLE_NAME, NAME); + EXPECT_EQ(nullptr, missionList->GetAbilityRecordByName(localElement)); +} + +/* + * Feature: MissionList + * Function: GetAbilityRecordByName + * SubFunction: NA + * FunctionPoints: MissionList GetAbilityRecordByName + * EnvConditions: NA + * CaseDescription: Verify GetAbilityRecordByName + */ +HWTEST_F(MissionListTest, mission_list_get_ability_record_by_name_004, TestSize.Level1) +{ + AppExecFwk::AbilityInfo abilityInfo; + abilityInfo.deviceId = DEVICE_ID; + abilityInfo.bundleName = BUNDLE_NAME; + abilityInfo.name = NAME; + Want want; + AppExecFwk::ApplicationInfo applicationInfo; + std::shared_ptr abilityRecord = std::make_shared(want, abilityInfo, applicationInfo); + + auto mission = std::make_shared(0, abilityRecord, "launcher"); + auto missionList = std::make_shared(); + missionList->AddMissionToTop(mission); + + AppExecFwk::ElementName localElement(DEVICE_ID, BUNDLE_NAME, INVALID_NAME); + EXPECT_EQ(nullptr, missionList->GetAbilityRecordByName(localElement)); +} +} // namespace AAFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/test/BUILD.gn b/services/test/BUILD.gn index 42d989e53933455c8b7f56fea362a2b0ed63195c..870809f4bc36459e6c988462d35217fb1a5e084a 100644 --- a/services/test/BUILD.gn +++ b/services/test/BUILD.gn @@ -46,9 +46,9 @@ group("moduletest") { deps = [ "moduletest/ability_mgr_service_test:moduletest", "moduletest/ability_record_test:moduletest", - # "moduletest/ability_stack_test:moduletest", "moduletest/common/ams:moduletest", + "moduletest/call_module_test:moduletest", "moduletest/dump_module_test:moduletest", "moduletest/ipc_ability_connect_test:moduletest", "moduletest/ipc_ability_mgr_test:moduletest", diff --git a/services/test/moduletest/call_module_test/BUILD.gn b/services/test/moduletest/call_module_test/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..b4d21519c44ccb1e86f4bff1827637691e22f305 --- /dev/null +++ b/services/test/moduletest/call_module_test/BUILD.gn @@ -0,0 +1,72 @@ +# Copyright (c) 2021-2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//build/test.gni") +import("//foundation/aafwk/standard/aafwk.gni") + +module_output_path = "ability_runtime/ability_call_test" + +ohos_moduletest("call_ability_service_module_test") { + module_out_path = module_output_path + + include_dirs = [ + "//foundation/aafwk/standard/services/test/mock/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", + "//foundation/aafwk/standard/frameworks/kits/ability/native/test/mock/include", + ] + + sources = [ + # add mock file + "//foundation/aafwk/standard/services/abilitymgr/test/mock/libs/appexecfwk_core/src/appmgr/mock_app_scheduler.cpp", + "call_ability_service_module_test.cpp", + ] + + configs = [ "${services_path}/abilitymgr:abilityms_config" ] + cflags = [] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + deps = [ + "${innerkits_path}/want:want", + "${services_path}/abilitymgr/test:abilityms_test_source", + "${services_path}/abilitymgr/test/mock/libs/aakit:aakit_mock", + "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_appmgr_mock", + "${services_path}/abilitymgr/test/mock/libs/appexecfwk_core:appexecfwk_bundlemgr_mock", + "${services_path}/common:perm_verification", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/frameworks/kits/ability/native:dummy_classes", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager:app_manager", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + "//third_party/libpng:libpng", + "//utils/native/base:utils", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "device_manager_base:devicemanagersdk", + "dsoftbus_standard:softbus_client", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] +} + +group("moduletest") { + testonly = true + deps = [ ":call_ability_service_module_test" ] +} diff --git a/services/test/moduletest/call_module_test/call_ability_service_module_test.cpp b/services/test/moduletest/call_module_test/call_ability_service_module_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2c1ecc8618875f4f2bc75c8da3b827900987a766 --- /dev/null +++ b/services/test/moduletest/call_module_test/call_ability_service_module_test.cpp @@ -0,0 +1,237 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#define private public +#define protected public +#include "ability_manager_service.h" +#include "ability_event_handler.h" +#undef private +#undef protected + +#include "app_process_data.h" +#include "system_ability_definition.h" +#include "ability_manager_errors.h" +#include "ability_scheduler.h" +#include "sa_mgr_client.h" +#include "mock_ability_connect_callback.h" +#include "mock_ability_token.h" +#include "mock_bundle_mgr.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" + +using namespace testing; +using namespace testing::ext; +using namespace OHOS::AppExecFwk; + +namespace { + const std::string DEVICE_ID = "15010038475446345206a332922cb765"; + const std::string BUNDLE_NAME = "testBundle"; + const std::string NAME = ".testMainAbility"; +} + +namespace OHOS { +namespace AAFwk { +static void WaitUntilTaskFinished() +{ + const uint32_t maxRetryCount = 1000; + const uint32_t sleepTime = 1000; + uint32_t count = 0; + auto handler = OHOS::DelayedSingleton::GetInstance()->GetEventHandler(); + std::atomic taskCalled(false); + auto f = [&taskCalled]() { taskCalled.store(true); }; + if (handler->PostTask(f)) { + while (!taskCalled.load()) { + ++count; + if (count >= maxRetryCount) { + break; + } + usleep(sleepTime); + } + } +} + +#define SLEEP(milli) std::this_thread::sleep_for(std::chrono::seconds(milli)) + +namespace { +const std::string WaitUntilTaskFinishedByTimer = "BundleMgrService"; +} // namespace + +class AbilityManagerServiceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + void OnStartAms(); + void OnStopAms(); + int StartAbility(const Want &want); + static constexpr int TEST_WAIT_TIME = 100000; + +public: + AbilityRequest abilityRequest_; + std::shared_ptr abilityRecord_ {nullptr}; + std::shared_ptr abilityMs_ = DelayedSingleton::GetInstance(); +}; + +int AbilityManagerServiceTest::StartAbility(const Want &want) +{ + int ref = -1; + auto topAbility = abilityMs_->GetStackManager()->GetCurrentTopAbility(); + if (topAbility) { + topAbility->SetAbilityState(OHOS::AAFwk::AbilityState::ACTIVE); + } + ref = abilityMs_->StartAbility(want); + WaitUntilTaskFinished(); + return ref; +} + +void AbilityManagerServiceTest::OnStartAms() +{ + if (abilityMs_) { + if (abilityMs_->state_ == ServiceRunningState::STATE_RUNNING) { + return; + } + + abilityMs_->state_ = ServiceRunningState::STATE_RUNNING; + + abilityMs_->eventLoop_ = AppExecFwk::EventRunner::Create(AbilityConfig::NAME_ABILITY_MGR_SERVICE); + EXPECT_TRUE(abilityMs_->eventLoop_); + + abilityMs_->handler_ = std::make_shared(abilityMs_->eventLoop_, abilityMs_); + abilityMs_->connectManager_ = std::make_shared(); + abilityMs_->connectManagers_.emplace(0, abilityMs_->connectManager_); + EXPECT_TRUE(abilityMs_->handler_); + EXPECT_TRUE(abilityMs_->connectManager_); + + abilityMs_->dataAbilityManager_ = std::make_shared(); + abilityMs_->dataAbilityManagers_.emplace(0, abilityMs_->dataAbilityManager_); + EXPECT_TRUE(abilityMs_->dataAbilityManager_); + + abilityMs_->amsConfigResolver_ = std::make_shared(); + EXPECT_TRUE(abilityMs_->amsConfigResolver_); + abilityMs_->amsConfigResolver_->Parse(); + + abilityMs_->pendingWantManager_ = std::make_shared(); + EXPECT_TRUE(abilityMs_->pendingWantManager_); + + abilityMs_->currentMissionListManager_ = std::make_shared(0); + abilityMs_->currentMissionListManager_->Init(); + int userId = abilityMs_->GetUserId(); + abilityMs_->SetStackManager(userId, true); + EXPECT_TRUE(abilityMs_->GetStackManager()); + abilityMs_->stackManagers_.emplace(0, abilityMs_->GetStackManager()); + abilityMs_->eventLoop_->Run(); + return; + } + + GTEST_LOG_(INFO) << "OnStart fail"; +} + +void AbilityManagerServiceTest::OnStopAms() +{ + abilityMs_->OnStop(); +} + +void AbilityManagerServiceTest::SetUpTestCase() +{ + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility( + OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, new BundleMgrService()); +} + +void AbilityManagerServiceTest::TearDownTestCase() +{ + OHOS::DelayedSingleton::DestroyInstance(); +} + +void AbilityManagerServiceTest::SetUp() +{ + OnStartAms(); + WaitUntilTaskFinished(); + if (abilityRecord_ == nullptr) { + abilityRequest_.appInfo.bundleName = "data.client.bundle"; + abilityRequest_.abilityInfo.name = "ClientAbility"; + abilityRequest_.abilityInfo.type = AbilityType::DATA; + abilityRecord_ = AbilityRecord::CreateAbilityRecord(abilityRequest_); + } +} + +void AbilityManagerServiceTest::TearDown() +{ + OnStopAms(); +} + +/** + * @tc.name: CheckCallPermissions_001 + * @tc.desc: Verify function CheckCallPermissions return RESOLVE_CALL_NO_PERMISSIONS + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AbilityManagerServiceTest, CheckCallPermissions_001, TestSize.Level1) +{ + abilityRequest_.callerUid = 0; + EXPECT_EQ(RESOLVE_CALL_NO_PERMISSIONS, abilityMs_->CheckCallPermissions(abilityRequest_)); +} + +/** + * @tc.name: CheckCallPermissions_002 + * @tc.desc: Verify function CheckCallPermissions return ERR_OK + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AbilityManagerServiceTest, CheckCallPermissions_002, TestSize.Level1) +{ + abilityRequest_.callerUid = 1000; + abilityRequest_.abilityInfo.type = AppExecFwk::AbilityType::PAGE; + abilityRequest_.abilityInfo.launchMode = AppExecFwk::LaunchMode::SINGLETON; + EXPECT_EQ(ERR_OK, abilityMs_->CheckCallPermissions(abilityRequest_)); +} + +/** + * @tc.name: OnCallConnectDied_001 + * @tc.desc: Verify function OnCallConnectDied call success + * @tc.type: FUNC + * @tc.require: + */ +HWTEST_F(AbilityManagerServiceTest, OnCallConnectDied_001, TestSize.Level1) +{ + std::shared_ptr callContainer = std::make_shared(); + EXPECT_EQ(callContainer->callRecordMap_.size(), 0); + + AbilityRequest abilityRequest; + abilityRequest.callerUid = 1; + abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE; + abilityRequest.connect = new MockAbilityConnectCallback(); + std::shared_ptr callRecord = CallRecord::CreateCallRecord( + abilityRequest.callerUid, abilityRecord_->shared_from_this(), + abilityRequest.connect, abilityRequest.callerToken); + callRecord->SetCallState(CallState::REQUESTED); + callContainer->AddCallRecord(abilityRequest.connect, callRecord); + EXPECT_EQ(callContainer->callRecordMap_.size(), 1); + + auto mission = std::make_shared(0, abilityRecord_, "launcher"); + auto missionList = std::make_shared(); + missionList->AddMissionToTop(mission); + abilityRecord_->callContainer_ = callContainer; + + std::shared_ptr missionListMgr = std::make_shared(0); + missionListMgr->currentMissionLists_.push_front(missionList); + + abilityMs_->currentMissionListManager_ = missionListMgr; + abilityMs_->OnCallConnectDied(callRecord); + EXPECT_EQ(callContainer->callRecordMap_.size(), 0); +} +} +} \ No newline at end of file