diff --git a/BUILD.gn b/BUILD.gn index a66651358217f17659689326901951ad4333a5b5..f8f883578cde620d1c31cf2714a005bc7adf47bf 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -36,11 +36,14 @@ ohos_shared_library("usagestatsinner") { "interfaces/innerkits/src/app_group_callback_stub.cpp", "interfaces/innerkits/src/bundle_active_client.cpp", "interfaces/innerkits/src/bundle_active_proxy.cpp", + "services/common/src/bundle_active_log.cpp", "services/packageusage/src/bundle_active_event.cpp", + "services/packageusage/src/bundle_active_event_stats.cpp", + "services/packageusage/src/bundle_active_form_record.cpp", + "services/packageusage/src/bundle_active_module_record.cpp", "services/packageusage/src/bundle_active_package_stats.cpp", ] public_configs = [ ":usagestatsinner_public_config" ] - deps = [ ":usagestatservice" ] external_deps = [ "c_utils:utils", "eventhandler:libeventhandler", @@ -188,7 +191,7 @@ ohos_shared_library("usagestatservice") { "relational_store:native_rdb", "safwk:system_ability_fwk", "samgr:samgr_proxy", - "time_service:time_service", + "time_service:time_client", ] if (os_account_part_enabled) { @@ -199,7 +202,7 @@ ohos_shared_library("usagestatservice") { defines = [] if (bgtaskmgr_enable) { external_deps += [ "background_task_mgr:bgtaskmgr_innerkits" ] - defines += [ "RESOURCESCHEDULE_BGTASKMGR_ENABLE" ] + defines += [ "BGTASKMGR_ENABLE" ] } part_name = "${device_usage_statistics_part_name}" subsystem_name = "resourceschedule" diff --git a/frameworks/src/app_group_observer_napi.cpp b/frameworks/src/app_group_observer_napi.cpp index 028b50dd7f22b99ac84c195bd447d3b572e0a0d9..f9ab0c16c4a0b09fbec68dbb7adcb0f05751330d 100644 --- a/frameworks/src/app_group_observer_napi.cpp +++ b/frameworks/src/app_group_observer_napi.cpp @@ -157,7 +157,7 @@ void AppGroupObserver::OnAppGroupChanged(const AppGroupCallbackInfo &appGroupCal callbackReceiveDataWorker->ref = bundleGroupCallbackInfo_.ref; delete callBackInfo; - work->data = (void *)callbackReceiveDataWorker; + work->data = static_cast(callbackReceiveDataWorker); int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, UvQueueWorkOnAppGroupChanged); if (ret != 0) { delete callbackReceiveDataWorker; diff --git a/frameworks/src/bundle_active_app_group_napi.cpp b/frameworks/src/bundle_active_app_group_napi.cpp index f06222293da2b84077c6463467c409a2807d6951..8fbdb5ceef2214645d4b9807c804441a6e4d65ad 100644 --- a/frameworks/src/bundle_active_app_group_napi.cpp +++ b/frameworks/src/bundle_active_app_group_napi.cpp @@ -60,9 +60,9 @@ napi_value ParseQueryAppGroupParameters(const napi_env &env, const napi_callback napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); if (valuetype == napi_function) { - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - if (valuetype != napi_function) { + napi_valuetype inputValueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[0], &inputValueType)); + if (inputValueType != napi_function) { params.errorCode = ERR_CALL_BACK_TYPE; return BundleStateCommon::HandleParamErr(env, ERR_CALL_BACK_TYPE, ""); } @@ -84,15 +84,13 @@ napi_value ParseQueryAppGroupParameters(const napi_env &env, const napi_callback return BundleStateCommon::HandleParamErr(env, ERR_PARAMETERS_EMPTY, "bundleName"); } // argv[1]: callback - if (argc == PRIORITY_GROUP_PARAMS) { - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); - if (valuetype != napi_function) { - params.errorCode = ERR_CALL_BACK_TYPE; - return BundleStateCommon::HandleParamErr(env, ERR_CALL_BACK_TYPE, ""); - } - napi_create_reference(env, argv[1], 1, ¶ms.callback); + napi_valuetype inputValueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[1], &inputValueType)); + if (inputValueType != napi_function) { + params.errorCode = ERR_CALL_BACK_TYPE; + return BundleStateCommon::HandleParamErr(env, ERR_CALL_BACK_TYPE, ""); } + napi_create_reference(env, argv[1], 1, ¶ms.callback); } BundleStateCommon::AsyncInit(env, params, asyncCallbackInfo); return BundleStateCommon::NapiGetNull(env); @@ -135,7 +133,7 @@ napi_value QueryAppGroup(napi_env env, napi_callback_info info) BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, - (void *)asyncCallbackInfo, + static_cast(asyncCallbackInfo), &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); if (callbackPtr->isCallback) { @@ -195,9 +193,9 @@ napi_value ParseSetAppGroupParameters(const napi_env &env, const napi_callback_i } // argv[SECOND_ARG]: callback if (argc == APP_USAGE_PARAMS_BUNDLE_GROUP) { - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, argv[SECOND_ARG], &valuetype)); - if (valuetype != napi_function) { + napi_valuetype inputValueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[SECOND_ARG], &inputValueType)); + if (inputValueType != napi_function) { params.errorCode = ERR_CALL_BACK_TYPE; return BundleStateCommon::HandleParamErr(env, ERR_CALL_BACK_TYPE, ""); } @@ -244,7 +242,7 @@ napi_value SetAppGroup(napi_env env, napi_callback_info info) BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, - (void *)asyncCallbackInfo, + static_cast(asyncCallbackInfo), &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); if (callbackPtr->isCallback) { @@ -259,7 +257,7 @@ napi_value SetAppGroup(napi_env env, napi_callback_info info) napi_value GetAppGroupChangeCallback(const napi_env &env, const napi_value &value) { napi_ref result = nullptr; - + registerObserver = new (std::nothrow) AppGroupObserver(); if (!registerObserver) { BUNDLE_ACTIVE_LOGE("RegisterAppGroupCallBack callback is null"); @@ -281,7 +279,7 @@ napi_value ParseRegisterAppGroupCallBackParameters(const napi_env &env, const na params.errorCode = ERR_PARAMETERS_NUMBER; return BundleStateCommon::HandleParamErr(env, ERR_PARAMETERS_NUMBER, ""); } - + // arg[0] : callback napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); @@ -298,9 +296,9 @@ napi_value ParseRegisterAppGroupCallBackParameters(const napi_env &env, const na // argv[1]: asyncCallback if (argc == REGISTER_GROUP_CALLBACK_PARAMS) { - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); - if (valuetype != napi_function) { + napi_valuetype inputValueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[1], &inputValueType)); + if (inputValueType != napi_function) { params.errorCode = ERR_CALL_BACK_TYPE; return BundleStateCommon::HandleParamErr(env, ERR_CALL_BACK_TYPE, ""); } @@ -340,8 +338,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; @@ -349,7 +347,7 @@ napi_value RegisterAppGroupCallBack(napi_env env, napi_callback_info info) BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, - (void *)asyncCallbackInfo, + static_cast(asyncCallbackInfo), &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); if (callbackPtr->isCallback) { @@ -372,7 +370,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 +418,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; @@ -430,7 +427,7 @@ napi_value UnRegisterAppGroupCallBack(napi_env env, napi_callback_info info) BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, - (void *)asyncCallbackInfo, + static_cast(asyncCallbackInfo), &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); if (callbackPtr->isCallback) { diff --git a/frameworks/src/bundle_state_common.cpp b/frameworks/src/bundle_state_common.cpp index 12a229201fcaa5175cee9e4cee6ffb587b0c0c32..065d9eef4c975484cbc9b6f40c3a6585803abbfa 100644 --- a/frameworks/src/bundle_state_common.cpp +++ b/frameworks/src/bundle_state_common.cpp @@ -102,7 +102,7 @@ void BundleStateCommon::SetCallbackInfo( } void BundleStateCommon::GetBundleActiveEventForResult( - napi_env env, const std::vector &bundleActiveStates, napi_value result) + napi_env env, const std::vector &bundleActiveStates, napi_value result, bool isNewVersion) { int32_t index = 0; for (const auto &item : bundleActiveStates) { @@ -116,12 +116,19 @@ void BundleStateCommon::GetBundleActiveEventForResult( napi_value eventId = nullptr; NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, item.eventId_, &eventId)); - NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, bundleActiveState, "eventId", eventId)); napi_value eventOccurredTime = nullptr; NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, item.timeStamp_, &eventOccurredTime)); - NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, bundleActiveState, "eventOccurredTime", - eventOccurredTime)); + + if (isNewVersion) { + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, bundleActiveState, "eventId", eventId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, bundleActiveState, "eventOccurredTime", + eventOccurredTime)); + } else { + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, bundleActiveState, "stateType", eventId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, bundleActiveState, "stateOccurredTime", + eventOccurredTime)); + } NAPI_CALL_RETURN_VOID(env, napi_set_element(env, result, index, bundleActiveState)); index++; @@ -238,45 +245,45 @@ void BundleStateCommon::GetBundleStateInfoForResult(napi_env env, } void BundleStateCommon::GetModuleRecordBasicForResult(napi_env env, - const BundleActiveModuleRecord &oneModuleRecord, napi_value moduleObject) + const BundleActiveModuleRecord &moduleRecords, napi_value moduleObject) { napi_value bundleName = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, oneModuleRecord.bundleName_.c_str(), + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, moduleRecords.bundleName_.c_str(), NAPI_AUTO_LENGTH, &bundleName)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "bundleName", bundleName)); napi_value appLabelId = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, oneModuleRecord.appLabelId_, &appLabelId)); + NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleRecords.appLabelId_, &appLabelId)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "appLabelId", appLabelId)); napi_value moduleName = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, oneModuleRecord.moduleName_.c_str(), NAPI_AUTO_LENGTH, + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, moduleRecords.moduleName_.c_str(), NAPI_AUTO_LENGTH, &moduleName)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "moduleName", moduleName)); napi_value labelId = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, oneModuleRecord.labelId_, &labelId)); + NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleRecords.labelId_, &labelId)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "labelId", labelId)); napi_value descriptionId = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, oneModuleRecord.descriptionId_, &descriptionId)); + NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleRecords.descriptionId_, &descriptionId)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "descriptionId", descriptionId)); napi_value abilityName = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, oneModuleRecord.abilityName_.c_str(), NAPI_AUTO_LENGTH, + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, moduleRecords.abilityName_.c_str(), NAPI_AUTO_LENGTH, &abilityName)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "abilityName", abilityName)); napi_value abilityLableId = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, oneModuleRecord.abilityLableId_, &abilityLableId)); + NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleRecords.abilityLableId_, &abilityLableId)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "abilityLableId", abilityLableId)); napi_value abilityDescriptionId = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, oneModuleRecord.abilityDescriptionId_, + NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleRecords.abilityDescriptionId_, &abilityDescriptionId)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "abilityDescriptionId", abilityDescriptionId)); napi_value abilityIconId = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, oneModuleRecord.abilityIconId_, &abilityIconId)); + NAPI_CALL_RETURN_VOID(env, napi_create_uint32(env, moduleRecords.abilityIconId_, &abilityIconId)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "abilityIconId", abilityIconId)); napi_value launchedCount = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, oneModuleRecord.launchedCount_, &launchedCount)); + NAPI_CALL_RETURN_VOID(env, napi_create_int32(env, moduleRecords.launchedCount_, &launchedCount)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "launchedCount", launchedCount)); napi_value lastModuleUsedTime = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, oneModuleRecord.lastModuleUsedTime_, &lastModuleUsedTime)); + NAPI_CALL_RETURN_VOID(env, napi_create_int64(env, moduleRecords.lastModuleUsedTime_, &lastModuleUsedTime)); NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, moduleObject, "lastModuleUsedTime", lastModuleUsedTime)); } @@ -359,8 +366,8 @@ napi_value BundleStateCommon::GetErrorValue(napi_env env, int32_t errCode) NAPI_CALL(env, napi_create_int32(env, reflectCode, &eCode)); NAPI_CALL(env, napi_create_string_utf8(env, errMsg.c_str(), errMsg.length(), &eMsg)); NAPI_CALL(env, napi_create_object(env, &result)); - NAPI_CALL(env, napi_set_named_property(env, result, "errCode", eCode)); - NAPI_CALL(env, napi_set_named_property(env, result, "errMessage", eMsg)); + NAPI_CALL(env, napi_set_named_property(env, result, "code", eCode)); + NAPI_CALL(env, napi_set_named_property(env, result, "message", eMsg)); return result; } diff --git a/frameworks/src/bundle_state_query.cpp b/frameworks/src/bundle_state_query.cpp index 3506569558e11d6952d58bfe22a1793649c798ff..14778aa64d24995fe79d84bc70e15014207ac8bf 100644 --- a/frameworks/src/bundle_state_query.cpp +++ b/frameworks/src/bundle_state_query.cpp @@ -63,9 +63,9 @@ napi_value ParseIsIdleStateParameters(const napi_env &env, const napi_callback_i // argv[1]: callback if (argc == IS_IDLE_STATE_PARAMS) { - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, + napi_valuetype inputValueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[1], &inputValueType)); + NAPI_ASSERT(env, inputValueType == napi_function, "ParseIsIdleStateParameters invalid parameter type, function expected."); napi_create_reference(env, argv[1], 1, ¶ms.callback); } @@ -117,7 +117,7 @@ napi_value IsIdleState(napi_env env, napi_callback_info info) BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, - (void *)asyncCallbackInfo, + static_cast(asyncCallbackInfo), &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); if (callbackPtr->isCallback) { @@ -209,7 +209,7 @@ napi_value QueryAppUsagePriorityGroup(napi_env env, napi_callback_info info) BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, - (void *)asyncCallbackInfo, + static_cast(asyncCallbackInfo), &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); if (callbackPtr->isCallback) { @@ -317,11 +317,12 @@ napi_value QueryCurrentBundleActiveStates(napi_env env, napi_callback_info info) if (asyncCallbackInfo != nullptr) { napi_value result = nullptr; napi_create_array(env, &result); - BundleStateCommon::GetBundleActiveEventForResult(env, asyncCallbackInfo->BundleActiveState, result); + BundleStateCommon::GetBundleActiveEventForResult( + env, asyncCallbackInfo->BundleActiveState, result, false); BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, - (void *)asyncCallbackInfo, + static_cast(asyncCallbackInfo), &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); if (callbackPtr->isCallback) { @@ -383,11 +384,12 @@ napi_value QueryBundleActiveStates(napi_env env, napi_callback_info info) if (asyncCallbackInfo != nullptr) { napi_value result = nullptr; napi_create_array(env, &result); - BundleStateCommon::GetBundleActiveEventForResult(env, asyncCallbackInfo->BundleActiveState, result); + BundleStateCommon::GetBundleActiveEventForResult( + env, asyncCallbackInfo->BundleActiveState, result, false); BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, - (void *)asyncCallbackInfo, + static_cast(asyncCallbackInfo), &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); if (callbackPtr->isCallback) { @@ -514,7 +516,7 @@ napi_value QueryBundleStateInfoByInterval(napi_env env, napi_callback_info info) BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, - (void *)asyncCallbackInfo, + static_cast(asyncCallbackInfo), &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); if (callbackPtr->isCallback) { @@ -623,7 +625,7 @@ napi_value QueryBundleStateInfos(napi_env env, napi_callback_info info) BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, - (void *)asyncCallbackInfo, + static_cast(asyncCallbackInfo), &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); if (callbackPtr->isCallback) { diff --git a/frameworks/src/bundle_state_query_napi.cpp b/frameworks/src/bundle_state_query_napi.cpp index 9847228032634f460311a6992fdb0622dcc778f0..c44d6fde917800ed0030aa69b7caf71859a78ab8 100644 --- a/frameworks/src/bundle_state_query_napi.cpp +++ b/frameworks/src/bundle_state_query_napi.cpp @@ -139,7 +139,7 @@ napi_value QueryModuleUsageRecords(napi_env env, napi_callback_info info) BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, - (void *)asyncCallbackInfo, + static_cast(asyncCallbackInfo), &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); if (callbackPtr->isCallback) { @@ -183,9 +183,9 @@ napi_value ParseIsIdleStateParameters(const napi_env &env, const napi_callback_i // argv[1]: callback if (argc == IS_IDLE_STATE_PARAMS) { - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); - if (valuetype != napi_function) { + napi_valuetype inputValueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[1], &inputValueType)); + if (inputValueType != napi_function) { params.errorCode = ERR_CALL_BACK_TYPE; return BundleStateCommon::HandleParamErr(env, ERR_CALL_BACK_TYPE, ""); } @@ -229,7 +229,7 @@ napi_value IsIdleState(napi_env env, napi_callback_info info) BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, - (void *)asyncCallbackInfo, + static_cast(asyncCallbackInfo), &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); if (callbackPtr->isCallback) { @@ -331,11 +331,12 @@ napi_value QueryCurrentBundleEvents(napi_env env, napi_callback_info info) if (asyncCallbackInfo != nullptr) { napi_value result = nullptr; napi_create_array(env, &result); - BundleStateCommon::GetBundleActiveEventForResult(env, asyncCallbackInfo->BundleActiveState, result); + BundleStateCommon::GetBundleActiveEventForResult( + env, asyncCallbackInfo->BundleActiveState, result, true); BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, - (void *)asyncCallbackInfo, + static_cast(asyncCallbackInfo), &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); if (callbackPtr->isCallback) { @@ -386,11 +387,12 @@ napi_value QueryBundleEvents(napi_env env, napi_callback_info info) if (asyncCallbackInfo != nullptr) { napi_value result = nullptr; napi_create_array(env, &result); - BundleStateCommon::GetBundleActiveEventForResult(env, asyncCallbackInfo->BundleActiveState, result); + BundleStateCommon::GetBundleActiveEventForResult( + env, asyncCallbackInfo->BundleActiveState, result, true); BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, - (void *)asyncCallbackInfo, + static_cast(asyncCallbackInfo), &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); if (callbackPtr->isCallback) { @@ -506,7 +508,7 @@ napi_value QueryBundleStatsInfoByInterval(napi_env env, napi_callback_info info) BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, - (void *)asyncCallbackInfo, + static_cast(asyncCallbackInfo), &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); if (callbackPtr->isCallback) { @@ -608,7 +610,7 @@ napi_value QueryBundleStatsInfos(napi_env env, napi_callback_info info) BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, - (void *)asyncCallbackInfo, + static_cast(asyncCallbackInfo), &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); if (callbackPtr->isCallback) { @@ -711,7 +713,7 @@ napi_value QueryDeviceEventStats(napi_env env, napi_callback_info info) BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, - (void *)asyncCallbackInfo, + static_cast(asyncCallbackInfo), &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); if (callbackPtr->isCallback) { @@ -764,7 +766,7 @@ napi_value QueryNotificationEventStats(napi_env env, napi_callback_info info) BundleStateCommon::GetCallbackPromiseResult(env, *asyncCallbackInfo, result); } }, - (void *)asyncCallbackInfo, + static_cast(asyncCallbackInfo), &asyncCallbackInfo->asyncWork)); NAPI_CALL(env, napi_queue_async_work(env, callbackPtr->asyncWork)); if (callbackPtr->isCallback) { diff --git a/interfaces/innerkits/include/app_group_callback_proxy.h b/interfaces/innerkits/include/app_group_callback_proxy.h index 2dcc8bdf45155e95a01271f0a07ac9a6fbe96050..1de0867b717b766d2cbd2f094a71b72073cdc73b 100644 --- a/interfaces/innerkits/include/app_group_callback_proxy.h +++ b/interfaces/innerkits/include/app_group_callback_proxy.h @@ -29,14 +29,14 @@ namespace DeviceUsageStats { class BundleActiveGroupCallbackProxy : public IRemoteProxy { public: explicit BundleActiveGroupCallbackProxy(const sptr& impl); - virtual ~BundleActiveGroupCallbackProxy() override; + ~BundleActiveGroupCallbackProxy() override; DISALLOW_COPY_AND_MOVE(BundleActiveGroupCallbackProxy); /* * function: OnAppGroupChanged, bundleGroupChanged callback, IPC proxy, send message to stub. * parameters: AppGroupCallbackInfo * return: void. */ - virtual void OnAppGroupChanged( + void OnAppGroupChanged( const AppGroupCallbackInfo& appGroupCallbackInfo) override; private: diff --git a/interfaces/innerkits/include/app_group_callback_stub.h b/interfaces/innerkits/include/app_group_callback_stub.h index 96d90b7353edec6a7bdb464696d9b0efbcfd5a83..50272de6ee325cc4b35d2586bed9a15a9501b662 100644 --- a/interfaces/innerkits/include/app_group_callback_stub.h +++ b/interfaces/innerkits/include/app_group_callback_stub.h @@ -30,14 +30,14 @@ public: * parameters: code, data, reply, option * return: errorcode. */ - virtual int OnRemoteRequest( + int OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; /* * function: OnAppGroupChanged, bundleGroupChanged callback, handle message from proxy. * parameters: AppGroupCallbackInfo * return: void. */ - virtual void OnAppGroupChanged(const AppGroupCallbackInfo &appGroupCallbackInfo) override; + void OnAppGroupChanged(const AppGroupCallbackInfo &appGroupCallbackInfo) override; private: DISALLOW_COPY_AND_MOVE(AppGroupCallbackStub); }; diff --git a/interfaces/innerkits/src/bundle_active_client.cpp b/interfaces/innerkits/src/bundle_active_client.cpp index 89cecd61342e4e9679a8274acc654f929c0a453d..483e894825c898743c426e4f3c5d0b631c2513bc 100644 --- a/interfaces/innerkits/src/bundle_active_client.cpp +++ b/interfaces/innerkits/src/bundle_active_client.cpp @@ -231,13 +231,12 @@ void BundleActiveClient::BundleActiveClientDeathRecipient::OnRemoteDied(const wp BundleActiveClient::GetInstance().bundleActiveProxy_ = nullptr; BundleActiveClient::GetInstance().bundleClientHandler_->PostTask([this]() { this->OnServiceDiedInner(); - }, - DELAY_TIME); + }, DELAY_TIME); } void BundleActiveClient::BundleActiveClientDeathRecipient::OnServiceDiedInner() { - while (!BundleActiveClient::GetInstance().GetBundleActiveProxy()) { + while (BundleActiveClient::GetInstance().GetBundleActiveProxy() != ERR_OK) { sleep(SLEEP_TIME); } if (observer_) { @@ -245,5 +244,4 @@ void BundleActiveClient::BundleActiveClientDeathRecipient::OnServiceDiedInner() } } } // namespace DeviceUsageStats -} // namespace OHOS - +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/src/bundle_active_proxy.cpp b/interfaces/innerkits/src/bundle_active_proxy.cpp index ae545d58b34370578bd45be3503726d6254ddd07..4b01289dcce2a27653f725347754a4a8a3275348 100644 --- a/interfaces/innerkits/src/bundle_active_proxy.cpp +++ b/interfaces/innerkits/src/bundle_active_proxy.cpp @@ -134,7 +134,6 @@ ErrCode BundleActiveProxy::QueryBundleStatsInfos(std::vector result; if (!data.WriteInterfaceToken(GetDescriptor())) { return ERR_PARCEL_WRITE_FALIED; } @@ -204,7 +203,7 @@ ErrCode BundleActiveProxy::QueryAppGroup(int32_t& appGroup, std::string& bundleN if (!data.WriteInterfaceToken(GetDescriptor())) { return ERR_PARCEL_WRITE_FALIED; } - + data.WriteString(bundleName); data.WriteInt32(userId); Remote() -> SendRequest(QUERY_APP_GROUP, data, reply, option); diff --git a/interfaces/kits/bundlestats/napi/include/app_group_observer_napi.h b/interfaces/kits/bundlestats/napi/include/app_group_observer_napi.h index f895d67881442d85a1eb0a3b6b21862f5281f7bd..12aec41db5f334211cbc18110f0cff8b4ed5144d 100644 --- a/interfaces/kits/bundlestats/napi/include/app_group_observer_napi.h +++ b/interfaces/kits/bundlestats/napi/include/app_group_observer_napi.h @@ -23,14 +23,14 @@ namespace OHOS { namespace DeviceUsageStats { -static const int8_t NO_ERROR = 0; +const int8_t NO_ERROR = 0; class AppGroupObserver : public AppGroupCallbackStub { public: AppGroupObserver() =default; ~AppGroupObserver(); - virtual void OnAppGroupChanged(const AppGroupCallbackInfo &appGroupCallbackInfo) override; + void OnAppGroupChanged(const AppGroupCallbackInfo &appGroupCallbackInfo) override; void SetCallbackInfo(const napi_env &env, const napi_ref &ref); diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_common.h b/interfaces/kits/bundlestats/napi/include/bundle_state_common.h index ab56949e1d5e0204e9899e727559292d2d6e6761..56db22bd57b2807d0f118d9645d54fd8f5cfe2c9 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_common.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_common.h @@ -51,7 +51,7 @@ public: const napi_env &env, const napi_ref &callbackIn, const int32_t &errorCode, const napi_value &result); static void GetBundleActiveEventForResult( - napi_env env, const std::vector &BundleActiveState, napi_value result); + napi_env env, const std::vector &BundleActiveState, napi_value result, bool isNewVersion); static void GetBundleStateInfoByIntervalForResult( napi_env env, const std::vector &packageStats, napi_value result); diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_condition.h b/interfaces/kits/bundlestats/napi/include/bundle_state_condition.h index 86e099963729da54916538df4813ec0404d4eb94..b281135a04b7bcb1a17a5deeac06860171ce637d 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_condition.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_condition.h @@ -15,8 +15,6 @@ #ifndef FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_STATE_CONDITION_H #define FOUNDATION_RESOURCESCHEDULE_DEVICE_USAGE_STATISTICS_BUNDLE_STATE_CONDITION_H -#include - namespace OHOS { namespace DeviceUsageStats { class BundleStateCondition { diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_init.h b/interfaces/kits/bundlestats/napi/include/bundle_state_init.h index 8e65667bcfce6f98b9cc62e4a618ef0c9968bb8d..7e17950cbe6d32698084c67bd06c3aa6b19045c7 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_init.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_init.h @@ -26,10 +26,10 @@ extern "C" { #endif __attribute__((constructor)) void RegisterModule(void); -static napi_value BundleStateInit(napi_env env, napi_value exports); -static napi_value InitIntervalType(napi_env env, napi_value exports); -static napi_value InitGroupType(napi_env env, napi_value exports); -static napi_value EnumTypeConstructor(napi_env env, napi_callback_info info); +napi_value BundleStateInit(napi_env env, napi_value exports); +napi_value InitIntervalType(napi_env env, napi_value exports); +napi_value InitGroupType(napi_env env, napi_value exports); +napi_value EnumTypeConstructor(napi_env env, napi_callback_info info); #ifdef __cplusplus } @@ -44,7 +44,7 @@ napi_module _module = { .nm_filename = nullptr, .nm_register_func = BundleStateInit, .nm_modname = "bundleState", - .nm_priv = ((void *)0), + .nm_priv = (static_cast(0)), .reserved = {0} }; } // namespace DeviceUsageStats diff --git a/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h b/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h index a709d3cc01bbfd469489ce2585feb7fc96abad79..3e37a885d7b0cf4a8da03aad3a7a67067dc437d2 100644 --- a/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h +++ b/interfaces/kits/bundlestats/napi/include/bundle_state_inner_errors.h @@ -105,7 +105,7 @@ enum ServiceError { ERR_REPEAT_SET_APP_GROUP, }; -static std::map saErrCodeMsgMap = { +std::map saErrCodeMsgMap = { {ERR_PERMISSION_DENIED, "Permission denied."}, {ERR_MEMORY_OPERATION_FAILED, "Memory operation failed. create object failed."}, {ERR_PARCEL_WRITE_FALIED, "Parcel operation failed. Failed to write the parcel."}, @@ -133,7 +133,7 @@ static std::map saErrCodeMsgMap = { "Get application group info failed. The application group infomation cannot be found."}, }; -static std::map paramErrCodeMsgMap = { +std::map paramErrCodeMsgMap = { {ERR_PARAMETERS_NUMBER, " api interface parameters count is error."}, {ERR_PARAMETERS_EMPTY, " cannot be empty."}, {ERR_CALL_BACK_TYPE, " Callback type must be function."}, diff --git a/interfaces/kits/bundlestats/napi/include/usage_statistics_init.h b/interfaces/kits/bundlestats/napi/include/usage_statistics_init.h index 10b8458536881a19f7123435f44c48c4f021585c..4d1ae2c274f245d207b7d1a994af3b214d2a7170 100644 --- a/interfaces/kits/bundlestats/napi/include/usage_statistics_init.h +++ b/interfaces/kits/bundlestats/napi/include/usage_statistics_init.h @@ -26,10 +26,10 @@ extern "C" { #endif __attribute__((constructor)) void RegisterModule(void); -static napi_value UsageStatisticsInit(napi_env env, napi_value exports); -static napi_value InitAppGroupType(napi_env env, napi_value exports); -static napi_value InitIntervalType(napi_env env, napi_value exports); -static napi_value EnumTypeConstructor(napi_env env, napi_callback_info info); +napi_value UsageStatisticsInit(napi_env env, napi_value exports); +napi_value InitAppGroupType(napi_env env, napi_value exports); +napi_value InitIntervalType(napi_env env, napi_value exports); +napi_value EnumTypeConstructor(napi_env env, napi_callback_info info); #ifdef __cplusplus @@ -45,7 +45,7 @@ napi_module _usageStatisticsModule = { .nm_filename = nullptr, .nm_register_func = UsageStatisticsInit, .nm_modname = "resourcescheduler.usageStatistics", - .nm_priv = ((void *)0), + .nm_priv = (static_cast(0)), .reserved = {0} }; } // namespace DeviceUsageStats diff --git a/interfaces/test/unittest/device_usage_statistics_jsunittest/config.json b/interfaces/test/unittest/device_usage_statistics_jsunittest/config.json index 349b7219b5002f497f8722a28aae41cafaad3f0a..f8dc60aaa6d6ca7611d842bf34cfc5bcac9bb02c 100644 --- a/interfaces/test/unittest/device_usage_statistics_jsunittest/config.json +++ b/interfaces/test/unittest/device_usage_statistics_jsunittest/config.json @@ -16,6 +16,7 @@ "package": "com.example.deviceUsageStatistics", "name": ".MyApplication", "deviceType": [ + "tablet", "default", "phone" ], @@ -72,4 +73,4 @@ ] } } - \ 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 fac99b86225bb8ecdf1ef62ee71948eb8b6b188d..d9bc3b745bcdc6662a1ba5abd4457debcd2557c1 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_account_helper.h b/services/common/include/bundle_active_account_helper.h index cf7d3111c25204362df97d21c5645dd5ec7bf01c..b304aed368cdc36e9809f58ed776cea2c09e288e 100644 --- a/services/common/include/bundle_active_account_helper.h +++ b/services/common/include/bundle_active_account_helper.h @@ -16,8 +16,6 @@ #ifndef BUNDLE_ACTIVE_ACCOUNT_HELPER_H #define BUNDLE_ACTIVE_ACCOUNT_HELPER_H -#include - #include "errors.h" #ifdef OS_ACCOUNT_PART_ENABLED #include "os_account_manager.h" diff --git a/services/common/include/bundle_active_continuous_task_observer.h b/services/common/include/bundle_active_continuous_task_observer.h index 4da128846f6b1d641bbcd2eae28db1d3ba51e769..ca7f97ebab0a2d5eb385a6fe596e575ad63e9c78 100644 --- a/services/common/include/bundle_active_continuous_task_observer.h +++ b/services/common/include/bundle_active_continuous_task_observer.h @@ -33,11 +33,11 @@ namespace DeviceUsageStats { class BundleActiveContinuousTaskObserver : public OHOS::BackgroundTaskMgr::BackgroundTaskSubscriber { public: using IBundleMgr = OHOS::AppExecFwk::IBundleMgr; - virtual void OnContinuousTaskStart(const std::shared_ptr + void OnContinuousTaskStart(const std::shared_ptr &continuousTaskCallbackInfo) override; - virtual void OnContinuousTaskStop(const std::shared_ptr + void OnContinuousTaskStop(const std::shared_ptr &continuousTaskCallbackInfo) override; - virtual void OnRemoteDied(const wptr &object) override; + void OnRemoteDied(const wptr &object) override; void Init(const std::shared_ptr& reportHandler); std::atomic isRemoteDied_ {false}; private: diff --git a/services/common/include/bundle_active_log.h b/services/common/include/bundle_active_log.h index 68f5282b1f3b2f251653d70110f42b475c0c40a4..046bb00de93b9f1fc006abc5349b423f35427fe3 100644 --- a/services/common/include/bundle_active_log.h +++ b/services/common/include/bundle_active_log.h @@ -29,7 +29,7 @@ namespace DeviceUsageStats { #define LOG_TAG_BUNDLE_ACTIVE "BUNDLE_ACTIVE" #endif -static constexpr OHOS::HiviewDFX::HiLogLabel BUNDLE_ACTIVE_LOG_LABEL = { +constexpr OHOS::HiviewDFX::HiLogLabel BUNDLE_ACTIVE_LOG_LABEL = { LOG_CORE, LOG_TAG_DOMAIN_ID_BUNDLE_ACTIVE, LOG_TAG_BUNDLE_ACTIVE diff --git a/services/common/include/bundle_active_service.h b/services/common/include/bundle_active_service.h index f2ff1e855d6cb0b591dd121729748ab8edda7a5b..f0e5dd3ae85139266363bca54018ceb7eaac1c63 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" @@ -227,6 +228,7 @@ private: ErrCode CheckBundleIsSystemAppAndHasPermission(const int32_t uid, OHOS::Security::AccessToken::AccessTokenID tokenId); ErrCode CheckSystemAppOrNativePermission(const int32_t uid, OHOS::Security::AccessToken::AccessTokenID tokenId); + ErrCode CheckNativePermission(OHOS::Security::AccessToken::AccessTokenID tokenId); void InitAppStateSubscriber(const std::shared_ptr& reportHandler); void InitContinuousSubscriber(const std::shared_ptr& reportHandler); bool SubscribeAppState(); diff --git a/services/common/src/bundle_active_continuous_task_observer.cpp b/services/common/src/bundle_active_continuous_task_observer.cpp index 6bfb491c3f43b9f58c1d9323b5de28e46343eab2..403ba82bdc6cea499bd01833820554d155194d6d 100644 --- a/services/common/src/bundle_active_continuous_task_observer.cpp +++ b/services/common/src/bundle_active_continuous_task_observer.cpp @@ -64,8 +64,13 @@ bool BundleActiveContinuousTaskObserver::GetBundleMgr() return false; } bundleMgr_ = iface_cast(remoteObject); - if ((!bundleMgr_) || (!bundleMgr_->AsObject())) { - BUNDLE_ACTIVE_LOGE("Failed to get system bundle manager services ability"); + if (!bundleMgr_) { + BUNDLE_ACTIVE_LOGE("Failed to get system bundle manager services ability, bundleMgr_"); + return false; + } + auto object = bundleMgr_->AsObject(); + if (!object) { + BUNDLE_ACTIVE_LOGE("Failed to get system bundle manager services ability, bundleMgr_->AsObject()"); return false; } } diff --git a/services/common/src/bundle_active_core.cpp b/services/common/src/bundle_active_core.cpp index d872af43706f8288c74a93ed949db98793b1fd5c..748ac9ee081ab5fad67235a3e85ac7236403c264 100644 --- a/services/common/src/bundle_active_core.cpp +++ b/services/common/src/bundle_active_core.cpp @@ -225,9 +225,6 @@ std::shared_ptr BundleActiveCore::GetUserDataAndInitial BUNDLE_ACTIVE_LOGI("first initialize user service"); std::shared_ptr service = std::make_shared(userId, *this, debug); - if (service == nullptr) { - return nullptr; - } service->Init(timeStamp); userStatServices_[userId] = service; BUNDLE_ACTIVE_LOGI("service is not null"); @@ -241,7 +238,7 @@ void BundleActiveCore::OnBundleUninstalled(const int32_t userId, const std::stri BUNDLE_ACTIVE_LOGD("OnBundleUninstalled CALLED"); std::lock_guard lock(mutex_); int64_t timeNow = CheckTimeChangeAndGetWallTime(userId); - if (timeNow == -1) { + if (timeNow == ERR_TIME_OPERATION_FAILED) { return; } auto service = GetUserDataAndInitializeIfNeeded(userId, timeNow, debugCore_); @@ -269,8 +266,8 @@ void BundleActiveCore::OnStatsChanged(const int32_t userId) void BundleActiveCore::RestoreAllData() { - for (auto it = userStatServices_.begin(); it != userStatServices_.end(); ++it) { - std::shared_ptr service = it->second; + for (const auto& it : userStatServices_) { + std::shared_ptr service = it.second; if (service == nullptr) { BUNDLE_ACTIVE_LOGI("service in BundleActiveCore::RestoreToDatabaseLocked() is null"); return; @@ -278,7 +275,7 @@ void BundleActiveCore::RestoreAllData() BUNDLE_ACTIVE_LOGI("userid is %{public}d ", service->userId_); service->RestoreStats(true); if (bundleGroupController_ != nullptr && bundleGroupController_->bundleUserHistory_ != nullptr) { - bundleGroupController_->RestoreToDatabase(it->first); + bundleGroupController_->RestoreToDatabase(it.first); } } if (bundleGroupController_ != nullptr) { @@ -483,7 +480,7 @@ int32_t BundleActiveCore::ReportEvent(BundleActiveEvent& event, int32_t userId) "eventid %{public}d, in lock range", event.bundleName_.c_str(), (long long)event.timeStamp_, userId, event.eventId_); int64_t timeNow = CheckTimeChangeAndGetWallTime(userId); - if (timeNow == -1) { + if (timeNow == ERR_TIME_OPERATION_FAILED) { return -1; } ConvertToSystemTimeLocked(event); @@ -527,15 +524,15 @@ int32_t BundleActiveCore::ReportEventToAllUserId(BundleActiveEvent& event) { BUNDLE_ACTIVE_LOGD("ReportEventToAllUserId called"); int64_t timeNow = CheckTimeChangeAndGetWallTime(); - if (timeNow == -1) { + if (timeNow == ERR_TIME_OPERATION_FAILED) { return -1; } if (userStatServices_.empty()) { return DEFAULT_USER_ID; } - for (auto it = userStatServices_.begin(); it != userStatServices_.end(); ++it) { + for (const auto& it : userStatServices_) { ConvertToSystemTimeLocked(event); - std::shared_ptr service = GetUserDataAndInitializeIfNeeded(it->first, timeNow, + std::shared_ptr service = GetUserDataAndInitializeIfNeeded(it.first, timeNow, debugCore_); if (service == nullptr) { BUNDLE_ACTIVE_LOGE("get user data service failed!"); @@ -753,36 +750,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 +809,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_power_state_callback_stub.cpp b/services/common/src/bundle_active_power_state_callback_stub.cpp index 6ec2ff17d6e6023fdb831ce91634e797685f33a2..7d344d2fc5feedefebf5f89a6154189728d004dc 100644 --- a/services/common/src/bundle_active_power_state_callback_stub.cpp +++ b/services/common/src/bundle_active_power_state_callback_stub.cpp @@ -23,7 +23,7 @@ int32_t BundleActivePowerStateCallbackStub::OnRemoteRequest(uint32_t code, Messa { std::u16string descriptor = BundleActivePowerStateCallbackStub::GetDescriptor(); std::u16string remoteDescriptor = data.ReadInterfaceToken(); - PowerMgr::PowerState state = (PowerMgr::PowerState)data.ReadInt32(); + PowerMgr::PowerState state = static_cast(data.ReadInt32()); if (descriptor != remoteDescriptor) { BUNDLE_ACTIVE_LOGE("BundleActivePowerStateCallbackStub::OnRemoteRequest cannot get power mgr service"); return -1; diff --git a/services/common/src/bundle_active_service.cpp b/services/common/src/bundle_active_service.cpp index 1b8ff5ce871496da7f762059714ac6e8e3a646ce..393d9f879cd4926a3e5bd3e1b3671f8a4e4db284 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" @@ -36,7 +35,6 @@ static const std::string PERMITTED_PROCESS_NAME = "foundation"; static const int32_t MAXNUM_UP_LIMIT = 1000; const int32_t EVENTS_PARAM = 5; static constexpr int32_t NO_DUMP_PARAM_NUMS = 0; -static constexpr int32_t MIN_DUMP_PARAM_NUMS = 1; const int32_t PACKAGE_USAGE_PARAM = 6; const int32_t MODULE_USAGE_PARAM = 4; const std::string NEEDED_PERMISSION = "ohos.permission.BUNDLE_ACTIVE_INFO"; @@ -74,31 +72,36 @@ void BundleActiveService::OnStart() void BundleActiveService::InitNecessaryState() { + std::set serviceIdSets{ + APP_MGR_SERVICE_ID, BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, POWER_MANAGER_SERVICE_ID, COMMON_EVENT_SERVICE_ID, + BACKGROUND_TASK_MANAGER_SERVICE_ID, TIME_SERVICE_ID, + }; sptr systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (systemAbilityManager == nullptr - || systemAbilityManager->CheckSystemAbility(APP_MGR_SERVICE_ID) == nullptr - || systemAbilityManager->CheckSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID) == nullptr - || systemAbilityManager->CheckSystemAbility(POWER_MANAGER_SERVICE_ID) == nullptr - || systemAbilityManager->CheckSystemAbility(COMMON_EVENT_SERVICE_ID) == nullptr - || systemAbilityManager->CheckSystemAbility(BACKGROUND_TASK_MANAGER_SERVICE_ID) == nullptr - || systemAbilityManager->CheckSystemAbility(TIME_SERVICE_ID) == nullptr) { - BUNDLE_ACTIVE_LOGI("request system service is not ready yet!"); + if (systemAbilityManager == nullptr) { + BUNDLE_ACTIVE_LOGI("GetSystemAbilityManager fail!"); auto task = [this]() { this->InitNecessaryState(); }; handler_->PostTask(task, DELAY_TIME); return; } + for (const auto& serviceItem : serviceIdSets) { + auto checkResult = systemAbilityManager->CheckSystemAbility(serviceItem); + if (!checkResult) { + BUNDLE_ACTIVE_LOGI("request system service is not ready yet!"); + auto task = [this]() { this->InitNecessaryState(); }; + handler_->PostTask(task, DELAY_TIME); + return; + } + } - if (systemAbilityManager->GetSystemAbility(APP_MGR_SERVICE_ID) == nullptr - || systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID) == nullptr - || systemAbilityManager->GetSystemAbility(POWER_MANAGER_SERVICE_ID) == nullptr - || systemAbilityManager->GetSystemAbility(COMMON_EVENT_SERVICE_ID) == nullptr - || systemAbilityManager->GetSystemAbility(BACKGROUND_TASK_MANAGER_SERVICE_ID) == nullptr - || systemAbilityManager->GetSystemAbility(TIME_SERVICE_ID) == nullptr) { - BUNDLE_ACTIVE_LOGI("request system service object is not ready yet!"); - auto task = [this]() { this->InitNecessaryState(); }; - handler_->PostTask(task, DELAY_TIME); - return; + for (const auto& serviceItem : serviceIdSets) { + auto getAbility = systemAbilityManager->GetSystemAbility(serviceItem); + if (!getAbility) { + BUNDLE_ACTIVE_LOGI("request system service object is not ready yet!"); + auto task = [this]() { this->InitNecessaryState(); }; + handler_->PostTask(task, DELAY_TIME); + return; + } } InitService(); ready_ = true; @@ -203,8 +206,8 @@ bool BundleActiveService::SubscribeContinuousTask() BUNDLE_ACTIVE_LOGE("SubscribeContinuousTask continuousTaskObserver_ is null, return"); return false; } - if (OHOS::BackgroundTaskMgr::BackgroundTaskMgrHelper::SubscribeBackgroundTask(*continuousTaskObserver_) - != OHOS::ERR_OK) { + ErrCode errCode = BackgroundTaskMgr::BackgroundTaskMgrHelper::SubscribeBackgroundTask(*continuousTaskObserver_); + if (errCode != ERR_OK) { BUNDLE_ACTIVE_LOGE("SubscribeBackgroundTask failed."); return false; } @@ -227,7 +230,7 @@ void BundleActiveService::OnStop() ErrCode BundleActiveService::ReportEvent(BundleActiveEvent& event, const int32_t userId) { AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); - if ((AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId) == AccessToken::TypeATokenTypeEnum::TOKEN_NATIVE)) { + if (CheckNativePermission(tokenId) == ERR_OK) { AccessToken::NativeTokenInfo callingTokenInfo; AccessToken::AccessTokenKit::GetNativeTokenInfo(tokenId, callingTokenInfo); int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); @@ -260,7 +263,7 @@ ErrCode BundleActiveService::IsBundleIdle(bool& isBundleIdle, const std::string& AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); ErrCode ret = GetBundleMgrProxy(); if (ret != ERR_OK) { - BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack Get bundle manager proxy failed!"); + BUNDLE_ACTIVE_LOGE("IsBundleIdle Get bundle manager proxy failed!"); return ret; } std::string callingBundleName = ""; @@ -320,7 +323,6 @@ ErrCode BundleActiveService::QueryBundleStatsInfoByInterval(std::vector& bundleActiveEvents, const int64_t beginTime, const int64_t endTime, int32_t userId) { - std::vector result; ErrCode ret = ERR_OK; int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); @@ -334,35 +336,37 @@ ErrCode BundleActiveService::QueryBundleEvents(std::vector& b ret = CheckSystemAppOrNativePermission(callingUid, tokenId); if (ret == ERR_OK) { ret = bundleActiveCore_->QueryBundleEvents(bundleActiveEvents, userId, beginTime, endTime, ""); - BUNDLE_ACTIVE_LOGI("QueryBundleEvents result is %{public}zu", result.size()); + BUNDLE_ACTIVE_LOGI("QueryBundleEvents result is %{public}zu", bundleActiveEvents.size()); } return ret; } ErrCode BundleActiveService::SetAppGroup(const std::string& bundleName, int32_t newGroup, int32_t userId) { - ErrCode ret = GetBundleMgrProxy(); + ErrCode ret = ERR_OK; + int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); + bool isFlush = false; + if (userId == -1) { + ret = BundleActiveAccountHelper::GetUserId(callingUid, userId); + if (ret != ERR_OK || userId == -1) { + return ERR_SYSTEM_ABILITY_SUPPORT_FAILED; + } + isFlush = true; + } + BUNDLE_ACTIVE_LOGI("SetAppGroup userId is %{public}d", userId); + + ret = GetBundleMgrProxy(); if (ret != ERR_OK) { - BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack Get bundle manager proxy failed!"); + BUNDLE_ACTIVE_LOGE("SetAppGroup Get bundle manager proxy failed!"); return ret; } std::string localBundleName = ""; - int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid(); sptrBundleMgr_->GetBundleNameForUid(callingUid, localBundleName); if (localBundleName == bundleName) { BUNDLE_ACTIVE_LOGI("SetAppGroup can not set its bundleName"); return ERR_PERMISSION_DENIED; } AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); - bool isFlush = false; - if (userId == -1) { - ret = BundleActiveAccountHelper::GetUserId(callingUid, userId); - if (ret != ERR_OK || userId == -1) { - return ERR_SYSTEM_ABILITY_SUPPORT_FAILED; - } - isFlush = true; - } - BUNDLE_ACTIVE_LOGI("SetAppGroup userid is %{public}d", userId); ret = CheckSystemAppOrNativePermission(callingUid, tokenId); if (ret == ERR_OK) { ret = bundleActiveCore_->SetAppGroup(bundleName, newGroup, userId, isFlush); @@ -441,7 +445,7 @@ ErrCode BundleActiveService::QueryAppGroup(int32_t& appGroup, std::string& bundl if (bundleName.empty()) { ret = GetBundleMgrProxy(); if (ret != ERR_OK) { - BUNDLE_ACTIVE_LOGE("Get bundle manager proxy failed!"); + BUNDLE_ACTIVE_LOGE("QueryAppGroup Get bundle manager proxy failed!"); return ret; } std::string localBundleName = ""; @@ -501,8 +505,13 @@ ErrCode BundleActiveService::GetBundleMgrProxy() return ERR_GET_SYSTEM_ABILITY_FAILED; } sptrBundleMgr_ = iface_cast(remoteObject); - if ((!sptrBundleMgr_) || (!sptrBundleMgr_->AsObject())) { - BUNDLE_ACTIVE_LOGE("Failed to get system bundle manager services ability"); + if (!sptrBundleMgr_) { + BUNDLE_ACTIVE_LOGE("Failed to get system bundle manager services ability, sptrBundleMgr_"); + return ERR_REMOTE_OBJECT_IF_CAST_FAILED; + } + auto object = sptrBundleMgr_->AsObject(); + if (!object) { + BUNDLE_ACTIVE_LOGE("Failed to get system bundle manager services ability, sptrBundleMgr_->AsObject()"); return ERR_REMOTE_OBJECT_IF_CAST_FAILED; } } @@ -524,7 +533,7 @@ ErrCode BundleActiveService::CheckBundleIsSystemAppAndHasPermission(const int32_ { ErrCode errCode = GetBundleMgrProxy(); if (errCode != ERR_OK) { - BUNDLE_ACTIVE_LOGE("RegisterGroupCallBack Get bundle manager proxy failed!"); + BUNDLE_ACTIVE_LOGE("CheckBundleIsSystemAppAndHasPermission Get bundle manager proxy failed!"); return errCode; } std::string bundleName = ""; @@ -539,12 +548,8 @@ ErrCode BundleActiveService::CheckBundleIsSystemAppAndHasPermission(const int32_ return ERR_OK; } -ErrCode BundleActiveService::CheckSystemAppOrNativePermission(const int32_t uid, - OHOS::Security::AccessToken::AccessTokenID tokenId) +ErrCode BundleActiveService::CheckNativePermission(OHOS::Security::AccessToken::AccessTokenID tokenId) { - if (CheckBundleIsSystemAppAndHasPermission(uid, tokenId) == ERR_OK) { - return ERR_OK; - } auto tokenFlag = AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId); if (tokenFlag == AccessToken::TypeATokenTypeEnum::TOKEN_NATIVE) { return ERR_OK; @@ -555,13 +560,22 @@ ErrCode BundleActiveService::CheckSystemAppOrNativePermission(const int32_t uid, return ERR_PERMISSION_DENIED; } +ErrCode BundleActiveService::CheckSystemAppOrNativePermission(const int32_t uid, + OHOS::Security::AccessToken::AccessTokenID tokenId) +{ + if (CheckBundleIsSystemAppAndHasPermission(uid, tokenId) == ERR_OK) { + return ERR_OK; + } + return CheckNativePermission(tokenId); +} + ErrCode BundleActiveService::QueryModuleUsageRecords(int32_t maxNum, std::vector& results, int32_t userId) { 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,18 +641,21 @@ ErrCode BundleActiveService::QueryNotificationEventStats(int64_t beginTime, int6 void BundleActiveService::QueryModuleRecordInfos(BundleActiveModuleRecord& moduleRecord) { - if (!GetBundleMgrProxy()) { + ErrCode errCode = GetBundleMgrProxy(); + if (errCode != ERR_OK) { return; } ApplicationInfo appInfo; - if (!sptrBundleMgr_->GetApplicationInfo(moduleRecord.bundleName_, ApplicationFlag::GET_BASIC_APPLICATION_INFO, - moduleRecord.userId_, appInfo)) { + bool getInfoIsSuccess = sptrBundleMgr_->GetApplicationInfo(moduleRecord.bundleName_, + ApplicationFlag::GET_BASIC_APPLICATION_INFO, moduleRecord.userId_, appInfo); + if (!getInfoIsSuccess) { BUNDLE_ACTIVE_LOGE("GetApplicationInfo failed!"); return; } BundleInfo bundleInfo; - if (!sptrBundleMgr_->GetBundleInfo(moduleRecord.bundleName_, BundleFlag::GET_BUNDLE_WITH_EXTENSION_INFO, - bundleInfo, moduleRecord.userId_)) { + getInfoIsSuccess = sptrBundleMgr_->GetBundleInfo(moduleRecord.bundleName_, + BundleFlag::GET_BUNDLE_WITH_EXTENSION_INFO, bundleInfo, moduleRecord.userId_); + if (!getInfoIsSuccess) { BUNDLE_ACTIVE_LOGE("GetBundleInfo failed!"); return; } @@ -682,7 +699,7 @@ int32_t BundleActiveService::Dump(int32_t fd, const std::vector int32_t ret = ERR_OK; if (argsInStr.size() == NO_DUMP_PARAM_NUMS) { DumpUsage(result); - } else if (argsInStr.size() >= MIN_DUMP_PARAM_NUMS) { + } else { std::vector infos; if (argsInStr[0] == "-h") { DumpUsage(result); diff --git a/services/common/src/bundle_active_stub.cpp b/services/common/src/bundle_active_stub.cpp index 5391fb44fb5923e700a57a795cc60fdcb4d35083..0408f068aa6cbb8bec5273c7ebf76c155cb142c5 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/common/src/bundle_active_usage_database.cpp b/services/common/src/bundle_active_usage_database.cpp index ce3d393a8cd5154141dc173b7dce726511b0c49b..d739e91916d44b7353cf69d7b8f951e3f5b11292 100644 --- a/services/common/src/bundle_active_usage_database.cpp +++ b/services/common/src/bundle_active_usage_database.cpp @@ -237,12 +237,12 @@ void BundleActiveUsageDatabase::HandleTableInfo(uint32_t databaseType) } int32_t tableNameIndex; bundleActiveResult->GetColumnIndex(SQLITE_MASTER_NAME, tableNameIndex); - string tableName; if (databaseType >= 0 && databaseType < sortedTableArray_.size()) { if (!sortedTableArray_.at(databaseType).empty()) { sortedTableArray_.at(databaseType).clear(); } for (int32_t i = 0; i < tableNumber; i++) { + string tableName; bundleActiveResult->GoToRow(i); bundleActiveResult->GetString(tableNameIndex, tableName); sortedTableArray_.at(databaseType).push_back(ParseStartTime(tableName)); @@ -434,9 +434,8 @@ shared_ptr BundleActiveUsageDatabase::GetBundleActiveRdbSto void BundleActiveUsageDatabase::CheckDatabaseFile(uint32_t databaseType) { std::string databaseFileName = databaseFiles_.at(databaseType); - std::string dbFile; for (uint32_t i = 0; i < sizeof(SUFFIX_TYPE) / sizeof(SUFFIX_TYPE[0]); i++) { - dbFile = BUNDLE_ACTIVE_DATABASE_DIR + DATABASE_TYPE[databaseType] + SUFFIX_TYPE[i]; + std::string dbFile = BUNDLE_ACTIVE_DATABASE_DIR + DATABASE_TYPE[databaseType] + SUFFIX_TYPE[i]; if ((access(dbFile.c_str(), F_OK) != 0) && (bundleActiveRdbStoreCache_.find(databaseFileName) != bundleActiveRdbStoreCache_.end())) { bundleActiveRdbStoreCache_.erase(databaseFileName); @@ -1123,7 +1122,7 @@ void BundleActiveUsageDatabase::RemoveOldData(int64_t currentTime) } } -void BundleActiveUsageDatabase::RenewTableTime(int64_t changedTime) +void BundleActiveUsageDatabase::RenewTableTime(int64_t timeDiffMillis) { lock_guard lock(databaseMutex_); for (uint32_t i = 0; i < sortedTableArray_.size(); i++) { @@ -1132,7 +1131,7 @@ void BundleActiveUsageDatabase::RenewTableTime(int64_t changedTime) } vector tableArray = sortedTableArray_.at(i); for (uint32_t j = 0; j < tableArray.size(); j++) { - int64_t newTime = tableArray.at(j) + changedTime; + int64_t newTime = tableArray.at(j) + timeDiffMillis; BUNDLE_ACTIVE_LOGI("new table time is %{public}lld", (long long)newTime); if (newTime < 0) { DeleteInvalidTable(i, tableArray.at(j)); @@ -1146,7 +1145,7 @@ void BundleActiveUsageDatabase::RenewTableTime(int64_t changedTime) } if (eventTableName_ != UNKNOWN_TABLE_NAME) { int64_t oldTime = ParseStartTime(eventTableName_); - int64_t newTime = oldTime + changedTime; + int64_t newTime = oldTime + timeDiffMillis; if (newTime < 0) { int32_t deletedResult = DeleteInvalidTable(EVENT_DATABASE_INDEX, oldTime); if (deletedResult == BUNDLE_ACTIVE_SUCCESS) { @@ -1161,7 +1160,7 @@ void BundleActiveUsageDatabase::RenewTableTime(int64_t changedTime) } if (formRecordsTableName_ != UNKNOWN_TABLE_NAME && moduleRecordsTableName_ != UNKNOWN_TABLE_NAME) { int64_t oldTime = ParseStartTime(moduleRecordsTableName_); - int64_t newTime = oldTime + changedTime; + int64_t newTime = oldTime + timeDiffMillis; int32_t renamedResult = RenameTableName(APP_GROUP_DATABASE_INDEX, oldTime, newTime); if (renamedResult == BUNDLE_ACTIVE_SUCCESS) { moduleRecordsTableName_ = MODULE_RECORD_LOG_TABLE + to_string(newTime); @@ -1511,8 +1510,8 @@ void BundleActiveUsageDatabase::RemoveFormData(const int32_t userId, const std:: return; } int32_t deletedRows = BUNDLE_ACTIVE_FAIL; - vector queryCondition; if (formRecordsTableName_ != UNKNOWN_TABLE_NAME) { + vector queryCondition; queryCondition.emplace_back(to_string(userId)); queryCondition.emplace_back(bundleName); queryCondition.emplace_back(moduleName); diff --git a/services/packagegroup/include/bundle_active_group_controller.h b/services/packagegroup/include/bundle_active_group_controller.h index dbbd6db3be030c19310f05af454ac4553a5b21a7..f3da15696c7e659a4914473b89d8d40f60b063fc 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 aceddcdeb38126eabb89161e7b3806fb19e18d60..888f08ea014509b2c70c25ef1769dce33e9eb4cf 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() @@ -121,7 +129,12 @@ bool BundleActiveGroupController::GetBundleMgrProxy() return false; } sptrBundleMgr_ = iface_cast(remoteObject); - if ((!sptrBundleMgr_) || (!sptrBundleMgr_->AsObject())) { + if (!sptrBundleMgr_) { + BUNDLE_ACTIVE_LOGE("Failed to get system bundle manager services ability, sptrBundleMgr_"); + return false; + } + auto object = sptrBundleMgr_->AsObject(); + if (!object) { BUNDLE_ACTIVE_LOGE("Failed to get system bundle manager services ability"); return false; } @@ -195,26 +208,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 +220,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, @@ -374,8 +363,12 @@ ErrCode BundleActiveGroupController::QueryAppGroup(int32_t& appGroup, bool BundleActiveGroupController::IsBundleInstalled(const std::string& bundleName, const int32_t userId) { ApplicationInfo bundleInfo; - if (sptrBundleMgr_ != nullptr && sptrBundleMgr_->GetApplicationInfo( - bundleName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, bundleInfo) == false) { + if (!sptrBundleMgr_) { + return false; + } + bool getInfoIsSuccess = sptrBundleMgr_->GetApplicationInfo(bundleName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, + userId, bundleInfo); + if (getInfoIsSuccess == false) { BUNDLE_ACTIVE_LOGE("IsBundleInstalled bundle is not installed!"); return false; } diff --git a/services/packagegroup/src/bundle_active_group_handler.cpp b/services/packagegroup/src/bundle_active_group_handler.cpp index 6c6ec4290f260fcb62d3dfbca1fda5dad7067b60..fd897f75afe9a172c5c6b1eacf3b7db16c067aba 100644 --- a/services/packagegroup/src/bundle_active_group_handler.cpp +++ b/services/packagegroup/src/bundle_active_group_handler.cpp @@ -75,13 +75,13 @@ void BundleActiveGroupHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointe BUNDLE_ACTIVE_LOGI("query activated account failed"); return; } + if (activatedOsAccountIds.size() == 0) { + return; + } #else // OS_ACCOUNT_PART_ENABLED activatedOsAccountIds.push_back(DEFAULT_OS_ACCOUNT_ID); BUNDLE_ACTIVE_LOGI("os account part not enabled, use default id."); #endif // OS_ACCOUNT_PART_ENABLED - if (activatedOsAccountIds.size() == 0) { - return; - } for (uint32_t i = 0; i < activatedOsAccountIds.size(); i++) { bundleActiveGroupController_->CheckEachBundleState(activatedOsAccountIds[i]); bundleActiveGroupController_->RestoreToDatabase(activatedOsAccountIds[i]); diff --git a/services/packagegroup/src/bundle_active_user_history.cpp b/services/packagegroup/src/bundle_active_user_history.cpp index cb117822068262644197f4fed427c7cc032d265b..27922ae7120b3461e135683432cefb347efdaa4e 100644 --- a/services/packagegroup/src/bundle_active_user_history.cpp +++ b/services/packagegroup/src/bundle_active_user_history.cpp @@ -214,16 +214,16 @@ int32_t BundleActiveUserHistory::SetAppGroup(const string& bundleName, const int bundleName.c_str(), newGroup, groupReason, userId); shared_ptr>> userBundleHistory = GetUserHistory(userId, false); if (!userBundleHistory) { - return -1; + return ERR_GET_BUNDLE_USED_HISTORY_FAILED; } shared_ptr oneBundleHistory = GetUsageHistoryInUserHistory(userBundleHistory, bundleName, bootBasedTimeStamp, false); if (!oneBundleHistory) { - return -1; + return ERR_GET_BUNDLE_USED_HISTORY_FAILED; } if (oneBundleHistory->currentGroup_ == newGroup && oneBundleHistory->reasonInGroup_ == groupReason) { BUNDLE_ACTIVE_LOGI("%{public}s group and reason is same as before, not update", bundleName.c_str()); - return 1; + return ERR_REPEAT_SET_APP_GROUP; } int32_t oldGroup = oneBundleHistory->currentGroup_; oneBundleHistory->currentGroup_ = newGroup; @@ -242,7 +242,7 @@ int32_t BundleActiveUserHistory::SetAppGroup(const string& bundleName, const int bundleActiveCore_.lock()->OnAppGroupChanged(callbackInfo); } } - return 0; + return ERR_OK; } void BundleActiveUserHistory::UpdateBootBasedAndScreenTime(const bool& isScreenOn, const int64_t bootBasedTimeStamp, diff --git a/services/packageusage/include/bundle_active_calendar.h b/services/packageusage/include/bundle_active_calendar.h index 41230b14395405bb8141e4b250df72885d23652f..5f9aefe2389314ae6e0f4ecbf1a850e1683bf0fd 100644 --- a/services/packageusage/include/bundle_active_calendar.h +++ b/services/packageusage/include/bundle_active_calendar.h @@ -16,7 +16,7 @@ #ifndef BUNDLE_ACTIVE_CALENDER_H #define BUNDLE_ACTIVE_CALENDER_H -#include +#include #include "bundle_active_constant.h" diff --git a/services/packageusage/include/bundle_active_event_stats.h b/services/packageusage/include/bundle_active_event_stats.h index 5b632398ca7ec664e23ced93f89e08eac76c6dda..a9b4949b50b23065cce3f4459b5f9cbf0e835b03 100644 --- a/services/packageusage/include/bundle_active_event_stats.h +++ b/services/packageusage/include/bundle_active_event_stats.h @@ -83,7 +83,7 @@ public: * parameters: parcel * return: result of mashalling, true means successful, flase means failed. */ - virtual bool Marshalling(Parcel &parcel) const override; + bool Marshalling(Parcel &parcel) const override; /* * function: UnMarshalling, Unmashalling event stats object from parcel. diff --git a/services/packageusage/include/bundle_active_form_record.h b/services/packageusage/include/bundle_active_form_record.h index 57d0c1c11026776a0d02931f7bb49884d7cf4eae..0155e043208c0aa5f59622f3e62ef75ffa90a1f7 100644 --- a/services/packageusage/include/bundle_active_form_record.h +++ b/services/packageusage/include/bundle_active_form_record.h @@ -86,7 +86,7 @@ public: * parameters: parcel * return: result of mashalling, true means successful, flase means failed. */ - virtual bool Marshalling(Parcel &parcel) const override; + bool Marshalling(Parcel &parcel) const override; /* * function: UnMarshalling, Unmashalling record object from parcel. * parameters: parcel diff --git a/services/packageusage/include/bundle_active_module_record.h b/services/packageusage/include/bundle_active_module_record.h index 0112a18ee812f412dcbc0e4649e1963781cef123..5146339d1c0bcf5d80b65c19cc211a4924f7fb43 100644 --- a/services/packageusage/include/bundle_active_module_record.h +++ b/services/packageusage/include/bundle_active_module_record.h @@ -30,7 +30,7 @@ public: BundleActiveModuleRecord(); ~BundleActiveModuleRecord() {} static bool cmp(const BundleActiveModuleRecord& moduleRecordA, const BundleActiveModuleRecord& moduleRecordB); - virtual bool Marshalling(Parcel &parcel) const override; + bool Marshalling(Parcel &parcel) const override; std::shared_ptr UnMarshalling(Parcel &parcel); std::string ToString(); diff --git a/services/packageusage/src/bundle_active_user_service.cpp b/services/packageusage/src/bundle_active_user_service.cpp index d2dfaeae4081308ebed89ba0caacca682cffc339..cddfcf7053b78edc60b4afe8f8f35cfa3b8938b6 100644 --- a/services/packageusage/src/bundle_active_user_service.cpp +++ b/services/packageusage/src/bundle_active_user_service.cpp @@ -340,7 +340,7 @@ ErrCode BundleActiveUserService::QueryBundleStatsInfos(std::vectorendTime_ != 0 && endTime > currentStats->beginTime_) { + if (endTime > currentStats->beginTime_) { BUNDLE_ACTIVE_LOGI("QueryBundleStatsInfos need in memory stats"); for (auto it : currentStats->bundleStats_) { if (bundleName.empty()) { @@ -375,8 +375,12 @@ ErrCode BundleActiveUserService::QueryBundleEvents(std::vectorendTime_ == 0) { + BUNDLE_ACTIVE_LOGI("QueryBundleEvents result in db is %{public}zu", bundleActiveEvent.size()); + return ERR_OK; + } // if we need a in-memory stats, combine current stats with bundleActiveEvent from database. - if (currentStats->endTime_ != 0 && endTime > currentStats->beginTime_) { + if (endTime > currentStats->beginTime_) { BUNDLE_ACTIVE_LOGI("QueryBundleEvents need in memory stats"); int32_t eventBeginIdx = currentStats->events_.FindBestIndex(beginTime); int32_t eventSize = currentStats->events_.Size(); @@ -388,7 +392,7 @@ ErrCode BundleActiveUserService::QueryBundleEvents(std::vector + +#include +#include "system_ability_definition.h" + +#include "bundle_active_client.h" +#include "bundle_active_event.h" +#include "bundle_active_service.h" +#include "bundle_active_group_map.h" +#include "app_group_callback_stub.h" +#include "app_group_callback_info.h" +#include "iapp_group_callback.h" + + +using namespace testing::ext; + +namespace OHOS { +namespace DeviceUsageStats { +static std::string g_defaultBundleName = "com.ohos.camera"; +static std::string g_defaultMoudleName = "defaultmodulename"; +static std::string g_defaultFormName = "defaultformname"; +static int32_t DEFAULT_DIMENSION = 4; +static int64_t DEFAULT_FORMID = 1; +static int32_t DEFAULT_USERID = 0; +static int32_t COMMON_USERID = 100; +static int64_t LARGE_NUM = 20000000000000; +static int32_t DEFAULT_GROUP = 10; +static sptr observer = nullptr; + +class DeviceUsageStatisticsMockTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void DeviceUsageStatisticsMockTest::SetUpTestCase(void) +{ +} + +void DeviceUsageStatisticsMockTest::TearDownTestCase(void) +{ +} + +void DeviceUsageStatisticsMockTest::SetUp(void) +{ +} + +void DeviceUsageStatisticsMockTest::TearDown(void) +{ +} + +/* + * @tc.name: DeviceUsageStatisticsMockTest_GetBundleActiveProxy_001 + * @tc.desc: test client getBundleActiveProxy boundary condition + * @tc.type: FUNC + * @tc.require: issuesI5SOZY + */ +HWTEST_F(DeviceUsageStatisticsMockTest, DeviceUsageStatisticsMockTest_GetBundleActiveProxy_001, + Function | MediumTest | Level0) +{ + BundleActiveEvent eventA(g_defaultBundleName, g_defaultMoudleName, g_defaultFormName, + DEFAULT_DIMENSION, DEFAULT_FORMID, BundleActiveEvent::FORM_IS_CLICKED); + EXPECT_NE(BundleActiveClient::GetInstance().ReportEvent(eventA, DEFAULT_USERID), ERR_OK); + + bool isIdle = false; + EXPECT_NE(BundleActiveClient::GetInstance().IsBundleIdle(isIdle, g_defaultBundleName, DEFAULT_USERID), ERR_OK); + + std::vector packageStats; + EXPECT_NE(BundleActiveClient::GetInstance().QueryBundleStatsInfoByInterval(packageStats, 4, 0, LARGE_NUM), ERR_OK); + EXPECT_NE(BundleActiveClient::GetInstance().QueryBundleStatsInfos(packageStats, 4, 0, LARGE_NUM), ERR_OK); + + std::vector event; + EXPECT_NE(BundleActiveClient::GetInstance().QueryBundleEvents(event, 0, LARGE_NUM, 100), ERR_OK); + EXPECT_NE(BundleActiveClient::GetInstance().QueryCurrentBundleEvents(event, 0, LARGE_NUM), ERR_OK); + + int32_t result = 0; + EXPECT_NE(BundleActiveClient::GetInstance().QueryAppGroup(result, g_defaultBundleName, COMMON_USERID), ERR_OK); + + EXPECT_NE(BundleActiveClient::GetInstance().SetAppGroup(g_defaultBundleName, DEFAULT_GROUP, COMMON_USERID), ERR_OK); + + EXPECT_NE(BundleActiveClient::GetInstance().RegisterAppGroupCallBack(observer), ERR_OK); + EXPECT_NE(BundleActiveClient::GetInstance().UnRegisterAppGroupCallBack(observer), ERR_OK); + + std::vector eventStats; + EXPECT_NE(BundleActiveClient::GetInstance().QueryDeviceEventStats(0, LARGE_NUM, eventStats), ERR_OK); + EXPECT_NE(BundleActiveClient::GetInstance().QueryNotificationEventStats(0, LARGE_NUM, eventStats), ERR_OK); + + std::vector moduleRecord; + int32_t maxNum = 1000; + EXPECT_NE(BundleActiveClient::GetInstance().QueryModuleUsageRecords(maxNum, moduleRecord, DEFAULT_USERID), ERR_OK); +} + +/* + * @tc.name: DeviceUsageStatisticsMockTest_GetBundleMgrProxy_001 + * @tc.desc: test service getBundleMgrProxy boundary condition + * @tc.type: FUNC + * @tc.require: issuesI5SOZY + */ +HWTEST_F(DeviceUsageStatisticsMockTest, DeviceUsageStatisticsMockTest_GetBundleMgrProxy_001, + Function | MediumTest | Level0) +{ + BundleActiveEvent eventA(g_defaultBundleName, g_defaultMoudleName, g_defaultFormName, + DEFAULT_DIMENSION, DEFAULT_FORMID, BundleActiveEvent::FORM_IS_CLICKED); + EXPECT_NE(BundleActiveClient::GetInstance().ReportEvent(eventA, DEFAULT_USERID), ERR_OK); +} + +/* + * @tc.name: DeviceUsageStatisticsMockTest_QueryDeviceEventStats_001 + * @tc.desc: test service queryDeviceEventStats boundary condition + * @tc.type: FUNC + * @tc.require: issuesI5SOZY + */ +HWTEST_F(DeviceUsageStatisticsMockTest, DeviceUsageStatisticsMockTest_QueryDeviceEventStats_001, + Function | MediumTest | Level0) +{ + auto service = std::make_shared(); + + std::vector eventStats; + EXPECT_NE(service->QueryDeviceEventStats(0, LARGE_NUM, eventStats, -1), ERR_OK); +} + +/* + * @tc.name: DeviceUsageStatisticsMockTest_QueryNotificationEventStats_001 + * @tc.desc: test service queryNotificationEventStats boundary condition + * @tc.type: FUNC + * @tc.require: issuesI5SOZY + */ +HWTEST_F(DeviceUsageStatisticsMockTest, DeviceUsageStatisticsMockTest_QueryNotificationEventStats_001, + Function | MediumTest | Level0) +{ + auto service = std::make_shared(); + + std::vector eventStats; + EXPECT_NE(service->QueryNotificationEventStats(0, LARGE_NUM, eventStats, -1), ERR_OK); +} + +/* + * @tc.name: DeviceUsageStatisticsMockTest_QueryModuleUsageRecords_001 + * @tc.desc: test service queryModuleUsageRecords boundary condition + * @tc.type: FUNC + * @tc.require: issuesI5SOZY + */ +HWTEST_F(DeviceUsageStatisticsMockTest, DeviceUsageStatisticsMockTest_QueryModuleUsageRecords_001, + Function | MediumTest | Level0) +{ + auto service = std::make_shared(); + + std::vector records; + EXPECT_NE(service->QueryModuleUsageRecords(1000, records, -1), ERR_OK); + + BundleActiveModuleRecord bundleActiveModuleRecord; + service->QueryModuleRecordInfos(bundleActiveModuleRecord); +} + +/* + * @tc.name: DeviceUsageStatisticsMockTest_QueryAppGroup_001 + * @tc.desc: test service queryAppGroup boundary condition + * @tc.type: FUNC + * @tc.require: issuesI5SOZY + */ +HWTEST_F(DeviceUsageStatisticsMockTest, DeviceUsageStatisticsMockTest_QueryAppGroup_001, + Function | MediumTest | Level0) +{ + auto service = std::make_shared(); + + int32_t appGroup; + std::string bundleName; + EXPECT_NE(service->QueryAppGroup(appGroup, bundleName, -1), ERR_OK); + EXPECT_NE(service->QueryAppGroup(appGroup, bundleName, 100), ERR_OK); +} + +/* + * @tc.name: DeviceUsageStatisticsMockTest_AppGroupCallback_001 + * @tc.desc: test service appGroupCallback boundary condition + * @tc.type: FUNC + * @tc.require: issuesI5SOZY + */ +HWTEST_F(DeviceUsageStatisticsMockTest, DeviceUsageStatisticsMockTest_AppGroupCallback_001, + Function | MediumTest | Level0) +{ + auto service = std::make_shared(); + + sptr observer = nullptr; + service->bundleActiveCore_ = nullptr; + EXPECT_NE(service->RegisterAppGroupCallBack(observer), ERR_OK); + EXPECT_NE(service->UnRegisterAppGroupCallBack(observer), ERR_OK); +} + +/* + * @tc.name: DeviceUsageStatisticsMockTest_QueryBundleEvents_001 + * @tc.desc: test service queryBundleEvents boundary condition + * @tc.type: FUNC + * @tc.require: issuesI5SOZY + */ +HWTEST_F(DeviceUsageStatisticsMockTest, DeviceUsageStatisticsMockTest_QueryBundleEvents_001, + Function | MediumTest | Level0) +{ + auto service = std::make_shared(); + + std::vector bundleActiveEvents; + EXPECT_NE(service->QueryBundleEvents(bundleActiveEvents, 0, LARGE_NUM, -1), ERR_OK); + EXPECT_NE(service->QueryCurrentBundleEvents(bundleActiveEvents, 0, LARGE_NUM), ERR_OK); +} + +/* + * @tc.name: DeviceUsageStatisticsMockTest_QueryBundleStatsInfoByInterval_001 + * @tc.desc: test service queryBundleStatsInfoByInterval boundary condition + * @tc.type: FUNC + * @tc.require: issuesI5SOZY + */ +HWTEST_F(DeviceUsageStatisticsMockTest, DeviceUsageStatisticsMockTest_QueryBundleStatsInfoByInterval_001, + Function | MediumTest | Level0) +{ + auto service = std::make_shared(); + + std::vector packageStats; + EXPECT_NE(service->QueryBundleStatsInfoByInterval(packageStats, 0, 0, LARGE_NUM, -1), ERR_OK); +} + +/* + * @tc.name: DeviceUsageStatisticsMockTest_QueryBundleStatsInfos_001 + * @tc.desc: test service queryBundleStatsInfos boundary condition + * @tc.type: FUNC + * @tc.require: issuesI5SOZY + */ +HWTEST_F(DeviceUsageStatisticsMockTest, DeviceUsageStatisticsMockTest_QueryBundleStatsInfos_001, + Function | MediumTest | Level0) +{ + auto service = std::make_shared(); + + std::vector packageStats; + EXPECT_NE(service->QueryBundleStatsInfos(packageStats, 0, 0, LARGE_NUM), ERR_OK); +} + +/* + * @tc.name: DeviceUsageStatisticsMockTest_QueryBundleStatsInfos_001 + * @tc.desc: test service queryBundleStatsInfos boundary condition + * @tc.type: FUNC + * @tc.require: issuesI5SOZY + */ +HWTEST_F(DeviceUsageStatisticsMockTest, DeviceUsageStatisticsMockTest_CheckTimeChangeAndGetWallTime_001, + Function | MediumTest | Level0) +{ + auto bundleActiveCore = std::make_shared(); + + std::vector eventStats; + EXPECT_NE(bundleActiveCore->QueryNotificationEventStats(0, LARGE_NUM, eventStats, COMMON_USERID), ERR_OK); + EXPECT_NE(bundleActiveCore->QueryDeviceEventStats(0, LARGE_NUM, eventStats, COMMON_USERID), ERR_OK); + + std::vector moduleRecords; + EXPECT_NE(bundleActiveCore->QueryModuleUsageRecords(1000, moduleRecords, COMMON_USERID), ERR_OK); + + std::vector activeEvent; + ErrCode code = bundleActiveCore->QueryBundleEvents(activeEvent, COMMON_USERID, 0, LARGE_NUM, g_defaultBundleName); + EXPECT_NE(code, ERR_OK); + + std::vector packageStats; + code = bundleActiveCore->QueryBundleStatsInfos(packageStats, COMMON_USERID, 4, 0, LARGE_NUM, g_defaultBundleName); + EXPECT_NE(code, ERR_OK); + + BundleActiveEvent event; + EXPECT_NE(bundleActiveCore->ReportEventToAllUserId(event), ERR_OK); + + bundleActiveCore->OnBundleUninstalled(COMMON_USERID, g_defaultBundleName); + + EXPECT_NE(bundleActiveCore->QueryNotificationEventStats(0, LARGE_NUM, eventStats, DEFAULT_USERID), ERR_OK); + EXPECT_NE(bundleActiveCore->QueryDeviceEventStats(0, LARGE_NUM, eventStats, DEFAULT_USERID), ERR_OK); + EXPECT_NE(bundleActiveCore->QueryModuleUsageRecords(1000, moduleRecords, DEFAULT_USERID), ERR_OK); + + code = bundleActiveCore->QueryBundleEvents(activeEvent, DEFAULT_USERID, 0, LARGE_NUM, g_defaultBundleName); + EXPECT_NE(code, ERR_OK); + + code = bundleActiveCore->QueryBundleStatsInfos(packageStats, DEFAULT_USERID, 4, 0, LARGE_NUM, g_defaultBundleName); + EXPECT_NE(code, ERR_OK); + + bundleActiveCore->OnBundleUninstalled(DEFAULT_USERID, g_defaultBundleName); +} +} // namespace DeviceUsageStats +} // namespace OHOS + 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 0000000000000000000000000000000000000000..1a0c43e9c73914a5a261af8009b30d9c23c0f3db --- /dev/null +++ b/test/unittest/device_usage_statistics_service_test.cpp @@ -0,0 +1,218 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define private public +#define protected public + +#include + +#include +#include "system_ability_definition.h" + +#include "bundle_active_service.h" +#include "app_group_callback_stub.h" +#include "app_group_callback_info.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) +{ +} + +class TestServiceAppGroupChangeCallback : public AppGroupCallbackStub { +public: + void OnAppGroupChanged(const AppGroupCallbackInfo &appGroupCallbackInfo) override; +}; + +void TestServiceAppGroupChangeCallback::OnAppGroupChanged(const AppGroupCallbackInfo &appGroupCallbackInfo) +{ + BUNDLE_ACTIVE_LOGI("TestServiceAppGroupChangeCallback::OnAppGroupChanged!"); +} + +/* + * @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); +} + +/* + * @tc.name: DeviceUsageStatisticsServiceTest_AppGroupCallback_001 + * @tc.desc: QueryModuleUsageRecords + * @tc.type: FUNC + * @tc.require: issuesI5SOZY + */ +HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_AppGroupCallback_001, + Function | MediumTest | Level0) +{ + auto service = std::make_shared(); + BUNDLE_ACTIVE_LOGI("DeviceUsageStatisticsServiceTest create BundleActiveService!"); + sptr observer = new (std::nothrow) TestServiceAppGroupChangeCallback(); + service->bundleActiveCore_ = std::make_shared(); + EXPECT_EQ(service->RegisterAppGroupCallBack(observer), ERR_OK); + EXPECT_NE(service->RegisterAppGroupCallBack(observer), ERR_OK); + service->bundleActiveCore_->AddObserverDeathRecipient(observer); + + EXPECT_EQ(service->UnRegisterAppGroupCallBack(observer), ERR_OK); + EXPECT_NE(service->UnRegisterAppGroupCallBack(observer), ERR_OK); + + observer = nullptr; + EXPECT_NE(service->RegisterAppGroupCallBack(observer), ERR_OK); + + service->bundleActiveCore_->AddObserverDeathRecipient(observer); + service->bundleActiveCore_->RemoveObserverDeathRecipient(observer); + + wptr remote = nullptr; + service->bundleActiveCore_->OnObserverDied(remote); + service->bundleActiveCore_->OnObserverDiedInner(remote); +} + +/* + * @tc.name: DeviceUsageStatisticsServiceTest_OnUserRemoved_001 + * @tc.desc: QueryModuleUsageRecords + * @tc.type: FUNC + * @tc.require: issuesI5SOZY + */ +HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_OnUserRemoved_001, + Function | MediumTest | Level0) +{ + int userId = 100; + auto coreObject = std::make_shared(); + coreObject->bundleGroupController_ = std::make_shared(coreObject->debugCore_); + coreObject->InitBundleGroupController(); + auto userService = std::make_shared(userId, *(coreObject.get()), false); + coreObject->userStatServices_[userId] = userService; + coreObject->currentUsedUser_ = userId; + coreObject->OnUserRemoved(userId); + coreObject->OnUserSwitched(userId); + coreObject->RestoreAllData(); + EXPECT_NE(coreObject, nullptr); +} + +/* + * @tc.name: DeviceUsageStatisticsServiceTest_RestoreAllData_001 + * @tc.desc: QueryModuleUsageRecords + * @tc.type: FUNC + * @tc.require: issuesI5SOZY + */ +HWTEST_F(DeviceUsageStatisticsServiceTest, DeviceUsageStatisticsServiceTest_RestoreAllData_001, + Function | MediumTest | Level0) +{ + auto coreObject = std::make_shared(); + coreObject->bundleGroupController_ = std::make_shared(coreObject->debugCore_); + coreObject->InitBundleGroupController(); + coreObject->RestoreAllData(); + BundleActiveEvent event; + coreObject->ReportEventToAllUserId(event); + EXPECT_NE(coreObject, nullptr); +} +} // 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 9a4c4addffcbd22c4d89e2545516573dedae81cd..bfc6b26e6d3eb2f3d8f29b849a01988d931d162e 100644 --- a/test/unittest/device_usage_statistics_test.cpp +++ b/test/unittest/device_usage_statistics_test.cpp @@ -25,6 +25,8 @@ #include "bundle_active_event.h" #include "app_group_callback_stub.h" #include "bundle_active_group_map.h" +#include "app_group_callback_info.h" +#include "iapp_group_callback.h" using namespace testing::ext; @@ -41,7 +43,7 @@ static int32_t DEFAULT_ERRCODE = 0; static int64_t LARGE_NUM = 20000000000000; static int32_t DEFAULT_GROUP = 10; static std::vector GROUP_TYPE {10, 20, 30, 40, 50}; -static sptr observer = nullptr; +static sptr observer = nullptr; class DeviceUsageStatisticsTest : public testing::Test { public: @@ -67,6 +69,21 @@ void DeviceUsageStatisticsTest::TearDown(void) { } +class TestAppGroupChangeCallback : public AppGroupCallbackStub { +public: + 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 @@ -111,6 +128,7 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryBundleEvents_ std::vector result; BundleActiveClient::GetInstance().QueryBundleEvents(result, 0, LARGE_NUM, 100); EXPECT_EQ(result.size() > 0, true); + EXPECT_NE(BundleActiveClient::GetInstance().QueryBundleEvents(result, LARGE_NUM, LARGE_NUM, 100), 0); } /* @@ -138,6 +156,7 @@ HWTEST_F(DeviceUsageStatisticsTest, DeviceUsageStatisticsTest_QueryPackagesStats std::vector result; BundleActiveClient::GetInstance().QueryBundleStatsInfoByInterval(result, 4, 0, LARGE_NUM); EXPECT_EQ(result.size(), 0); + EXPECT_NE(BundleActiveClient::GetInstance().QueryBundleStatsInfoByInterval(result, 4, LARGE_NUM, LARGE_NUM), 0); } /* @@ -185,6 +204,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 +227,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 +247,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 +325,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 +350,16 @@ 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->AddObserver(observer); + deathTest->RemoveObserver(); + deathTest->OnServiceDiedInner(); + + deathTest->observer_ = new (std::nothrow) TestAppGroupChangeCallback(); + deathTest->OnServiceDiedInner(); + EXPECT_TRUE(deathTest != nullptr); deathTest->OnRemoteDied(nullptr); } } // namespace DeviceUsageStats diff --git a/test/unittest/mock/bundle_active_account_helper_mock.cpp b/test/unittest/mock/bundle_active_account_helper_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ea9c9c4b909b72616f3c51f7ff96a3c45ec4708c --- /dev/null +++ b/test/unittest/mock/bundle_active_account_helper_mock.cpp @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include + +#include "bundle_active_account_helper.h" + +namespace OHOS { +namespace DeviceUsageStats { +ErrCode BundleActiveAccountHelper::GetUserId(const int32_t uid, int32_t& userId) +{ + return -1; +} +} // namespace DeviceUsageStats +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/bundle_active_client_mock.cpp b/test/unittest/mock/bundle_active_client_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e96349de6c840bb2ee925c7d8407893cf092cc6f --- /dev/null +++ b/test/unittest/mock/bundle_active_client_mock.cpp @@ -0,0 +1,26 @@ +/* + * 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 "bundle_active_client.h" +#include "bundle_state_inner_errors.h" + +namespace OHOS { +namespace DeviceUsageStats { +ErrCode BundleActiveClient::GetBundleActiveProxy() +{ + return ERR_SYSTEM_SERVICE_OPERATION_FAILED; +} +} // namespace DeviceUsageStats +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/bundle_active_core_mock.cpp b/test/unittest/mock/bundle_active_core_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7104408eb4a960799034d954fccdade68f350664 --- /dev/null +++ b/test/unittest/mock/bundle_active_core_mock.cpp @@ -0,0 +1,36 @@ +/* + * 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 "bundle_active_core.h" +#include "bundle_state_inner_errors.h" + +namespace OHOS { +namespace DeviceUsageStats { +static int64_t LARGE_NUM = 20000000000000; +int64_t BundleActiveCore::CheckTimeChangeAndGetWallTime(int32_t userId) +{ + if (userId == 0) { + return LARGE_NUM; + } + return ERR_TIME_OPERATION_FAILED; +} + +std::shared_ptr BundleActiveCore::GetUserDataAndInitializeIfNeeded(const int32_t userId, + const int64_t timeStamp, const bool debug) +{ + return nullptr; +} +} // namespace DeviceUsageStats +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/bundle_active_service_mock.cpp b/test/unittest/mock/bundle_active_service_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6cb0babaccbed7697625904728eb1cf7444b7f86 --- /dev/null +++ b/test/unittest/mock/bundle_active_service_mock.cpp @@ -0,0 +1,26 @@ +/* + * 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 "bundle_active_service.h" +#include "bundle_state_inner_errors.h" + +namespace OHOS { +namespace DeviceUsageStats { +ErrCode BundleActiveService::GetBundleMgrProxy() +{ + return ERR_SYSTEM_SERVICE_OPERATION_FAILED; +} +} // namespace DeviceUsageStats +} // namespace OHOS \ No newline at end of file