From ab0d8c2d132a308c26b042bfd200bb080466c9d0 Mon Sep 17 00:00:00 2001 From: "yupeng74@huawei.com" Date: Fri, 28 Oct 2022 14:33:21 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=88=86=E6=94=AF=E8=A6=86?= =?UTF-8?q?=E7=9B=96=E7=8E=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yupeng74@huawei.com --- .../src/bundle_active_app_group_napi.cpp | 5 +- .../innerkits/src/bundle_active_client.cpp | 5 +- .../device_usage_statistics_jsunit.test.js | 114 ++++++++++++--- .../common/include/bundle_active_service.h | 1 + services/common/src/bundle_active_core.cpp | 40 ++++-- services/common/src/bundle_active_service.cpp | 6 +- services/common/src/bundle_active_stub.cpp | 1 + .../include/bundle_active_group_controller.h | 2 +- .../src/bundle_active_group_controller.cpp | 38 ++--- test/unittest/BUILD.gn | 36 ++++- .../device_usage_statistics_service_test.cpp | 135 ++++++++++++++++++ .../unittest/device_usage_statistics_test.cpp | 39 ++++- 12 files changed, 342 insertions(+), 80 deletions(-) create mode 100644 test/unittest/device_usage_statistics_service_test.cpp diff --git a/frameworks/src/bundle_active_app_group_napi.cpp b/frameworks/src/bundle_active_app_group_napi.cpp index f062222..ba4b201 100644 --- a/frameworks/src/bundle_active_app_group_napi.cpp +++ b/frameworks/src/bundle_active_app_group_napi.cpp @@ -340,8 +340,8 @@ napi_value RegisterAppGroupCallBack(napi_env env, napi_callback_info info) [](napi_env env, napi_status status, void *data) { AsyncRegisterCallbackInfo *asyncCallbackInfo = (AsyncRegisterCallbackInfo *)data; if (asyncCallbackInfo) { - std::lock_guard lock(g_observerMutex_); if (asyncCallbackInfo->errorCode != ERR_OK) { + std::lock_guard lock(g_observerMutex_); registerObserver = nullptr; } napi_value result = nullptr; @@ -372,7 +372,6 @@ napi_value ParseUnRegisterAppGroupCallBackParameters(const napi_env &env, const return BundleStateCommon::HandleParamErr(env, ERR_PARAMETERS_NUMBER, ""); } - // argv[1]: callback if (argc == UN_REGISTER_GROUP_CALLBACK_PARAMS) { napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); @@ -421,8 +420,8 @@ napi_value UnRegisterAppGroupCallBack(napi_env env, napi_callback_info info) [](napi_env env, napi_status status, void *data) { AsyncUnRegisterCallbackInfo *asyncCallbackInfo = (AsyncUnRegisterCallbackInfo *)data; if (asyncCallbackInfo != nullptr) { - std::lock_guard lock(g_observerMutex_); if (asyncCallbackInfo->errorCode == ERR_OK) { + std::lock_guard lock(g_observerMutex_); registerObserver = nullptr; } napi_value result = nullptr; diff --git a/interfaces/innerkits/src/bundle_active_client.cpp b/interfaces/innerkits/src/bundle_active_client.cpp index 89cecd6..12d4da2 100644 --- a/interfaces/innerkits/src/bundle_active_client.cpp +++ b/interfaces/innerkits/src/bundle_active_client.cpp @@ -237,7 +237,7 @@ void BundleActiveClient::BundleActiveClientDeathRecipient::OnRemoteDied(const wp void BundleActiveClient::BundleActiveClientDeathRecipient::OnServiceDiedInner() { - while (!BundleActiveClient::GetInstance().GetBundleActiveProxy()) { + while (BundleActiveClient::GetInstance().GetBundleActiveProxy() != ERR_OK) { sleep(SLEEP_TIME); } if (observer_) { @@ -245,5 +245,4 @@ void BundleActiveClient::BundleActiveClientDeathRecipient::OnServiceDiedInner() } } } // namespace DeviceUsageStats -} // namespace OHOS - +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js index fac99b8..d9bc3b7 100644 --- a/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js +++ b/interfaces/test/unittest/device_usage_statistics_jsunittest/device_usage_statistics_jsunit.test.js @@ -857,51 +857,67 @@ describe("DeviceUsageStatisticsJsTest", function () { /* * @tc.name: DeviceUsageStatisticsJsTest033 - * @tc.desc: test unRegisterAppGroupCallBack callback. + * @tc.desc: test registerAppGroupCallBack callback. * @tc.type: FUNC * @tc.require: issueI5V2T4 */ it("DeviceUsageStatisticsJsTest033", 0, async function (done) { console.info('----------------------DeviceUsageStatisticsJsTest033---------------------------'); + let onBundleGroupChanged = (err, res) =>{ + console.log('BUNDLE_ACTIVE onBundleGroupChanged registerAppGroupCallBack callback success.'); + console.log('BUNDLE_ACTIVE registerAppGroupCallBack result appUsageOldGroup is : ' + res.appOldGroup); + console.log('BUNDLE_ACTIVE registerAppGroupCallBack result appUsageNewGroup is : ' + res.appNewGroup); + console.log('BUNDLE_ACTIVE registerAppGroupCallBack result changeReason is : ' + res.changeReason); + console.log('BUNDLE_ACTIVE registerAppGroupCallBack result userId is : ' + res.userId); + console.log('BUNDLE_ACTIVE registerAppGroupCallBack result bundleName is : ' + res.bundleName); + }; try{ - usageStatistics.unRegisterAppGroupCallBack((err, res) => { + usageStatistics.registerAppGroupCallBack(onBundleGroupChanged, (err, res) => { if(err) { - console.info('BUNDLE_ACTIVE unRegisterAppGroupCallBack callback failure.'); + console.info('BUNDLE_ACTIVE registerAppGroupCallBack callback failure.'); expect(false).assertEqual(true); done(); } else { - console.info('BUNDLE_ACTIVE unRegisterAppGroupCallBack callback success.'); - expect(false).assertEqual(true); + console.info('BUNDLE_ACTIVE registerAppGroupCallBack callback success.'); + expect(true).assertEqual(true); done(); } }); } catch (error) { - console.info('BUNDLE_ACTIVE unRegisterAppGroupCallBack callback throw error.'); - expect(true).assertEqual(true); + console.info('BUNDLE_ACTIVE registerAppGroupCallBack callback failure.'); + expect(false).assertEqual(true); done(); } }) /* * @tc.name: DeviceUsageStatisticsJsTest034 - * @tc.desc: test unRegisterAppGroupCallBack promise. + * @tc.desc: test registerAppGroupCallBack promise. * @tc.type: FUNC * @tc.require: issueI5V2T4 */ it("DeviceUsageStatisticsJsTest034", 0, async function (done) { console.info('----------------------DeviceUsageStatisticsJsTest034---------------------------'); + let onBundleGroupChanged = (err, res) =>{ + console.log('BUNDLE_ACTIVE registerAppGroupCallBack registerAppGroupCallBack callback success.'); + console.log('BUNDLE_ACTIVE registerAppGroupCallBack result appOldGroup is : ' + res.appOldGroup); + console.log('BUNDLE_ACTIVE registerAppGroupCallBack result appNewGroup is : ' + res.appNewGroup); + console.log('BUNDLE_ACTIVE registerAppGroupCallBack result changeReason is : ' + res.changeReason); + console.log('BUNDLE_ACTIVE registerAppGroupCallBack result userId is : ' + res.userId); + console.log('BUNDLE_ACTIVE registerAppGroupCallBack result bundleName is : ' + res.bundleName); + }; try{ - usageStatistics.unRegisterAppGroupCallBack().then( (res) => { - console.info('BUNDLE_ACTIVE unRegisterAppGroupCallBack promise success.'); + usageStatistics.registerAppGroupCallBack(onBundleGroupChanged).then( (res) => { + console.info('BUNDLE_ACTIVE registerAppGroupCallBack promise success.'); expect(false).assertEqual(true); done(); }).catch( err => { - console.info('BUNDLE_ACTIVE unRegisterAppGroupCallBack promise failure.'); - expect(false).assertEqual(true); + console.info('BUNDLE_ACTIVE registerAppGroupCallBack promise failure.'); + expect(true).assertEqual(true); done(); }); } catch (error) { - console.info('BUNDLE_ACTIVE unRegisterAppGroupCallBack promise throw error.'); + console.info('BUNDLE_ACTIVE registerAppGroupCallBack promise failure.'); expect(true).assertEqual(true); done(); } @@ -909,12 +925,64 @@ describe("DeviceUsageStatisticsJsTest", function () { /* * @tc.name: DeviceUsageStatisticsJsTest035 - * @tc.desc: test queryDeviceEventStats callback. + * @tc.desc: test unregisterAppGroupCallBack callback. * @tc.type: FUNC * @tc.require: issueI5V2T4 */ it("DeviceUsageStatisticsJsTest035", 0, async function (done) { console.info('----------------------DeviceUsageStatisticsJsTest035---------------------------'); + try{ + usageStatistics.unregisterAppGroupCallBack((err, res) => { + if(err) { + console.info('BUNDLE_ACTIVE unregisterAppGroupCallBack callback failure.'); + expect(false).assertEqual(true); + done(); + } else { + console.info('BUNDLE_ACTIVE unregisterAppGroupCallBack callback success.'); + expect(true).assertEqual(true); + done(); + } + }); + } catch (error) { + console.info('BUNDLE_ACTIVE unregisterAppGroupCallBack callback throw error.'); + expect(false).assertEqual(true); + done(); + } + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest036 + * @tc.desc: test unregisterAppGroupCallBack promise. + * @tc.type: FUNC + * @tc.require: issueI5V2T4 + */ + it("DeviceUsageStatisticsJsTest036", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest036---------------------------'); + try{ + usageStatistics.unregisterAppGroupCallBack().then( (res) => { + console.info('BUNDLE_ACTIVE unregisterAppGroupCallBack promise success.'); + expect(false).assertEqual(true); + done(); + }).catch( err => { + console.info('BUNDLE_ACTIVE unregisterAppGroupCallBack promise failure.'); + expect(false).assertEqual(true); + done(); + }); + } catch (error) { + console.info('BUNDLE_ACTIVE unregisterAppGroupCallBack promise throw error.'); + expect(true).assertEqual(true); + done(); + } + }) + + /* + * @tc.name: DeviceUsageStatisticsJsTest037 + * @tc.desc: test queryDeviceEventStats callback. + * @tc.type: FUNC + * @tc.require: issueI5V2T4 + */ + it("DeviceUsageStatisticsJsTest037", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest037---------------------------'); let beginTime = 0; let endTime = 20000000000000; try{ @@ -937,13 +1005,13 @@ describe("DeviceUsageStatisticsJsTest", function () { }) /* - * @tc.name: DeviceUsageStatisticsJsTest036 + * @tc.name: DeviceUsageStatisticsJsTest038 * @tc.desc: test queryDeviceEventStats promise. * @tc.type: FUNC * @tc.require: issueI5V2T4 */ - it("DeviceUsageStatisticsJsTest036", 0, async function (done) { - console.info('----------------------DeviceUsageStatisticsJsTest036---------------------------'); + it("DeviceUsageStatisticsJsTest038", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest038---------------------------'); let beginTime = 0; let endTime = 20000000000000; try{ @@ -964,13 +1032,13 @@ describe("DeviceUsageStatisticsJsTest", function () { }) /* - * @tc.name: DeviceUsageStatisticsJsTest037 + * @tc.name: DeviceUsageStatisticsJsTest039 * @tc.desc: test queryNotificationEventStats callback. * @tc.type: FUNC * @tc.require: issueI5V2T4 */ - it("DeviceUsageStatisticsJsTest037", 0, async function (done) { - console.info('----------------------DeviceUsageStatisticsJsTest037---------------------------'); + it("DeviceUsageStatisticsJsTest039", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest039---------------------------'); let beginTime = 0; let endTime = 20000000000000; try{ @@ -993,13 +1061,13 @@ describe("DeviceUsageStatisticsJsTest", function () { }) /* - * @tc.name: DeviceUsageStatisticsJsTest038 + * @tc.name: DeviceUsageStatisticsJsTest040 * @tc.desc: test queryNotificationEventStats promise. * @tc.type: FUNC * @tc.require: issueI5V2T4 */ - it("DeviceUsageStatisticsJsTest038", 0, async function (done) { - console.info('----------------------DeviceUsageStatisticsJsTest038---------------------------'); + it("DeviceUsageStatisticsJsTest040", 0, async function (done) { + console.info('----------------------DeviceUsageStatisticsJsTest040---------------------------'); let beginTime = 0; let endTime = 20000000000000; try{ diff --git a/services/common/include/bundle_active_service.h b/services/common/include/bundle_active_service.h index f2ff1e8..a0fd14c 100644 --- a/services/common/include/bundle_active_service.h +++ b/services/common/include/bundle_active_service.h @@ -19,6 +19,7 @@ #include "bundle_mgr_interface.h" #include "singleton.h" +#include "app_mgr_interface.h" #include "ibundle_active_service.h" #include "bundle_active_stub.h" #include "bundle_active_core.h" diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp index d872af4..f325fd0 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -753,36 +753,43 @@ ErrCode BundleActiveCore::UnRegisterAppGroupCallBack(const AccessToken::AccessTo void BundleActiveCore::AddObserverDeathRecipient(const sptr &observer) { std::lock_guard lock(deathRecipientMutex_); - if (!observer || !(observer->AsObject())) { + if (!observer) { BUNDLE_ACTIVE_LOGI("observer nullptr."); return; } + auto object = observer->AsObject(); + if (!object) { + BUNDLE_ACTIVE_LOGI("observer->AsObject() nullptr."); + return; + } auto it = recipientMap_.find(observer->AsObject()); if (it != recipientMap_.end()) { BUNDLE_ACTIVE_LOGI("This death recipient has been added."); return; - } else { - sptr deathRecipient = new (std::nothrow) RemoteDeathRecipient( - [this](const wptr &remote) { this->OnObserverDied(remote); }); - if (!deathRecipient) { - BUNDLE_ACTIVE_LOGI("create death recipient failed"); - return ; - } - observer->AsObject()->AddDeathRecipient(deathRecipient); - recipientMap_.emplace(observer->AsObject(), deathRecipient); } + sptr deathRecipient = new (std::nothrow) RemoteDeathRecipient( + [this](const wptr &remote) { this->OnObserverDied(remote); }); + if (!deathRecipient) { + BUNDLE_ACTIVE_LOGI("create death recipient failed"); + return ; + } + observer->AsObject()->AddDeathRecipient(deathRecipient); + recipientMap_.emplace(observer->AsObject(), deathRecipient); } void BundleActiveCore::RemoveObserverDeathRecipient(const sptr &observer) { std::lock_guard lock(deathRecipientMutex_); - if (!observer || !(observer->AsObject())) { + if (!observer) { + return; + } + auto object = observer->AsObject(); + if (!object) { return ; } auto iter = recipientMap_.find(observer->AsObject()); if (iter != recipientMap_.end()) { iter->first->RemoveDeathRecipient(iter->second); recipientMap_.erase(iter); - return ; } } @@ -805,7 +812,14 @@ void BundleActiveCore::OnObserverDiedInner(const wptr &remote) return; } for (const auto& item : groupChangeObservers_) { - if ((item.second) && ((item.second)->AsObject()) && ((item.second)->AsObject() == objectProxy)) { + if (!(item.second)) { + continue; + } + auto object = (item.second)->AsObject(); + if (!object) { + continue; + } + if (object == objectProxy) { groupChangeObservers_.erase(item.first); break; } diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index 1b8ff5c..d04bf10 100644 --- a/services/common/src/bundle_active_service.cpp +++ b/services/common/src/bundle_active_service.cpp @@ -17,7 +17,6 @@ #include "power_mgr_client.h" #include "unistd.h" #include "accesstoken_kit.h" -#include "app_mgr_interface.h" #include "bundle_state_inner_errors.h" #include "bundle_active_event.h" @@ -561,7 +560,7 @@ ErrCode BundleActiveService::QueryModuleUsageRecords(int32_t maxNum, std::vector ErrCode errCode = ERR_OK; if (maxNum > MAXNUM_UP_LIMIT || maxNum <= 0) { BUNDLE_ACTIVE_LOGE("MaxNum is Invalid!"); - return errCode; + return ERR_FIND_APP_USAGE_RECORDS_FAILED; } int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); if (userId == -1) { @@ -627,7 +626,8 @@ ErrCode BundleActiveService::QueryNotificationEventStats(int64_t beginTime, int6 void BundleActiveService::QueryModuleRecordInfos(BundleActiveModuleRecord& moduleRecord) { - if (!GetBundleMgrProxy()) { + ErrCode errCode = GetBundleMgrProxy(); + if (errCode != ERR_OK) { return; } ApplicationInfo appInfo; diff --git a/services/common/src/bundle_active_stub.cpp b/services/common/src/bundle_active_stub.cpp index 5391fb4..0408f06 100644 --- a/services/common/src/bundle_active_stub.cpp +++ b/services/common/src/bundle_active_stub.cpp @@ -20,6 +20,7 @@ #include "bundle_active_event.h" #include "bundle_active_event_stats.h" +#include "bundle_state_inner_errors.h" #include "bundle_active_log.h" #include "bundle_active_module_record.h" #include "bundle_active_package_stats.h" diff --git a/services/packagegroup/include/bundle_active_group_controller.h b/services/packagegroup/include/bundle_active_group_controller.h index dbbd6db..f3da156 100644 --- a/services/packagegroup/include/bundle_active_group_controller.h +++ b/services/packagegroup/include/bundle_active_group_controller.h @@ -79,11 +79,11 @@ private: std::mutex mutex_; bool GetBundleMgrProxy(); std::weak_ptr activeGroupHandler_; - uint32_t EventToGroupReason(const int32_t eventId); int64_t timeoutForDirectlyUse_; int64_t timeoutForNotifySeen_; int64_t timeoutForSystemInteraction_; int64_t timeoutCalculated_ = 0; + std::map eventIdMatchReason_; sptr sptrBundleMgr_; bool calculationTimeOut(const std::shared_ptr& oneBundleHistory, const int64_t bootBasedTimeStamp); diff --git a/services/packagegroup/src/bundle_active_group_controller.cpp b/services/packagegroup/src/bundle_active_group_controller.cpp index aceddcd..d096cd9 100644 --- a/services/packagegroup/src/bundle_active_group_controller.cpp +++ b/services/packagegroup/src/bundle_active_group_controller.cpp @@ -38,6 +38,14 @@ BundleActiveGroupController::BundleActiveGroupController(const bool debug) screenTimeLevel_ = {0, 0, debug ? TWO_MINUTE : ONE_HOUR, debug ? FOUR_MINUTE : TWO_HOUR}; bootTimeLevel_ = {0, debug ? TWO_MINUTE : TWELVE_HOUR, debug ? FOUR_MINUTE : TWENTY_FOUR_HOUR, debug ? SIXTEEN_MINUTE : FOURTY_EIGHT_HOUR}; + eventIdMatchReason_ = { + {BundleActiveEvent::ABILITY_FOREGROUND, GROUP_EVENT_REASON_FOREGROUND}, + {BundleActiveEvent::ABILITY_BACKGROUND, GROUP_EVENT_REASON_BACKGROUND}, + {BundleActiveEvent::SYSTEM_INTERACTIVE, GROUP_EVENT_REASON_SYSTEM}, + {BundleActiveEvent::USER_INTERACTIVE, GROUP_EVENT_REASON_USER_INTERACTION}, + {BundleActiveEvent::NOTIFICATION_SEEN, GROUP_EVENT_REASON_NOTIFY_SEEN}, + {BundleActiveEvent::LONG_TIME_TASK_STARTTED, GROUP_EVENT_REASON_LONG_TIME_TASK_STARTTED}, + }; } void BundleActiveGroupController::RestoreDurationToDatabase() @@ -195,26 +203,6 @@ bool BundleActiveGroupController::calculationTimeOut( - lastGroupCalculatedTimeStamp > timeoutCalculated_; } -uint32_t BundleActiveGroupController::EventToGroupReason(const int32_t eventId) -{ - switch (eventId) { - case BundleActiveEvent::ABILITY_FOREGROUND: - return GROUP_EVENT_REASON_FOREGROUND; - case BundleActiveEvent::ABILITY_BACKGROUND: - return GROUP_EVENT_REASON_BACKGROUND; - case BundleActiveEvent::SYSTEM_INTERACTIVE: - return GROUP_EVENT_REASON_SYSTEM; - case BundleActiveEvent::USER_INTERACTIVE: - return GROUP_EVENT_REASON_USER_INTERACTION; - case BundleActiveEvent::NOTIFICATION_SEEN: - return GROUP_EVENT_REASON_NOTIFY_SEEN; - case BundleActiveEvent::LONG_TIME_TASK_STARTTED: - return GROUP_EVENT_REASON_LONG_TIME_TASK_STARTTED; - default: - return 0; - } -} - void BundleActiveGroupController::ReportEvent(const BundleActiveEvent& event, const int64_t bootBasedTimeStamp, const int32_t userId) { @@ -227,19 +215,15 @@ void BundleActiveGroupController::ReportEvent(const BundleActiveEvent& event, co return; } int32_t eventId = event.eventId_; - if (eventId == BundleActiveEvent::ABILITY_FOREGROUND || - eventId == BundleActiveEvent::ABILITY_BACKGROUND || - eventId == BundleActiveEvent::SYSTEM_INTERACTIVE || - eventId == BundleActiveEvent::USER_INTERACTIVE || - eventId == BundleActiveEvent::NOTIFICATION_SEEN || - eventId == BundleActiveEvent::LONG_TIME_TASK_STARTTED) { + auto item = eventIdMatchReason_.find(eventId); + if (item != eventIdMatchReason_.end()) { std::shared_ptr bundleUsageHistory = bundleUserHistory_->GetUsageHistoryForBundle( event.bundleName_, userId, bootBasedTimeStamp, true); if (bundleUsageHistory == nullptr) { return; } int64_t timeUntilNextCheck; - uint32_t eventReason = EventToGroupReason(eventId); + uint32_t eventReason = item->second; switch (eventId) { case BundleActiveEvent::NOTIFICATION_SEEN: bundleUserHistory_->ReportUsage(bundleUsageHistory, event.bundleName_, ACTIVE_GROUP_DAILY, diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 4151a21..9dd5c38 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -49,7 +49,41 @@ ohos_unittest("DeviceUsageStatsTest") { ] } +ohos_unittest("DeviceUsageStatsServiceTest") { + module_out_path = module_output_path + + sources = [ "device_usage_statistics_service_test.cpp" ] + + configs = [ + ":module_private_config", + "//foundation/ability/ability_runtime/interfaces/inner_api/wantagent:wantagent_innerkits_public_config", + ] + + deps = [ + "//foundation/resourceschedule/device_usage_statistics:usagestatservice", + "//foundation/resourceschedule/device_usage_statistics:usagestatsinner", + ] + + external_deps = [ + "ability_runtime:app_manager", + "access_token:libaccesstoken_sdk", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "power_manager:powermgr_client", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "time_service:time_service", + ] +} + group("unittest") { testonly = true - deps = [ ":DeviceUsageStatsTest" ] + deps = [ + ":DeviceUsageStatsServiceTest", + ":DeviceUsageStatsTest", + ] } diff --git a/test/unittest/device_usage_statistics_service_test.cpp b/test/unittest/device_usage_statistics_service_test.cpp new file mode 100644 index 0000000..0479c62 --- /dev/null +++ b/test/unittest/device_usage_statistics_service_test.cpp @@ -0,0 +1,135 @@ +/* + * 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. + */ + +#define private public +#define protected public + +#include + +#include +#include "system_ability_definition.h" + +#include "bundle_active_service.h" + +using namespace testing::ext; + +namespace OHOS { +namespace DeviceUsageStats { + +class DeviceUsageStatisticsServiceTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void DeviceUsageStatisticsServiceTest::SetUpTestCase(void) +{ +} + +void DeviceUsageStatisticsServiceTest::TearDownTestCase(void) +{ +} + +void DeviceUsageStatisticsServiceTest::SetUp(void) +{ +} + +void DeviceUsageStatisticsServiceTest::TearDown(void) +{ +} + +/* + * @tc.name: DeviceUsageStatisticsServiceTest_GetServiceObject_001 + * @tc.desc: get service object + * @tc.type: FUNC + * @tc.require: issuesI5SOZY + */ +HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_GetServiceObject_001, + Function | MediumTest | Level0) +{ + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + EXPECT_NE(systemAbilityManager, nullptr); + + sptr remoteObject = + systemAbilityManager->GetSystemAbility(DEVICE_USAGE_STATISTICS_SYS_ABILITY_ID); + EXPECT_NE(remoteObject, nullptr); +} + +/* + * @tc.name: DeviceUsageStatisticsServiceTest_dump_001 + * @tc.desc: test dump + * @tc.type: FUNC + * @tc.require: issuesI5SOZY + */ +HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_dump_001, Function | MediumTest | Level0) +{ + auto service = std::make_shared(); + BUNDLE_ACTIVE_LOGI("DeviceUsageStatisticsServiceTest create BundleActiveService!"); + + std::vector dumpOption{"-A", "Events"}; + std::vector dumpInfo; + service->ShellDump(dumpOption, dumpInfo); + + dumpOption.clear(); + dumpInfo.clear(); + dumpOption = {"-A", "PackageUsage"}; + service->ShellDump(dumpOption, dumpInfo); + + dumpOption.clear(); + dumpInfo.clear(); + dumpOption = {"-A", "ModuleUsage"}; + service->ShellDump(dumpOption, dumpInfo); + + std::vector args; + service->Dump(-1, args); + + args.clear(); + args = {to_utf16("-h")}; + service->Dump(-1, args); + + args.clear(); + args = {to_utf16("-A")}; + service->Dump(-1, args); + + args.clear(); + args = {to_utf16("-D")}; + service->Dump(-1, args); + EXPECT_TRUE(service!=nullptr); +} + +/* + * @tc.name: DeviceUsageStatisticsServiceTest_QueryModuleUsageRecords_001 + * @tc.desc: QueryModuleUsageRecords + * @tc.type: FUNC + * @tc.require: issuesI5SOZY + */ +HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_QueryModuleUsageRecords_001, + Function | MediumTest | Level0) +{ + auto service = std::make_shared(); + std::vector results; + int32_t maxNum = 0; + ErrCode errCode = service->QueryModuleUsageRecords(maxNum, results, 100); + EXPECT_NE(errCode, 0); + + maxNum = 1001; + errCode = service->QueryModuleUsageRecords(maxNum, results, 100); + EXPECT_NE(errCode, 0); +} +} // namespace DeviceUsageStats +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/device_usage_statistics_test.cpp b/test/unittest/device_usage_statistics_test.cpp index 9a4c4ad..edbb4f3 100644 --- a/test/unittest/device_usage_statistics_test.cpp +++ b/test/unittest/device_usage_statistics_test.cpp @@ -25,6 +25,7 @@ #include "bundle_active_event.h" #include "app_group_callback_stub.h" #include "bundle_active_group_map.h" +#include "app_group_callback_info.h" using namespace testing::ext; @@ -67,6 +68,20 @@ void DeviceUsageStatisticsTest::TearDown(void) { } +class TestAppGroupChangeCallback : public AppGroupCallbackStub { + void OnAppGroupChanged(const AppGroupCallbackInfo &appGroupCallbackInfo) override; +}; + +void TestAppGroupChangeCallback::OnAppGroupChanged(const AppGroupCallbackInfo &appGroupCallbackInfo) +{ + BUNDLE_ACTIVE_LOGI("TestAppGroupChangeCallback::OnAppGroupChanged!"); + MessageParcel data; + if (!appGroupCallbackInfo.Marshalling(data)) { + BUNDLE_ACTIVE_LOGE("Marshalling fail"); + } + appGroupCallbackInfo.Unmarshalling(data); +} + /* * @tc.name: DeviceUsageStatisticsTest_GetServiceObject_001 * @tc.desc: get service object @@ -185,6 +200,16 @@ HWTEST_F(DeviceUsageStatisticsTest, int32_t errCode = BundleActiveClient::GetInstance().QueryModuleUsageRecords(maxNum, results, DEFAULT_USERID); EXPECT_EQ(errCode, 0); EXPECT_EQ(results.size(), 0); + + results.clear(); + maxNum = 0; + errCode = BundleActiveClient::GetInstance().QueryModuleUsageRecords(maxNum, results, DEFAULT_USERID); + EXPECT_NE(errCode, 0); + + results.clear(); + maxNum = 1001; + errCode = BundleActiveClient::GetInstance().QueryModuleUsageRecords(maxNum, results, DEFAULT_USERID); + EXPECT_NE(errCode, 0); } /* @@ -198,7 +223,7 @@ HWTEST_F(DeviceUsageStatisticsTest, { if (!observer) { BUNDLE_ACTIVE_LOGI("RegisterAppGroupCallBack construct observer!"); - observer = std::make_unique().release(); + observer = new (std::nothrow) TestAppGroupChangeCallback(); } ASSERT_NE(observer, nullptr); int32_t result = BundleActiveClient::GetInstance().RegisterAppGroupCallBack(observer); @@ -218,6 +243,9 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_SetAppGroup_001, F DEFAULT_GROUP = (result == DEFAULT_GROUP) ? (result + 10) : DEFAULT_GROUP; result = BundleActiveClient::GetInstance().SetAppGroup(g_defaultBundleName, DEFAULT_GROUP, COMMON_USERID); EXPECT_EQ(result, DEFAULT_ERRCODE); + + result = BundleActiveClient::GetInstance().SetAppGroup(g_defaultBundleName, DEFAULT_GROUP, -1); + EXPECT_NE(result, DEFAULT_ERRCODE); } /* @@ -293,8 +321,7 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryNotificationE * @tc.type: FUNC * @tc.require: SR000H0G4F AR000H2US8 */ -HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_BundleActiveGroupMap_001, Function - | MediumTest | Level0) +HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_BundleActiveGroupMap_001, Function | MediumTest | Level0) { int64_t minInterval = DeviceUsageStatsGroupMap::groupIntervalMap_ .at(DeviceUsageStatsGroupConst::ACTIVE_GROUP_FORCED_SET); @@ -319,11 +346,11 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_BundleActiveGroupM * @tc.type: FUNC * @tc.require: issuesI5SOZY */ -HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_DeathRecipient_001, Function - | MediumTest | Level0) +HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_DeathRecipient_001, Function | MediumTest | Level0) { auto deathTest = std::make_shared(); - EXPECT_TRUE(deathTest!=nullptr); + deathTest->OnServiceDiedInner(); + EXPECT_TRUE(deathTest != nullptr); deathTest->OnRemoteDied(nullptr); } } // namespace DeviceUsageStats -- Gitee