diff --git a/frameworks/native/cloud_file_kit_inner/src/big_data_statistics/gallery_download_file_stat.cpp b/frameworks/native/cloud_file_kit_inner/src/big_data_statistics/gallery_download_file_stat.cpp index 5e18358bbc7597d75d49f9e36fce81e74f5e06f3..821c6de4bc842d1668201cf0355c5a467a028518 100644 --- a/frameworks/native/cloud_file_kit_inner/src/big_data_statistics/gallery_download_file_stat.cpp +++ b/frameworks/native/cloud_file_kit_inner/src/big_data_statistics/gallery_download_file_stat.cpp @@ -198,7 +198,15 @@ static inline DownloadFileStatInfo SumTwoDownloadFileStat(DownloadFileStatInfo d void GalleryDownloadFileStat::OutputToFile() { DownloadFileStatInfo tmpInfo = ReadVecFromLocal(); - stat_ = SumTwoDownloadFileStat(stat_, tmpInfo); + + if (tmpInfo.bundleName != stat_.bundleName) { + auto ret = ReportDownloadFileStat(tmpInfo); + if (ret != E_OK) { + LOGE("report CLOUD_SYNC_DOWNLOAD_FILE_STAT error %{public}d", ret); + } + } else { + stat_ = SumTwoDownloadFileStat(stat_, tmpInfo); + } std::vector lines; /* Keep code order below */ @@ -267,6 +275,19 @@ void GalleryDownloadFileStat::ClearDownloadFileStat() std::fill(stat_.videoDownloadSpeed.begin(), stat_.videoDownloadSpeed.end(), 0); } +int32_t GalleryDownloadFileStat::ReportDownloadFileStat(DownloadFileStatInfo info) +{ + int32_t ret = CLOUD_SYNC_SYS_EVENT("CLOUD_SYNC_DOWNLOAD_FILE_STAT", + HiviewDFX::HiSysEvent::EventType::STATISTIC, + "bundle_name", info.bundleName, + "download_file", info.downloadFileError, + "image_size", info.imageSize, + "image_download_speed", info.imageDownloadSpeed, + "video_size", info.videoSize, + "video_download_speed", info.videoDownloadSpeed); + return ret; +} + void GalleryDownloadFileStat::Report() { const std::string path = DOWNLOAD_FILE_STAT_LOCAL_PATH + DOWNLOAD_FILE_STAT_NAME; @@ -278,14 +299,7 @@ void GalleryDownloadFileStat::Report() /* read stat from dist */ stat_ = ReadVecFromLocal(); - int32_t ret = CLOUD_SYNC_SYS_EVENT("CLOUD_SYNC_DOWNLOAD_FILE_STAT", - HiviewDFX::HiSysEvent::EventType::STATISTIC, - "bundle_name", stat_.bundleName, - "download_file", stat_.downloadFileError, - "image_size", stat_.imageSize, - "image_download_speed", stat_.imageDownloadSpeed, - "video_size", stat_.videoSize, - "video_download_speed", stat_.videoDownloadSpeed); + int32_t ret = ReportDownloadFileStat(stat_); if (ret != E_OK) { LOGE("report CLOUD_SYNC_DOWNLOAD_FILE_STAT error %{public}d", ret); } diff --git a/frameworks/native/cloud_file_kit_inner/src/data_sync/sync_state_manager.cpp b/frameworks/native/cloud_file_kit_inner/src/data_sync/sync_state_manager.cpp index 17c899af02b45e2a91dcde05630b48eb75d2c00e..e0ca232aafa2a0b865d2ac3ab164020dc540b0f9 100644 --- a/frameworks/native/cloud_file_kit_inner/src/data_sync/sync_state_manager.cpp +++ b/frameworks/native/cloud_file_kit_inner/src/data_sync/sync_state_manager.cpp @@ -32,6 +32,7 @@ Action SyncStateManager::UpdateSyncState(SyncState newState) bool SyncStateManager::CheckAndSetPending(bool forceFlag, SyncTriggerType triggerType) { + LOGD("state: %{public}d", state_); std::unique_lock lck(syncMutex_); if (!CheckCleaningFlag() && !CheckDisableCloudFlag() && @@ -58,16 +59,32 @@ bool SyncStateManager::CheckAndSetPending(bool forceFlag, SyncTriggerType trigge bool SyncStateManager::CheckMediaLibCleaning() { - auto ret = system::GetParameter(CLOUDSYNC_STATUS_KEY, ""); - LOGI("CLOUDSYNC_STATUS_KEY %{public}s", ret.c_str()); - return ret == CLOUDSYNC_STATUS_CLEANING; + std::string closeSwitchTime = system::GetParameter(CLOUDSYNC_SWITCH_STATUS, ""); + if (closeSwitchTime.empty() || closeSwitchTime == "0") { + LOGI("current no clean task"); + return false; + } + if (closeSwitchTime.size() > MICROSECOND_TIME_LENGTH_LIMIT || + !std::all_of(closeSwitchTime.begin(), closeSwitchTime.end(), ::isdigit)) { + LOGW("prev closeSwitch is invalid, reset to 0"); + system::SetParameter(CLOUDSYNC_SWITCH_STATUS, "0"); + return false; + } + + uint64_t prevTime = std::stoull(closeSwitchTime); + uint64_t curTime = GetCurrentTimeStamp(); + uint64_t intervalTime = curTime - prevTime; + if (prevTime > curTime || intervalTime >= TWELVE_HOURS_MICROSECOND) { + LOGW("prev closeSwitch over 12h, reset to 0"); + system::SetParameter(CLOUDSYNC_SWITCH_STATUS, "0"); + return false; + } + return true; } bool SyncStateManager::CheckCleaningFlag() { - auto ret = syncSignal.test(static_cast(SignalPos::CLEANING)); - LOGI("CleaningFlag %{public}d", ret); - return ret; + return syncSignal.test(static_cast(SignalPos::CLEANING)); } void SyncStateManager::SetCleaningFlag() @@ -86,9 +103,7 @@ Action SyncStateManager::ClearCleaningFlag() bool SyncStateManager::CheckDisableCloudFlag() { - auto ret = syncSignal.test(static_cast(SignalPos::DISABLE_CLOUD)); - LOGI("DisableCloudFlag %{public}d", ret); - return ret; + return syncSignal.test(static_cast(SignalPos::DISABLE_CLOUD)); } void SyncStateManager::SetDisableCloudFlag() diff --git a/frameworks/native/cloud_file_kit_inner/src/sync_rule/battery_status.cpp b/frameworks/native/cloud_file_kit_inner/src/sync_rule/battery_status.cpp index e8324dcf3e383bb0a3ea9d3592b47a5593cb9c70..150219869481d2d3ee5f6bfc069afd2835042d2e 100644 --- a/frameworks/native/cloud_file_kit_inner/src/sync_rule/battery_status.cpp +++ b/frameworks/native/cloud_file_kit_inner/src/sync_rule/battery_status.cpp @@ -29,16 +29,10 @@ void BatteryStatus::GetInitChargingStatus() { #ifdef SUPPORT_POWER auto &batterySrvClient = PowerMgr::BatterySrvClient::GetInstance(); - auto chargingStatus = batterySrvClient.GetChargingStatus(); - isCharging_ = (chargingStatus == PowerMgr::BatteryChargeState::CHARGE_STATE_ENABLE || - chargingStatus == PowerMgr::BatteryChargeState::CHARGE_STATE_FULL); - if (!isCharging_) { - auto pluggedType = batterySrvClient.GetPluggedType(); - LOGI("battery not charging, pluggedType: %{public}d", pluggedType); - isCharging_ = pluggedType != PowerMgr::BatteryPluggedType::PLUGGED_TYPE_NONE && - pluggedType != PowerMgr::BatteryPluggedType::PLUGGED_TYPE_BUTT; - } - LOGI("battery isCharging_: %{public}d", isCharging_.load()); + auto pluggedType = batterySrvClient.GetPluggedType(); + isCharging_ = pluggedType != PowerMgr::BatteryPluggedType::PLUGGED_TYPE_NONE && + pluggedType != PowerMgr::BatteryPluggedType::PLUGGED_TYPE_BUTT; + LOGI("pluggedType: %{public}d, isCharging: %{public}d", pluggedType, isCharging_.load()); #endif } diff --git a/frameworks/native/cloud_file_kit_inner/src/sync_rule/cloud_status.cpp b/frameworks/native/cloud_file_kit_inner/src/sync_rule/cloud_status.cpp index ac9400908d40fc0357433cb769183caade3c724c..1226a50bfc498dc01b2c490ebb2b7e3379d7a4b0 100644 --- a/frameworks/native/cloud_file_kit_inner/src/sync_rule/cloud_status.cpp +++ b/frameworks/native/cloud_file_kit_inner/src/sync_rule/cloud_status.cpp @@ -18,6 +18,7 @@ #include "cloud_file_kit.h" #include "dfs_error.h" #include "utils_log.h" +#include "settings_data_manager.h" namespace OHOS::FileManagement::CloudSync { int32_t CloudStatus::GetCurrentCloudInfo(const std::string &bundleName, const int32_t userId) @@ -28,15 +29,24 @@ int32_t CloudStatus::GetCurrentCloudInfo(const std::string &bundleName, const in return E_NULLPTR; } - auto ret = instance->GetCloudUserInfo(userId, userInfo_); + int32_t ret = instance->GetCloudUserInfo(userId, userInfo_); if (ret != E_OK) { + LOGE("GetCloudUserInfo failed"); return ret; } bool switchStatus = false; - ret = instance->GetAppSwitchStatus(bundleName, userId, switchStatus); - if (ret != E_OK) { - return ret; + SwitchStatus curSwitch = SettingsDataManager::GetSwitchStatusByCache(); + if (bundleName == HDC_BUNDLE_NAME) { + switchStatus = curSwitch == SwitchStatus::AI_FAMILY; + } else if (bundleName == GALLERY_BUNDLE_NAME) { + switchStatus = curSwitch == SwitchStatus::CLOUD_SPACE; + } else { + ret = instance->GetAppSwitchStatus(bundleName, userId, switchStatus); + if (ret != E_OK) { + LOGE("GetAppSwitchStatus failed"); + return ret; + } } /* insert key-value */ appSwitches_.insert(std::make_pair(bundleName, switchStatus)); @@ -61,14 +71,14 @@ bool CloudStatus::IsCloudStatusOkay(const std::string &bundleName, const int32_t /* Obtain cloud information only during first sync */ auto iter = appSwitches_.find(bundleName); if (iter == appSwitches_.end()) { - LOGI("appSwitches unknown, bundleName:%{private}s, userId:%{public}d", bundleName.c_str(), userId); - auto ret = GetCurrentCloudInfo(bundleName, userId); - if (ret) { + LOGI("appSwitches unknown, bundleName: %{private}s, userId: %{public}d", bundleName.c_str(), userId); + int32_t ret = GetCurrentCloudInfo(bundleName, userId); + if (ret != E_OK) { return false; } } - LOGI("bundleName:%{private}s, cloudSatus:%{public}d, switcheStatus:%{public}d", bundleName.c_str(), + LOGI("bundleName: %{private}s, cloudSatus: %{public}d, switcheStatus: %{public}d", bundleName.c_str(), userInfo_.enableCloud, appSwitches_[bundleName]); return appSwitches_[bundleName]; } diff --git a/frameworks/native/cloud_file_kit_inner/src/sync_rule/network_set_manager.cpp b/frameworks/native/cloud_file_kit_inner/src/sync_rule/network_set_manager.cpp index ea8cab91ddec32888bc176d07efa86da0e1d0415..409f972defa4619efd754e1e5e6870ea96191268 100644 --- a/frameworks/native/cloud_file_kit_inner/src/sync_rule/network_set_manager.cpp +++ b/frameworks/native/cloud_file_kit_inner/src/sync_rule/network_set_manager.cpp @@ -26,6 +26,7 @@ #include "parameters.h" #include "system_ability_definition.h" #include "utils_log.h" +#include "settings_data_manager.h" namespace OHOS::FileManagement::CloudSync { const std::string QUERY_URI = "datashareproxy://"; @@ -174,8 +175,8 @@ bool NetworkSetManager::GetConfigParams(const std::string &bundleName, int32_t u } std::string networkDataStr = param["useMobileNetworkData"]; bool isValid = std::all_of(networkDataStr.begin(), networkDataStr.end(), ::isdigit); - if (!isValid) { - LOGE("invalid param"); + if (networkDataStr.empty() || !isValid) { + LOGE("invalid param: %{public}s", networkDataStr.c_str()); return false; } int32_t networkData = std::stoi(networkDataStr); @@ -280,14 +281,17 @@ bool NetworkSetManager::IsAllowNetConnect(const std::string &bundleName, const i void NetworkSetManager::InitNetworkSetManager(const std::string &bundleName, const int32_t userId) { LOGI("InitNetworkSetManager bundleName: %{public}s", bundleName.c_str()); - if (bundleName != PHOTOS_BUNDLE_NAME) { + if (bundleName == GALLERY_BUNDLE_NAME) { + RegisterObserver(bundleName, userId, CELLULARCONNECT); + RegisterObserver(bundleName, userId, NETCONNECT); + GetCellularConnect(bundleName, userId); + GetNetConnect(bundleName, userId); + } else if (bundleName == HDC_BUNDLE_NAME) { + SettingsDataManager::GetNetworkConnectionStatus(); + SettingsDataManager::GetMobileDataStatus(); + } else { LOGE("InitNetworkSetManager bundleName is illegals"); - return; } - RegisterObserver(bundleName, userId, CELLULARCONNECT); - RegisterObserver(bundleName, userId, NETCONNECT); - GetCellularConnect(bundleName, userId); - GetNetConnect(bundleName, userId); } void NetworkSetManager::InitDataSyncManager(std::shared_ptr dataSyncManager) diff --git a/frameworks/native/cloud_file_kit_inner/src/sync_rule/network_status.cpp b/frameworks/native/cloud_file_kit_inner/src/sync_rule/network_status.cpp index 4deac6742b57d6460d53971c2dd6b52811a93b31..ee8e06f7b2c667d385039da236d4f4625e8de70a 100644 --- a/frameworks/native/cloud_file_kit_inner/src/sync_rule/network_status.cpp +++ b/frameworks/native/cloud_file_kit_inner/src/sync_rule/network_status.cpp @@ -25,6 +25,7 @@ #include "network_set_manager.h" #include "net_conn_callback_observer.h" #include "utils_log.h" +#include "settings_data_manager.h" using namespace OHOS::NetManagerStandard; @@ -135,26 +136,35 @@ NetworkStatus::NetConnStatus NetworkStatus::GetNetConnStatus() bool NetworkStatus::CheckMobileNetwork(const std::string &bundleName, const int32_t userId) { - if (bundleName != "com.ohos.photos") { - return true; - } - if (NetworkSetManager::IsAllowCellularConnect(bundleName, userId)) { - LOGI("datashare status open, CheckMobileNetwork success"); - return true; - } - if (CheckWifiOrEthernet()) { + if (bundleName == GALLERY_BUNDLE_NAME) { + if (NetworkSetManager::IsAllowCellularConnect(bundleName, userId)) { + LOGI("datashare status open, CheckMobileNetwork success"); + return true; + } + } else if (bundleName == HDC_BUNDLE_NAME) { + if (SettingsDataManager::GetMobileDataStatus() == "on") { + LOGI("ailife is setting mobie data sync"); + return true; + } + } else { return true; } - return false; + return CheckWifiOrEthernet(); } bool NetworkStatus::CheckNetwork(const std::string &bundleName, const int32_t userId) { - if (bundleName != "com.ohos.photos") { - return true; - } - if (NetworkSetManager::IsAllowNetConnect(bundleName, userId)) { - LOGI("CheckNetwork on"); + if (bundleName == GALLERY_BUNDLE_NAME) { + if (NetworkSetManager::IsAllowNetConnect(bundleName, userId)) { + LOGI("CheckNetwork on"); + return true; + } + } else if (bundleName == HDC_BUNDLE_NAME) { + if (SettingsDataManager::GetNetworkConnectionStatus() == "on") { + LOGI("ailife is setting network connection status"); + return true; + } + } else { return true; } LOGI("CheckNetwork off"); @@ -171,6 +181,7 @@ bool NetworkStatus::CheckWifiOrEthernet() LOGI("datashare status close, network_status:ethernet"); return true; } + LOGI("CheckWifiOrEthernet off"); return false; } } // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/frameworks/native/cloud_file_kit_inner/src/sync_rule/settings_data_manager.cpp b/frameworks/native/cloud_file_kit_inner/src/sync_rule/settings_data_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2530dae13c2c89650e6c715ca0a36a6f7b342718 --- /dev/null +++ b/frameworks/native/cloud_file_kit_inner/src/sync_rule/settings_data_manager.cpp @@ -0,0 +1,308 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "settings_data_manager.h" + +#include "datashare_helper.h" +#include "datashare_errno.h" +#include "datashare_result_set.h" +#include "dfs_error.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudSync { +static const std::string SETTING_DATA_QUERY_URI = "datashareproxy://"; +static const std::string SETTING_DATA_COMMON_URI = + "datashare:///com.ohos.settingsdata/entry/settingsdata/SETTINGSDATA?Proxy=true"; +static const std::string SYNC_SWITCH_KEY = "photos_sync_options"; +static const std::string NETWORK_CONNECTION_KEY = "photos_network_connection_status"; +static const std::string LOCAL_SPACE_FREE_KEY = "photos_local_space_free"; +static const std::string LOCAL_SPACE_DAYS_KEY = "photos_local_space_days"; +static const std::string MOBILE_DATA_SYNC_KEY = "photos_mobile_data_sync"; +static const std::string AI_FAMILY_STATUS = "2"; +static const std::string CLOUD_STATUS = "1"; +static const std::string SUCCESS_STATUS = "on"; + +void SettingsDataManager::InitSettingsDataManager() +{ + LOGI("InitSettingsDataManager"); + RegisterObserver(SYNC_SWITCH_KEY); + RegisterObserver(NETWORK_CONNECTION_KEY); + RegisterObserver(MOBILE_DATA_SYNC_KEY); + QuerySwitchStatus(); + QueryNetworkConnectionStatus(); + QueryLocalSpaceFreeStatus(); + QueryLocalSpaceFreeDays(); + QueryMobileDataStatus(); +} + +int32_t SettingsDataManager::QuerySwitchStatus() +{ + std::string value; + int32_t ret = QueryParamInSettingsData(SYNC_SWITCH_KEY, value); + if (ret != E_OK) { + LOGE("query SYNC_SWITCH_KEY failed"); + settingsDataMap_.Erase(SYNC_SWITCH_KEY); + return ret; + } + settingsDataMap_.EnsureInsert(SYNC_SWITCH_KEY, value); + return E_OK; +} + +int32_t SettingsDataManager::QueryNetworkConnectionStatus() +{ + std::string value; + int32_t ret = QueryParamInSettingsData(NETWORK_CONNECTION_KEY, value); + if (ret != E_OK) { + LOGE("query NETWORK_CONNECTION_KEY failed"); + settingsDataMap_.Erase(NETWORK_CONNECTION_KEY); + return ret; + } + settingsDataMap_.EnsureInsert(NETWORK_CONNECTION_KEY, value); + return E_OK; +} + +int32_t SettingsDataManager::QueryLocalSpaceFreeStatus() +{ + std::string value; + int32_t ret = QueryParamInSettingsData(LOCAL_SPACE_FREE_KEY, value); + if (ret != E_OK) { + LOGE("query LOCAL_SPACE_FREE_KEY failed"); + settingsDataMap_.Erase(LOCAL_SPACE_FREE_KEY); + return ret; + } + settingsDataMap_.EnsureInsert(LOCAL_SPACE_FREE_KEY, value); + return E_OK; +} + +int32_t SettingsDataManager::QueryLocalSpaceFreeDays() +{ + std::string value; + int32_t ret = QueryParamInSettingsData(LOCAL_SPACE_DAYS_KEY, value); + if (ret != E_OK) { + LOGE("query LOCAL_SPACE_DAYS_KEY failed"); + settingsDataMap_.Erase(LOCAL_SPACE_DAYS_KEY); + return ret; + } + settingsDataMap_.EnsureInsert(LOCAL_SPACE_DAYS_KEY, value); + return E_OK; +} + +int32_t SettingsDataManager::QueryMobileDataStatus() +{ + std::string value; + int32_t ret = QueryParamInSettingsData(MOBILE_DATA_SYNC_KEY, value); + if (ret != E_OK) { + LOGE("query MOBILE_DATA_SYNC_KEY failed"); + settingsDataMap_.Erase(MOBILE_DATA_SYNC_KEY); + return ret; + } + settingsDataMap_.EnsureInsert(MOBILE_DATA_SYNC_KEY, value); + return E_OK; +} + +SwitchStatus SettingsDataManager::GetSwitchStatus() +{ + std::string value; + int32_t ret = QuerySwitchStatus(); + if (ret == E_INNER_RDB) { + return SwitchStatus::CLOUD_SPACE; + } else if (ret == E_RDB) { + return SwitchStatus::NONE; + } + + value = settingsDataMap_.ReadVal(SYNC_SWITCH_KEY); + if (value == AI_FAMILY_STATUS) { + return SwitchStatus::AI_FAMILY; + } else if (value == CLOUD_STATUS) { + return SwitchStatus::CLOUD_SPACE; + } else { + return SwitchStatus::NONE; + } +} + +SwitchStatus SettingsDataManager::GetSwitchStatusByCache() +{ + std::string value; + if (!settingsDataMap_.Find(SYNC_SWITCH_KEY, value)) { + return GetSwitchStatus(); + } + + value = settingsDataMap_.ReadVal(SYNC_SWITCH_KEY); + if (value == AI_FAMILY_STATUS) { + return SwitchStatus::AI_FAMILY; + } else if (value == CLOUD_STATUS) { + return SwitchStatus::CLOUD_SPACE; + } else { + return SwitchStatus::NONE; + } +} + +std::string SettingsDataManager::GetNetworkConnectionStatus() +{ + std::string value; + if (!settingsDataMap_.Find(NETWORK_CONNECTION_KEY, value)) { + if (QueryNetworkConnectionStatus() != E_OK) { + return SUCCESS_STATUS; + } + } + + value = settingsDataMap_.ReadVal(NETWORK_CONNECTION_KEY); + return value; +} + +int32_t SettingsDataManager::GetLocalSpaceFreeStatus() +{ + std::string value; + if (!settingsDataMap_.Find(LOCAL_SPACE_FREE_KEY, value)) { + if (QueryLocalSpaceFreeStatus() != E_OK) { + return 0; + } + } + + value = settingsDataMap_.ReadVal(LOCAL_SPACE_FREE_KEY); + return std::stol(value); +} + +int32_t SettingsDataManager::GetLocalSpaceFreeDays() +{ + std::string value; + if (!settingsDataMap_.Find(LOCAL_SPACE_DAYS_KEY, value)) { + if (QueryLocalSpaceFreeDays() != E_OK) { + return 0; + } + } + + value = settingsDataMap_.ReadVal(LOCAL_SPACE_DAYS_KEY); + return std::stol(value); +} + +std::string SettingsDataManager::GetMobileDataStatus() +{ + std::string value; + if (!settingsDataMap_.Find(MOBILE_DATA_SYNC_KEY, value)) { + if (QueryMobileDataStatus() != E_OK) { + return SUCCESS_STATUS; + } + } + + value = settingsDataMap_.ReadVal(MOBILE_DATA_SYNC_KEY); + return value; +} + +int32_t SettingsDataManager::QueryParamInSettingsData(const std::string &key, std::string &value) +{ + LOGI("Query key: %{public}s", key.c_str()); + DataShare::DataSharePredicates predicates; + predicates.EqualTo("KEYWORD", key); + std::vector columns = {"value"}; + DataShare::CreateOptions options; + options.enabled_ = true; + auto dataShareHelper = DataShare::DataShareHelper::Creator(SETTING_DATA_QUERY_URI, options); + if (dataShareHelper == nullptr) { + LOGE("dataShareHelper == nullptr"); + return E_RDB; + } + + std::string queryUri = SETTING_DATA_COMMON_URI + "&key=" + key; + Uri uri(queryUri); + std::shared_ptr resultSet = dataShareHelper->Query(uri, predicates, columns); + dataShareHelper->Release(); + if (resultSet == nullptr) { + LOGE("resultSet == nullptr"); + return E_RDB; + } + if (resultSet->GoToFirstRow() != E_OK) { + LOGW("not found key: %{public}s", key.c_str()); + return E_INNER_RDB; + } + int32_t columnIndex = 0; + if (resultSet->GetColumnIndex("value", columnIndex) != E_OK) { + LOGE("GetColumnIndex failed"); + return E_RDB; + } + if (resultSet->GetString(columnIndex, value) != E_OK) { + LOGE("GetString failed"); + return E_RDB; + } + + LOGI("Query success, value: %{public}s", value.c_str()); + return E_OK; +} + +void SettingsDataManager::RegisterObserver(const std::string &key) +{ + LOGD("register key: %{public}s", key.c_str()); + DataShare::CreateOptions options; + options.enabled_ = true; + auto dataShareHelper = DataShare::DataShareHelper::Creator(SETTING_DATA_QUERY_URI, options); + if (dataShareHelper == nullptr) { + LOGE("dataShareHelper == nullptr"); + return; + } + sptr dataObserver(new (std::nothrow) SettingsDataObserver(key)); + Uri observerUri(SETTING_DATA_COMMON_URI + "&key=" + key); + dataShareHelper->RegisterObserver(observerUri, dataObserver); + dataShareHelper->Release(); + LOGI("Register SettingsDataObserver key: %{public}s finish", key.c_str()); +} + +void SettingsDataManager::RegisterObserver(const std::string &key, sptr dataObserver) +{ + LOGD("register key: %{public}s", key.c_str()); + DataShare::CreateOptions options; + options.enabled_ = true; + auto dataShareHelper = DataShare::DataShareHelper::Creator(SETTING_DATA_QUERY_URI, options); + if (dataShareHelper == nullptr) { + LOGE("dataShareHelper == nullptr"); + return; + } + + Uri observerUri(SETTING_DATA_COMMON_URI + "&key=" + key); + dataShareHelper->RegisterObserver(observerUri, dataObserver); + dataShareHelper->Release(); + LOGI("Register SettingsDataObserver key: %{public}s finish", key.c_str()); +} + +void SettingsDataManager::UnregisterObserver(const std::string &key) +{ + DataShare::CreateOptions options; + options.enabled_ = true; + auto dataShareHelper = DataShare::DataShareHelper::Creator(SETTING_DATA_QUERY_URI, options); + if (dataShareHelper == nullptr) { + LOGE("dataShareHelper == nullptr"); + return; + } + sptr dataObserver(new (std::nothrow) SettingsDataObserver(key)); + Uri observerUri(SETTING_DATA_COMMON_URI + "&key=" + key); + dataShareHelper->UnregisterObserver(observerUri, dataObserver); + dataShareHelper->Release(); + LOGI("Unregister SettingsDataObserver key: %{public}s finish", key.c_str()); +} + +void SettingsDataObserver::OnChange() +{ + LOGD("change key: %{public}s", key_.c_str()); + if (key_ == SYNC_SWITCH_KEY) { + SettingsDataManager::QuerySwitchStatus(); + } else if (key_ == NETWORK_CONNECTION_KEY) { + SettingsDataManager::QueryNetworkConnectionStatus(); + } else if (key_ == LOCAL_SPACE_FREE_KEY) { + SettingsDataManager::QueryLocalSpaceFreeStatus(); + } else if (key_ == LOCAL_SPACE_DAYS_KEY) { + SettingsDataManager::QueryLocalSpaceFreeDays(); + } else if (key_ == MOBILE_DATA_SYNC_KEY) { + SettingsDataManager::QueryMobileDataStatus(); + } +} +} \ No newline at end of file diff --git a/frameworks/native/cloudsync_kit_inner/src/cloud_sync_manager_impl.cpp b/frameworks/native/cloudsync_kit_inner/src/cloud_sync_manager_impl.cpp index 7e3e764f1d8c8a4e09575a7f61bf70f097ee9dae..3d9545568c026cb68a501eba539393658b73e4a0 100644 --- a/frameworks/native/cloudsync_kit_inner/src/cloud_sync_manager_impl.cpp +++ b/frameworks/native/cloudsync_kit_inner/src/cloud_sync_manager_impl.cpp @@ -687,7 +687,9 @@ int32_t CloudSyncManagerImpl::CleanFileCache(const std::string &uri) return E_SA_LOAD_FAILED; } SetDeathRecipient(CloudSyncServiceProxy->AsObject()); - return CloudSyncServiceProxy->CleanFileCacheInner(uri); + int32_t ret = CloudSyncServiceProxy->CleanFileCacheInner(uri); + LOGI("CleanFileCache end, ret: %{public}d", ret); + return ret; } int32_t CloudSyncManagerImpl::BatchDentryFileInsert(const std::vector &fileInfo, @@ -782,6 +784,7 @@ void CloudSyncManagerImpl::SystemAbilityStatusChange::OnRemoveSystemAbility(int3 void CloudSyncManagerImpl::CleanGalleryDentryFile() { + LOGI("CleanGalleryDentryFile start"); const std::string photoDir = "/storage/media/cloud/files/Photo"; const std::string thumbsDir = "/storage/media/cloud/files/.thumbs/Photo"; if (!OHOS::Storage::DistributedFile::Utils::ForceRemoveDirectoryDeepFirst(photoDir)) { @@ -811,7 +814,7 @@ static std::string GetThumbsPath(const std::string& path) { const string str = "files/"; size_t len = str.size() - 1; - std::string newPath = "/storage/media/cloud/files/.thumbs" + path.substr(path.find(str) + len); + std::string newPath = "/storage/media/cloud/files/.thumbs" + path.substr(path.find(str) + len); // 待删除的文件路径 return newPath; } diff --git a/frameworks/native/distributed_file_inner/include/copy/file_copy_listener.h b/frameworks/native/distributed_file_inner/include/copy/file_copy_listener.h index 6864ed1672bedea7b792b15b7437f6225ff859bd..0066161e85bbd120b2540fa73912183f4589d0bf 100644 --- a/frameworks/native/distributed_file_inner/include/copy/file_copy_listener.h +++ b/frameworks/native/distributed_file_inner/include/copy/file_copy_listener.h @@ -55,7 +55,7 @@ public: void StartListener(); void StopListener(); void AddFile(const std::string &fileName); - void AddListenerFile(const std::string &destPath, uint32_t mode); + int32_t AddListenerFile(const std::string &srcPath, const std::string &destPath, uint32_t mode); std::set GetFilePath() { std::lock_guard lock(filePathsMutex_); diff --git a/frameworks/native/distributed_file_inner/include/copy/file_copy_manager.h b/frameworks/native/distributed_file_inner/include/copy/file_copy_manager.h index df9e18e1d61a3475f992294f3abf32af4ccaf86f..ca95276ec6c00aa5c416dabf742864480636ccc0 100644 --- a/frameworks/native/distributed_file_inner/include/copy/file_copy_manager.h +++ b/frameworks/native/distributed_file_inner/include/copy/file_copy_manager.h @@ -95,12 +95,15 @@ private: // operator of file int32_t CreateFileInfos(const std::string &srcUri, const std::string &destUri, std::shared_ptr &infos); int32_t CheckOrCreatePath(const std::string &destPath); + int32_t ExecCopy(std::shared_ptr infos); int MakeDir(const std::string &path); bool IsRemoteUri(const std::string &uri); bool IsMediaUri(const std::string &uriPath); void AddFileInfos(std::shared_ptr infos); void RemoveFileInfos(std::shared_ptr infos); void DeleteResFile(std::shared_ptr infos); + bool IsDirectory(const std::string &path); + bool IsFile(const std::string &path); }; } // namespace DistributedFile } // namespace Storage diff --git a/frameworks/native/distributed_file_inner/include/copy/remote_file_copy_manager.h b/frameworks/native/distributed_file_inner/include/copy/remote_file_copy_manager.h index 882929c1494607d49c4c385d901427f27285f578..295b0a5a79ba5ab19f7be0969f6a804564956a14 100644 --- a/frameworks/native/distributed_file_inner/include/copy/remote_file_copy_manager.h +++ b/frameworks/native/distributed_file_inner/include/copy/remote_file_copy_manager.h @@ -36,6 +36,7 @@ private: const int32_t userId, const std::string ©Path); bool IsMediaUri(const std::string &uriPath); void AddFileInfos(std::shared_ptr infos); + bool IsFile(const std::string &path); private: static std::shared_ptr instance_; std::mutex FileInfosVecMutex_; diff --git a/frameworks/native/distributed_file_inner/src/copy/file_copy_listener.cpp b/frameworks/native/distributed_file_inner/src/copy/file_copy_listener.cpp index 949056bc52751dea1935dc5cc705736cc11439a7..a7cb4d11aabdf725c31ca998ba7f4fd0f4886977 100644 --- a/frameworks/native/distributed_file_inner/src/copy/file_copy_listener.cpp +++ b/frameworks/native/distributed_file_inner/src/copy/file_copy_listener.cpp @@ -15,6 +15,7 @@ #include "copy/file_copy_listener.h" +#include #include #include "copy/file_size_utils.h" @@ -38,6 +39,7 @@ FileCopyLocalListener::FileCopyLocalListener(const std::string &srcPath, bool isFile, const ProcessCallback &processCallback) : isFile_(isFile), processCallback_(processCallback) { if (processCallback_ == nullptr) { + LOGI("processCallback is nullptr"); return; } @@ -51,18 +53,6 @@ FileCopyLocalListener::FileCopyLocalListener(const std::string &srcPath, LOGE("Failed to init eventFd, errno:%{public}d", errno); return; } - - uint64_t fileSize = 0; - int32_t err; - if (!isFile_) { - err = FileSizeUtils::GetDirSize(srcPath, fileSize); - } else { - err = FileSizeUtils::GetFileSize(srcPath, fileSize); - } - if (err == E_OK) { - totalSize_ = fileSize; - } - notifyTime_ = std::chrono::steady_clock::now() + NOTIFY_PROGRESS_DELAY; } FileCopyLocalListener::~FileCopyLocalListener() @@ -80,6 +70,7 @@ std::shared_ptr FileCopyLocalListener::GetLocalListener(c void FileCopyLocalListener::StartListener() { if (processCallback_ == nullptr || totalSize_ == 0) { + LOGI("processCallback is nullptr or totalSize is zero, totalSize = %{public}" PRId64 "B", totalSize_); return; } notifyHandler_ = std::thread([this] { @@ -91,9 +82,11 @@ void FileCopyLocalListener::StartListener() void FileCopyLocalListener::StopListener() { LOGI("StopListener start."); - if (processCallback_ != nullptr) { - processCallback_(progressSize_, totalSize_); + if (processCallback_ == nullptr) { + LOGI("processCallback is nullptr"); + return; } + processCallback_(progressSize_, totalSize_); CloseNotifyFdLocked(); notifyRun_.store(false); { @@ -111,25 +104,41 @@ void FileCopyLocalListener::AddFile(const std::string &fileName) filePaths_.insert(fileName); } -void FileCopyLocalListener::AddListenerFile(const std::string &destPath, uint32_t mode) +int32_t FileCopyLocalListener::AddListenerFile(const std::string &srcPath, const std::string &destPath, uint32_t mode) { - if (processCallback_ == nullptr || totalSize_ == 0) { - return; + LOGI("AddListenerFile start"); + if (processCallback_ == nullptr) { + LOGI("processCallback is nullptr"); + return E_OK; } - std::lock_guard lock(wdsMutex_); int newWd = inotify_add_watch(notifyFd_, destPath.c_str(), mode); if (newWd < 0) { LOGE("inotify_add_watch, newWd is unvaild, newWd = %{public}d, errno = %{public}d", newWd, errno); - return; + return errno; } std::shared_ptr receiveInfo = std::make_shared(); if (receiveInfo == nullptr) { LOGE("Failed to request heap memory."); - return; + return ENOMEM; } receiveInfo->path = destPath; wds_.insert(std::make_pair(newWd, receiveInfo)); + uint64_t fileSize = 0; + int32_t err; + if (!isFile_) { + err = FileSizeUtils::GetDirSize(srcPath, fileSize); + } else { + err = FileSizeUtils::GetFileSize(srcPath, fileSize); + } + if (err != E_OK) { + LOGE("Failed to get src size, isFile=%{public}d, err=%{public}d", isFile_, err); + return err; + } + totalSize_ = fileSize; + notifyTime_ = std::chrono::steady_clock::now() + NOTIFY_PROGRESS_DELAY; + LOGI("AddListenerFile end"); + return E_OK; } void FileCopyLocalListener::GetNotifyEvent() diff --git a/frameworks/native/distributed_file_inner/src/copy/file_copy_manager.cpp b/frameworks/native/distributed_file_inner/src/copy/file_copy_manager.cpp index 413281a341db54217011f5c48959c26f6ac6ab0f..7e45728b997f492d474a92793a8ac85d2247db75 100644 --- a/frameworks/native/distributed_file_inner/src/copy/file_copy_manager.cpp +++ b/frameworks/native/distributed_file_inner/src/copy/file_copy_manager.cpp @@ -192,27 +192,18 @@ int32_t FileCopyManager::Copy(const std::string &srcUri, const std::string &dest return EINVAL; } auto infos = std::make_shared(); - auto ret = CreateFileInfos(srcUri, destUri, infos); - if (ret != E_OK) { - if (processCallback == nullptr) { - return EINVAL; - } - return ret; - } - + CreateFileInfos(srcUri, destUri, infos); if (IsRemoteUri(infos->srcUri)) { - ret = ExecRemote(infos, processCallback); + auto ret = ExecRemote(infos, processCallback); RemoveFileInfos(infos); return ret; } - infos->localListener = FileCopyLocalListener::GetLocalListener(infos->srcPath, infos->srcUriIsFile, processCallback); - infos->localListener->StartListener(); auto result = ExecLocal(infos); RemoveFileInfos(infos); infos->localListener->StopListener(); - + LOGE("FileCopyManager Copy end"); if (result != E_OK) { return result; } @@ -332,14 +323,59 @@ void FileCopyManager::DeleteResFile(std::shared_ptr infos) } } -int32_t FileCopyManager::ExecLocal(std::shared_ptr infos) +bool FileCopyManager::IsDirectory(const std::string &path) +{ + struct stat buf {}; + int ret = stat(path.c_str(), &buf); + if (ret == -1) { + LOGE("stat failed, errno is %{public}d", errno); + return false; + } + return (buf.st_mode & S_IFMT) == S_IFDIR; +} + +bool FileCopyManager::IsFile(const std::string &path) +{ + struct stat buf {}; + int ret = stat(path.c_str(), &buf); + if (ret == -1) { + LOGI("stat failed, errno is %{public}d, ", errno); + return false; + } + return (buf.st_mode & S_IFMT) == S_IFREG; +} + +int32_t FileCopyManager::ExecCopy(std::shared_ptr infos) { - LOGI("start ExecLocal"); if (infos == nullptr) { LOGE("infos is nullptr"); return EINVAL; } - // 文件到文件, 文件到目录的形式由上层改写为文件到文件的形式 + if (infos->srcUriIsFile && IsFile(infos->destPath)) { + // copy file + return CopyFile(infos->srcPath, infos->destPath, infos); + } + if (!infos->srcUriIsFile && IsDirectory(infos->destPath)) { + if (infos->srcPath.back() != '/') { + infos->srcPath += '/'; + } + if (infos->destPath.back() != '/') { + infos->destPath += '/'; + } + // copyDir + return CopyDirFunc(infos->srcPath, infos->destPath, infos); + } + LOGI("ExecLocal not support this srcUri and destUri"); + return EINVAL; +} + +int32_t FileCopyManager::ExecLocal(std::shared_ptr infos) +{ + LOGI("start ExecLocal"); + if (infos == nullptr || infos->localListener == nullptr) { + LOGE("infos or localListener is nullptr"); + return EINVAL; + } if (infos->srcUriIsFile) { if (infos->srcPath == infos->destPath) { LOGE("The src and dest is same"); @@ -350,39 +386,14 @@ int32_t FileCopyManager::ExecLocal(std::shared_ptr infos) LOGE("check or create fail, error code is %{public}d", ret); return ret; } - bool isFile = false; - ret = FileSizeUtils::IsFile(infos->destPath, isFile); - if (ret != E_OK || !isFile) { - LOGE("IsFile fail or dest is not file"); - return EINVAL; - } - if (infos->localListener == nullptr) { - LOGE("local listener is nullptr"); - return EINVAL; - } - infos->localListener->AddListenerFile(infos->destPath, IN_MODIFY); - return CopyFile(infos->srcPath, infos->destPath, infos); } - - bool destIsDirectory; - auto ret = FileSizeUtils::IsDirectory(infos->destUri, false, destIsDirectory); + auto ret = infos->localListener->AddListenerFile(infos->srcPath, infos->destPath, IN_MODIFY); if (ret != E_OK) { - LOGE("destPath not find, error=%{public}d", ret); + LOGE("AddListenerFile fail, errno = %{public}d", ret); return ret; } - - if (destIsDirectory) { - if (infos->srcPath.back() != '/') { - infos->srcPath += '/'; - } - if (infos->destPath.back() != '/') { - infos->destPath += '/'; - } - // copyDir - return CopyDirFunc(infos->srcPath, infos->destPath, infos); - } - LOGI("ExecLocal not support this srcUri and destUri"); - return EINVAL; + infos->localListener->StartListener(); + return ExecCopy(infos); } int32_t FileCopyManager::CopyFile(const std::string &src, const std::string &dest, std::shared_ptr infos) @@ -394,11 +405,11 @@ int32_t FileCopyManager::CopyFile(const std::string &src, const std::string &des if (srcFd < 0) { return ret; } - #if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) && !defined(CROSS_PLATFORM) +#if !defined(WIN_PLATFORM) && !defined(IOS_PLATFORM) && !defined(CROSS_PLATFORM) if (g_apiCompatibleVersion == 0) { g_apiCompatibleVersion = GetApiCompatibleVersion(); } - #endif +#endif int32_t destFd = -1; if (g_apiCompatibleVersion >= OPEN_TRUC_VERSION) { @@ -515,11 +526,6 @@ int32_t FileCopyManager::CopySubDir(const std::string &srcPath, std::lock_guard lock(infos->subDirsMutex); infos->subDirs.insert(destPath); } - if (infos->localListener == nullptr) { - LOGE("local listener is nullptr"); - return EINVAL; - } - infos->localListener->AddListenerFile(destPath, IN_MODIFY); return RecurCopyDir(srcPath, destPath, infos); } @@ -574,14 +580,7 @@ int32_t FileCopyManager::CreateFileInfos(const std::string &srcUri, infos->destUri = destUri; infos->srcPath = FileSizeUtils::GetPathFromUri(srcUri, true); infos->destPath = FileSizeUtils::GetPathFromUri(destUri, false); - - bool isDirectory; - auto ret = FileSizeUtils::IsDirectory(infos->srcUri, true, isDirectory); - if (ret != E_OK) { - LOGE("srcPath not find, err=%{public}d", ret); - return ret; - } - infos->srcUriIsFile = IsMediaUri(infos->srcUri) || !isDirectory; + infos->srcUriIsFile = IsMediaUri(infos->srcUri) || IsFile(infos->srcPath); AddFileInfos(infos); return E_OK; } diff --git a/frameworks/native/distributed_file_inner/src/copy/remote_file_copy_manager.cpp b/frameworks/native/distributed_file_inner/src/copy/remote_file_copy_manager.cpp index e157e0ffa3ec95ed0ea3cc5bdd497806ce0a4002..d7f0b93204c1a116323d4000bdfdc5168379d68e 100644 --- a/frameworks/native/distributed_file_inner/src/copy/remote_file_copy_manager.cpp +++ b/frameworks/native/distributed_file_inner/src/copy/remote_file_copy_manager.cpp @@ -89,22 +89,6 @@ static int32_t ChangeOwnerRecursive(const std::string &path, uid_t uid, gid_t gi return E_OK; } -static bool CheckPath(const std::shared_ptr &infos) -{ - std::string destPath = infos->destPath; - if (infos->srcUriIsFile) { - auto pos = destPath.rfind("/"); - if (pos == std::string::npos) { - return false; - } - destPath.resize(pos); - } - if (!(SandboxHelper::CheckValidPath(infos->srcPath) && SandboxHelper::CheckValidPath(destPath))) { - return false; - } - return true; -} - bool RemoteFileCopyManager::IsMediaUri(const std::string &uriPath) { Uri uri(uriPath); @@ -112,30 +96,15 @@ bool RemoteFileCopyManager::IsMediaUri(const std::string &uriPath) return bundleName == MEDIA_AUTHORITY; } -static int32_t IsDirectory(const std::string &path, bool &isDirectory) +bool RemoteFileCopyManager::IsFile(const std::string &path) { - if (!FileSizeUtils::IsFilePathValid(path)) { - LOGE("path is forbidden"); - return EINVAL; - } - - bool isDir = false; - auto ret = FileSizeUtils::IsDirectory(path, isDir); - if (ret != E_OK) { - return ret; - } - - bool isFile = false; - ret = FileSizeUtils::IsFile(path, isFile); - if (ret != E_OK) { - return ret; - } - - if (isDir == isFile) { - return EINVAL; + struct stat buf {}; + int ret = stat(path.c_str(), &buf); + if (ret == -1) { + LOGI("stat failed, errno is %{public}d, ", errno); + return false; } - isDirectory = isDir; - return E_OK; + return (buf.st_mode & S_IFMT) == S_IFREG; } static std::string GetFileName(const std::string &path) @@ -189,14 +158,7 @@ int32_t RemoteFileCopyManager::CreateFileInfos(const std::string &srcUri, } infos->srcPath = srcPhysicalPath; infos->destPath = dstPhysicalPath; - LOGI("Remote copy srcPath: , destPath: "); - bool isDirectory; - auto ret = IsDirectory(infos->srcPath, isDirectory); - if (ret != E_OK) { - LOGE("srcPath not find, err=%{public}d", ret); - return ret; - } - infos->srcUriIsFile = IsMediaUri(infos->srcUri) || !isDirectory; + infos->srcUriIsFile = IsMediaUri(infos->srcUri) || IsFile(infos->srcPath); infos->callingUid = IPCSkeleton::GetCallingUid(); AddFileInfos(infos); return E_OK; @@ -261,25 +223,21 @@ int32_t RemoteFileCopyManager::RemoteCopy(const std::string &srcUri, const std:: LOGE("CreateFileInfos failed,ret= %{public}d", ret); return ret; } - - if (!CheckPath(infos)) { - LOGE("invalid srcPath or destPath"); - return EINVAL; - } std::function processCallback = [&listener](uint64_t processSize, uint64_t totalSize) -> void { - listener->OnFileReceive(totalSize, processSize); + if (processSize != totalSize) { + listener->OnFileReceive(totalSize, processSize); + } }; infos->localListener = FileCopyLocalListener::GetLocalListener(infos->srcPath, infos->srcUriIsFile, processCallback); - infos->localListener->StartListener(); auto result = FileCopyManager::GetInstance()->ExecLocal(infos); if (ChangeOwnerRecursive(infos->destPath, infos->callingUid, infos->callingUid) != 0) { LOGE("ChangeOwnerRecursive failed, calling uid= %{public}d", infos->callingUid); } RemoveFileInfos(infos); infos->localListener->StopListener(); - + if (result != E_OK) { return result; } diff --git a/interfaces/inner_api/native/cloud_file_kit_inner/BUILD.gn b/interfaces/inner_api/native/cloud_file_kit_inner/BUILD.gn index af582e30112ec0d7ac106ad67bd16c3275d63cba..581e69e77a1cedd026c531c604f22dc9cbe1ef05 100644 --- a/interfaces/inner_api/native/cloud_file_kit_inner/BUILD.gn +++ b/interfaces/inner_api/native/cloud_file_kit_inner/BUILD.gn @@ -68,6 +68,7 @@ ohos_shared_library("cloudfile_kit") { "${distributedfile_path}/frameworks/native/cloud_file_kit_inner/src/sync_rule/network_set_manager.cpp", "${distributedfile_path}/frameworks/native/cloud_file_kit_inner/src/sync_rule/network_status.cpp", "${distributedfile_path}/frameworks/native/cloud_file_kit_inner/src/sync_rule/screen_status.cpp", + "${distributedfile_path}/frameworks/native/cloud_file_kit_inner/src/sync_rule/settings_data_manager.cpp", "${distributedfile_path}/frameworks/native/cloud_file_kit_inner/src/sync_rule/system_load.cpp", ] @@ -164,6 +165,7 @@ ohos_shared_library("cloudfile_kit_core") { "${distributedfile_path}/frameworks/native/cloud_file_kit_inner/src/cloud_file_kit.cpp", "${distributedfile_path}/frameworks/native/cloud_file_kit_inner/src/cloud_sync_helper.cpp", "${distributedfile_path}/frameworks/native/cloud_file_kit_inner/src/data_sync_manager.cpp", + "${distributedfile_path}/frameworks/native/cloud_file_kit_inner/src/sync_rule/settings_data_manager.cpp", ] sources += big_data_statistics @@ -176,7 +178,9 @@ ohos_shared_library("cloudfile_kit_core") { public_configs = [ ":cloudfile_kit_lite_public_config" ] external_deps = [ + "ability_runtime:dataobs_manager", "c_utils:utils", + "data_share:datashare_consumer", "hilog:libhilog", "hisysevent:libhisysevent", "ipc:ipc_core", diff --git a/interfaces/inner_api/native/cloud_file_kit_inner/big_data_statistics/gallery_download_file_stat.h b/interfaces/inner_api/native/cloud_file_kit_inner/big_data_statistics/gallery_download_file_stat.h index 90f260faace3d76dabd8b4c337a20b2906e14fa3..cf2736e64a24b16915f2c5ac03dd965f8c62d897 100644 --- a/interfaces/inner_api/native/cloud_file_kit_inner/big_data_statistics/gallery_download_file_stat.h +++ b/interfaces/inner_api/native/cloud_file_kit_inner/big_data_statistics/gallery_download_file_stat.h @@ -63,6 +63,7 @@ private: void UpdateDownloadSpeedStat(uint32_t mediaType, uint64_t size, uint64_t duration); void UpdateDownloadSizeStat(uint32_t mediaType, uint64_t size, uint64_t duration); DownloadFileStatInfo ReadVecFromLocal(); + int32_t ReportDownloadFileStat(DownloadFileStatInfo info); DownloadFileStatInfo stat_; }; diff --git a/interfaces/inner_api/native/cloud_file_kit_inner/data_sync_const.h b/interfaces/inner_api/native/cloud_file_kit_inner/data_sync_const.h index 470877acccf13d3e016bb9a59d257325258fc32b..882cee62981dcca2bb38fa9a02f3218b97f3b33f 100644 --- a/interfaces/inner_api/native/cloud_file_kit_inner/data_sync_const.h +++ b/interfaces/inner_api/native/cloud_file_kit_inner/data_sync_const.h @@ -80,6 +80,8 @@ const int32_t DIRECTORY = 1; const int32_t MILLISECOND_TO_SECOND = 1000; const int32_t SECOND_TO_MILLISECOND = 1000; const int64_t MILLISECOND_TO_NANOSECOND = 1e6; +const uint64_t TWELVE_HOURS_MICROSECOND = 12 * 60 * 60 * MILLISECOND_TO_NANOSECOND; +const int32_t MICROSECOND_TIME_LENGTH_LIMIT = 16; const int32_t NOT_IN_TRASH = 0; const int32_t NOT_IN_PENDING = 0; @@ -87,6 +89,7 @@ const int32_t NOT_HIDDEN = 0; const int32_t NOT_TEMP_FILE = 0; const int32_t IS_BURST_COVER = 1; +const std::string HDC_BUNDLE_NAME = "com.ohos.ailife"; const std::string GALLERY_BUNDLE_NAME = "com.ohos.photos"; const std::string MEDIALIBRARY_BUNDLE_NAME = "com.ohos.medialibrary.medialibrarydata"; @@ -99,6 +102,8 @@ static const std::string CLOUDSYNC_STATUS_FINISH = "4"; static const std::string CLOUDSYNC_STATUS_SWITCHOFF = "5"; static const std::string CLOUDSYNC_STATUS_CLEANING = "6"; +static const std::string CLOUDSYNC_SWITCH_STATUS = "persist.kernel.cloudsync.switch_status"; + static inline uint64_t GetCurrentTimeStamp() { struct timespec t; diff --git a/interfaces/inner_api/native/cloud_file_kit_inner/settings_data_manager.h b/interfaces/inner_api/native/cloud_file_kit_inner/settings_data_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..bb178cbcb1c4edd18a70bbfcb64d21497aaa2d1a --- /dev/null +++ b/interfaces/inner_api/native/cloud_file_kit_inner/settings_data_manager.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILEMGMT_CLOUD_SYNC_SETTINGS_DATA_MANAGER_H +#define OHOS_FILEMGMT_CLOUD_SYNC_SETTINGS_DATA_MANAGER_H + +#include + +#include "data_ability_observer_stub.h" +#include "safe_map.h" + +namespace OHOS::FileManagement::CloudSync { +enum SwitchStatus { + NONE = 0, + CLOUD_SPACE, + AI_FAMILY, +}; + +class SettingsDataObserver : public AAFwk::DataAbilityObserverStub { +public: + SettingsDataObserver(const std::string &key) : key_(key) {} + ~SettingsDataObserver() {} + void OnChange() override; + +private: + std::string key_; +}; + +class SettingsDataManager { +public: + static void InitSettingsDataManager(); + + static int32_t QuerySwitchStatus(); + static int32_t QueryNetworkConnectionStatus(); + static int32_t QueryLocalSpaceFreeStatus(); + static int32_t QueryLocalSpaceFreeDays(); + static int32_t QueryMobileDataStatus(); + + static SwitchStatus GetSwitchStatus(); + static SwitchStatus GetSwitchStatusByCache(); + static std::string GetNetworkConnectionStatus(); + static int32_t GetLocalSpaceFreeStatus(); + static int32_t GetLocalSpaceFreeDays(); + static std::string GetMobileDataStatus(); + + static void RegisterObserver(const std::string &key); + static void RegisterObserver(const std::string &key, sptr dataObserver); + +private: + static int32_t QueryParamInSettingsData(const std::string &key, std::string &value); + static void UnregisterObserver(const std::string &key); + + static inline SafeMap settingsDataMap_; +}; +} // OHOS + +#endif // OHOS_FILEMGMT_CLOUD_SYNC_SETTINGS_DATA_MANAGER_H \ No newline at end of file diff --git a/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_common.h b/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_common.h index c8a9d2fd581e803ba616720f0ca24bcdb9dc1e22..508b18c679f18a26edc9c7c223cec711bf1b7b09 100644 --- a/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_common.h +++ b/interfaces/inner_api/native/cloudsync_kit_inner/cloud_sync_common.h @@ -236,4 +236,4 @@ struct CloudFileInfo : public Parcelable { static CloudFileInfo *Unmarshalling(Parcel &parcel); }; } // namespace OHOS::FileManagement::CloudSync -#endif +#endif // OHOS_FILEMGMT_CLOUD_SYNC_COMMON_H diff --git a/interfaces/kits/js/ani/file_cloud_sync/include/download_progress_ani.h b/interfaces/kits/js/ani/file_cloud_sync/include/download_progress_ani.h index 2db2c4229188be5aabb5da557cb7b440f0742368..7c529e84806aa79ffd15ab775ea619b6ad1149a4 100644 --- a/interfaces/kits/js/ani/file_cloud_sync/include/download_progress_ani.h +++ b/interfaces/kits/js/ani/file_cloud_sync/include/download_progress_ani.h @@ -31,7 +31,6 @@ public: virtual void Update(const DownloadProgressObj &progress) = 0; virtual ani_object ConvertToObject(ani_env *env) = 0; - // Use default inline int64_t GetTaskId() const { return taskId_; diff --git a/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.cpp b/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.cpp index 943a0071417a54af041bead56622b5927b2e5b65..d13f74cfee45918e61cee42ed91bf228fc8e196e 100644 --- a/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.cpp +++ b/interfaces/kits/js/cloudfilesync/cloud_file_cache_napi.cpp @@ -16,10 +16,10 @@ #include "cloud_file_cache_napi.h" #include -#include #include #include #include +#include #include "async_work.h" #include "cloud_sync_manager.h" @@ -32,7 +32,8 @@ namespace OHOS::FileManagement::CloudSync { using namespace FileManagement::LibN; using namespace std; -static const std::set errForSingleFileSync = { ENOENT, EACCES, EAGAIN, EINTR, ENOSYS, E_ILLEGAL_URI }; +static const std::unordered_set errForSingleFileSync = { ENOENT, EACCES, EAGAIN, + EINTR, ENOSYS, E_ILLEGAL_URI }; int32_t CloudFileCacheCallbackImplNapi::StartDownloadInner(const std::string &uri, int32_t fieldKey) { diff --git a/interfaces/kits/js/cloudfilesync/cloud_sync_napi.cpp b/interfaces/kits/js/cloudfilesync/cloud_sync_napi.cpp index 2b0dbe1bf03824a6216f3b7d0caba620ed6c3e83..c92c1db48a145e50ee9eaf06579c5298a1a2c3de 100644 --- a/interfaces/kits/js/cloudfilesync/cloud_sync_napi.cpp +++ b/interfaces/kits/js/cloudfilesync/cloud_sync_napi.cpp @@ -1031,7 +1031,6 @@ napi_value CloudSyncNapi::GetFileSyncState(napi_env env, napi_callback_info info int ret = CheckPermissions(PERM_CLOUD_SYNC, true); if (ret != 0) { - LOGE("Permission denied"); NError(Convert2JsErrNum(ret)).ThrowErr(env); return nullptr; } diff --git a/interfaces/kits/js/cloudsyncmanager/downgrade_download_napi.h b/interfaces/kits/js/cloudsyncmanager/downgrade_download_napi.h index 2016d8b68102d3aa2c79bfeac2e4a7ad9998bb33..62e3bb9c89fcb6910b3545563bdc6e3d5db6e579 100644 --- a/interfaces/kits/js/cloudsyncmanager/downgrade_download_napi.h +++ b/interfaces/kits/js/cloudsyncmanager/downgrade_download_napi.h @@ -68,4 +68,4 @@ struct DowngradeEntity { std::shared_ptr callbackImpl{nullptr}; }; } // namespace OHOS::FileManagement::CloudSync -#endif // OHOS_FILEMGMT_CLOUD_FILE_DOWNLOAD_NAPI_H \ No newline at end of file +#endif // OHOS_FILEMGMT_DOWNGRADE_DOWNLOAD_NAPI_H \ No newline at end of file diff --git a/services/clouddisk_database/include/file_column.h b/services/clouddisk_database/include/file_column.h index 8deefb89f61afecb6a74e244deebc8c910f7d5db..523f797c0d0246652521948a6b646377e2ceeb03 100644 --- a/services/clouddisk_database/include/file_column.h +++ b/services/clouddisk_database/include/file_column.h @@ -96,6 +96,7 @@ public: // set attribute static const std::string ADD_ATTRIBUTE; + // set thm static const std::string ADD_THM_FLAG; static const std::string ADD_LCD_FLAG; diff --git a/services/clouddisk_database/src/clouddisk_rdbstore.cpp b/services/clouddisk_database/src/clouddisk_rdbstore.cpp index 78154be161a6de09c432d48936189a7c40f1388b..0698210eabb58c8185fae5c0f44d83bed5a51a91 100644 --- a/services/clouddisk_database/src/clouddisk_rdbstore.cpp +++ b/services/clouddisk_database/src/clouddisk_rdbstore.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Copyright (c) 2024 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 @@ -29,7 +29,6 @@ #include "clouddisk_rdb_utils.h" #include "clouddisk_sync_helper.h" #include "clouddisk_type_const.h" -#include "concurrent_queue.h" #include "data_sync_const.h" #include "dfs_error.h" #include "directory_ex.h" @@ -1539,7 +1538,7 @@ int32_t CloudDiskRdbStore::Rename(const std::string &oldParentCloudId, const std } CloudDiskSyncHelper::GetInstance().RegisterTriggerSync(bundleName_, userId_); }; - ConcurrentQueue::GetInstance().Submit(rdbUpdate); + ffrt::thread(rdbUpdate).detach(); return E_OK; } diff --git a/services/cloudfiledaemon.cfg b/services/cloudfiledaemon.cfg index ca6c19acdc6d9bc439892f0c5277d986001904a9..b485ba99734efa41d849ee17658b7e4d9642787b 100644 --- a/services/cloudfiledaemon.cfg +++ b/services/cloudfiledaemon.cfg @@ -3,7 +3,7 @@ "name": "cloudfiledaemon", "path": ["/system/bin/sa_main", "/system/profile/cloudfiledaemon.json"], "uid": "1009", - "gid": ["dfs", "user_data_rw", "ddms", "netsys_socket", "dfs_share", "readproc"], + "gid": ["dfs", "user_data_rw", "ddms", "dfs_share", "readproc"], "sandbox": 0, "secon": "u:r:cloudfiledaemon:s0", "apl": "system_basic", diff --git a/services/cloudfiledaemon/BUILD.gn b/services/cloudfiledaemon/BUILD.gn index b949a145253c0f0305ffc9471a905fc0d27a1473..ae5f0ea52e70cfe4b8add87d9aa3f3539cc3becc 100644 --- a/services/cloudfiledaemon/BUILD.gn +++ b/services/cloudfiledaemon/BUILD.gn @@ -55,6 +55,7 @@ ohos_shared_library("cloudfiledaemon") { "src/fuse_manager/fuse_manager.cpp", "src/ipc/cloud_daemon.cpp", "src/ipc/cloud_daemon_stub.cpp", + "src/utils/setting_data_helper.cpp", ] sources += cloud_disk @@ -71,10 +72,12 @@ ohos_shared_library("cloudfiledaemon") { "${utils_path}/ioctl/include", "${utils_path}/system/include", "${innerkits_native_path}/cloud_daemon_kit_inner", + "${innerkits_native_path}/cloud_file_kit_inner", "${innerkits_native_path}/cloud_file_kit_inner/big_data_statistics", "${services_path}/cloudfiledaemon/include/cloud_disk/", "${services_path}/cloudfiledaemon/include/fuse_manager/", "${services_path}/cloudfiledaemon/include/ipc/", + "${services_path}/cloudfiledaemon/include/utils/", "${services_path}/cloudsyncservice/include/data_sync/", "${clouddisk_database_path}/include", ] @@ -90,6 +93,7 @@ ohos_shared_library("cloudfiledaemon") { "ability_runtime:dataobs_manager", "c_utils:utils", "common_event_service:cesfwk_innerkits", + "data_share:datashare_consumer", "ffrt:libffrt", "hilog:libhilog", "hisysevent:libhisysevent", diff --git a/services/cloudfiledaemon/include/fuse_manager/cloud_daemon_statistic.h b/services/cloudfiledaemon/include/fuse_manager/cloud_daemon_statistic.h index 1c39f73735dee5127639779bd624e848f30dcb35..28e30fc2abb2118f75b5025e1a2796046b15bbf0 100644 --- a/services/cloudfiledaemon/include/fuse_manager/cloud_daemon_statistic.h +++ b/services/cloudfiledaemon/include/fuse_manager/cloud_daemon_statistic.h @@ -31,11 +31,34 @@ enum VideoReadInfoIndex { READ_SUM, }; +enum ReadSize { + READ_SIZE_128K = 0, + READ_SIZE_256K, + READ_SIZE_512K, + READ_SIZE_1M, + READ_SIZE_2M, + READ_SIZE_4M +} + namespace OHOS { namespace FileManagement { namespace CloudFile { using namespace std; +struct CloudDaemonStatisticInfo { +public: + ~CloudDaemonStatisticInfo() = default; + + vector openSizeStat = vector(OPEN_SIZE_MAX, 0); + vector> openTimeStat = + vector>(FILE_TYPE_MAX, vector(OPEN_TIME_MAX, 0)); + vector readSizeStat = vector(READ_SIZE_MAX, 0); + vector> readTimeStat = + vector>(READ_SIZE_MAX, vector(READ_TIME_MAX, 0)); + vector videoReadInfo = vector(VIDEO_READ_INFO, 0); + std::string bundleName; +}; + class CloudDaemonStatistic final { public: static CloudDaemonStatistic &GetInstance(); @@ -49,14 +72,18 @@ public: void UpdateReadTimeStat(uint64_t size, uint64_t time); void UpdateStatData(); void UpdateReadInfo(uint32_t index); + void UpdateBundleName(std::string bundleName); mutex mutex_; private: CloudDaemonStatistic() = default; ~CloudDaemonStatistic() = default; - void AddFileData(); + void AddFileData(CloudDaemonStatisticInfo &info); void ClearStat(); void OutputToFile(); int32_t CheckFileStat(); + void SumTwoReadStat(CloudDaemonStatisticInfo info); + int32_t ReportReadStat(); + vector openSizeStat_ = vector(OPEN_SIZE_MAX, 0); vector> openTimeStat_ = vector>(FILE_TYPE_MAX, vector(OPEN_TIME_MAX, 0)); @@ -64,6 +91,7 @@ private: vector> readTimeStat_ = vector>(READ_SIZE_MAX, vector(READ_TIME_MAX, 0)); vector videoReadInfo_ = vector(VIDEO_READ_INFO, 0); + std::string bundleName_; }; } // namespace CloudFile } // namespace FileManagement diff --git a/utils/ffrt/include/concurrent_queue.h b/services/cloudfiledaemon/include/utils/setting_data_helper.h similarity index 46% rename from utils/ffrt/include/concurrent_queue.h rename to services/cloudfiledaemon/include/utils/setting_data_helper.h index 61e0fb092940bfa879596ec2c7a3ba0a3a79153e..904b95b8bef53d6608152e0efcbae5e578a371c8 100644 --- a/utils/ffrt/include/concurrent_queue.h +++ b/services/cloudfiledaemon/include/utils/setting_data_helper.h @@ -12,23 +12,44 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef OHOS_FILEMGMT_CONCURRENT_QUEUE_H -#define OHOS_FILEMGMT_CONCURRENT_QUEUE_H +#ifndef SETTING_DATA_HELPER_H +#define SETTING_DATA_HELPER_H +#include +#include -#include "ffrt_inner.h" +#include "data_ability_observer_stub.h" namespace OHOS { namespace FileManagement { -class ConcurrentQueue final { +namespace CloudFile { +class SyncSwitchObserver : public AAFwk::DataAbilityObserverStub { public: - static ConcurrentQueue &GetInstance(); - void Init(int32_t qos, int32_t maxConcurrencyNum); - void Deinit(); - void Submit(std::function &&func, const ffrt::task_attr &attr = {}); - void Submit(const std::function &func, const ffrt::task_attr &attr = {}); + SyncSwitchObserver() = default; + ~SyncSwitchObserver() = default; + void OnChange() override; +}; + +class SettingDataHelper { +public: + static SettingDataHelper &GetInstance(); + void SetUserData(void *data); + bool InitActiveBundle(); + void UpdateActiveBundle(); + +private: + std::string GetActiveBundle(); + bool IsDataShareReady(); + void RegisterObserver(); + void SetActiveBundle(std::string bundle); + private: - std::unique_ptr queue_ = nullptr; + void *data_ = nullptr; + bool isDataShareReady_ = false; + bool isBundleInited_ = false; + std::mutex dataMtx_; + std::mutex initMtx_; }; +} // namespace CloudFile } // namespace FileManagement } // namespace OHOS #endif \ No newline at end of file diff --git a/services/cloudfiledaemon/src/cloud_disk/account_status_listener.cpp b/services/cloudfiledaemon/src/cloud_disk/account_status_listener.cpp index 510686113b8712530027a5685b5798af682f9fea..c84147583cfa6fc76352b571950c7adda7613bf2 100644 --- a/services/cloudfiledaemon/src/cloud_disk/account_status_listener.cpp +++ b/services/cloudfiledaemon/src/cloud_disk/account_status_listener.cpp @@ -26,6 +26,7 @@ #include "file_operations_helper.h" #include "fuse_manager.h" #include "meta_file.h" +#include "setting_data_helper.h" #include "utils_log.h" namespace OHOS { @@ -78,6 +79,9 @@ void AccountStatusSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &ev } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) { LOGI("Package removed and Clean clouddisk!"); RemovedClean(eventData); + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_DATA_SHARE_READY) { + bool ret = CloudFile::SettingDataHelper::GetInstance().InitActiveBundle(); + LOGI("READY: Init active bundle, ret: %{public}d", ret); } } @@ -88,12 +92,13 @@ AccountStatusListener::~AccountStatusListener() void AccountStatusListener::Start() { - /* subscribe Account login and logout status */ + /* subscribe Account login, logout, Package remove and Datashare ready */ EventFwk::MatchingSkills matchingSkills; matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN); matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT); matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF); matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_DATA_SHARE_READY); EventFwk::CommonEventSubscribeInfo info(matchingSkills); commonEventSubscriber_ = std::make_shared(info); auto subRet = EventFwk::CommonEventManager::SubscribeCommonEvent(commonEventSubscriber_); diff --git a/services/cloudfiledaemon/src/cloud_disk/file_operations_cloud.cpp b/services/cloudfiledaemon/src/cloud_disk/file_operations_cloud.cpp index 374dc8a0c4ce9d958e558c7860f0036fdda6863d..333a97db072402cca3bec44308acd6ac56f9b59a 100644 --- a/services/cloudfiledaemon/src/cloud_disk/file_operations_cloud.cpp +++ b/services/cloudfiledaemon/src/cloud_disk/file_operations_cloud.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024-2025 Huawei Device Co., Ltd. + * Copyright (c) 2024 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 @@ -28,7 +28,6 @@ #include "clouddisk_rdb_transaction.h" #include "clouddisk_rdb_utils.h" #include "clouddisk_notify.h" -#include "concurrent_queue.h" #include "database_manager.h" #include "directory_ex.h" #include "ffrt_inner.h" @@ -96,6 +95,10 @@ static void InitInodeAttr(struct CloudDiskFuseData *data, fuse_ino_t parent, HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); auto parentInode = FileOperationsHelper::FindCloudDiskInode(data, static_cast(parent)); + if (parentInode == nullptr) { + LOGE("parent inode not found"); + return; + } childInode->stat = parentInode->stat; childInode->stat.st_ino = static_cast(inodeId); childInode->stat.st_mtime = metaBase.mtime / MILLISECOND_TO_SECONDS_TIMES; @@ -437,7 +440,8 @@ static int32_t HandleCloudOpenSuccess(struct fuse_file_info *fi, struct CloudDis auto rdbstore = databaseManager.GetRdbStore(inoPtr->bundleName, data->userId); rdbstore->UpdateTHMStatus(metaFile, metaBase, CloudSync::DOWNLOADED_THM); } else { - LOGE("path rename failed, tmpPath:%{public}s, errno:%{public}d", tmpPath.c_str(), errno); + LOGE("path rename failed, tmpPath:%{public}s, errno:%{public}d", + GetAnonyString(tmpPath).c_str(), errno); return errno; } } @@ -1413,7 +1417,7 @@ void RDBUnlinkAsync(shared_ptr rdbStore, const string& cloudI "Failed to unlink DB cloudId: " + cloudId}); } }; - ConcurrentQueue::GetInstance().Submit(rdbUnlink); + ffrt::thread(rdbUnlink).detach(); } int32_t DoCloudUnlink(fuse_req_t req, fuse_ino_t parent, const char *name) @@ -1617,6 +1621,12 @@ static void DoCloudRead(fuse_req_t req, shared_ptr filePtr, auto session = filePtr->readSession; if (!session) { LOGE("readSession is nullptr"); + { + unique_lock lck(filePtr->readLock); + *readFinish = true; + } + *error = CloudError::CK_LOCAL_ERROR; + cond->notify_one(); return; } *readSize = session->PRead(offset, size, buf.get(), *error); @@ -1643,7 +1653,6 @@ static void DoCloudRead(fuse_req_t req, shared_ptr filePtr, filePtr->type = CLOUD_DISK_FILE_TYPE_CLOUD; fuse_reply_buf(req, buf.get(), *readSize); } else { - filePtr->readSession = nullptr; LOGE("read fail"); fuse_reply_err(req, ret); } @@ -1961,6 +1970,11 @@ void FileOperationsCloud::SetAttr(fuse_req_t req, fuse_ino_t ino, struct stat *a } auto parentInode = FileOperationsHelper::FindCloudDiskInode(data, static_cast(inoPtr->parent)); + if (parentInode == nullptr) { + LOGE("parent inode not found"); + fuse_reply_err(req, EINVAL); + return; + } if (static_cast(valid) & FUSE_SET_ATTR_SIZE) { DatabaseManager &databaseManager = DatabaseManager::GetInstance(); auto rdbStore = databaseManager.GetRdbStore(inoPtr->bundleName, data->userId); diff --git a/services/cloudfiledaemon/src/fuse_manager/cloud_daemon_statistic.cpp b/services/cloudfiledaemon/src/fuse_manager/cloud_daemon_statistic.cpp index 393f4411ffe61b108ed6156449a4d69918958385..ed0212ecb96f8ef5d8244a98c265b23d94fc01e4 100644 --- a/services/cloudfiledaemon/src/fuse_manager/cloud_daemon_statistic.cpp +++ b/services/cloudfiledaemon/src/fuse_manager/cloud_daemon_statistic.cpp @@ -20,8 +20,10 @@ #include #include -#include "utils_log.h" #include "dfs_error.h" +#include "meta_file.h" +#include "hisysevent.h" +#include "utils_log.h" namespace OHOS { namespace FileManagement { @@ -33,6 +35,9 @@ using namespace std; #define STAT_TIME_MS_TO_S 1000 #define CLOUD_FILE_DIR_MOD 0770 #define CLOUD_FILE_MOD 0660 +#define CLOUD_SYNC_SYS_EVENT(eventName, type, ...) \ + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::FILEMANAGEMENT, eventName, \ + type, ##__VA_ARGS__) \ static const string STAT_DATA_DIR_NAME = "/data/service/el1/public/cloudfile/cloud_data_statistic"; static const string STAT_DATA_FILE_NAME = "cloud_sync_read_file_stat"; @@ -127,7 +132,12 @@ void CloudDaemonStatistic::UpdateReadInfo(uint32_t index) CheckOverflow(videoReadInfo_[index], 1); } -void CloudDaemonStatistic::AddFileData() +void CloudDaemonStatistic::UpdateBundleName(std::string bundleName) +{ + bundleName_ = bundleName; +} + +void CloudDaemonStatistic::AddFileData(CloudDaemonStatisticInfo &info) { /* file not exist means first time, no former data, normal case */ auto ret = access(STAT_DATA_DIR_NAME.c_str(), F_OK); @@ -141,31 +151,27 @@ void CloudDaemonStatistic::AddFileData() return; } - uint64_t tmpData; + CloudDaemonStatisticInfo tmpInfo; for (uint32_t i = 0; i < OPEN_SIZE_MAX; i++) { - statDataFile >> tmpData; - CheckOverflow(openSizeStat_[i], tmpData); + statDataFile >> tmpInfo.openSizeStat[i]; } for (uint32_t i = 0; i < FILE_TYPE_MAX; i++) { for (uint32_t j = 0; j < OPEN_TIME_MAX; j++) { - statDataFile >> tmpData; - CheckOverflow(openTimeStat_[i][j], tmpData); + statDataFile >> tmpInfo.openTimeStat[i][j]; } } for (uint32_t i = 0; i < READ_SIZE_MAX; i++) { - statDataFile >> tmpData; - CheckOverflow(readSizeStat_[i], tmpData); + statDataFile >> tmpInfo.readSizeStat[i]; } for (uint32_t i = 0; i < READ_SIZE_MAX; i++) { for (uint32_t j = 0; j < READ_TIME_MAX; j++) { - statDataFile >> tmpData; - CheckOverflow(readTimeStat_[i][j], tmpData); + statDataFile >> tmpInfo.readTimeStat[i][j]; } } for (uint32_t i = 0; i < VIDEO_READ_INFO; i++) { - statDataFile >> tmpData; - CheckOverflow(videoReadInfo_[i], tmpData); + statDataFile >> tmpInfo.videoReadInfo[i]; } + statDataFile >> tmpInfo.bundleName; statDataFile.close(); } @@ -234,6 +240,7 @@ void CloudDaemonStatistic::OutputToFile() tmpStr += (to_string(videoReadInfo_[i]) + " "); } statDataFile << tmpStr << endl; + statDataFile << bundleName_ << endl; statDataFile.close(); } @@ -258,12 +265,66 @@ void CloudDaemonStatistic::ClearStat() for (uint32_t i = 0; i < VIDEO_READ_INFO; i++) { videoReadInfo_[i] = 0; } + bundleName_ = ""; +} + +void CloudDaemonStatistic::SumTwoReadStat(CloudDaemonStatisticInfo info) +{ + for (uint32_t i = 0; i < OPEN_SIZE_MAX; i++) { + CheckOverflow(openSizeStat_[i], info.openSizeStat[i]); + } + for (uint32_t i = 0; i < FILE_TYPE_MAX; i++) { + for (uint32_t j = 0; j < OPEN_TIME_MAX; j++) { + CheckOverflow(openTimeStat_[i][j], info.openTimeStat[i][j]); + } + } + for (uint32_t i = 0; i < READ_SIZE_MAX; i++) { + CheckOverflow(readSizeStat_[i], info.readSizeStat[i]); + } + for (uint32_t i = 0; i < READ_SIZE_MAX; i++) { + for (uint32_t j = 0; j < READ_TIME_MAX; j++) { + CheckOverflow(readTimeStat_[i][j], info.readTimeStat[i][j]); + } + } + for (uint32_t i = 0; i < VIDEO_READ_INFO; i++) { + CheckOverflow(videoReadInfo_[i], info.videoReadInfo[i]); + } +} + +int32_t CloudDaemonStatistic::ReportReadStat() +{ + int32_t ret = CLOUD_SYNC_SYS_EVENT("CLOUD_SYNC_READ_FILE_STAT", + HiviewDFX::HisysEvent::EventType::STATISTIC, + "open_size", openSizeStat_, + "open_thm_time", openTimeStat_[FILE_TYPE_THUMBNAIL], + "open_lcd_time", openTimeStat_[FILE_TYPE_LCD], + "open_content_time", openTimeStat_[FILE_TYPE_CONTENT], + "read_size", readSizeStat_, + "read_time_128KB", readTimeStat_[READ_SIZE_128K], + "read_time_256KB", readTimeStat_[READ_SIZE_256K], + "read_time_512KB", readTimeStat_[READ_SIZE_512K], + "read_time_1M", readTimeStat_[READ_SIZE_1M], + "read_time_2M", readTimeStat_[READ_SIZE_2M], + "read_time_4M", readTimeStat_[READ_SIZE_4M], + "video_read_info", videoReadInfo_, + "bundle_name", bundleName_ + ); + return ret; } void CloudDaemonStatistic::UpdateStatData() { lock_guard lock(mutex_); - AddFileData(); + CloudDaemonStatisticInfo info; + AddFileData(info); + if (info.bundleName != bundleName_) { + auto ret = ReportReadStat(); + if (ret != E_OK) { + LOGE("report CLOUD_SYNC_READ_FILE_STAT error %{public}d", ret); + } + } else { + SumTwoReadStat(info); + } OutputToFile(); ClearStat(); } diff --git a/services/cloudfiledaemon/src/fuse_manager/fuse_manager.cpp b/services/cloudfiledaemon/src/fuse_manager/fuse_manager.cpp index 6c567cda866c2cb1a045d9937fda34e6c5563e26..3feacd5720675429b80603b7816191ed27023156 100644 --- a/services/cloudfiledaemon/src/fuse_manager/fuse_manager.cpp +++ b/services/cloudfiledaemon/src/fuse_manager/fuse_manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Copyright (c) 2023-2024 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 @@ -48,7 +48,6 @@ #include "cloud_file_kit.h" #include "cloud_file_utils.h" #include "clouddisk_type_const.h" -#include "concurrent_queue.h" #include "database_manager.h" #include "datetime_ex.h" #include "dfs_error.h" @@ -58,6 +57,7 @@ #include "fuse_ioctl.h" #include "fuse_operations.h" #include "parameters.h" +#include "setting_data_helper.h" #ifdef HICOLLIE_ENABLE #include "xcollie_helper.h" #endif @@ -85,6 +85,7 @@ static const string LOCAL_PATH_SUFFIX = "/account/device_view/local"; static const string CLOUD_MERGE_VIEW_PATH_SUFFIX = "/account/cloud_merge_view"; static const string PATH_TEMP_SUFFIX = ".temp.fuse"; static const string PHOTOS_BUNDLE_NAME = "com.ohos.photos"; +static const string HDC_BUNDLE_NAME = "com.ohos.ailife"; static const string PATH_INVALID_FLAG1 = "../"; static const string PATH_INVALID_FLAG2 = "/.."; static const uint32_t PATH_INVALID_FLAG_LEN = 3; @@ -251,6 +252,7 @@ struct FuseData { shared_ptr database; struct fuse_session *se; string photoBundleName{""}; + string activeBundle{PHOTOS_BUNDLE_NAME}; }; static shared_ptr FindKeyInCloudFdCache(struct FuseData *data, uint64_t key) @@ -400,7 +402,7 @@ static shared_ptr GetDatabase(struct FuseData *data) return nullptr; } - data->database = instance->GetCloudDatabase(data->userId, PHOTOS_BUNDLE_NAME); + data->database = instance->GetCloudDatabase(data->userId, data->activeBundle); if (data->database == nullptr) { LOGE("get cloud file kit database fail"); return nullptr; @@ -882,7 +884,7 @@ static int DoCloudOpen(shared_ptr cInode, struct fuse_file_info *fi, auto error = make_shared(); auto openFinish = make_shared(false); auto cond = make_shared(); - ConcurrentQueue::GetInstance().Submit([cInode, error, openFinish, cond, data] { + ffrt::submit([cInode, error, openFinish, cond, data] { if (IsVideoType(cInode->mBase->name)) { LoadCacheFileIndex(cInode, data); } @@ -909,6 +911,11 @@ static bool IsLocalFile(struct FuseData *data, shared_ptr cInode) return access(localPath.c_str(), F_OK) == 0; } +static bool IsHdc(struct FuseData *data) +{ + return data->activeBundle == HDC_BUNDLE_NAME; +} + static bool NeedReCloudOpen(struct FuseData *data, shared_ptr cInode) { if (cInode->mBase->fileType == FILE_TYPE_CONTENT) { @@ -948,12 +955,14 @@ static void HandleReopen(fuse_req_t req, struct FuseData *data, shared_ptr cInode, uint64_t startTime) +static void UpdateReadStat(shared_ptr cInode, uint64_t startTime, + std::string bundleName) { uint64_t endTime = UTCTimeMilliSeconds(); CloudDaemonStatistic &readStat = CloudDaemonStatistic::GetInstance(); readStat.UpdateOpenSizeStat(cInode->mBase->size); readStat.UpdateOpenTimeStat(cInode->mBase->fileType, (endTime > startTime) ? (endTime - startTime) : 0); + readStat.UpdateBundleName(bundleName); } static string GetPrepareTraceId(int32_t userId) @@ -979,7 +988,7 @@ static void CloudOpenHelper(fuse_req_t req, fuse_ino_t ino, struct fuse_file_inf struct FuseData *data, shared_ptr& cInode) { pid_t pid = GetPidFromTid(req->ctx.pid); - string recordId = MetaFileMgr::GetInstance().CloudIdToRecordId(cInode->mBase->cloudId); + string recordId = MetaFileMgr::GetInstance().CloudIdToRecordId(cInode->mBase->cloudId, IsHdc(data)); shared_ptr database = GetDatabase(data); std::unique_lock wSesLock(cInode->sessionLock, std::defer_lock); string prepareTraceId = GetPrepareTraceId(data->userId); @@ -1013,7 +1022,7 @@ static void CloudOpenHelper(fuse_req_t req, fuse_ino_t ino, struct fuse_file_inf fuse_reply_err(req, -ret); cInode->readSession = nullptr; } - UpdateReadStat(cInode, startTime); + UpdateReadStat(cInode, startTime, data->activeBundle); wSesLock.unlock(); return; } @@ -1323,6 +1332,12 @@ static void SaveCacheToFile(shared_ptr readArgs, return; } int fd = fileno(file); + /* + * In the implementation of fopen, if the contained fd < 0, reutrn nullptr. + * There is no case where the fd < 0 when the pointer is non-null. + * This is to judge the exception where the file carrying the fd has been closed. + * In such cases, fclose is not needed. + */ if (fd < 0) { LOGE("Failed to get fd, err: %{public}d", errno); return; @@ -1337,7 +1352,8 @@ static void SaveCacheToFile(shared_ptr readArgs, } } -static void UpdateReadStatInfo(size_t size, std::string name, uint64_t readTime) +static void UpdateReadStatInfo(size_t size, std::string name, uint64_t readTime, + std::string bundleName) { CloudDaemonStatistic &readStat = CloudDaemonStatistic::GetInstance(); readStat.UpdateReadSizeStat(size); @@ -1345,6 +1361,7 @@ static void UpdateReadStatInfo(size_t size, std::string name, uint64_t readTime) if (IsVideoType(name)) { readStat.UpdateReadInfo(READ_SUM); } + readStat.UpdateBundleName(bundleName); } static void CloudReadOnCloudFile(pid_t pid, @@ -1378,7 +1395,7 @@ static void CloudReadOnCloudFile(pid_t pid, readSession->PRead(readArgs->offset, readArgs->size, readArgs->buf.get(), *readArgs->ckError, readArgs->appId); uint64_t endTime = UTCTimeMilliSeconds(); uint64_t readTime = (endTime > startTime) ? (endTime - startTime) : 0; - UpdateReadStatInfo(readArgs->size, cInode->mBase->name, readTime); + UpdateReadStatInfo(readArgs->size, cInode->mBase->name, readTime, data->activeBundle); { unique_lock lck(cInode->readLock); *readArgs->readStatus = READ_FINISHED; @@ -1393,7 +1410,7 @@ static void CloudReadOnCloudFile(pid_t pid, static_cast(cacheIndex)); } if (IsVideoType(cInode->mBase->name) && *readArgs->readResult > 0) { - ConcurrentQueue::GetInstance().Submit( + ffrt::submit( [data, readArgs, cInode, cacheIndex] { SaveCacheToFile(readArgs, cInode, cacheIndex, data); }); } wSesLock.unlock(); @@ -1434,7 +1451,7 @@ static void CloudReadOnCacheFile(shared_ptr readArgs, uint64_t endTime = UTCTimeMilliSeconds(); uint64_t readTime = (endTime > startTime) ? (endTime - startTime) : 0; - UpdateReadStatInfo(readArgs->size, cInode->mBase->name, startTime); + UpdateReadStatInfo(readArgs->size, cInode->mBase->name, startTime, data->activeBundle); cInode->SetReadCacheFlag(cacheIndex, PG_UPTODATE); wSesLock.lock(); @@ -1444,8 +1461,7 @@ static void CloudReadOnCacheFile(shared_ptr readArgs, static_cast(cacheIndex)); } if (IsVideoType(cInode->mBase->name) && *readArgs->readResult > 0) { - ConcurrentQueue::GetInstance().Submit( - [readArgs, cInode, cacheIndex, data] { SaveCacheToFile(readArgs, cInode, cacheIndex, data); }); + ffrt::submit([readArgs, cInode, cacheIndex, data] { SaveCacheToFile(readArgs, cInode, cacheIndex, data); }); } wSesLock.unlock(); return; @@ -1584,6 +1600,12 @@ static ssize_t ReadCacheFile(shared_ptr readArgs, const string &p return -1; } int fd = fileno(file); + /* + * In the implementation of fopen, if the contained fd < 0, reutrn nullptr. + * There is no case where the fd < 0 when the pointer is non-null. + * This is to judge the exception where the file carrying the fd has been closed. + * In such cases, fclose is not needed. + */ if (fd < 0) { LOGE("get fd faild, errno: %{public}d", errno); return fd; @@ -1632,7 +1654,7 @@ static bool DoReadSlice(fuse_req_t req, fuse_reply_err(req, ENETUNREACH); return false; } - ConcurrentQueue::GetInstance().Submit([pid, readArgs, cInode, readSession, data] { + ffrt::submit([pid, readArgs, cInode, readSession, data] { CloudReadOnCloudFile(pid, data, readArgs, cInode, readSession); }); return true; @@ -1668,7 +1690,7 @@ static bool DoCloudRead(fuse_req_t req, int flags, DoCloudReadParams params) LOGE("Init readArgsCache failed"); break; } - ConcurrentQueue::GetInstance().Submit([readArgsCache, params, data] { + ffrt::submit([readArgsCache, params, data] { CloudReadOnCacheFile(readArgsCache, params.cInode, params.readSession, data); }); } @@ -1853,6 +1875,8 @@ static int SetNewSessionInfo(struct fuse_session *se, struct fuse_loop_config &c } else { LOGE("get cloudfile helper instance failed"); } + // update userdata + SettingDataHelper::GetInstance().SetUserData(nullptr); return ret; } @@ -1877,7 +1901,6 @@ int32_t FuseManager::StartFuse(int32_t userId, int32_t devFd, const string &path LOGE("FUSE: log failed"); return ; } - LOGE("FUSE: %{public}s", str); free(str); #pragma clang diagnostic pop @@ -1902,11 +1925,11 @@ int32_t FuseManager::StartFuse(int32_t userId, int32_t devFd, const string &path data.userId = userId; data.se = se; data.photoBundleName = system::GetParameter(PHOTOS_KEY, ""); + SettingDataHelper::GetInstance().SetUserData(&data); config.max_idle_threads = MAX_IDLE_THREADS; } LOGI("fuse_session_new success, userId: %{public}d", userId); - int ret = SetNewSessionInfo(se, config, devFd, path, userId); - return ret; + return SetNewSessionInfo(se, config, devFd, path, userId); } struct fuse_session* FuseManager::GetSession(std::string path) @@ -1926,6 +1949,20 @@ FuseManager &FuseManager::GetInstance() return instance_; } +void SettingDataHelper::SetActiveBundle(string bundle) +{ + lock_guard lck(dataMtx_); + if (data_ == nullptr) { + LOGI("FuseData is null, no need update"); + return; + } + struct FuseData *data = static_cast(data_); + LOGI("reset database, old: %{public}s new: %{public}s", data->activeBundle.c_str(), bundle.c_str()); + if (data->activeBundle != bundle) { + data->activeBundle = bundle; + data->database = nullptr; + } +} } // namespace CloudFile } // namespace FileManagement } // namespace OHOS diff --git a/services/cloudfiledaemon/src/ipc/cloud_daemon.cpp b/services/cloudfiledaemon/src/ipc/cloud_daemon.cpp index 1876808a89046b5363a2ba7036b1f3fa9676dd80..97e0869e8d0abb13148023fbce554f572374cde6 100644 --- a/services/cloudfiledaemon/src/ipc/cloud_daemon.cpp +++ b/services/cloudfiledaemon/src/ipc/cloud_daemon.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2025 Huawei Device Co., Ltd. + * Copyright (c) 2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -16,20 +16,21 @@ #include "ipc/cloud_daemon.h" #include -#include #include +#include +#include #include #include -#include #include "appstate_observer.h" #include "cloud_file_fault_event.h" -#include "concurrent_queue.h" #include "dfs_error.h" +#include "ffrt_inner.h" #include "fuse_manager/fuse_manager.h" #include "iremote_object.h" #include "parameters.h" #include "plugin_loader.h" +#include "setting_data_helper.h" #include "system_ability_definition.h" #include "utils_directory.h" #include "utils_log.h" @@ -50,7 +51,6 @@ namespace { static const int32_t STAT_MODE_DIR = 0771; static const int32_t STAT_MODE_DIR_DENTRY_CACHE = 02771; static const int32_t OID_DFS = 1009; - static const int32_t MAX_CONCURRENT_THREADS = 12; } REGISTER_SYSTEM_ABILITY_BY_ID(CloudDaemon, FILEMANAGEMENT_CLOUD_DAEMON_SERVICE_SA_ID, true); @@ -107,6 +107,7 @@ void CloudDaemon::OnStart() try { PublishSA(); AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID); + AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID); mode_t mode = 002; umask(mode); ModSysParam(); @@ -117,8 +118,7 @@ void CloudDaemon::OnStart() state_ = ServiceRunningState::STATE_RUNNING; /* load cloud file ext plugin */ CloudFile::PluginLoader::GetInstance().LoadCloudKitPlugin(); - ConcurrentQueue::GetInstance().Init(ffrt_qos_user_initiated, MAX_CONCURRENT_THREADS); - + std::thread listenThread([&] { vector bundleNameList = {}; CloudDisk::AppStateObserverManager::GetInstance().SubscribeAppState(bundleNameList); @@ -169,7 +169,6 @@ void CloudDaemon::OnStop() LOGI("Begin to stop"); state_ = ServiceRunningState::STATE_NOT_START; registerToService_ = false; - ConcurrentQueue::GetInstance().Deinit(); CloudDisk::AppStateObserverManager::GetInstance().UnSubscribeAppState(); LOGI("Stop finished successfully"); } @@ -178,6 +177,11 @@ void CloudDaemon::OnAddSystemAbility(int32_t systemAbilityId, const std::string { LOGI("OnAddSystemAbility systemAbilityId:%{public}d added!", systemAbilityId); accountStatusListener_->Start(); + // get setting data when sa load + if (systemAbilityId == DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID) { + bool ret = SettingDataHelper::GetInstance().InitActiveBundle(); + LOGI("SERVICE LOAD: Init active bundle, ret: %{public}d", ret); + } } void CloudDaemon::ExecuteStartFuse(int32_t userId, int32_t devFd, const std::string& path) diff --git a/services/cloudfiledaemon/src/utils/setting_data_helper.cpp b/services/cloudfiledaemon/src/utils/setting_data_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..40f1173911b5cf1790d0866b84a67fe1bc7cbf3a --- /dev/null +++ b/services/cloudfiledaemon/src/utils/setting_data_helper.cpp @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "setting_data_helper.h" + +#include "data_sync_const.h" +#include "datashare_helper.h" +#include "settings_data_manager.h" +#include "utils_log.h" + +namespace OHOS { +namespace FileManagement { +namespace CloudFile { +using namespace std; +using namespace OHOS::FileManagement::CloudSync; +namespace { +static const string SETTING_DATA_QUERY_URI = "datashareproxy://"; +static const string SYNC_SWITCH_KEY = "photos_sync_options"; +} // namespace + +SettingDataHelper &SettingDataHelper::GetInstance() +{ + static SettingDataHelper instance_; + return instance_; +} + +void SettingDataHelper::SetUserData(void *data) +{ + lock_guard lck(dataMtx_); + data_ = data; +} + +bool SettingDataHelper::IsDataShareReady() +{ + if (isDataShareReady_) { + return true; + } + // try get DataShareHelper + DataShare::CreateOptions options; + options.enabled_ = true; + auto dataShareHelper = DataShare::DataShareHelper::Creator(SETTING_DATA_QUERY_URI, options); + if (dataShareHelper == nullptr) { + LOGE("get data share helper fail, will retry again after recv ready event"); + return false; + } + bool ret = dataShareHelper->Release(); + LOGI("release data share helper, ret=%{public}d", ret); + isDataShareReady_ = true; + return true; +} + +string SettingDataHelper::GetActiveBundle() +{ + // get from datashare + SwitchStatus status = SettingsDataManager::GetSwitchStatus(); + if (status == AI_FAMILY) { + return HDC_BUNDLE_NAME; + } + return GALLERY_BUNDLE_NAME; +} + +bool SettingDataHelper::InitActiveBundle() +{ + lock_guard lck(initMtx_); + if (isBundleInited_) { + return true; + } + if (!IsDataShareReady()) { + return false; + } + UpdateActiveBundle(); + RegisterObserver(); + isBundleInited_ = true; + return true; +} + +void SettingDataHelper::UpdateActiveBundle() +{ + // get latest data + string bundle = GetActiveBundle(); + // update FuseData + SetActiveBundle(bundle); +} + +void SettingDataHelper::RegisterObserver() +{ + sptr observer(new (std::nothrow) SyncSwitchObserver()); + SettingsDataManager::RegisterObserver(SYNC_SWITCH_KEY, observer); +} + +void SyncSwitchObserver::OnChange() +{ + SettingDataHelper::GetInstance().UpdateActiveBundle(); +} +} // namespace CloudFile +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/services/cloudsyncservice/src/cycle_task/tasks/optimize_cache_task.cpp b/services/cloudsyncservice/src/cycle_task/tasks/optimize_cache_task.cpp index a2f66a5428b0f20ad1e3034a5280e92d64f5a290..7fbfcf39fe0be6f73d526cd4de49b09e1f2c87d4 100644 --- a/services/cloudsyncservice/src/cycle_task/tasks/optimize_cache_task.cpp +++ b/services/cloudsyncservice/src/cycle_task/tasks/optimize_cache_task.cpp @@ -24,8 +24,10 @@ namespace FileManagement { namespace CloudSync { static const std::string FILEMANAGER_KEY = "persist.kernel.bundle_name.filemanager"; OptimizeCacheTask::OptimizeCacheTask(std::shared_ptr dataSyncManager) - : CycleTask("optimize_cache_task", {"com.ohos.photos", system::GetParameter(FILEMANAGER_KEY, "")}, ONE_DAY, - dataSyncManager) + : CycleTask("optimize_cache_task", + {GALLERY_BUNDLE_NAME, system::GetParameter(FILEMANAGER_KEY, ""), HDC_BUNDLE_NAME}, + ONE_DAY, + dataSyncManager) {} int32_t OptimizeCacheTask::RunTaskForBundle(int32_t userId, std::string bundleName) diff --git a/services/cloudsyncservice/src/cycle_task/tasks/optimize_storage_task.cpp b/services/cloudsyncservice/src/cycle_task/tasks/optimize_storage_task.cpp index 705e994927a015e953556aa4271bbb13800c72a5..420a1b9eaf9f894dacb6726d4369766dd4dd74ac 100644 --- a/services/cloudsyncservice/src/cycle_task/tasks/optimize_storage_task.cpp +++ b/services/cloudsyncservice/src/cycle_task/tasks/optimize_storage_task.cpp @@ -15,6 +15,7 @@ #include "optimize_storage_task.h" #include "cloud_file_kit.h" +#include "settings_data_manager.h" #include "system_load.h" #include "utils_log.h" @@ -22,7 +23,7 @@ namespace OHOS { namespace FileManagement { namespace CloudSync { OptimizeStorageTask::OptimizeStorageTask(std::shared_ptr dataSyncManager) - : CycleTask("optimize_storage_task", {"com.ohos.photos"}, ONE_DAY, dataSyncManager) + : CycleTask("optimize_storage_task", {GALLERY_BUNDLE_NAME, HDC_BUNDLE_NAME}, ONE_DAY, dataSyncManager) { } @@ -41,15 +42,23 @@ int32_t OptimizeStorageTask::RunTaskForBundle(int32_t userId, std::string bundle if (dataSyncManager_->CleanRemainFile(bundleName, userId) != E_OK) { LOGW(" clean reamin file fail"); } - std::map param; - auto ret = instance->GetAppConfigParams(userId, bundleName, param); - if (ret != E_OK || param.empty()) { - LOGE("GetAppConfigParams failed"); - return ret; + + int32_t agingDays = -1; + int32_t agingPolicy = -1; + if (bundleName == HDC_BUNDLE_NAME) { + agingDays = SettingsDataManager::GetLocalSpaceFreeDays(); + agingPolicy = SettingsDataManager::GetLocalSpaceFreeStatus(); + } else { + std::map param; + auto ret = instance->GetAppConfigParams(userId, bundleName, param); + if (ret != E_OK || param.empty()) { + LOGE("GetAppConfigParams failed"); + return ret; + } + agingDays = std::stoi(param["validDays"]); + agingPolicy = std::stoi(param["dataAgingPolicy"]); } - int32_t agingDays = std::stoi(param["validDays"]); - int32_t agingPolicy = std::stoi(param["dataAgingPolicy"]); if (agingPolicy == 0) { return dataSyncManager_->OptimizeStorage(bundleName, userId, agingDays); } diff --git a/services/cloudsyncservice/src/cycle_task/tasks/periodic_check_task.cpp b/services/cloudsyncservice/src/cycle_task/tasks/periodic_check_task.cpp index aff5ec9815d9f92059831e9a6f581b951db7ce8e..de13ebf6c3f3933e108d903e92c456b5e3daf65a 100644 --- a/services/cloudsyncservice/src/cycle_task/tasks/periodic_check_task.cpp +++ b/services/cloudsyncservice/src/cycle_task/tasks/periodic_check_task.cpp @@ -24,7 +24,8 @@ namespace FileManagement { namespace CloudSync { static const std::string FILEMANAGER_KEY = "persist.kernel.bundle_name.filemanager"; PeriodicCheckTask::PeriodicCheckTask(std::shared_ptr dataSyncManager) - : CycleTask(PeriodicCheckTaskName, {"com.ohos.photos", system::GetParameter(FILEMANAGER_KEY, "")}, + : CycleTask(PeriodicCheckTaskName, + {GALLERY_BUNDLE_NAME, system::GetParameter(FILEMANAGER_KEY, ""), HDC_BUNDLE_NAME}, THREE_DAY, dataSyncManager) { diff --git a/services/cloudsyncservice/src/cycle_task/tasks/report_statistics_task.cpp b/services/cloudsyncservice/src/cycle_task/tasks/report_statistics_task.cpp index 98d290d71fdf89146fadabae56c8e62519a700e8..9070243f888595dcbd4f4de06f497647f66583bc 100644 --- a/services/cloudsyncservice/src/cycle_task/tasks/report_statistics_task.cpp +++ b/services/cloudsyncservice/src/cycle_task/tasks/report_statistics_task.cpp @@ -21,7 +21,7 @@ namespace OHOS { namespace FileManagement { namespace CloudSync { ReportStatisticsTask::ReportStatisticsTask(std::shared_ptr dataSyncManager) - : CycleTask("report_statistics_task", {"com.ohos.photos"}, ONE_DAY, dataSyncManager) + : CycleTask("report_statistics_task", {GALLERY_BUNDLE_NAME, HDC_BUNDLE_NAME}, ONE_DAY, dataSyncManager) { } diff --git a/services/cloudsyncservice/src/ipc/cloud_sync_service.cpp b/services/cloudsyncservice/src/ipc/cloud_sync_service.cpp index 5a946abe474b964b43cafbbb0505e88b2097b6bf..1a0f3314ec57d1db20921bdc649fc23ae5959b7e 100644 --- a/services/cloudsyncservice/src/ipc/cloud_sync_service.cpp +++ b/services/cloudsyncservice/src/ipc/cloud_sync_service.cpp @@ -43,6 +43,7 @@ #include "system_load.h" #include "task_state_manager.h" #include "utils_log.h" +#include "settings_data_manager.h" namespace OHOS::FileManagement::CloudSync { using namespace std; @@ -194,6 +195,7 @@ void CloudSyncService::OnStart(const SystemAbilityOnDemandReason& startReason) TaskStateManager::GetInstance().StartTask(); // 跟随进程生命周期 ffrt::submit([startReason, this]() { + SettingsDataManager::InitSettingsDataManager(); this->HandleStartReason(startReason); int32_t userId = 0; if (dataSyncManager_->GetUserId(userId) != E_OK) { @@ -689,7 +691,11 @@ int32_t CloudSyncService::ChangeAppSwitch(const std::string &accoutId, const std LOGI("Begin ChangeAppSwitch"); RETURN_ON_ERR(CheckPermissions("", true)); - auto callerUserId = DfsuAccessTokenHelper::GetUserId(); + int32_t callerUserId = DfsuAccessTokenHelper::GetUserId(); + /* SA is 0 */ + if (callerUserId == 0) { + DfsuAccessTokenHelper::GetAccountId(callerUserId); + } LOGI("ChangeAppSwitch, bundleName: %{private}s, status: %{public}d, callerUserId: %{public}d", bundleName.c_str(), status, callerUserId); @@ -761,9 +767,13 @@ int32_t CloudSyncService::DisableCloud(const std::string &accoutId) LOGI("Begin DisableCloud"); RETURN_ON_ERR(CheckPermissions(PERM_CLOUD_SYNC_MANAGER, true)); - auto callerUserId = DfsuAccessTokenHelper::GetUserId(); + int32_t callerUserId = DfsuAccessTokenHelper::GetUserId(); + /* SA is 0 */ + if (callerUserId == 0) { + DfsuAccessTokenHelper::GetAccountId(callerUserId); + } int32_t ret = dataSyncManager_->DisableCloud(callerUserId); - LOGI("End DisableCloud"); + LOGI("End DisableCloud, ret: %{public}d", ret); return ret; } diff --git a/services/cloudsyncservice/src/sync_rule/battery_status_listener.cpp b/services/cloudsyncservice/src/sync_rule/battery_status_listener.cpp index f96c7354a24290101cf035b7b4299813654b553e..747f34b9503f98d0b1dc3250109c482e2d36f23a 100644 --- a/services/cloudsyncservice/src/sync_rule/battery_status_listener.cpp +++ b/services/cloudsyncservice/src/sync_rule/battery_status_listener.cpp @@ -36,13 +36,12 @@ void BatteryStatusSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &ev listener_->OnStatusNormal(); return; } - if (action == EventFwk::CommonEventSupport::COMMON_EVENT_CHARGING) { - LOGI("Charging status changed: charging"); - BatteryStatus::SetChargingStatus(true); - } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_DISCHARGING) { + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_POWER_DISCONNECTED) { LOGI("Charging status changed: discharging"); - BatteryStatus::GetInitChargingStatus(); + BatteryStatus::SetChargingStatus(false); } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_POWER_CONNECTED) { + LOGI("Charging status changed: charging"); + BatteryStatus::SetChargingStatus(true); listener_->OnPowerConnected(); } else { LOGI("OnReceiveEvent action is invalid"); @@ -64,8 +63,7 @@ void BatteryStatusListener::Start() /* subscribe Battery Okay Status and Charging status */ EventFwk::MatchingSkills matchingSkills; matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_BATTERY_OKAY); - matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_CHARGING); - matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_DISCHARGING); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_POWER_DISCONNECTED); matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_POWER_CONNECTED); EventFwk::CommonEventSubscribeInfo info(matchingSkills); commonEventSubscriber_ = std::make_shared(info, shared_from_this()); @@ -92,8 +90,8 @@ void BatteryStatusListener::OnStatusAbnormal() {} void BatteryStatusListener::OnPowerConnected() { + dataSyncManager_->TriggerRecoverySync(SyncTriggerType::POWER_CONNECT_TRIGGER); dataSyncManager_->DownloadThumb(); dataSyncManager_->CacheVideo(); - dataSyncManager_->TriggerRecoverySync(SyncTriggerType::POWER_CONNECT_TRIGGER); } } // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/services/cloudsyncservice/src/sync_rule/screen_status_listener.cpp b/services/cloudsyncservice/src/sync_rule/screen_status_listener.cpp index d915696f2d56b4ee84134c1ea041fdd1658e49df..df03619108092ff339c398e2ce2d850d55dc641d 100644 --- a/services/cloudsyncservice/src/sync_rule/screen_status_listener.cpp +++ b/services/cloudsyncservice/src/sync_rule/screen_status_listener.cpp @@ -53,9 +53,9 @@ ScreenStatusListener::~ScreenStatusListener() void ScreenStatusListener::ScreenOff() { + dataSyncManager_->TriggerRecoverySync(SyncTriggerType::SCREEN_OFF_TRIGGER); dataSyncManager_->DownloadThumb(); dataSyncManager_->CacheVideo(); - dataSyncManager_->TriggerRecoverySync(SyncTriggerType::SCREEN_OFF_TRIGGER); } void ScreenStatusListener::Start() diff --git a/services/distributedfile.cfg b/services/distributedfile.cfg index 5e308d80a4468c34cbca0340d95d4ab9e72f312e..959fa75cc39a60540874ad5b3f0bf4034758b091 100644 --- a/services/distributedfile.cfg +++ b/services/distributedfile.cfg @@ -37,7 +37,7 @@ "name": "cloudfileservice", "path": ["/system/bin/sa_main", "/system/profile/cloudfileservice.json"], "uid": "dfs", - "gid": ["dfs", "user_data_rw", "ddms", "netsys_socket", "dfs_share"], + "gid": ["dfs", "user_data_rw", "ddms", "dfs_share"], "sandbox": 0, "jobs" : { "on-start" : "services:cloudfileservice" diff --git a/services/distributedfiledaemon/BUILD.gn b/services/distributedfiledaemon/BUILD.gn index 945035e348e8853a85ebb91311455f3c1c52dc00..c0cd8cdbb6026e648abc273898081978a26f3c0e 100644 --- a/services/distributedfiledaemon/BUILD.gn +++ b/services/distributedfiledaemon/BUILD.gn @@ -125,9 +125,12 @@ ohos_shared_library("libdistributedfiledaemon") { } if (support_device_profile) { - sources += [ "src/device/dfs_static_capability.cpp" ] + sources += [ + "src/device/dfs_static_capability.cpp" + ] external_deps += [ + "app_file_service:remote_file_share_native", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", ] diff --git a/services/distributedfiledaemon/include/device/device_profile_adapter.h b/services/distributedfiledaemon/include/device/device_profile_adapter.h index b24dbd27d32260752edd4244042361e8cd0c9734..7bae78d33e055e21142e4114ebcbd04fe8bbd32f 100644 --- a/services/distributedfiledaemon/include/device/device_profile_adapter.h +++ b/services/distributedfiledaemon/include/device/device_profile_adapter.h @@ -70,7 +70,7 @@ private: } return it->second; } -#ifndef SUPPORT_DEVICE_PROFILE +#ifdef SUPPORT_DEVICE_PROFILE int32_t GetDfsVersionDataFromAppInfo(const std::string &packageNamesData, const std::string &versionsData, VersionPackageName packageName, std::string &dfsVersionData); int32_t GetAppInfoFromDP(const std::string &udid, const std::string &serviceName, std::string &appInfoJsonData); diff --git a/services/distributedfiledaemon/include/ipc/daemon.h b/services/distributedfiledaemon/include/ipc/daemon.h index e156efb3e0449b36b801cdc837403b6f8235eafd..e21c348e07b6d93ce33f7fad8f6667bcba0eb32d 100644 --- a/services/distributedfiledaemon/include/ipc/daemon.h +++ b/services/distributedfiledaemon/include/ipc/daemon.h @@ -136,6 +136,11 @@ private: void OnRemoteDied(const wptr &remote) override; }; static inline sptr dfsListenerDeathRecipient_; + int32_t CopyBaseOnRPC(const std::string &srcUri, + const std::string &dstUri, + const std::string &srcDeviceId, + const sptr &listenerCallback, + HmdfsInfo &info); void DisconnectByRemote(const std::string &networkId); int32_t CreatControlLink(const std::string &networkId); diff --git a/services/distributedfiledaemon/src/ipc/daemon.cpp b/services/distributedfiledaemon/src/ipc/daemon.cpp index acecbae4ffa8d475757e992a31c019e056bae97b..1249a9715004e6fb59f577ca3cab38e3e85e35e4 100644 --- a/services/distributedfiledaemon/src/ipc/daemon.cpp +++ b/services/distributedfiledaemon/src/ipc/daemon.cpp @@ -81,6 +81,7 @@ constexpr mode_t DEFAULT_UMASK = 0002; constexpr int32_t BLOCK_INTERVAL_SEND_FILE = 10 * 1000; constexpr int32_t DEFAULT_USER_ID = 100; constexpr int32_t VALID_MOUNT_NETWORKID_LEN = 16; +constexpr uint64_t INNER_COPY_LIMIT = 1024 * 1024 * 1024; } // namespace REGISTER_SYSTEM_ABILITY_BY_ID(Daemon, FILEMANAGEMENT_DISTRIBUTED_FILE_DAEMON_SA_ID, true); @@ -222,7 +223,6 @@ int32_t Daemon::CloseP2PConnection(const DistributedHardware::DmDeviceInfo &devi int32_t Daemon::ConnectionCount(const DistributedHardware::DmDeviceInfo &deviceInfo) { - LOGI("Connection Count networkId %{public}s", Utils::GetAnonyString(deviceInfo.networkId).c_str()); auto path = ConnectionDetector::ParseHmdfsPath(); stringstream ss; auto st_dev = ConnectionDetector::MocklispHash(path); @@ -308,6 +308,10 @@ int32_t Daemon::OpenP2PConnectionEx(const std::string &networkId, sptr &listener, HmdfsInfo &info) +int32_t Daemon::PrepareSession(const std::string &srcUri, + const std::string &dstUri, + const std::string &srcDeviceId, + const sptr &listener, + HmdfsInfo &info) { auto listenerCallback = iface_cast(listener); if (listenerCallback == nullptr) { LOGE("ListenerCallback is nullptr"); return E_NULLPTR; } + + std::string srcPhysicalPath; + if (SandboxHelper::GetPhysicalPath(srcUri, std::to_string(QueryActiveUserId()), srcPhysicalPath) != E_OK) { + LOGE("Get src path failed, invalid uri"); + return EINVAL; + } + + uint64_t fileSize = 0; + struct stat fileStat; + if (stat(srcPhysicalPath.c_str(), &fileStat) == 0) { + fileSize = fileStat.st_size; + } else { + LOGE("Stat srcPhysicalPath failed."); + } + + DfsVersion remoteDfsVersion; + auto ret = DeviceProfileAdapter::GetInstance().GetDfsVersionFromNetworkId(srcDeviceId, remoteDfsVersion); + LOGI("GetRemoteVersion: ret:%{public}d, version:%{public}s", ret, remoteDfsVersion.dump().c_str()); + + if ((ret == FileManagement::ERR_OK) && (remoteDfsVersion.majorVersionNum != 0) && fileSize < INNER_COPY_LIMIT) { + return InnerCopy(srcUri, dstUri, srcDeviceId, listenerCallback, info); + } + + return CopyBaseOnRPC(srcUri, dstUri, srcDeviceId, listenerCallback, info); +} + +int32_t Daemon::CopyBaseOnRPC(const std::string &srcUri, + const std::string &dstUri, + const std::string &srcDeviceId, + const sptr &listenerCallback, + HmdfsInfo &info) +{ auto daemon = GetRemoteSA(srcDeviceId); if (daemon == nullptr) { LOGE("Daemon is nullptr"); @@ -481,8 +520,8 @@ int32_t Daemon::PrepareSession(const std::string &srcUri, const std::string &dst } auto prepareSessionBlock = std::make_shared>(BLOCK_INTERVAL_SEND_FILE, ERR_BAD_VALUE); - auto prepareSessionData = std::make_shared( - srcUri, physicalPath, info.sessionName, daemon, info, prepareSessionBlock); + auto prepareSessionData = + std::make_shared(srcUri, physicalPath, info.sessionName, daemon, info, prepareSessionBlock); auto msgEvent = AppExecFwk::InnerEvent::Get(DEAMON_EXECUTE_PREPARE_SESSION, prepareSessionData, 0); { std::lock_guard lock(eventHandlerMutex_); @@ -858,7 +897,7 @@ void Daemon::StartEventHandler() int32_t Daemon::SendDfsDelayTask(const std::string &networkId) { LOGI("Daemon::SendDfsDelayTask enter."); - constexpr int32_t DEFAULT_DELAY_INTERVAL = 120 * 1000; // 120s + constexpr int32_t DEFAULT_DELAY_INTERVAL = 1 * 1000; if (networkId.empty()) { LOGE("networkId is empty."); return E_NULLPTR; diff --git a/services/distributedfiledaemon/src/network/softbus/softbus_asset_recv_listener.cpp b/services/distributedfiledaemon/src/network/softbus/softbus_asset_recv_listener.cpp index 014614c8c36ad576e8631cb95ca89e65143c2685..ca3f390d7862e0a6b516cf770afecc4cc1672e61 100644 --- a/services/distributedfiledaemon/src/network/softbus/softbus_asset_recv_listener.cpp +++ b/services/distributedfiledaemon/src/network/softbus/softbus_asset_recv_listener.cpp @@ -15,6 +15,7 @@ #include "network/softbus/softbus_asset_recv_listener.h" +#include #include #include @@ -28,7 +29,6 @@ #include "os_account_manager.h" #include "refbase.h" #include "utils_log.h" -#include "inttypes.h" namespace OHOS { namespace Storage { diff --git a/services/distributedfiledaemon/test/unittest/BUILD.gn b/services/distributedfiledaemon/test/unittest/BUILD.gn index ec806e8ddcb67808b1bb627940b03be00624938a..f6c8f2bf365f945ea908ae59471ddd8bb93385fe 100644 --- a/services/distributedfiledaemon/test/unittest/BUILD.gn +++ b/services/distributedfiledaemon/test/unittest/BUILD.gn @@ -47,7 +47,9 @@ ohos_unittest("device_info_test") { "${utils_path}:compiler_configs", ] - deps = [ "${utils_path}:libdistributedfileutils" ] + deps = [ + "${utils_path}:libdistributedfileutils" + ] external_deps = [ "app_file_service:remote_file_share_native", @@ -80,9 +82,6 @@ ohos_unittest("device_manager_agent_sup_test") { "${distributedfile_path}/test/mock/device_manager_impl_mock.cpp", "${distributedfile_path}/test/mock/device_manager_mock.cpp", "${distributedfile_path}/test/mock/softbus_bus_center_mock.cpp", - ] - - sources += [ "device/device_manager_agent_sup_test.cpp", "device/mock_other_method.cpp", ] @@ -848,6 +847,7 @@ ohos_unittest("softbus_handler_asset_test") { "os_account:os_account_innerkits", "samgr:samgr_proxy", "zlib:shared_libz", + "dataclassification:data_transit_mgr", ] defines = [ "private=public" ] diff --git a/services/distributedfiledaemon/test/unittest/device/device_manager_agent_test.cpp b/services/distributedfiledaemon/test/unittest/device/device_manager_agent_test.cpp index aa5c9f6136f99823ad822042452c72175439a7b7..727401819d32236bdca362432dc055753e86d0af 100644 --- a/services/distributedfiledaemon/test/unittest/device/device_manager_agent_test.cpp +++ b/services/distributedfiledaemon/test/unittest/device/device_manager_agent_test.cpp @@ -205,8 +205,8 @@ HWTEST_F(DeviceManagerAgentTest, DeviceManagerAgentTest_OnDeviceOffline_0300, Te bool res = true; try { - EXPECT_CALL(*deviceManagerImplMock_, GetLocalDeviceInfo(_, _)).WillOnce(Return(0)).WillOnce(Return(0)) - .WillOnce(Return(0)); + EXPECT_CALL(*deviceManagerImplMock_, GetLocalDeviceInfo(_, _)).WillOnce(Return(0)) + .WillOnce(Return(0)).WillOnce(Return(0)); DeviceManagerAgent::GetInstance()->InitLocalNodeInfo(); auto smp = make_shared(Utils::DfsuMountArgumentDescriptors::Alpha(100, "relativePath")); auto agent1 = make_shared(smp); diff --git a/services/distributedfiledaemon/test/unittest/device/device_profile_adapter/BUILD.gn b/services/distributedfiledaemon/test/unittest/device/device_profile_adapter/BUILD.gn index 367d58b503bc409e35c436f25b7acaaab227fc44..c8b2b66b317bada22d01368aab38a8e97e283741 100644 --- a/services/distributedfiledaemon/test/unittest/device/device_profile_adapter/BUILD.gn +++ b/services/distributedfiledaemon/test/unittest/device/device_profile_adapter/BUILD.gn @@ -75,6 +75,10 @@ ohos_unittest("device_profile_adapter_test") { "private=public", "LOG_TAG=\"distributedfile_daemon\"", ] + + if (support_device_profile) { + defines += [ "SUPPORT_DEVICE_PROFILE" ] + } } group("unittest") { diff --git a/services/distributedfiledaemon/test/unittest/ipc/daemon/BUILD.gn b/services/distributedfiledaemon/test/unittest/ipc/daemon/BUILD.gn index 391d158b1b419259b222a95afd91a29ba452429d..b2b582d6b2c96e5c14afd4808d3bf4e0926253f5 100644 --- a/services/distributedfiledaemon/test/unittest/ipc/daemon/BUILD.gn +++ b/services/distributedfiledaemon/test/unittest/ipc/daemon/BUILD.gn @@ -40,6 +40,7 @@ ohos_unittest("daemon_test") { module_out_path = module_output_path include_dirs = [ + "${distributedfile_path}/services/distributedfiledaemon/include/device", "${distributedfile_path}/services/distributedfiledaemon/include/channel_manager", "${distributedfile_path}/services/distributedfiledaemon/include/network/softbus", "${distributedfile_path}/services/distributedfiledaemon/test/mock/include", @@ -49,15 +50,6 @@ ohos_unittest("daemon_test") { sources = [ "${distributedfile_path}/test/mock/device_manager_impl_mock.cpp", "${services_path}/distributedfiledaemon/src/ipc/daemon.cpp", - "${services_path}/distributedfiledaemon/src/ipc/daemon_eventhandler.cpp", - "${services_path}/distributedfiledaemon/src/ipc/daemon_execute.cpp", - "${services_path}/distributedfiledaemon/src/ipc/daemon_stub.cpp", - "${services_path}/distributedfiledaemon/src/ipc/file_trans_listener_proxy.cpp", - "${services_path}/distributedfiledaemon/src/ipc/trans_mananger.cpp", - "${services_path}/distributedfiledaemon/src/mountpoint/mount_point.cpp", - "${services_path}/distributedfiledaemon/src/multiuser/os_account_observer.cpp", - "${services_path}/distributedfiledaemon/src/network/softbus/softbus_asset_send_listener.cpp", - "${services_path}/distributedfiledaemon/src/network/softbus/softbus_session_pool.cpp", "${services_path}/distributedfiledaemon/test/mock/all_connect_manager_mock.cpp", "${services_path}/distributedfiledaemon/test/mock/channel_manager_mock.cpp", "${services_path}/distributedfiledaemon/test/mock/connection_detector_mock.cpp", diff --git a/services/distributedfiledaemon/test/unittest/ipc/daemon/daemon_test.cpp b/services/distributedfiledaemon/test/unittest/ipc/daemon/daemon_test.cpp index 7b9d837de0d7c4301b47f79c023ad4a68d02b464..85fd35d67c689d520b52ade6a8aed72af7c7c00b 100644 --- a/services/distributedfiledaemon/test/unittest/ipc/daemon/daemon_test.cpp +++ b/services/distributedfiledaemon/test/unittest/ipc/daemon/daemon_test.cpp @@ -25,6 +25,7 @@ #include "common_event_manager.h" #include "connect_count/connect_count.h" #include "connection_detector_mock.h" +#include "copy/file_size_utils.h" #include "daemon.h" #include "daemon_execute.h" #include "daemon_mock.h" @@ -32,6 +33,7 @@ #include "device_manager_agent_mock.h" #include "device_manager_impl.h" #include "device_manager_impl_mock.h" +#include "device_profile_adapter.h" #include "dfs_error.h" #include "dfsu_access_token_helper.h" #include "i_file_trans_listener.h" @@ -80,6 +82,15 @@ int32_t DeviceProfileAdapter::GetDfsVersionFromNetworkId(const std::string &netw DfsVersion &dfsVersion, VersionPackageName packageName) { + if (networkId == NETWORKID_ONE) { + dfsVersion.majorVersionNum = 0; + return OHOS::FileManagement::E_OK; + } + + if (networkId == NETWORKID_TWO) { + dfsVersion.majorVersionNum = 1; + return OHOS::FileManagement::E_OK; + } dfsVersion = g_dfsVersion; return g_getDfsVersionFromNetworkId; } @@ -280,6 +291,8 @@ void DaemonTest::TearDownTestCase(void) DfsDeviceManagerImpl::dfsDeviceManagerImpl = nullptr; channelManagerMock_ = nullptr; IChannelManagerMock::iChannelManagerMock = nullptr; + deviceManagerImplMock_ = nullptr; + DfsDeviceManagerImpl::dfsDeviceManagerImpl = nullptr; std::string path = "/mnt/hmdfs/100/account/device_view/local/data/com.example.app"; if (std::filesystem::exists(path)) { @@ -597,8 +610,8 @@ HWTEST_F(DaemonTest, DaemonTest_ConnectionAndMount_001, TestSize.Level1) EXPECT_CALL(*connectionDetectorMock_, RepeatGetConnectionStatus(_, _)).WillOnce(Return(E_OK)); EXPECT_EQ(daemon_->ConnectionAndMount(deviceInfo, "test", 100, remoteReverseObj), ERR_BAD_VALUE); - EXPECT_CALL(*deviceManagerAgentMock_, OnDeviceP2POnline(_)).WillOnce(Return(E_OK)); - EXPECT_CALL(*connectionDetectorMock_, RepeatGetConnectionStatus(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*deviceManagerAgentMock_, OnDeviceP2POnline(_)).WillRepeatedly(Return(E_OK)); + EXPECT_CALL(*connectionDetectorMock_, RepeatGetConnectionStatus(_, _)).WillRepeatedly(Return(E_OK)); EXPECT_CALL(*deviceManagerAgentMock_, GetDeviceIdByNetworkId(_)).WillOnce(Return("test")); EXPECT_CALL(*deviceManagerAgentMock_, MountDfsDocs(_, _)).WillOnce(Return(E_OK)); EXPECT_EQ(daemon_->ConnectionAndMount(deviceInfo, "test", 100, remoteReverseObj), E_OK); @@ -761,51 +774,58 @@ HWTEST_F(DaemonTest, DaemonTest_RequestSendFile_003, TestSize.Level1) /** * @tc.name: DaemonTest_PrepareSession_001 - * @tc.desc: verify PrepareSession. + * @tc.desc: 验证 PrepareSession 方法在多种场景下的分支覆盖 * @tc.type: FUNC * @tc.require: I7TDJK */ HWTEST_F(DaemonTest, DaemonTest_PrepareSession_001, TestSize.Level1) { - GTEST_LOG_(INFO) << "DaemonTest_PrepareSession_001 begin"; + GTEST_LOG_(INFO) << "DaemonTest_PrepareSession_001 start"; ASSERT_NE(daemon_, nullptr); HmdfsInfo hmdfsInfo; - EXPECT_EQ(daemon_->PrepareSession("", "", "", nullptr, hmdfsInfo), E_NULLPTR); - + std::string srcUri = "file://docs/storage/el2/distributedfiles/test.txt"; + std::string dstUri = "file://media/storage/el2/distributedfiles/test.txt?networkid=testDevice"; + std::string srcDeviceId = "testDevice"; sptr listener = new (std::nothrow) FileTransListenerMock(); - ASSERT_TRUE(listener != nullptr) << "listener assert failed!"; - sptr sysAbilityManager = new (std::nothrow) ISystemAbilityManagerMock(); - ASSERT_TRUE(sysAbilityManager != nullptr) << "sysAbilityManager assert failed!"; - EXPECT_CALL(*smc_, GetSystemAbilityManager()).WillOnce(Return(sysAbilityManager)); - EXPECT_CALL(*sysAbilityManager, GetSystemAbility(_, _)).WillOnce(Return(nullptr)); - EXPECT_EQ(daemon_->PrepareSession("", "", "", listener, hmdfsInfo), E_SA_LOAD_FAILED); + ASSERT_TRUE(listener != nullptr) << "监听器创建失败"; - sptr daemon = new (std::nothrow) DaemonMock(); - ASSERT_TRUE(daemon != nullptr) << "daemon assert failed!"; - EXPECT_CALL(*smc_, GetSystemAbilityManager()).WillOnce(Return(sysAbilityManager)); - EXPECT_CALL(*sysAbilityManager, GetSystemAbility(_, _)).WillOnce(Return(daemon)); - EXPECT_CALL(*daemon, GetRemoteCopyInfo(_, _, _)).WillOnce(Return(ERR_BAD_VALUE)); - EXPECT_EQ(daemon_->PrepareSession("", "", "", listener, hmdfsInfo), E_SOFTBUS_SESSION_FAILED); + // 测试用例 1: 空监听器 + EXPECT_EQ(daemon_->PrepareSession("", "", "", nullptr, hmdfsInfo), E_NULLPTR); - g_getHapTokenInfo = Security::AccessToken::AccessTokenKitRet::RET_SUCCESS; + // 测试用例 2: 有效 URI,物理路径无效 + g_getPhysicalPath = ERR_BAD_VALUE; + g_checkValidPath = false; + EXPECT_EQ(daemon_->PrepareSession(srcUri, dstUri, srcDeviceId, listener, hmdfsInfo), EINVAL); + + // 测试用例 3: 有效 URI,物理路径有效,stat 失败 g_getPhysicalPath = E_OK; + g_physicalPath = "/mnt/hmdfs/100/account/device_view/local/data/com.example.app/docs/test.txt"; + g_checkValidPath = true; g_isFile = false; - g_isFolder = true; - hmdfsInfo.dirExistFlag = true; - g_physicalPath = "tes@t/test"; - std::string dstUri = "file://docs/data/storage/el2/distributedfiles/images/1.png"; - EXPECT_CALL(*smc_, GetSystemAbilityManager()).WillOnce(Return(sysAbilityManager)); - EXPECT_CALL(*sysAbilityManager, GetSystemAbility(_, _)).WillOnce(Return(daemon)); - EXPECT_CALL(*daemon, GetRemoteCopyInfo(_, _, _)).WillOnce(Return(E_OK)); - SoftBusSessionPool::SessionInfo sessionInfo; - while (true) { - auto ret = SoftBusSessionPool::GetInstance().GenerateSessionName(sessionInfo); - if (ret.empty()) { - break; - } + EXPECT_EQ(daemon_->PrepareSession(srcUri, dstUri, srcDeviceId, listener, hmdfsInfo), E_SA_LOAD_FAILED); + + // 测试用例 4: 有效 URI,物理路径有效,stat 成功,DFS 版本为 0,文件大小 < 1GB, 走innerCopy + g_getPhysicalPath = E_OK; + g_physicalPath = "/mnt/hmdfs/100/account/device_view/local/data/com.example.app/docs/1.txt"; + g_checkValidPath = true; + g_isFile = true; + g_isFolder = false; + std::ofstream file(g_physicalPath); + ASSERT_TRUE(file.good()) << "创建测试文件失败"; + file.close(); + EXPECT_EQ(daemon_->PrepareSession(srcUri, dstUri, NETWORKID_ONE, listener, hmdfsInfo), E_SA_LOAD_FAILED); + + // 测试用例 5: DFS 有效 URI,物理路径有效,stat 成功,DFS 版本为 1,文件大小 < 1GB, CopyBaseOnRPC + EXPECT_EQ(daemon_->PrepareSession(srcUri, dstUri, NETWORKID_TWO, listener, hmdfsInfo), 22); + + // 测试用例 6: DFS 有效 URI,物理路径有效,stat 成功,DFS 版本获取失败,文件大小 < 1GB, CopyBaseOnRPC + EXPECT_EQ(daemon_->PrepareSession(srcUri, dstUri, "invalidDevice", listener, hmdfsInfo), E_SA_LOAD_FAILED); + + // 清理 + if (std::filesystem::exists(g_physicalPath)) { + std::filesystem::remove(g_physicalPath); } - EXPECT_EQ(daemon_->PrepareSession("", dstUri, "", listener, hmdfsInfo), E_SOFTBUS_SESSION_FAILED); - SoftBusSessionPool::GetInstance().sessionMap_.clear(); + GTEST_LOG_(INFO) << "DaemonTest_PrepareSession_001 end"; } diff --git a/services/distributedfiledaemon/test/unittest/ipc/daemon_execute/BUILD.gn b/services/distributedfiledaemon/test/unittest/ipc/daemon_execute/BUILD.gn index b84a62bb8a0ae21aa1f87c1ca92f261ef6dde4a2..15c22b13f5f0875d7bc60ed7f83af2da103f69fe 100644 --- a/services/distributedfiledaemon/test/unittest/ipc/daemon_execute/BUILD.gn +++ b/services/distributedfiledaemon/test/unittest/ipc/daemon_execute/BUILD.gn @@ -47,19 +47,6 @@ ohos_unittest("daemon_execute_test") { ] sources = [ - "${distributedfile_path}/frameworks/native/distributed_file_inner/src/asset/asset_obj.cpp", - "${services_path}/distributedfiledaemon/src/connect_count/connect_count.cpp", - "${services_path}/distributedfiledaemon/src/ipc/asset_callback_manager.cpp", - "${services_path}/distributedfiledaemon/src/ipc/daemon.cpp", - "${services_path}/distributedfiledaemon/src/ipc/daemon_eventhandler.cpp", - "${services_path}/distributedfiledaemon/src/ipc/daemon_execute.cpp", - "${services_path}/distributedfiledaemon/src/ipc/daemon_stub.cpp", - "${services_path}/distributedfiledaemon/src/ipc/file_trans_listener_proxy.cpp", - "${services_path}/distributedfiledaemon/src/ipc/trans_mananger.cpp", - "${services_path}/distributedfiledaemon/src/mountpoint/mount_point.cpp", - "${services_path}/distributedfiledaemon/src/multiuser/os_account_observer.cpp", - "${services_path}/distributedfiledaemon/src/network/softbus/softbus_asset_send_listener.cpp", - "${services_path}/distributedfiledaemon/src/network/softbus/softbus_session_pool.cpp", "${services_path}/distributedfiledaemon/test/mock/all_connect_manager_mock.cpp", "${services_path}/distributedfiledaemon/test/mock/connection_detector_mock.cpp", "${services_path}/distributedfiledaemon/test/mock/device_manager_agent_mock.cpp", diff --git a/test/fuzztest/daemonstub_fuzzer/BUILD.gn b/test/fuzztest/daemonstub_fuzzer/BUILD.gn index b7e42b97c0fb0812eab6676f8500b00b7908f739..368e61c5080c648393ec36020dd98db4d51911a3 100644 --- a/test/fuzztest/daemonstub_fuzzer/BUILD.gn +++ b/test/fuzztest/daemonstub_fuzzer/BUILD.gn @@ -17,7 +17,7 @@ import("//build/test.gni") import("//foundation/filemanagement/dfs_service/distributedfile.gni") ohos_fuzztest("DaemonStubFuzzTest") { - module_out_path = "distributed_file_system/dfs_service_daemon" + module_out_path = "dfs_service/dfs_service_daemon" fuzz_config_file = "${distributedfile_path}/test/fuzztest/daemonstub_fuzzer" include_dirs = [ "${distributedfile_path}/services/distributedfiledaemon/include", diff --git a/test/fuzztest/daemonstub_fuzzer/daemonstub_fuzzer.cpp b/test/fuzztest/daemonstub_fuzzer/daemonstub_fuzzer.cpp index 92f39cd91ddeb223781b2fd60b00ed70b6a97cb3..717f38bb2cb140ba547df75d955d216fe73631a1 100644 --- a/test/fuzztest/daemonstub_fuzzer/daemonstub_fuzzer.cpp +++ b/test/fuzztest/daemonstub_fuzzer/daemonstub_fuzzer.cpp @@ -19,6 +19,7 @@ #include #include +#include "copy/ipc_wrapper.h" #include "daemon_stub.h" #include "distributed_file_daemon_ipc_interface_code.h" #include "ipc_skeleton.h" @@ -343,6 +344,51 @@ void HandleInnerCancelCopyTaskFuzzTest(std::shared_ptr daemonStubPtr daemonStubPtr->OnRemoteRequest(code, datas, reply, option); } +void WriteUriByRawDataFuzzTest(const uint8_t *data, size_t size) +{ + MessageParcel datas; + std::vector uriVec { std::string(reinterpret_cast(data), size) }; + + IpcWrapper::WriteUriByRawData(datas, uriVec); + IpcWrapper::WriteBatchUris(datas, uriVec); + + void* buf = nullptr; + if (IpcWrapper::GetData(buf, size, data)) { + free(buf); + buf = nullptr; + } +} + +void ReadBatchUriByRawDataFuzzTest(const uint8_t *data, size_t size) +{ + MessageParcel datas; + std::vector uriVec; + + datas.WriteInt32(0); + IpcWrapper::ReadBatchUriByRawData(datas, uriVec); + + datas.WriteInt32(1); + datas.WriteBuffer(data, size); + datas.RewindRead(0); + + IpcWrapper::ReadBatchUriByRawData(datas, uriVec); +} + +void ReadBatchUrisFuzzTest(const uint8_t *data, size_t size) +{ + MessageParcel datas; + std::vector uriVec; + + datas.WriteUint32(0); + IpcWrapper::ReadBatchUris(datas, uriVec); + + datas.WriteUint32(1); + datas.WriteBuffer(data, size); + datas.RewindRead(0); + + IpcWrapper::ReadBatchUris(datas, uriVec); +} + void SetAccessTokenPermission() { uint64_t tokenId; @@ -396,5 +442,9 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) OHOS::HandleUnRegisterRecvCallbackFuzzTest(daemonStubPtr, data, size); OHOS::HandleGetDfsUrisDirFromLocalFuzzTest(daemonStubPtr, data, size); OHOS::HandleInnerCancelCopyTaskFuzzTest(daemonStubPtr, data, size); + + OHOS::WriteUriByRawDataFuzzTest(data, size); + OHOS::ReadBatchUriByRawDataFuzzTest(data, size); + OHOS::ReadBatchUrisFuzzTest(data, size); return 0; } diff --git a/test/fuzztest/filetranslistenerstub_fuzzer/BUILD.gn b/test/fuzztest/filetranslistenerstub_fuzzer/BUILD.gn index b3153c7e2fc03546bfc16915843047d10397c637..6fff548458ee5b73b6e84ad3d2277a39c2b3ba39 100644 --- a/test/fuzztest/filetranslistenerstub_fuzzer/BUILD.gn +++ b/test/fuzztest/filetranslistenerstub_fuzzer/BUILD.gn @@ -17,7 +17,7 @@ import("//build/test.gni") import("//foundation/filemanagement/dfs_service/distributedfile.gni") ohos_fuzztest("FileTransListenerStubFuzzTest") { - module_out_path = "distributed_file_system/dfs_service_daemon" + module_out_path = "dfs_service/dfs_service_daemon" fuzz_config_file = "${distributedfile_path}/test/fuzztest/filetranslistenerstub_fuzzer" include_dirs = [ diff --git a/test/mock/message_parcel_mock.cpp b/test/mock/message_parcel_mock.cpp index 669fbf90cb45d63cd6c646409e535df5ffab6369..fb33c08d0945ada2c7a1de281bc7f2e044edbe8f 100644 --- a/test/mock/message_parcel_mock.cpp +++ b/test/mock/message_parcel_mock.cpp @@ -267,6 +267,6 @@ uint32_t Parcel::ReadUint32() return DfsMessageParcel::messageParcel->ReadUint32(); } std::cout << "ReadUint32 mock failed, messageParcel is nullptr" << std::endl; - return 1; // 1: default value + return 1; // : default value } } // namespace OHOS \ No newline at end of file diff --git a/test/unittests/cloud_disk/BUILD.gn b/test/unittests/cloud_disk/BUILD.gn index 68d5126875b1949712604046ecdd0369f26dc176..9206c3791e6261ed19c62510fe11c87960c4daf2 100644 --- a/test/unittests/cloud_disk/BUILD.gn +++ b/test/unittests/cloud_disk/BUILD.gn @@ -27,6 +27,7 @@ ohos_unittest("account_status_listener_test") { "${services_path}/cloudfiledaemon/include/", "${services_path}/cloudfiledaemon/include/cloud_disk/", "${services_path}/cloudfiledaemon/include/fuse_manager/", + "${services_path}/cloudfiledaemon/include/utils/", ] sources = [ @@ -35,11 +36,13 @@ ohos_unittest("account_status_listener_test") { "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_helper.cpp", "${services_path}/cloudfiledaemon/src/fuse_manager/cloud_daemon_statistic.cpp", "${services_path}/cloudfiledaemon/src/fuse_manager/fuse_manager.cpp", + "${services_path}/cloudfiledaemon/src/utils/setting_data_helper.cpp", "account_status_listener_test.cpp", ] deps = [ "${clouddisk_database_path}:clouddisk_database", + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit_core", "${innerkits_native_path}/cloudsync_kit_inner:cloudsync_kit_inner", "${innerkits_native_path}/cloudsync_kit_inner:cloudsync_kit_inner_lite", "${utils_path}:libdistributedfiledentry", @@ -49,8 +52,10 @@ ohos_unittest("account_status_listener_test") { external_deps = [ "ability_base:want", + "ability_runtime:dataobs_manager", "c_utils:utils", "common_event_service:cesfwk_innerkits", + "data_share:datashare_consumer", "ffrt:libffrt", "googletest:gmock_main", "googletest:gtest_main", @@ -58,6 +63,7 @@ ohos_unittest("account_status_listener_test") { "hisysevent:libhisysevent", "hitrace:hitrace_meter", "init:libbegetutil", + "ipc:ipc_single", "libfuse:libfuse", "relational_store:native_rdb", ] @@ -164,7 +170,6 @@ ohos_unittest("database_manager_test") { ] deps = [ - "${distributedfile_path}/adapter/cloud_adapter_example:cloud_adapter", "${innerkits_native_path}/cloudsync_kit_inner:cloudsync_kit_inner_lite", "${utils_path}:libdistributedfiledentry", "${utils_path}:libdistributedfileutils", diff --git a/test/unittests/cloud_disk/account_status_listener_test.cpp b/test/unittests/cloud_disk/account_status_listener_test.cpp index c6afd037c9e717914def4baa0bd6e191247df340..220afb725d1892ffe1fa0ec6cd0dbc438baa8ffa 100644 --- a/test/unittests/cloud_disk/account_status_listener_test.cpp +++ b/test/unittests/cloud_disk/account_status_listener_test.cpp @@ -19,11 +19,13 @@ #include "account_status_listener.h" #include "common_event_manager.h" #include "common_event_support.h" +#include "setting_data_helper.h" namespace OHOS::FileManagement::CloudDisk::Test { using namespace testing; using namespace testing::ext; using namespace std; +using namespace OHOS::FileManagement::CloudFile; using Want = OHOS::AAFwk::Want; constexpr int32_t USER_ID = 101; @@ -46,6 +48,7 @@ void AccountStatusListenerTest::SetUpTestCase(void) matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN); matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT); matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_DATA_SHARE_READY); subscribeInfo_ = make_shared(matchingSkills); accountStatusSubscriber_ = make_shared(*subscribeInfo_); accountStatusListener_ = make_shared(); @@ -135,6 +138,30 @@ HWTEST_F(AccountStatusListenerTest, OnReceiveEventTest003, TestSize.Level1) GTEST_LOG_(INFO) << "OnReceiveEventTest003 End"; } +/** + * @tc.name: OnReceiveEventTest004 + * @tc.desc: Verify the OnReceiveEvent function + * @tc.type: FUNC + */ +HWTEST_F(AccountStatusListenerTest, OnReceiveEventTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnReceiveEventTest004 Start"; + try { + Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_DATA_SHARE_READY); + string data(EventFwk::CommonEventSupport::COMMON_EVENT_DATA_SHARE_READY); + EventFwk::CommonEventData eventData(want, USER_ID, data); + + SettingDataHelper::GetInstance().isBundleInited_ = true; + accountStatusSubscriber_->OnReceiveEvent(eventData); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnReceiveEventTest004 ERROR"; + } + GTEST_LOG_(INFO) << "OnReceiveEventTest004 End"; +} + /** * @tc.name: StopTest001 * @tc.desc: Verify the Stop function diff --git a/test/unittests/cloud_disk/file_operations_cloud_test.cpp b/test/unittests/cloud_disk/file_operations_cloud_test.cpp index 7ff7cec2be6cbcbc7ddd1e544cec82b80517fa81..f31bb9e6d2738f997d61471be458599f18974669 100644 --- a/test/unittests/cloud_disk/file_operations_cloud_test.cpp +++ b/test/unittests/cloud_disk/file_operations_cloud_test.cpp @@ -694,7 +694,7 @@ HWTEST_F(FileOperationsCloudTest, CreateTest002, TestSize.Level1) EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))) .WillOnce(Return(reinterpret_cast(&data))); - EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillRepeatedly(Return(E_OK)); EXPECT_CALL(*insMock, fuse_reply_create(_, _, _)).WillOnce(Return(E_OK)); fileOperationsCloud_->Create(req, parent, name, mode, &fi); EXPECT_TRUE(true); @@ -751,7 +751,7 @@ HWTEST_F(FileOperationsCloudTest, ReadDirTest002, TestSize.Level1) struct fuse_file_info fi; EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); - EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillRepeatedly(Return(E_OK)); fileOperationsCloud_->ReadDir(req, ino, size, off, &fi); EXPECT_TRUE(true); } catch (...) { @@ -1241,7 +1241,7 @@ HWTEST_F(FileOperationsCloudTest, GetXattrTest001, TestSize.Level1) string name = HMDFS_PERMISSION_XATTR; EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); - EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillRepeatedly(Return(E_OK)); fileOperationsCloud_->GetXattr(req, ino, name.c_str(), size); EXPECT_TRUE(true); } catch (...) { @@ -1322,7 +1322,7 @@ HWTEST_F(FileOperationsCloudTest, GetXattrTest004, TestSize.Level1) string name = IS_FAVORITE_XATTR; EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); - EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillRepeatedly(Return(E_OK)); fileOperationsCloud_->GetXattr(req, ino, name.c_str(), size); EXPECT_TRUE(true); } catch (...) { @@ -1376,7 +1376,7 @@ HWTEST_F(FileOperationsCloudTest, GetXattrTest006, TestSize.Level1) string name = IS_FILE_STATUS_XATTR; EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); - EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillRepeatedly(Return(E_OK)); fileOperationsCloud_->GetXattr(req, ino, name.c_str(), size); EXPECT_TRUE(true); } catch (...) { @@ -1457,7 +1457,7 @@ HWTEST_F(FileOperationsCloudTest, GetXattrTest009, TestSize.Level1) string name = CLOUD_FILE_LOCATION; EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); - EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillRepeatedly(Return(E_OK)); fileOperationsCloud_->GetXattr(req, ino, name.c_str(), size); EXPECT_TRUE(true); } catch (...) { @@ -1510,7 +1510,7 @@ HWTEST_F(FileOperationsCloudTest, GetXattrTest011, TestSize.Level1) string name = CLOUD_CLOUD_RECYCLE_XATTR; EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); - EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillRepeatedly(Return(E_OK)); fileOperationsCloud_->GetXattr(req, ino, name.c_str(), size); EXPECT_TRUE(true); } catch (...) { @@ -1564,7 +1564,7 @@ HWTEST_F(FileOperationsCloudTest, GetXattrTest013, TestSize.Level1) string name = CLOUD_CLOUD_RECYCLE_XATTR; EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillRepeatedly(Return(reinterpret_cast(&data))); - EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillRepeatedly(Return(E_OK)); fileOperationsCloud_->GetXattr(req, ino, name.c_str(), size); EXPECT_TRUE(true); } catch (...) { @@ -2551,7 +2551,7 @@ HWTEST_F(FileOperationsCloudTest, SetAttrTest001, TestSize.Level1) struct fuse_file_info fi; EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); - EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*insMock, fuse_reply_err(_, _)).WillRepeatedly(Return(E_OK)); fileOperationsCloud_->SetAttr(req, ino, &attr, valid, &fi); EXPECT_TRUE(true); } catch (...) { @@ -2579,10 +2579,7 @@ HWTEST_F(FileOperationsCloudTest, SetAttrTest002, TestSize.Level1) struct fuse_file_info fi; EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))); - EXPECT_CALL(*insMock, fuse_reply_attr(_, _, _)) - .WillOnce(Return(E_OK)) - .WillOnce(Return(E_OK)) - .WillOnce(Return(E_OK)); + EXPECT_CALL(*insMock, fuse_reply_attr(_, _, _)).WillRepeatedly(Return(E_OK)); fileOperationsCloud_->SetAttr(req, ino, &attr, valid, &fi); EXPECT_TRUE(true); } catch (...) { diff --git a/test/unittests/cloud_disk/fuse_operations_test.cpp b/test/unittests/cloud_disk/fuse_operations_test.cpp index f44db94cea3869d7c83f7ec6bf8e8ebc57236d47..30a65b3a7b1c00f848bb128acd5270b6c7548479 100644 --- a/test/unittests/cloud_disk/fuse_operations_test.cpp +++ b/test/unittests/cloud_disk/fuse_operations_test.cpp @@ -26,10 +26,13 @@ #include "utils_log.h" #include "assistant.h" +#define FUSE_ROOT_TWO 2 + namespace OHOS::FileManagement::CloudDisk::Test { using namespace testing; using namespace testing::ext; using namespace std; +static const string RECYCLE_NAME = ".trash"; class FuseOperationsTest : public testing::Test { public: @@ -129,8 +132,8 @@ HWTEST_F(FuseOperationsTest, LookupTest, TestSize.Level1) EXPECT_CALL(*insMock, fuse_req_userdata(_)).WillOnce(Return(reinterpret_cast(&data))) .WillOnce(Return(reinterpret_cast(&data))); fuse_req_t req = nullptr; - const char *name = ""; - fuse_ino_t parent = 0; + const char *name = RECYCLE_NAME.c_str(); + fuse_ino_t parent = FUSE_ROOT_TWO; fuseoperations_->Lookup(req, parent, name); EXPECT_NE(parent, FUSE_ROOT_ID); diff --git a/test/unittests/cloud_file_kit_inner/data_sync/sync_state_manager_test.cpp b/test/unittests/cloud_file_kit_inner/data_sync/sync_state_manager_test.cpp index be060ad7462a043529c4ae023b793ed66546ccac..53f8cdc359bc9acb9f9fe86e34a362080333cddb 100644 --- a/test/unittests/cloud_file_kit_inner/data_sync/sync_state_manager_test.cpp +++ b/test/unittests/cloud_file_kit_inner/data_sync/sync_state_manager_test.cpp @@ -12,14 +12,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "sync_state_manager.h" #include #include +#include "sync_state_manager.h" +#include "system_mock.h" +#include "data_sync_const.h" namespace OHOS::FileManagement::CloudSync::Test { using namespace testing; using namespace testing::ext; using namespace std; +using namespace system; class MockSyncStateManager : public SyncStateManager { public: @@ -504,4 +507,143 @@ HWTEST_F(SyncStateManagerTest, SyncStateManagerTest_022, TestSize.Level1) } GTEST_LOG_(INFO) << "SyncStateManagerTest_022 End"; } + +HWTEST_F(SyncStateManagerTest, CheckMediaLibCleaningTest_001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckMediaLibCleaningTest_001 start"; + try { + std::shared_ptr systemMock = std::make_shared(); + ISystem::system_ = systemMock; + EXPECT_CALL(*systemMock, GetParameter(_, _)).WillOnce(Return("")); + SyncStateManager syncStateManager; + bool ret = syncStateManager.CheckMediaLibCleaning(); + EXPECT_EQ(ret, false); + + ISystem::system_ = nullptr; + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CheckMediaLibCleaningTest_001 ERROR"; + } + GTEST_LOG_(INFO) << "CheckMediaLibCleaningTest_001 End"; +} + +HWTEST_F(SyncStateManagerTest, CheckMediaLibCleaningTest_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckMediaLibCleaningTest_002 start"; + try { + std::shared_ptr systemMock = std::make_shared(); + ISystem::system_ = systemMock; + EXPECT_CALL(*systemMock, GetParameter(_, _)).WillOnce(Return("0")); + SyncStateManager syncStateManager; + bool ret = syncStateManager.CheckMediaLibCleaning(); + EXPECT_EQ(ret, false); + + ISystem::system_ = nullptr; + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CheckMediaLibCleaningTest_002 ERROR"; + } + GTEST_LOG_(INFO) << "CheckMediaLibCleaningTest_002 End"; +} + +HWTEST_F(SyncStateManagerTest, CheckMediaLibCleaningTest_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckMediaLibCleaningTest_003 start"; + try { + std::shared_ptr systemMock = std::make_shared(); + ISystem::system_ = systemMock; + EXPECT_CALL(*systemMock, GetParameter(_, _)).WillOnce(Return("xxx")); + EXPECT_CALL(*systemMock, SetParameter(_, _)).WillOnce(Return(true)); + SyncStateManager syncStateManager; + bool ret = syncStateManager.CheckMediaLibCleaning(); + EXPECT_EQ(ret, false); + + ISystem::system_ = nullptr; + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CheckMediaLibCleaningTest_003 ERROR"; + } + GTEST_LOG_(INFO) << "CheckMediaLibCleaningTest_003 End"; +} + +HWTEST_F(SyncStateManagerTest, CheckMediaLibCleaningTest_004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckMediaLibCleaningTest_004 start"; + try { + std::shared_ptr systemMock = std::make_shared(); + ISystem::system_ = systemMock; + EXPECT_CALL(*systemMock, GetParameter(_, _)).WillOnce(Return("123456789123456789")); + EXPECT_CALL(*systemMock, SetParameter(_, _)).WillOnce(Return(true)); + SyncStateManager syncStateManager; + bool ret = syncStateManager.CheckMediaLibCleaning(); + EXPECT_EQ(ret, false); + + ISystem::system_ = nullptr; + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CheckMediaLibCleaningTest_004 ERROR"; + } + GTEST_LOG_(INFO) << "CheckMediaLibCleaningTest_004 End"; +} + +HWTEST_F(SyncStateManagerTest, CheckMediaLibCleaningTest_005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckMediaLibCleaningTest_005 start"; + try { + std::shared_ptr systemMock = std::make_shared(); + ISystem::system_ = systemMock; + EXPECT_CALL(*systemMock, GetParameter(_, _)).WillOnce(Return("1")); + EXPECT_CALL(*systemMock, SetParameter(_, _)).WillOnce(Return(true)); + SyncStateManager syncStateManager; + bool ret = syncStateManager.CheckMediaLibCleaning(); + EXPECT_EQ(ret, false); + + ISystem::system_ = nullptr; + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CheckMediaLibCleaningTest_005 ERROR"; + } + GTEST_LOG_(INFO) << "CheckMediaLibCleaningTest_005 End"; +} + +HWTEST_F(SyncStateManagerTest, CheckMediaLibCleaningTest_006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckMediaLibCleaningTest_006 start"; + try { + std::shared_ptr systemMock = std::make_shared(); + ISystem::system_ = systemMock; + uint64_t curTime = GetCurrentTimeStamp() - TWELVE_HOURS_MICROSECOND; + EXPECT_CALL(*systemMock, GetParameter(_, _)).WillOnce(Return(std::to_string(curTime))); + EXPECT_CALL(*systemMock, SetParameter(_, _)).WillOnce(Return(true)); + SyncStateManager syncStateManager; + bool ret = syncStateManager.CheckMediaLibCleaning(); + EXPECT_EQ(ret, false); + + ISystem::system_ = nullptr; + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CheckMediaLibCleaningTest_006 ERROR"; + } + GTEST_LOG_(INFO) << "CheckMediaLibCleaningTest_006 End"; +} + +HWTEST_F(SyncStateManagerTest, CheckMediaLibCleaningTest_007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckMediaLibCleaningTest_007 start"; + try { + std::shared_ptr systemMock = std::make_shared(); + ISystem::system_ = systemMock; + uint64_t curTime = GetCurrentTimeStamp() - 10; + EXPECT_CALL(*systemMock, GetParameter(_, _)).WillOnce(Return(std::to_string(curTime))); + SyncStateManager syncStateManager; + bool ret = syncStateManager.CheckMediaLibCleaning(); + EXPECT_EQ(ret, true); + + ISystem::system_ = nullptr; + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CheckMediaLibCleaningTest_007 ERROR"; + } + GTEST_LOG_(INFO) << "CheckMediaLibCleaningTest_007 End"; +} } \ No newline at end of file diff --git a/test/unittests/cloud_file_kit_inner/data_sync/system_mock.h b/test/unittests/cloud_file_kit_inner/data_sync/system_mock.h index eb273a44733339b7a7bd23e664ec4586e670b93a..633e5d533f6aaf1e83eaa126f0793edd92a47518 100644 --- a/test/unittests/cloud_file_kit_inner/data_sync/system_mock.h +++ b/test/unittests/cloud_file_kit_inner/data_sync/system_mock.h @@ -37,12 +37,18 @@ public: std::string GetParameter(const std::string &key, const std::string &def) { - return ISystem::system_->GetParameter(key, def); + if (ISystem::system_ != nullptr) { + return ISystem::system_->GetParameter(key, def); + } + return ""; } bool SetParameter(const std::string &key, const std::string &def) { - return ISystem::system_->SetParameter(key, def); + if (ISystem::system_ != nullptr) { + return ISystem::system_->SetParameter(key, def); + } + return true; } } // system } // OHOS diff --git a/test/unittests/cloudsync_api/cloudsync_impl/BUILD.gn b/test/unittests/cloudsync_api/cloudsync_impl/BUILD.gn index 5b7c57c7ec3f820757b09f3933e91b620ca20000..5b66c8cd8b1ccf0b5a0b039a404b6a0ec237862c 100644 --- a/test/unittests/cloudsync_api/cloudsync_impl/BUILD.gn +++ b/test/unittests/cloudsync_api/cloudsync_impl/BUILD.gn @@ -180,32 +180,6 @@ ohos_unittest("cloud_sync_manager_test") { use_exceptions = true } -ohos_unittest("cloud_sync_service_proxy_test") { - module_out_path = "dfs_service/dfs_service" - - sources = [ "cloud_sync_service_proxy_test.cpp" ] - - include_dirs = [ - "${services_path}/cloudsyncservice/include/ipc", - "${distributedfile_path}/test/unittests/cloudsync_api/cloudsync_impl/include", - "${distributedfile_path}/frameworks/native/cloudsync_kit_inner/include", - "${distributedfile_path}/utils/log/include", - ] - - external_deps = [ - "c_utils:utils", - "dfs_service:cloudsync_kit_inner", - "googletest:gmock_main", - "googletest:gtest_main", - "hilog:libhilog", - "ipc:ipc_single", - ] - - defines = [ "private=public" ] - - use_exceptions = true -} - ohos_unittest("cloud_download_callback_client_test") { module_out_path = "dfs_service/dfs_service" diff --git a/test/unittests/cloudsync_sa/dentry/dentry_meta_file_test.cpp b/test/unittests/cloudsync_sa/dentry/dentry_meta_file_test.cpp index 43729e354ab6ac15e59d65938007b4e0a8ad74a9..3995d7b90cee8cca28170219689ba56eec1deea4 100644 --- a/test/unittests/cloudsync_sa/dentry/dentry_meta_file_test.cpp +++ b/test/unittests/cloudsync_sa/dentry/dentry_meta_file_test.cpp @@ -453,6 +453,69 @@ HWTEST_F(DentryMetaFileTest, RecordIdToCloudId002, TestSize.Level1) GTEST_LOG_(INFO) << "RecordIdToCloudId002 End"; } +/** + * @tc.name: CloudIdToRecordId001 + * @tc.desc: Verify the CloudIdToRecordId + * @tc.type: FUNC + */ +HWTEST_F(DentryMetaFileTest, CloudIdToRecordId001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CloudIdToRecordId001 Start"; + try { + std::string hexStr = "123456789"; + string cloudId = MetaFileMgr::GetInstance().RecordIdToCloudId(hexStr, true); + string reocrdId = MetaFileMgr::GetInstance().CloudIdToRecordId(cloudId, true); + EXPECT_EQ(reocrdId, hexStr); + MetaFileMgr::GetInstance().ClearAll(); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "CloudIdToRecordId001 ERROR"; + } + GTEST_LOG_(INFO) << "CloudIdToRecordId001 End"; +} + +/** + * @tc.name:CloudIdToRecordId002 + * @tc.desc: Verify the CloudIdToRecordId + * @tc.type: FUNC + */ +HWTEST_F(DentryMetaFileTest, CloudIdToRecordId002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CloudIdToRecordId002 Start"; + try { + std::string hexStr = "1234567890"; + string cloudId = MetaFileMgr::GetInstance().RecordIdToCloudId(hexStr, true); + string reocrdId = MetaFileMgr::GetInstance().CloudIdToRecordId(cloudId, true); + EXPECT_EQ(reocrdId, hexStr); + MetaFileMgr::GetInstance().ClearAll(); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "CloudIdToRecordId002 ERROR"; + } + GTEST_LOG_(INFO) << "CloudIdToRecordId002 End"; +} + +/** + * @tc.name:CloudIdToRecordId003 + * @tc.desc: Verify the CloudIdToRecordId + * @tc.type: FUNC + */ +HWTEST_F(DentryMetaFileTest, CloudIdToRecordId003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CloudIdToRecordId003 Start"; + try { + std::string hexStr = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + string cloudId = MetaFileMgr::GetInstance().RecordIdToCloudId(hexStr); + string reocrdId = MetaFileMgr::GetInstance().CloudIdToRecordId(cloudId, true); + EXPECT_EQ(reocrdId, hexStr); + MetaFileMgr::GetInstance().ClearAll(); + } catch (...) { + EXPECT_FALSE(false); + GTEST_LOG_(INFO) << "CloudIdToRecordId003 ERROR"; + } + GTEST_LOG_(INFO) << "CloudIdToRecordId003 End"; +} + /** * @tc.name: GetParentDir001 * @tc.desc: Verify the GetParentDir diff --git a/test/unittests/cloudsync_sa/mock/data_ability_observer_stub.cpp b/test/unittests/cloudsync_sa/mock/data_ability_observer_stub.cpp index 00f12bc8b7ff4d2bde630039785540df05525a3d..6a7b78f9d35d82fa6aed38e9a69006c8b56294b4 100644 --- a/test/unittests/cloudsync_sa/mock/data_ability_observer_stub.cpp +++ b/test/unittests/cloudsync_sa/mock/data_ability_observer_stub.cpp @@ -20,6 +20,7 @@ #include "ipc_skeleton.h" #include "common_utils.h" #include "string_ex.h" +#include "dataobs_mgr_changeinfo.h" namespace OHOS { namespace AAFwk { @@ -78,7 +79,6 @@ int32_t DataAbilityObserverStub::OnChangeExtInner(MessageParcel &data, MessagePa if (!ChangeInfo::Unmarshalling(changeInfo, data)) { return IPC_STUB_INVALID_DATA_ERR; } - OnChangeExt(changeInfo); return ERR_NONE; } diff --git a/test/unittests/cloudsync_sa/mock/datashare_helper.cpp b/test/unittests/cloudsync_sa/mock/datashare_helper.cpp index fe284e1c2316ec1de367cb0919b06f67a55dccff..d5e8c731e2a7451c4746ce80580b4183c8308f97 100644 --- a/test/unittests/cloudsync_sa/mock/datashare_helper.cpp +++ b/test/unittests/cloudsync_sa/mock/datashare_helper.cpp @@ -15,6 +15,7 @@ #include "datashare_helper.h" #include "datashare_result_set.h" +#include "datashare_helper_mock.h" namespace OHOS { namespace DataShare { @@ -27,6 +28,9 @@ DataSharePredicates *DataSharePredicates::EqualTo(const std::string &field, cons std::shared_ptr DataShareHelper::Creator( const std::string &strUri, const CreateOptions &options, const std::string &bundleName) { + if (DataShareHelperMock::proxy_ != nullptr) { + return DataShareHelperMock::proxy_->Creator(strUri, options, bundleName); + } if (instance_ != nullptr) { return instance_; } @@ -37,6 +41,9 @@ std::shared_ptr DataShareHelper::Creator( std::shared_ptr DataShareHelper::Query(Uri &uri, const DataSharePredicates &predicates, std::vector &columns, DatashareBusinessError *businessError) { + if (DataShareHelperMock::proxy_ != nullptr) { + return DataShareHelperMock::proxy_->Query(uri, predicates, columns, businessError); + } if (resultSet_ != nullptr) { return resultSet_; } diff --git a/test/unittests/cloudsync_sa/mock/datashare_helper_mock.h b/test/unittests/cloudsync_sa/mock/datashare_helper_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..7e211d639757dd6eda4e43f538a10c0a9a85e572 --- /dev/null +++ b/test/unittests/cloudsync_sa/mock/datashare_helper_mock.h @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DATASHARE_HELPER_MOCK_H +#define DATASHARE_HELPER_MOCK_H + +#include +#include +#include "datashare_helper.h" + +namespace OHOS { +namespace DataShare { +class DataShareHelperMock : public DataShareHelper { +public: + MOCK_METHOD3(Creator, std::shared_ptr(const std::string &, const CreateOptions &, + const std::string &)); + MOCK_METHOD4(Query, std::shared_ptr(Uri &, const DataSharePredicates &, + std::vector &, DatashareBusinessError *)); + MOCK_METHOD2(RegisterObserver, void(const Uri &, const sptr &)); + MOCK_METHOD2(UnregisterObserver, void(const Uri &, const sptr &)); + MOCK_METHOD0(Release, bool()); + static inline std::shared_ptr proxy_ = nullptr; +}; +} // namespace OHOS +} // namespace DataShare +#endif // DATASHARE_HELPER_MOCK_H \ No newline at end of file diff --git a/test/unittests/cloudsync_sa/mock/datashare_result_set.cpp b/test/unittests/cloudsync_sa/mock/datashare_result_set.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a899cbf8f0cc1a42bcfad777ac16fe8090d9241c --- /dev/null +++ b/test/unittests/cloudsync_sa/mock/datashare_result_set.cpp @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2024 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 "datashare_result_set.h" +#include "datashare_result_set_mock.h" + +namespace OHOS { +namespace DataShare { +int32_t DataShareResultSet::GetColumnIndex(const std::string &columnName, int32_t &columnIndex) +{ + if (DataShareResultSetMock::proxy_ != nullptr) { + return DataShareResultSetMock::proxy_->GetColumnIndex(columnName, columnIndex); + } + return 0; +} + +int32_t DataShareResultSet::GetString(int32_t columnIndex, std::string &value) +{ + if (DataShareResultSetMock::proxy_ != nullptr) { + return DataShareResultSetMock::proxy_->GetString(columnIndex, value); + } + return 0; +} + +int32_t DataShareResultSet::GetLong(int32_t columnIndex, int64_t &value) +{ + if (DataShareResultSetMock::proxy_ != nullptr) { + return DataShareResultSetMock::proxy_->GetLong(columnIndex, value); + } + return 0; +} + +int32_t DataShareResultSet::GetInt(int32_t columnIndex, int32_t &value) +{ + if (DataShareResultSetMock::proxy_ != nullptr) { + return DataShareResultSetMock::proxy_->GetInt(columnIndex, value); + } + return 0; +} + +int32_t DataShareResultSet::GoToFirstRow() +{ + if (DataShareResultSetMock::proxy_ != nullptr) { + return DataShareResultSetMock::proxy_->GoToFirstRow(); + } + return 0; +} + +int32_t DataShareResultSet::GoToNextRow() +{ + if (DataShareResultSetMock::proxy_ != nullptr) { + return DataShareResultSetMock::proxy_->GoToNextRow(); + } + return 0; +} + +int32_t DataShareResultSet::Close() +{ + if (DataShareResultSetMock::proxy_ != nullptr) { + return DataShareResultSetMock::proxy_->Close(); + } + return 0; +} +} // namespace OHOS +} // namespace DataShare \ No newline at end of file diff --git a/test/unittests/cloudsync_sa/mock/datashare_result_set.h b/test/unittests/cloudsync_sa/mock/datashare_result_set.h index 0bf4b76449b62337fe2f8d7dd10a1cb2e6c04df7..2312f6a054808f4594ea4145650bbebd96c8c794 100644 --- a/test/unittests/cloudsync_sa/mock/datashare_result_set.h +++ b/test/unittests/cloudsync_sa/mock/datashare_result_set.h @@ -16,40 +16,21 @@ #ifndef DATASHARE_RESULT_SET_H #define DATASHARE_RESULT_SET_H +#include +#include + namespace OHOS { namespace DataShare { class DataShareResultSet { public: - static int GetColumnIndex(const std::string &columnName, int &columnIndex) - { - return 0; - } - static int GetString(int columnIndex, std::string &value) - { - return 0; - } - static int GetLong(int columnIndex, int64_t &value) - { - return 0; - } - static int GetInt(int columnIndex, int &value) - { - return 0; - } - static int GoToFirstRow() - { - return 0; - } - static int GoToNextRow() - { - return 0; - } - static int Close() - { - return 0; - } + static int32_t GetColumnIndex(const std::string &columnName, int32_t &columnIndex); + static int32_t GetString(int32_t columnIndex, std::string &value); + static int32_t GetLong(int32_t columnIndex, int64_t &value); + static int32_t GetInt(int32_t columnIndex, int32_t &value); + static int32_t GoToFirstRow(); + static int32_t GoToNextRow(); + static int32_t Close(); }; - } } #endif // DATASHARE_RESULT_SET_H \ No newline at end of file diff --git a/test/unittests/cloudsync_sa/mock/datashare_result_set_mock.h b/test/unittests/cloudsync_sa/mock/datashare_result_set_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..a1afc1ea15020e1e588edf9ff901063efde9eddc --- /dev/null +++ b/test/unittests/cloudsync_sa/mock/datashare_result_set_mock.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DATASHARE_RESULT_SET_MOCK_H +#define DATASHARE_RESULT_SET_MOCK_H + +#include +#include +#include "datashare_result_set.h" + +namespace OHOS { +namespace DataShare { +class DataShareResultSetMock : public DataShareResultSet { +public: + MOCK_METHOD2(GetColumnIndex, int32_t(const std::string &, int32_t &)); + MOCK_METHOD2(GetString, int32_t(int32_t, std::string &)); + MOCK_METHOD2(GetLong, int32_t(int32_t, int64_t &)); + MOCK_METHOD2(GetInt, int32_t(int32_t, int32_t &)); + MOCK_METHOD0(GoToFirstRow, int32_t()); + MOCK_METHOD0(GoToNextRow, int32_t()); + MOCK_METHOD0(Close, int32_t()); + static inline std::shared_ptr proxy_ = nullptr; +}; +} +} +#endif // DATASHARE_RESULT_SET_MOCK_H \ No newline at end of file diff --git a/test/unittests/cloudsync_sa/sync_rule/BUILD.gn b/test/unittests/cloudsync_sa/sync_rule/BUILD.gn index e9a240dabfdd7a96c129e6bdb0480af56a028633..4f252ad2f2d09022c5a9075807c41bfefd21dacd 100644 --- a/test/unittests/cloudsync_sa/sync_rule/BUILD.gn +++ b/test/unittests/cloudsync_sa/sync_rule/BUILD.gn @@ -185,6 +185,7 @@ ohos_unittest("cloud_status_test") { sources = [ "${distributedfile_path}/frameworks/native/cloud_file_kit_inner/src/sync_rule/cloud_status.cpp", "${distributedfile_path}/test/mock/cloud_file_kit_mock.cpp", + "${distributedfile_path}/test/unittests/cloudsync_sa/mock/datashare_helper.cpp", "${distributedfile_path}/utils/log/src/dfs_error.cpp", "cloud_status_test.cpp", ] @@ -194,6 +195,7 @@ ohos_unittest("cloud_status_test") { "${services_path}/cloudsyncservice/include", "${distributedfile_path}/adapter/cloud_adapter_example/include", "${distributedfile_path}/test/mock", + "${distributedfile_path}/test/unittests/cloudsync_sa/mock", ] deps = [ @@ -204,6 +206,7 @@ ohos_unittest("cloud_status_test") { ] external_deps = [ + "ability_base:zuri", "c_utils:utils", "googletest:gmock_main", "googletest:gtest_main", @@ -561,6 +564,51 @@ ohos_unittest("package_status_listener_test") { use_exceptions = true } +ohos_unittest("settings_data_manager_test") { + branch_protector_ret = "pac_ret" + sanitize = { + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = true + blocklist = "${distributedfile_path}/cfi_blocklist.txt" + } + + module_out_path = "dfs_service/dfs_service" + sources = [ + "settings_data_manager_test.cpp", + "${distributedfile_path}/frameworks/native/cloud_file_kit_inner/src/sync_rule/settings_data_manager.cpp", + "${distributedfile_path}/test/unittests/cloudsync_sa/mock/data_ability_observer_stub.cpp", + "${distributedfile_path}/test/unittests/cloudsync_sa/mock/datashare_helper.cpp", + "${distributedfile_path}/test/unittests/cloudsync_sa/mock/datashare_result_set.cpp", + ] + + include_dirs = [ + "${distributedfile_path}/interfaces/inner_api/native/cloud_file_kit_inner", + "${distributedfile_path}/test/unittests/cloudsync_sa/mock", + "${utils_path}/log/include", + ] + + deps = [ + "${utils_path}:libdistributedfileutils", + ] + + external_deps = [ + "ability_base:zuri", + "ability_runtime:dataobs_manager", + "c_utils:utils", + "googletest:gmock_main", + "googletest:gtest_main", + "hilog:libhilog", + "ipc:ipc_core", + "ipc:ipc_single", + ] + + defines = [ "private=public" ] + use_exceptions = true +} + group("cloudsync_sa_sync_rule_test") { testonly = true deps = [ @@ -572,6 +620,7 @@ group("cloudsync_sa_sync_rule_test") { ":network_status_test", ":package_status_listener_test", ":screen_status_listener_test", + ":settings_data_manager_test", ":system_load_test", ":user_status_listener_test", ] diff --git a/test/unittests/cloudsync_sa/sync_rule/battery_status_listener_test.cpp b/test/unittests/cloudsync_sa/sync_rule/battery_status_listener_test.cpp index 909e71e807ebd8957fd7b15235e5d3fd271c1625..0f2c6277024bc6bd9031ecc0dd8ed0587a7f6b93 100644 --- a/test/unittests/cloudsync_sa/sync_rule/battery_status_listener_test.cpp +++ b/test/unittests/cloudsync_sa/sync_rule/battery_status_listener_test.cpp @@ -152,7 +152,7 @@ HWTEST_F(BatteryStatusListenerTest, OnReceiveEventTest002, TestSize.Level1) GTEST_LOG_(INFO) << "OnReceiveEventTest002 Start"; try { Want want; - want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_CHARGING); + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_POWER_CONNECTED); EventFwk::CommonEventData eventData(want); auto dataSyncManager = std::make_shared(); auto batteryStatusListener = std::make_shared(dataSyncManager); @@ -178,16 +178,14 @@ HWTEST_F(BatteryStatusListenerTest, OnReceiveEventTest003, TestSize.Level1) GTEST_LOG_(INFO) << "OnReceiveEventTest003 Start"; try { Want want; - want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_DISCHARGING); + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_POWER_DISCONNECTED); EventFwk::CommonEventData eventData(want); auto dataSyncManager = std::make_shared(); auto batteryStatusListener = std::make_shared(dataSyncManager); auto subscriber = std::make_shared(EventFwk::CommonEventSubscribeInfo(), batteryStatusListener); - EXPECT_CALL(*dfsBatterySrvClient_, GetChargingStatus()) - .WillOnce(Return(ChargeState::CHARGE_STATE_ENABLE)); subscriber->OnReceiveEvent(eventData); - EXPECT_TRUE(batteryStatus_->IsCharging()); + EXPECT_FALSE(batteryStatus_->IsCharging()); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << " OnReceiveEventTest003 FAILED"; @@ -199,23 +197,18 @@ HWTEST_F(BatteryStatusListenerTest, OnReceiveEventTest003, TestSize.Level1) * @tc.name: OnReceiveEventTest * @tc.desc: Verify the OnReceiveEvent function * @tc.type: FUNC - * @tc.require: I6JPKG */ HWTEST_F(BatteryStatusListenerTest, OnReceiveEventTest004, TestSize.Level1) { GTEST_LOG_(INFO) << "OnReceiveEventTest004 Start"; try { Want want; - want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_DISCHARGING); + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_POWER_CONNECTED); EventFwk::CommonEventData eventData(want); auto dataSyncManager = std::make_shared(); auto batteryStatusListener = std::make_shared(dataSyncManager); auto subscriber = std::make_shared(EventFwk::CommonEventSubscribeInfo(), batteryStatusListener); - EXPECT_CALL(*dfsBatterySrvClient_, GetChargingStatus()) - .WillOnce(Return(ChargeState::CHARGE_STATE_DISABLE)); - EXPECT_CALL(*dfsBatterySrvClient_, GetPluggedType()) - .WillOnce(Return(PluggedType::PLUGGED_TYPE_USB)); subscriber->OnReceiveEvent(eventData); EXPECT_TRUE(batteryStatus_->IsCharging()); } catch (...) { @@ -225,61 +218,6 @@ HWTEST_F(BatteryStatusListenerTest, OnReceiveEventTest004, TestSize.Level1) GTEST_LOG_(INFO) << "OnReceiveEventTest004 End"; } -/** - * @tc.name: OnReceiveEventTest - * @tc.desc: Verify the OnReceiveEvent function - * @tc.type: FUNC - */ -HWTEST_F(BatteryStatusListenerTest, OnReceiveEventTest005, TestSize.Level1) -{ - GTEST_LOG_(INFO) << "OnReceiveEventTest005 Start"; - try { - Want want; - want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_DISCHARGING); - EventFwk::CommonEventData eventData(want); - auto dataSyncManager = std::make_shared(); - auto batteryStatusListener = std::make_shared(dataSyncManager); - auto subscriber = std::make_shared(EventFwk::CommonEventSubscribeInfo(), - batteryStatusListener); - EXPECT_CALL(*dfsBatterySrvClient_, GetChargingStatus()) - .WillOnce(Return(ChargeState::CHARGE_STATE_DISABLE)); - EXPECT_CALL(*dfsBatterySrvClient_, GetPluggedType()) - .WillOnce(Return(PluggedType::PLUGGED_TYPE_NONE)); - subscriber->OnReceiveEvent(eventData); - EXPECT_FALSE(batteryStatus_->IsCharging()); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << " OnReceiveEventTest005 FAILED"; - } - GTEST_LOG_(INFO) << "OnReceiveEventTest005 End"; -} - -/** - * @tc.name: OnReceiveEventTest - * @tc.desc: Verify the OnReceiveEvent function - * @tc.type: FUNC - */ -HWTEST_F(BatteryStatusListenerTest, OnReceiveEventTest006, TestSize.Level1) -{ - GTEST_LOG_(INFO) << "OnReceiveEventTest006 Start"; - try { - Want want; - want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_POWER_CONNECTED); - EventFwk::CommonEventData eventData(want); - auto dataSyncManager = std::make_shared(); - auto batteryStatusListener = std::make_shared(dataSyncManager); - auto subscriber = std::make_shared(EventFwk::CommonEventSubscribeInfo(), - batteryStatusListener); - batteryStatus_->SetChargingStatus(true); - subscriber->OnReceiveEvent(eventData); - EXPECT_TRUE(batteryStatus_->IsCharging()); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << " OnReceiveEventTest006 FAILED"; - } - GTEST_LOG_(INFO) << "OnReceiveEventTest006 End"; -} - /** * @tc.name: OnPowerConnectedTest001 * @tc.desc: Verify the OnPowerConnected function diff --git a/test/unittests/cloudsync_sa/sync_rule/battery_status_test.cpp b/test/unittests/cloudsync_sa/sync_rule/battery_status_test.cpp index ca436a52903a40bb8de9372196e8836207a4e7a8..09cb70665686e6dc9149b46f7d264ce67c7ba99e 100644 --- a/test/unittests/cloudsync_sa/sync_rule/battery_status_test.cpp +++ b/test/unittests/cloudsync_sa/sync_rule/battery_status_test.cpp @@ -236,28 +236,26 @@ HWTEST_F(BatteryStatusTest, IsBatteryCapcityOkayTest003, TestSize.Level1) GTEST_LOG_(INFO) << "IsBatteryCapcityOkayTest003 End"; } -HWTEST_F(BatteryStatusTest, GetInitChargingStatus_Enable, TestSize.Level1) +HWTEST_F(BatteryStatusTest, GetInitChargingStatus_Plugged_BUTT, TestSize.Level1) { - EXPECT_CALL(*dfsBatterySrvClient_, GetChargingStatus()) - .WillOnce(Return(ChargeState::CHARGE_STATE_ENABLE)); + EXPECT_CALL(*dfsBatterySrvClient_, GetPluggedType()) + .WillOnce(Return(PluggedType::PLUGGED_TYPE_BUTT)); batteryStatus_->GetInitChargingStatus(); - EXPECT_TRUE(batteryStatus_->IsCharging()); + EXPECT_FALSE(batteryStatus_->IsCharging()); } -HWTEST_F(BatteryStatusTest, GetInitChargingStatus_Full, TestSize.Level1) +HWTEST_F(BatteryStatusTest, GetInitChargingStatus_Plugged_AC, TestSize.Level1) { - EXPECT_CALL(*dfsBatterySrvClient_, GetChargingStatus()) - .WillOnce(Return(ChargeState::CHARGE_STATE_FULL)); + EXPECT_CALL(*dfsBatterySrvClient_, GetPluggedType()) + .WillOnce(Return(PluggedType::PLUGGED_TYPE_AC)); batteryStatus_->GetInitChargingStatus(); EXPECT_TRUE(batteryStatus_->IsCharging()); } -HWTEST_F(BatteryStatusTest, GetInitChargingStatus_Plugged, TestSize.Level1) +HWTEST_F(BatteryStatusTest, GetInitChargingStatus_Plugged_USB, TestSize.Level1) { - EXPECT_CALL(*dfsBatterySrvClient_, GetChargingStatus()) - .WillOnce(Return(ChargeState::CHARGE_STATE_DISABLE)); EXPECT_CALL(*dfsBatterySrvClient_, GetPluggedType()) .WillOnce(Return(PluggedType::PLUGGED_TYPE_USB)); @@ -265,10 +263,8 @@ HWTEST_F(BatteryStatusTest, GetInitChargingStatus_Plugged, TestSize.Level1) EXPECT_TRUE(batteryStatus_->IsCharging()); } -HWTEST_F(BatteryStatusTest, GetInitChargingStatus_NotCharging_NotPlugged_Battery_Low, TestSize.Level1) +HWTEST_F(BatteryStatusTest, GetInitChargingStatus_NotCharging_NotPlugged, TestSize.Level1) { - EXPECT_CALL(*dfsBatterySrvClient_, GetChargingStatus()) - .WillOnce(Return(ChargeState::CHARGE_STATE_DISABLE)); EXPECT_CALL(*dfsBatterySrvClient_, GetPluggedType()) .WillOnce(Return(PluggedType::PLUGGED_TYPE_NONE)); diff --git a/test/unittests/cloudsync_sa/sync_rule/cloud_status_test.cpp b/test/unittests/cloudsync_sa/sync_rule/cloud_status_test.cpp index 975c504a55a5312a40d725ef5675ebebfb99ba13..2d0d9b95b17a7cecedb0c04ec543b010244c9e06 100644 --- a/test/unittests/cloudsync_sa/sync_rule/cloud_status_test.cpp +++ b/test/unittests/cloudsync_sa/sync_rule/cloud_status_test.cpp @@ -66,11 +66,7 @@ HWTEST_F(CloudStatusTest, GetCurrentCloudInfo001, TestSize.Level1) const string bundleName = "ohos.com.test"; const int32_t userId = 1; auto ret = cloudStatus.GetCurrentCloudInfo(bundleName, userId); -#if CLOUD_ADAPTER_ENABLED EXPECT_EQ(ret, E_NULLPTR); -#else - EXPECT_EQ(ret, E_OK); -#endif } /** @@ -107,6 +103,36 @@ HWTEST_F(CloudStatusTest, GetCurrentCloudInfo003, TestSize.Level1) EXPECT_EQ(ret, E_RDB); } +/** + * @tc.name: GetCurrentCloudInfo004 + * @tc.desc: Verify the CloudStatus::GetCurrentCloudInfo function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudStatusTest, GetCurrentCloudInfo004, TestSize.Level1) +{ + CloudStatus cloudStatus; + const string bundleName = "com.ohos.photos"; + const int32_t userId = 1; + auto ret = cloudStatus.GetCurrentCloudInfo(bundleName, userId); + EXPECT_EQ(ret, E_OK); +} + +/** + * @tc.name: GetCurrentCloudInfo005 + * @tc.desc: Verify the CloudStatus::GetCurrentCloudInfo function + * @tc.type: FUNC + * @tc.require: SR000HRKKA + */ +HWTEST_F(CloudStatusTest, GetCurrentCloudInfo005, TestSize.Level1) +{ + CloudStatus cloudStatus; + const string bundleName = "com.ohos.ailife"; + const int32_t userId = 1; + auto ret = cloudStatus.GetCurrentCloudInfo(bundleName, userId); + EXPECT_EQ(ret, E_OK); +} + /** * @tc.name: IsCloudStatusOkay001 * @tc.desc: Verify the CloudStatus::IsCloudStatusOkay function diff --git a/test/unittests/cloudsync_sa/sync_rule/network_set_manager_test.cpp b/test/unittests/cloudsync_sa/sync_rule/network_set_manager_test.cpp index ea58881f033fa66b7515a08c0cff3495b8e18df4..196289389e7a74229ef92b1862b67c9a7d4f55cb 100644 --- a/test/unittests/cloudsync_sa/sync_rule/network_set_manager_test.cpp +++ b/test/unittests/cloudsync_sa/sync_rule/network_set_manager_test.cpp @@ -321,4 +321,67 @@ HWTEST_F(NetworkSetManagerTest, GetConfigParams001, TestSize.Level1) } GTEST_LOG_(INFO) << "GetConfigParams End"; } + +/** + * @tc.name: InitNetworkSetManagerTest001 + * @tc.desc: Verify the GetConfigParams function when driveKit is not null. + * @tc.type: FUNC + * @tc.require: ICEGLJ + */ +HWTEST_F(NetworkSetManagerTest, InitNetworkSetManager001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "InitNetworkSetManager001 Start"; + try { + int32_t userId = 100; + string bundleName = "com.ohos.photos"; + NetworkSetManager::InitNetworkSetManager(bundleName, userId); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "InitNetworkSetManager001 FAILED"; + } + GTEST_LOG_(INFO) << "InitNetworkSetManager001 End"; +} + +/** + * @tc.name: InitNetworkSetManagerTest002 + * @tc.desc: Verify the GetConfigParams function when driveKit is not null. + * @tc.type: FUNC + * @tc.require: ICEGLJ + */ +HWTEST_F(NetworkSetManagerTest, InitNetworkSetManager002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "InitNetworkSetManager002 Start"; + try { + int32_t userId = 100; + string bundleName = "com.ohos.ailife"; + NetworkSetManager::InitNetworkSetManager(bundleName, userId); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "InitNetworkSetManager002 FAILED"; + } + GTEST_LOG_(INFO) << "InitNetworkSetManager002 End"; +} + +/** + * @tc.name: InitNetworkSetManagerTest003 + * @tc.desc: Verify the GetConfigParams function when driveKit is not null. + * @tc.type: FUNC + * @tc.require: ICEGLJ + */ +HWTEST_F(NetworkSetManagerTest, InitNetworkSetManager003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "InitNetworkSetManager003 Start"; + try { + int32_t userId = 100; + string bundleName = "xxxxxxx"; + NetworkSetManager::InitNetworkSetManager(bundleName, userId); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "InitNetworkSetManager003 FAILED"; + } + GTEST_LOG_(INFO) << "InitNetworkSetManager003 End"; +} } \ No newline at end of file diff --git a/test/unittests/cloudsync_sa/sync_rule/network_status_test.cpp b/test/unittests/cloudsync_sa/sync_rule/network_status_test.cpp index 1de6389ee4b6b662e287a95348541923eaf647ba..c07770b00754069cf04a2fd94292141ebffb8b73 100644 --- a/test/unittests/cloudsync_sa/sync_rule/network_status_test.cpp +++ b/test/unittests/cloudsync_sa/sync_rule/network_status_test.cpp @@ -26,6 +26,8 @@ #include "utils_log.h" #include "net_conn_client_mock.h" #include "net_handle.h" +#include "settings_data_manager.h" +#include "network_set_manager.h" namespace OHOS::FileManagement::CloudSync::Test { using namespace testing; @@ -356,6 +358,128 @@ HWTEST_F(NetworkStatusTest, CheckMobileNetworkTest004, TestSize.Level1) GTEST_LOG_(INFO) << "CheckMobileNetworkTest End"; } +/** + * @tc.name: CheckMobileNetworkTest005 + * @tc.desc: Verify the CheckMobileNetwork function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, CheckMobileNetworkTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckMobileNetworkTest005 Start"; + try { + NetworkStatus networkStatus; + string bundleName = "com.ohos.ailife"; + int32_t userId = 100; + SettingsDataManager::settingsDataMap_.EnsureInsert("photos_mobile_data_sync", "on"); + bool ret = networkStatus.CheckMobileNetwork(bundleName, userId); + EXPECT_EQ(ret, true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CheckMobileNetworkTest005 FAILED"; + } + GTEST_LOG_(INFO) << "CheckMobileNetworkTest005 End"; +} + +/** + * @tc.name: CheckMobileNetworkTest006 + * @tc.desc: Verify the CheckMobileNetwork function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, CheckMobileNetworkTest006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckMobileNetworkTest006 Start"; + try { + NetworkStatus networkStatus; + string bundleName = "com.ohos.photos"; + int32_t userId = 100; + std::string key = std::to_string(userId) + "/" + bundleName; + NetworkSetManager::cellularNetMap_.EnsureInsert(key, true); + bool ret = networkStatus.CheckMobileNetwork(bundleName, userId); + EXPECT_EQ(ret, true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CheckMobileNetworkTest006 FAILED"; + } + GTEST_LOG_(INFO) << "CheckMobileNetworkTest006 End"; +} + +/** + * @tc.name: CheckMobileNetworkTest007 + * @tc.desc: Verify the CheckMobileNetwork function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, CheckMobileNetworkTest007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckMobileNetworkTest007 Start"; + try { + NetworkStatus networkStatus; + string bundleName = "com.ohos.photos"; + int32_t userId = 100; + std::string key = std::to_string(userId) + "/" + bundleName; + networkStatus.SetNetConnStatus(NetworkStatus::WIFI_CONNECT); + NetworkSetManager::cellularNetMap_.EnsureInsert(key, false); + bool ret = networkStatus.CheckMobileNetwork(bundleName, userId); + EXPECT_EQ(ret, true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CheckMobileNetworkTest007 FAILED"; + } + GTEST_LOG_(INFO) << "CheckMobileNetworkTest007 End"; +} + +/** + * @tc.name: CheckMobileNetworkTest008 + * @tc.desc: Verify the CheckMobileNetwork function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, CheckMobileNetworkTest008, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckMobileNetworkTest008 Start"; + try { + NetworkStatus networkStatus; + string bundleName = "com.ohos.photos"; + int32_t userId = 100; + std::string key = std::to_string(userId) + "/" + bundleName; + networkStatus.SetNetConnStatus(NetworkStatus::NO_NETWORK); + NetworkSetManager::cellularNetMap_.EnsureInsert(key, false); + bool ret = networkStatus.CheckMobileNetwork(bundleName, userId); + EXPECT_EQ(ret, false); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CheckMobileNetworkTest008 FAILED"; + } + GTEST_LOG_(INFO) << "CheckMobileNetworkTest008 End"; +} + +/** + * @tc.name: CheckMobileNetworkTest009 + * @tc.desc: Verify the CheckMobileNetwork function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, CheckMobileNetworkTest009, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckMobileNetworkTest009 Start"; + try { + NetworkStatus networkStatus; + string bundleName = "xxxxxxxxx"; + int32_t userId = 100; + std::string key = std::to_string(userId) + "/" + bundleName; + networkStatus.SetNetConnStatus(NetworkStatus::NO_NETWORK); + NetworkSetManager::cellularNetMap_.EnsureInsert(key, false); + bool ret = networkStatus.CheckMobileNetwork(bundleName, userId); + EXPECT_EQ(ret, true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CheckMobileNetworkTest009 FAILED"; + } + GTEST_LOG_(INFO) << "CheckMobileNetworkTest009 End"; +} + /** * @tc.name: CheckNetworkTest001 * @tc.desc: Verify the CheckNetwork function @@ -422,6 +546,52 @@ HWTEST_F(NetworkStatusTest, CheckNetworkTest003, TestSize.Level1) GTEST_LOG_(INFO) << "CheckNetworkTest End"; } +/** + * @tc.name: CheckNetworkTest004 + * @tc.desc: Verify the CheckNetwork function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, CheckNetworkTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckNetworkTest004 Start"; + try { + NetworkStatus networkStatus; + string bundleName = "com.ohos.ailife"; + int32_t userId = 100; + SettingsDataManager::settingsDataMap_.EnsureInsert("photos_network_connection_status", "on"); + bool ret = networkStatus.CheckNetwork(bundleName, userId); + EXPECT_EQ(ret, true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CheckNetworkTest004 FAILED"; + } + GTEST_LOG_(INFO) << "CheckNetworkTest004 End"; +} + +/** + * @tc.name: CheckNetworkTest005 + * @tc.desc: Verify the CheckNetwork function + * @tc.type: FUNC + * @tc.require: I6JPKG + */ +HWTEST_F(NetworkStatusTest, CheckNetworkTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CheckNetworkTest005 Start"; + try { + NetworkStatus networkStatus; + string bundleName = "com.ohos.ailife"; + int32_t userId = 100; + SettingsDataManager::settingsDataMap_.EnsureInsert("photos_network_connection_status", "false"); + bool ret = networkStatus.CheckNetwork(bundleName, userId); + EXPECT_EQ(ret, false); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "CheckNetworkTest005 FAILED"; + } + GTEST_LOG_(INFO) << "CheckNetworkTest005 End"; +} + /** * @tc.name: OnNetworkAvailTest001 * @tc.desc: Verify the OnNetworkAvail function diff --git a/test/unittests/cloudsync_sa/sync_rule/screen_status_listener_test.cpp b/test/unittests/cloudsync_sa/sync_rule/screen_status_listener_test.cpp index 1d39d286bfd081ee5ec13118890df1e4eb237207..00da962e4a0f4aab25ffe842ed43b7cb8d7312cd 100644 --- a/test/unittests/cloudsync_sa/sync_rule/screen_status_listener_test.cpp +++ b/test/unittests/cloudsync_sa/sync_rule/screen_status_listener_test.cpp @@ -136,7 +136,7 @@ HWTEST_F(ScreenStatusListenerTest, OnReceiveEventTest002, TestSize.Level1) GTEST_LOG_(INFO) << "OnReceiveEventTest002 start"; try { Want want; - want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_CHARGING); + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_POWER_CONNECTED); EventFwk::CommonEventData eventData(want); auto dataSyncManager = std::make_shared(); auto screenStatusListener = std::make_shared(dataSyncManager); @@ -162,7 +162,7 @@ HWTEST_F(ScreenStatusListenerTest, OnReceiveEventTest003, TestSize.Level1) GTEST_LOG_(INFO) << "OnReceiveEventTest003 start"; try { Want want; - want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_DISCHARGING); + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_POWER_DISCONNECTED); EventFwk::CommonEventData eventData(want); auto dataSyncManager = std::make_shared(); auto screenStatusListener = std::make_shared(dataSyncManager); diff --git a/test/unittests/cloudsync_sa/sync_rule/settings_data_manager_test.cpp b/test/unittests/cloudsync_sa/sync_rule/settings_data_manager_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a8bb5758e20d2ad689e60ead5122630486ccc3a9 --- /dev/null +++ b/test/unittests/cloudsync_sa/sync_rule/settings_data_manager_test.cpp @@ -0,0 +1,571 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "datashare_helper_mock.h" +#include "datashare_result_set_mock.h" +#include "dfs_error.h" +#include "settings_data_manager.h" + +namespace OHOS::FileManagement::CloudSync::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; +using namespace OHOS::DataShare; + +static const std::string SYNC_SWITCH_KEY = "photos_sync_options"; +static const std::string NETWORK_CONNECTION_KEY = "photos_network_connection_status"; +static const std::string LOCAL_SPACE_FREE_KEY = "photos_local_space_free"; +static const std::string LOCAL_SPACE_DAYS_KEY = "photos_local_space_days"; +static const std::string MOBILE_DATA_SYNC_KEY = "photos_mobile_data_sync"; + +class SettingsDataManagerTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr dataShareHelperMock_ = nullptr; + static inline shared_ptr resultSetMock_ = nullptr; +}; + +void SettingsDataManagerTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + dataShareHelperMock_ = std::make_shared(); + resultSetMock_ = std::make_shared(); + DataShareHelperMock::proxy_ = dataShareHelperMock_; + DataShareResultSetMock::proxy_ = resultSetMock_; +} + +void SettingsDataManagerTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; + dataShareHelperMock_ = nullptr; + DataShareHelperMock::proxy_ = nullptr; + resultSetMock_ = nullptr; + DataShareResultSetMock::proxy_ = nullptr; +} + +void SettingsDataManagerTest::SetUp(void) +{ + DataShareHelperMock::proxy_ = dataShareHelperMock_; + DataShareResultSetMock::proxy_ = resultSetMock_; +} + +void SettingsDataManagerTest::TearDown(void) {} + +HWTEST_F(SettingsDataManagerTest, QueryParamInSettingsDataTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "QueryParamInSettingsDataTest001 Start"; + DataShareResultSetMock::proxy_ = nullptr; + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(nullptr)); + std::string key = ""; + std::string value; + int32_t ret = SettingsDataManager::QueryParamInSettingsData(key, value); + EXPECT_EQ(ret, E_RDB); + + GTEST_LOG_(INFO) << "QueryParamInSettingsDataTest001 End"; +} + +HWTEST_F(SettingsDataManagerTest, QueryParamInSettingsDataTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "QueryParamInSettingsDataTest002 Start"; + DataShareResultSetMock::proxy_ = nullptr; + std::shared_ptr dataShareHelper = std::make_shared(); + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(dataShareHelper)); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).WillOnce(Return(resultSet)); + std::string key = ""; + std::string value; + int32_t ret = SettingsDataManager::QueryParamInSettingsData(key, value); + EXPECT_EQ(ret, E_OK); + + GTEST_LOG_(INFO) << "QueryParamInSettingsDataTest002 End"; +} + +HWTEST_F(SettingsDataManagerTest, QueryParamInSettingsDataTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "QueryParamInSettingsDataTest003 Start"; + DataShareResultSetMock::proxy_ = nullptr; + std::shared_ptr dataShareHelper = std::make_shared(); + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(dataShareHelper)); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).WillOnce(Return(nullptr)); + std::string key = ""; + std::string value; + int32_t ret = SettingsDataManager::QueryParamInSettingsData(key, value); + EXPECT_EQ(ret, E_RDB); + + GTEST_LOG_(INFO) << "QueryParamInSettingsDataTest003 End"; +} + +HWTEST_F(SettingsDataManagerTest, QueryParamInSettingsDataTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "QueryParamInSettingsDataTest004 Start"; + std::shared_ptr dataShareHelper = std::make_shared(); + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(dataShareHelper)); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).WillOnce(Return(resultSet)); + EXPECT_CALL(*resultSetMock_, GoToFirstRow()).WillOnce(Return(E_OK)); + EXPECT_CALL(*resultSetMock_, GetColumnIndex(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*resultSetMock_, GetString(_, _)).WillOnce(Return(E_OK)); + std::string key = ""; + std::string value; + int32_t ret = SettingsDataManager::QueryParamInSettingsData(key, value); + EXPECT_EQ(ret, E_OK); + + GTEST_LOG_(INFO) << "QueryParamInSettingsDataTest004 End"; +} + +HWTEST_F(SettingsDataManagerTest, QueryParamInSettingsDataTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "QueryParamInSettingsDataTest005 Start"; + std::shared_ptr dataShareHelper = std::make_shared(); + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(dataShareHelper)); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).WillOnce(Return(resultSet)); + EXPECT_CALL(*resultSetMock_, GoToFirstRow()).WillOnce(Return(-1)); + EXPECT_CALL(*resultSetMock_, GetColumnIndex(_, _)).Times(0); + EXPECT_CALL(*resultSetMock_, GetString(_, _)).Times(0); + std::string key = ""; + std::string value; + int32_t ret = SettingsDataManager::QueryParamInSettingsData(key, value); + EXPECT_EQ(ret, E_INNER_RDB); + + GTEST_LOG_(INFO) << "QueryParamInSettingsDataTest005 End"; +} + +HWTEST_F(SettingsDataManagerTest, QueryParamInSettingsDataTest006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "QueryParamInSettingsDataTest006 Start"; + std::shared_ptr dataShareHelper = std::make_shared(); + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(dataShareHelper)); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).WillOnce(Return(resultSet)); + EXPECT_CALL(*resultSetMock_, GoToFirstRow()).WillOnce(Return(E_OK)); + EXPECT_CALL(*resultSetMock_, GetColumnIndex(_, _)).WillOnce(Return(-1)); + EXPECT_CALL(*resultSetMock_, GetString(_, _)).Times(0); + std::string key = ""; + std::string value; + int32_t ret = SettingsDataManager::QueryParamInSettingsData(key, value); + EXPECT_EQ(ret, E_RDB); + + GTEST_LOG_(INFO) << "QueryParamInSettingsDataTest006 End"; +} + +HWTEST_F(SettingsDataManagerTest, QueryParamInSettingsDataTest007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "QueryParamInSettingsDataTest007 Start"; + std::shared_ptr dataShareHelper = std::make_shared(); + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(dataShareHelper)); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).WillOnce(Return(resultSet)); + EXPECT_CALL(*resultSetMock_, GoToFirstRow()).WillOnce(Return(E_OK)); + EXPECT_CALL(*resultSetMock_, GetColumnIndex(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*resultSetMock_, GetString(_, _)).WillOnce(Return(-1)); + std::string key = ""; + std::string value; + int32_t ret = SettingsDataManager::QueryParamInSettingsData(key, value); + EXPECT_EQ(ret, E_RDB); + + GTEST_LOG_(INFO) << "QueryParamInSettingsDataTest007 End"; +} + +HWTEST_F(SettingsDataManagerTest, GetSwitchStatusByCacheTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetSwitchStatusByCacheTest001 Start"; + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(nullptr)); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).Times(0); + SwitchStatus status = SettingsDataManager::GetSwitchStatusByCache(); + EXPECT_EQ(status, SwitchStatus::NONE); + + GTEST_LOG_(INFO) << "GetSwitchStatusByCacheTest001 End"; +} + +HWTEST_F(SettingsDataManagerTest, GetSwitchStatusByCacheTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetSwitchStatusByCacheTest002 Start"; + std::shared_ptr dataShareHelper = std::make_shared(); + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(dataShareHelper)); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).WillOnce(Return(resultSet)); + EXPECT_CALL(*resultSetMock_, GoToFirstRow()).WillOnce(Return(-1)); + EXPECT_CALL(*resultSetMock_, GetColumnIndex(_, _)).Times(0); + EXPECT_CALL(*resultSetMock_, GetString(_, _)).Times(0); + SwitchStatus status = SettingsDataManager::GetSwitchStatusByCache(); + EXPECT_EQ(status, SwitchStatus::CLOUD_SPACE); + + GTEST_LOG_(INFO) << "GetSwitchStatusByCacheTest002 End"; +} + +HWTEST_F(SettingsDataManagerTest, GetSwitchStatusByCacheTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetSwitchStatusByCacheTest003 Start"; + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).Times(0); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).Times(0); + SettingsDataManager::settingsDataMap_.EnsureInsert(SYNC_SWITCH_KEY, "0"); + SwitchStatus status = SettingsDataManager::GetSwitchStatusByCache(); + EXPECT_EQ(status, SwitchStatus::NONE); + + SettingsDataManager::settingsDataMap_.Clear(); + GTEST_LOG_(INFO) << "GetSwitchStatusByCacheTest003 End"; +} + +HWTEST_F(SettingsDataManagerTest, GetSwitchStatusByCacheTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetSwitchStatusByCacheTest004 Start"; + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).Times(0); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).Times(0); + SettingsDataManager::settingsDataMap_.EnsureInsert(SYNC_SWITCH_KEY, "1"); + SwitchStatus status = SettingsDataManager::GetSwitchStatusByCache(); + EXPECT_EQ(status, SwitchStatus::CLOUD_SPACE); + + SettingsDataManager::settingsDataMap_.Clear(); + GTEST_LOG_(INFO) << "GetSwitchStatusByCacheTest004 End"; +} + +HWTEST_F(SettingsDataManagerTest, GetSwitchStatusByCacheTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetSwitchStatusByCacheTest005 Start"; + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).Times(0); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).Times(0); + SettingsDataManager::settingsDataMap_.EnsureInsert(SYNC_SWITCH_KEY, "2"); + SwitchStatus status = SettingsDataManager::GetSwitchStatusByCache(); + EXPECT_EQ(status, SwitchStatus::AI_FAMILY); + + SettingsDataManager::settingsDataMap_.Clear(); + GTEST_LOG_(INFO) << "GetSwitchStatusByCacheTest005 End"; +} + +HWTEST_F(SettingsDataManagerTest, GetSwitchStatusByCacheTest006, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetSwitchStatusByCacheTest006 Start"; + std::shared_ptr dataShareHelper = std::make_shared(); + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(dataShareHelper)); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).WillOnce(Return(resultSet)); + EXPECT_CALL(*resultSetMock_, GoToFirstRow()).WillOnce(Return(E_OK)); + EXPECT_CALL(*resultSetMock_, GetColumnIndex(_, _)).WillOnce(Return(-1)); + EXPECT_CALL(*resultSetMock_, GetString(_, _)).Times(0); + SwitchStatus status = SettingsDataManager::GetSwitchStatusByCache(); + EXPECT_EQ(status, SwitchStatus::NONE); + + GTEST_LOG_(INFO) << "GetSwitchStatusByCacheTest006 End"; +} + +HWTEST_F(SettingsDataManagerTest, GetSwitchStatusTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetSwitchStatusTest001 Start"; + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(nullptr)); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).Times(0); + SwitchStatus status = SettingsDataManager::GetSwitchStatus(); + EXPECT_EQ(status, SwitchStatus::NONE); + + GTEST_LOG_(INFO) << "GetSwitchStatusTest001 End"; +} + +HWTEST_F(SettingsDataManagerTest, GetSwitchStatusTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetSwitchStatusTest002 Start"; + std::shared_ptr dataShareHelper = std::make_shared(); + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(dataShareHelper)); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).WillOnce(Return(resultSet)); + EXPECT_CALL(*resultSetMock_, GoToFirstRow()).WillOnce(Return(-1)); + EXPECT_CALL(*resultSetMock_, GetColumnIndex(_, _)).Times(0); + EXPECT_CALL(*resultSetMock_, GetString(_, _)).Times(0); + SwitchStatus status = SettingsDataManager::GetSwitchStatus(); + EXPECT_EQ(status, SwitchStatus::CLOUD_SPACE); + + GTEST_LOG_(INFO) << "GetSwitchStatusTest002 End"; +} + +HWTEST_F(SettingsDataManagerTest, GetSwitchStatusTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetSwitchStatusTest003 Start"; + std::shared_ptr dataShareHelper = std::make_shared(); + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(dataShareHelper)); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).WillOnce(Return(resultSet)); + EXPECT_CALL(*resultSetMock_, GoToFirstRow()).WillOnce(Return(E_OK)); + EXPECT_CALL(*resultSetMock_, GetColumnIndex(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*resultSetMock_, GetString(_, _)).WillOnce(Return(E_OK)); + SettingsDataManager::settingsDataMap_.EnsureInsert(SYNC_SWITCH_KEY, "2"); + SwitchStatus status = SettingsDataManager::GetSwitchStatus(); + EXPECT_EQ(status, SwitchStatus::NONE); + + SettingsDataManager::settingsDataMap_.Clear(); + GTEST_LOG_(INFO) << "GetSwitchStatusTest003 End"; +} + +HWTEST_F(SettingsDataManagerTest, GetSwitchStatusTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetSwitchStatusTest004 Start"; + std::shared_ptr dataShareHelper = std::make_shared(); + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(dataShareHelper)); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).WillOnce(Return(resultSet)); + EXPECT_CALL(*resultSetMock_, GoToFirstRow()).WillOnce(Return(E_OK)); + EXPECT_CALL(*resultSetMock_, GetColumnIndex(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*resultSetMock_, GetString(_, _)).WillOnce(Return(E_OK)); + SettingsDataManager::settingsDataMap_.EnsureInsert(SYNC_SWITCH_KEY, "1"); + SwitchStatus status = SettingsDataManager::GetSwitchStatus(); + EXPECT_EQ(status, SwitchStatus::NONE); + + SettingsDataManager::settingsDataMap_.Clear(); + GTEST_LOG_(INFO) << "GetSwitchStatusTest004 End"; +} + +HWTEST_F(SettingsDataManagerTest, GetSwitchStatusTest005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetSwitchStatusTest005 Start"; + std::shared_ptr dataShareHelper = std::make_shared(); + std::shared_ptr resultSet = std::make_shared(); + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(dataShareHelper)); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).WillOnce(Return(resultSet)); + EXPECT_CALL(*resultSetMock_, GoToFirstRow()).WillOnce(Return(E_OK)); + EXPECT_CALL(*resultSetMock_, GetColumnIndex(_, _)).WillOnce(Return(E_OK)); + EXPECT_CALL(*resultSetMock_, GetString(_, _)).WillOnce(Return(E_OK)); + SettingsDataManager::settingsDataMap_.EnsureInsert(SYNC_SWITCH_KEY, "0"); + SwitchStatus status = SettingsDataManager::GetSwitchStatus(); + EXPECT_EQ(status, SwitchStatus::NONE); + + SettingsDataManager::settingsDataMap_.Clear(); + GTEST_LOG_(INFO) << "GetSwitchStatusTest005 End"; +} + +HWTEST_F(SettingsDataManagerTest, GetNetworkConnectionStatusTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetNetworkConnectionStatusTest001 Start"; + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(nullptr)); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).Times(0); + std::string status = SettingsDataManager::GetNetworkConnectionStatus(); + EXPECT_EQ(status, "on"); + + GTEST_LOG_(INFO) << "GetNetworkConnectionStatusTest001 End"; +} + +HWTEST_F(SettingsDataManagerTest, GetNetworkConnectionStatusTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetNetworkConnectionStatusTest002 Start"; + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).Times(0); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).Times(0); + SettingsDataManager::settingsDataMap_.EnsureInsert(NETWORK_CONNECTION_KEY, "false"); + std::string status = SettingsDataManager::GetNetworkConnectionStatus(); + EXPECT_EQ(status, "false"); + + SettingsDataManager::settingsDataMap_.Clear(); + GTEST_LOG_(INFO) << "GetNetworkConnectionStatusTest002 End"; +} + +HWTEST_F(SettingsDataManagerTest, GetLocalSpaceFreeStatusTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetLocalSpaceFreeStatusTest001 Start"; + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(nullptr)); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).Times(0); + int32_t status = SettingsDataManager::GetLocalSpaceFreeStatus(); + EXPECT_EQ(status, 0); + GTEST_LOG_(INFO) << "GetLocalSpaceFreeStatusTest001 End"; +} + +HWTEST_F(SettingsDataManagerTest, GetLocalSpaceFreeStatusTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetLocalSpaceFreeStatusTest002 Start"; + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).Times(0); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).Times(0); + SettingsDataManager::settingsDataMap_.EnsureInsert(LOCAL_SPACE_FREE_KEY, "1"); + int32_t status = SettingsDataManager::GetLocalSpaceFreeStatus(); + EXPECT_EQ(status, 1); + SettingsDataManager::settingsDataMap_.Clear(); + GTEST_LOG_(INFO) << "GetLocalSpaceFreeStatusTest002 End"; +} + +HWTEST_F(SettingsDataManagerTest, GetLocalSpaceFreeDaysTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetLocalSpaceFreeDaysTest001 Start"; + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(nullptr)); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).Times(0); + int32_t status = SettingsDataManager::GetLocalSpaceFreeDays(); + EXPECT_EQ(status, 0); + GTEST_LOG_(INFO) << "GetLocalSpaceFreeDaysTest001 End"; +} + +HWTEST_F(SettingsDataManagerTest, GetLocalSpaceFreeDaysTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetLocalSpaceFreeDaysTest002 Start"; + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).Times(0); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).Times(0); + SettingsDataManager::settingsDataMap_.EnsureInsert(LOCAL_SPACE_DAYS_KEY, "10"); + int32_t status = SettingsDataManager::GetLocalSpaceFreeDays(); + EXPECT_EQ(status, 10); + SettingsDataManager::settingsDataMap_.Clear(); + GTEST_LOG_(INFO) << "GetLocalSpaceFreeDaysTest002 End"; +} + +HWTEST_F(SettingsDataManagerTest, GetMobileDataStatusTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetMobileDataStatusTest001 Start"; + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(nullptr)); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).Times(0); + std::string status = SettingsDataManager::GetMobileDataStatus(); + EXPECT_EQ(status, "on"); + + GTEST_LOG_(INFO) << "GetMobileDataStatusTest001 End"; +} + +HWTEST_F(SettingsDataManagerTest, GetMobileDataStatusTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetMobileDataStatusTest002 Start"; + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).Times(0); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).Times(0); + SettingsDataManager::settingsDataMap_.EnsureInsert(MOBILE_DATA_SYNC_KEY, "false"); + std::string status = SettingsDataManager::GetMobileDataStatus(); + EXPECT_EQ(status, "false"); + + SettingsDataManager::settingsDataMap_.Clear(); + GTEST_LOG_(INFO) << "GetMobileDataStatusTest002 end"; +} + +HWTEST_F(SettingsDataManagerTest, RegisterObserverTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterObserverTest001 Start"; + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(nullptr)); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).Times(0); + SettingsDataManager::RegisterObserver(""); + EXPECT_TRUE(true); + + GTEST_LOG_(INFO) << "RegisterObserverTest001 End"; +} + +HWTEST_F(SettingsDataManagerTest, RegisterObserverTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterObserverTest002 Start"; + std::shared_ptr dataShareHelper = std::make_shared(); + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(dataShareHelper)); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).Times(0); + SettingsDataManager::RegisterObserver(""); + EXPECT_TRUE(true); + + GTEST_LOG_(INFO) << "RegisterObserverTest002 End"; +} + +HWTEST_F(SettingsDataManagerTest, RegisterObserverTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterObserverTest003 Start"; + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(nullptr)); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).Times(0); + SettingsDataManager::RegisterObserver("", nullptr); + EXPECT_TRUE(true); + + GTEST_LOG_(INFO) << "RegisterObserverTest003 End"; +} + +HWTEST_F(SettingsDataManagerTest, RegisterObserverTest004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterObserverTest004 Start"; + std::shared_ptr dataShareHelper = std::make_shared(); + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(dataShareHelper)); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).Times(0); + SettingsDataManager::RegisterObserver("", nullptr); + EXPECT_TRUE(true); + + GTEST_LOG_(INFO) << "RegisterObserverTest004 End"; +} + +HWTEST_F(SettingsDataManagerTest, UnregisterObserverTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnregisterObserverTest001 Start"; + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(nullptr)); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).Times(0); + SettingsDataManager::UnregisterObserver(""); + EXPECT_TRUE(true); + + GTEST_LOG_(INFO) << "UnregisterObserverTest001 End"; +} + +HWTEST_F(SettingsDataManagerTest, UnregisterObserverTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UnregisterObserverTest002 Start"; + std::shared_ptr dataShareHelper = std::make_shared(); + EXPECT_CALL(*dataShareHelperMock_, Creator(_, _, _)).WillOnce(Return(dataShareHelper)); + EXPECT_CALL(*dataShareHelperMock_, Query(_, _, _, _)).Times(0); + SettingsDataManager::UnregisterObserver(""); + EXPECT_TRUE(true); + + GTEST_LOG_(INFO) << "UnregisterObserverTest002 End"; +} + +HWTEST_F(SettingsDataManagerTest, QueryTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "QueryTest001 Start"; + DataShareHelperMock::proxy_ = nullptr; + DataShareResultSetMock::proxy_ = nullptr; + int32_t ret = -1; + int32_t size = -1; + ret = SettingsDataManager::QuerySwitchStatus(); + EXPECT_EQ(ret, E_OK); + size = SettingsDataManager::settingsDataMap_.Size(); + EXPECT_EQ(size, 1); + + ret = SettingsDataManager::QueryNetworkConnectionStatus(); + EXPECT_EQ(ret, E_OK); + size = SettingsDataManager::settingsDataMap_.Size(); + EXPECT_EQ(size, 2); + + ret = SettingsDataManager::QueryLocalSpaceFreeStatus(); + EXPECT_EQ(ret, E_OK); + size = SettingsDataManager::settingsDataMap_.Size(); + EXPECT_EQ(size, 3); + + ret = SettingsDataManager::QueryLocalSpaceFreeDays(); + EXPECT_EQ(ret, E_OK); + size = SettingsDataManager::settingsDataMap_.Size(); + EXPECT_EQ(size, 4); + + ret = SettingsDataManager::QueryMobileDataStatus(); + EXPECT_EQ(ret, E_OK); + size = SettingsDataManager::settingsDataMap_.Size(); + EXPECT_EQ(size, 5); + + GTEST_LOG_(INFO) << "QueryTest001 End"; +} + +HWTEST_F(SettingsDataManagerTest, OnChangeTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnChangeTest001 Start"; + DataShareHelperMock::proxy_ = nullptr; + DataShareResultSetMock::proxy_ = nullptr; + + SettingsDataObserver observer1(SYNC_SWITCH_KEY); + observer1.OnChange(); + + SettingsDataObserver observer2(NETWORK_CONNECTION_KEY); + observer2.OnChange(); + + SettingsDataObserver observer3(LOCAL_SPACE_FREE_KEY); + observer3.OnChange(); + + SettingsDataObserver observer4(LOCAL_SPACE_DAYS_KEY); + observer4.OnChange(); + + SettingsDataObserver observer5(MOBILE_DATA_SYNC_KEY); + observer5.OnChange(); + + GTEST_LOG_(INFO) << "OnChangeTest001 End"; +} +} \ No newline at end of file diff --git a/test/unittests/cloudsync_sa/system/BUILD.gn b/test/unittests/cloudsync_sa/system/BUILD.gn index ee4437027c1b30d0a42c184fcc13c3d471c1d832..f7cbf51e52b9170dcca89fa0fc3cc84ffb439696 100644 --- a/test/unittests/cloudsync_sa/system/BUILD.gn +++ b/test/unittests/cloudsync_sa/system/BUILD.gn @@ -83,6 +83,7 @@ ohos_unittest("dfsu_access_token_helper_test") { "hisysevent:libhisysevent", "image_framework:image_native", "ipc:ipc_core", + "os_account:os_account_innerkits", "preferences:native_preferences", ] diff --git a/test/unittests/cloudsync_sa/system/dfsu_access_token_helper_test.cpp b/test/unittests/cloudsync_sa/system/dfsu_access_token_helper_test.cpp index 32a1e381276155257eed00f9a096b7bd9154aaad..d57ad480d843f332905c710ab01640cf4c4cfba3 100644 --- a/test/unittests/cloudsync_sa/system/dfsu_access_token_helper_test.cpp +++ b/test/unittests/cloudsync_sa/system/dfsu_access_token_helper_test.cpp @@ -208,4 +208,67 @@ HWTEST_F(DfsuAccessTokenHelperTest, GetUserIdTest, TestSize.Level1) GTEST_LOG_(INFO) << "GetUserIdTest End"; } + +/** + * @tc.name: IsUserVerified001 + * @tc.desc: Verify the IsUserVerifyed function + * @tc.type: FUNC + */ +HWTEST_F(DfsuAccessTokenHelperTest, IsUserVerified001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsUserVerified001 Begin"; + try { + int32_t userId = 100; + auto res = DfsuAccessTokenHelper::IsUserVerifyed(userId); + // permission denied + EXPECT_EQ(res, false); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " IsUserVerified001 ERROR"; + } + + GTEST_LOG_(INFO) << "IsUserVerified001 End"; +} + +/** + * @tc.name: IsUserVerified002 + * @tc.desc: Verify the IsUserVerifyed function + * @tc.type: FUNC + */ +HWTEST_F(DfsuAccessTokenHelperTest, IsUserVerified002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsUserVerified002 Begin"; + try { + int32_t userId = 10; + auto res = DfsuAccessTokenHelper::IsUserVerifyed(userId); + // permission denied + EXPECT_EQ(res, false); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " IsUserVerified002 ERROR"; + } + + GTEST_LOG_(INFO) << "IsUserVerified002 End"; +} + +/** + * @tc.name: GetAccountId001 + * @tc.desc: Verify the GetAccountId function + * @tc.type: FUNC + */ +HWTEST_F(DfsuAccessTokenHelperTest, GetAccountId001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetAccountId001 Begin"; + try { + int32_t userId = 0; + auto res = DfsuAccessTokenHelper::GetAccountId(userId); + // permission denied + EXPECT_NE(res, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << " GetAccountId001 ERROR"; + } + + GTEST_LOG_(INFO) << "GetAccountId001 End"; +} } // namespace OHOS::FileManagement::Test diff --git a/test/unittests/distributed_file_inner/copy/file_copy_listener_test.cpp b/test/unittests/distributed_file_inner/copy/file_copy_listener_test.cpp index a197b9afba5f7503973f2fa873d4a46568b3009d..11fb005e944483e17a0f79fa9fdd333b78ac0c1b 100644 --- a/test/unittests/distributed_file_inner/copy/file_copy_listener_test.cpp +++ b/test/unittests/distributed_file_inner/copy/file_copy_listener_test.cpp @@ -147,6 +147,7 @@ HWTEST_F(FileCopyLocalListenerTest, FileCopyLocalListener_StartStop_0001, TestSi { GTEST_LOG_(INFO) << "FileCopyLocalListener_StartStop_0001 Start"; + std::string srcPath = "/data/test.txt"; std::string testPath = "/data/test_file_listener.txt"; std::function callback = [](uint64_t current, uint64_t total) { GTEST_LOG_(INFO) << "Progress: " << current << "/" << total; @@ -157,11 +158,15 @@ HWTEST_F(FileCopyLocalListenerTest, FileCopyLocalListener_StartStop_0001, TestSi out << "init"; out.close(); + std::ofstream out1(srcPath); + out1 << "test"; + out1.close(); + auto listener = FileCopyLocalListener::GetLocalListener(testPath, true, callback); ASSERT_NE(listener, nullptr); // 添加监听路径 - listener->AddListenerFile(testPath, IN_MODIFY | IN_CLOSE_WRITE); + listener->AddListenerFile(srcPath, testPath, IN_MODIFY | IN_CLOSE_WRITE); listener->AddFile(testPath); // 使其通过 CheckFileValid 校验 listener->StartListener(); diff --git a/test/unittests/distributed_file_inner/copy/file_copy_manager_test.cpp b/test/unittests/distributed_file_inner/copy/file_copy_manager_test.cpp index 8323690123b7f886c02f3fdd6afb2cef2f72fb45..501f247d7642661b0d42eb991749871426ee1714 100644 --- a/test/unittests/distributed_file_inner/copy/file_copy_manager_test.cpp +++ b/test/unittests/distributed_file_inner/copy/file_copy_manager_test.cpp @@ -30,7 +30,6 @@ using namespace testing; using namespace testing::ext; using namespace std; constexpr int32_t FILE_NOT_FOUND = 2; -constexpr int32_t FILE_CAN_NOT_CREATE = 30; class FileCopyManagerTest : public testing::Test { public: static void SetUpTestCase(void); @@ -117,6 +116,7 @@ HWTEST_F(FileCopyManagerTest, FileCopyManager_Copy_0002, TestSize.Level0) string srcUri = "file://docs/storage/media/100/local/files/Docs/1.txt"; string destUri = "file://docs/storage/media/100/local/files/Docs/dest1.txt"; string srcPath = "/storage/media/100/local/files/Docs/1.txt"; + string dstPath = "/storage/media/100/local/files/Docs/dest1.txt"; int fd = open(srcPath.c_str(), O_RDWR | O_CREAT); ASSERT_TRUE(fd != -1) <<"Failed to open file in FileCopyManager_Copy_0002!" << errno; close(fd); @@ -124,112 +124,177 @@ HWTEST_F(FileCopyManagerTest, FileCopyManager_Copy_0002, TestSize.Level0) auto ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Copy(srcUri, destUri, listener_); EXPECT_EQ(ret, E_OK); ASSERT_EQ(remove(srcPath.c_str()), 0); + ASSERT_EQ(remove(dstPath.c_str()), 0); GTEST_LOG_(INFO) << "FileCopyManager_Copy_0002 End"; } /** * @tc.name: FileCopyManager_Copy_0003 -* @tc.desc: The execution of the Copy failed. +* @tc.desc: The execution of the Copy succeed. * @tc.type: FUNC * @tc.require: I7TDJK */ HWTEST_F(FileCopyManagerTest, FileCopyManager_Copy_0003, TestSize.Level0) { + //same uri GTEST_LOG_(INFO) << "FileCopyManager_Copy_0003 Start"; string srcUri = "file://docs/storage/media/100/local/files/Docs/1.txt"; - string destUri = "*"; + string destUri = "file://docs/storage/media/100/local/files/Docs/1.txt"; string srcPath = "/storage/media/100/local/files/Docs/1.txt"; int fd = open(srcPath.c_str(), O_RDWR | O_CREAT); ASSERT_TRUE(fd != -1) <<"Failed to open file in FileCopyManager_Copy_0003!" << errno; close(fd); auto ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Copy(srcUri, destUri, listener_); - EXPECT_EQ(ret, FILE_CAN_NOT_CREATE); + EXPECT_EQ(ret, EINVAL); ASSERT_EQ(remove(srcPath.c_str()), 0); GTEST_LOG_(INFO) << "FileCopyManager_Copy_0003 End"; } /** * @tc.name: FileCopyManager_Copy_0004 -* @tc.desc: The execution of the cancel succeed. +* @tc.desc: The execution of the Copy succeed. * @tc.type: FUNC * @tc.require: I7TDJK */ HWTEST_F(FileCopyManagerTest, FileCopyManager_Copy_0004, TestSize.Level0) { GTEST_LOG_(INFO) << "FileCopyManager_Copy_0004 Start"; - auto infos1 = std::make_shared(); - infos1->srcUri = "srcUri1"; - infos1->destUri = "destUri1"; - infos1->transListener = nullptr; - infos1->localListener = std::make_shared("", - true, [](uint64_t processSize, uint64_t totalSize) -> void {}); - std::string srcUri = "srcUri1"; - std::string destUri = "destUri3"; - - Storage::DistributedFile::FileCopyManager::GetInstance()->FileInfosVec_.emplace_back(infos1); - auto ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Cancel(srcUri, destUri); - EXPECT_EQ(ret, E_OK); - srcUri = "srcUri2"; - destUri = "destUri1"; - ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Cancel(srcUri, destUri); - EXPECT_EQ(ret, E_OK); - - srcUri = "srcUri2"; - destUri = "destUri2"; - ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Cancel(srcUri, destUri); - EXPECT_EQ(ret, E_OK); + string srcUri = "file://docs/storage/media/100/local/files/Docs/1.txt"; + string destUri = "file://docs/storage/media/100/local/files/Docs/a1.txt"; + string srcPath = "/storage/media/100/local/files/Docs/1.txt"; + string destPath = "/storage/media/100/local/files/Docs/a1.txt"; + int fd = open(srcPath.c_str(), O_RDWR | O_CREAT); + ASSERT_TRUE(fd != -1) <<"Failed to open file in FileCopyManager_Copy_0004!" << errno; + close(fd); - srcUri = "srcUri1"; - destUri = "destUri1"; - ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Cancel(srcUri, destUri); + auto ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Copy(srcUri, destUri, listener_); EXPECT_EQ(ret, E_OK); + ASSERT_EQ(remove(srcPath.c_str()), 0); + ASSERT_EQ(remove(destPath.c_str()), 0); GTEST_LOG_(INFO) << "FileCopyManager_Copy_0004 End"; } /** * @tc.name: FileCopyManager_Copy_0005 -* @tc.desc: The execution of the execlocal failed. +* @tc.desc: The execution of the Copy failed. * @tc.type: FUNC * @tc.require: I7TDJK */ -HWTEST_F(FileCopyManagerTest, FileCopyManager_Copy_0005, TestSize.Level0) +HWTEST_F(FileCopyManagerTest, FileCopyManager_Copy_0006, TestSize.Level0) { GTEST_LOG_(INFO) << "FileCopyManager_Copy_0005 Start"; + string localUri = "/data/test/test.txt"; + string dstUri = "/data/test/test.txt"; + + auto ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Copy("", localUri, emptyCallback_); + EXPECT_EQ(ret, EINVAL); + + ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Copy(localUri, "", listener_); + EXPECT_EQ(ret, EINVAL); + + ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Copy(localUri, dstUri, listener_); + EXPECT_EQ(ret, EINVAL); + + ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Copy(localUri, dstUri, emptyCallback_); + EXPECT_EQ(ret, EINVAL); + + GTEST_LOG_(INFO) << "FileCopyManager_Copy_0005 End"; +} + +/** + * @tc.name: FileCopyManager_Copy_0007 + * @tc.desc: The execution of the Copy failed. + * @tc.type: FUNC + * @tc.require: I7TDJK + */ +HWTEST_F(FileCopyManagerTest, FileCopyManager_Copy_0007, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FileCopyManager_Copy_0007 Start"; + string srcUri = "file://docs/storage/media/100/local/files/Docs/1.txt"; + string destUri = "file://docs/storage/media/100/local/files/Docs/a1.txt"; + string srcPath = "/storage/media/100/local/files/Docs/1.txt"; + + EXPECT_TRUE(OHOS::RemoveFile(srcPath)); + auto ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Copy(srcUri, destUri, emptyCallback_); + EXPECT_EQ(ret, EINVAL); + + ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Copy(srcUri, destUri, listener_); + EXPECT_EQ(ret, ENOENT); + + GTEST_LOG_(INFO) << "FileCopyManager_Copy_0007 End"; +} + +/** +* @tc.name: FileCopyManager_ExecLocal_0001 +* @tc.desc: The execution of the execlocal failed. +* @tc.type: FUNC +* @tc.require: I7TDJK + */ +HWTEST_F(FileCopyManagerTest, FileCopyManager_ExecLocal_0001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FileCopyManager_ExecLocal_0001 Start"; string srcuri = "file://docs/storage/media/100/local/files/Docs/11.txt"; string desturi = "file://docs/storage/media/100/local/files/Docs/dest11.txt"; string srcpath = "/storage/media/100/local/files/Docs/11.txt"; - int fd = open(srcpath.c_str(), O_RDWR | O_CREAT); - ASSERT_TRUE(fd != -1) <<"Failed to open file in FileCopyManager_Copy_0005!" << errno; - close(fd); - + string destpath = "/storage/media/100/local/files/Docs/dest11.txt"; + // infos is nullptr auto ret = Storage::DistributedFile::FileCopyManager::GetInstance()->ExecLocal(nullptr); EXPECT_EQ(ret, EINVAL); auto infos = std::make_shared(); infos->srcUri = srcuri; infos->destUri = desturi; + // infos localListener is nullptr + ret = Storage::DistributedFile::FileCopyManager::GetInstance()->ExecLocal(infos); + EXPECT_EQ(ret, EINVAL); + + infos->srcUriIsFile = true; infos->srcPath = srcpath; + infos->destPath = srcpath; + infos->localListener = FileCopyLocalListener::GetLocalListener(infos->srcPath, + infos->srcUriIsFile, listener_); + // srcPath and destPath is same + ret = Storage::DistributedFile::FileCopyManager::GetInstance()->ExecLocal(infos); + EXPECT_EQ(ret, EINVAL); + + infos->destPath = destpath; + // src file not exist + ret = Storage::DistributedFile::FileCopyManager::GetInstance()->ExecLocal(infos); + EXPECT_EQ(ret, ENOENT); + + int fd = open(srcpath.c_str(), O_RDWR | O_CREAT); + ASSERT_TRUE(fd != -1) <<"Failed to open file in FileCopyManager_ExecLocal_0001" << errno; + close(fd); ret = Storage::DistributedFile::FileCopyManager::GetInstance()->ExecLocal(infos); - EXPECT_EQ(ret, 2); + EXPECT_EQ(ret, E_OK); + EXPECT_TRUE(std::filesystem::exists("/storage/media/100/local/files/Docs/dest11.txt")); ASSERT_EQ(remove(srcpath.c_str()), 0); - GTEST_LOG_(INFO) << "FileCopyManager_Copy_0005 End"; + ASSERT_EQ(remove(destpath.c_str()), 0); + + infos->localListener = FileCopyLocalListener::GetLocalListener(infos->srcPath, + infos->srcUriIsFile, emptyCallback_); + // src file not exist, callback is nullptr + ret = Storage::DistributedFile::FileCopyManager::GetInstance()->ExecLocal(infos); + EXPECT_EQ(ret, ENOENT); + ASSERT_EQ(remove(destpath.c_str()), 0); + GTEST_LOG_(INFO) << "FileCopyManager_ExecLocal_0001 End"; } /** -* @tc.name: FileCopyManager_Copy_0006 +* @tc.name: FileCopyManager_ExecLocal_0002 * @tc.desc: The execution of the execlocal failed. * @tc.type: FUNC * @tc.require: I7TDJK */ -HWTEST_F(FileCopyManagerTest, FileCopyManager_Copy_0006, TestSize.Level0) +HWTEST_F(FileCopyManagerTest, FileCopyManager_ExecLocal_0002, TestSize.Level0) { //无对应子文件夹,errno返回2 - GTEST_LOG_(INFO) << "FileCopyManager_Copy_0006 Start"; - string srcuri = "file://docs/storage/media/100/local/files/Docs/aa/"; - string desturi = "file://docs/storage/media/100/local/files/Docs/aa1/"; - string srcpath = "/storage/media/100/local/files/Docs/aa/"; - string destpath = "/storage/media/100/local/files/Docs/aa1/"; + GTEST_LOG_(INFO) << "FileCopyManager_ExecLocal_0002 Start"; + string srcuri = "file://docs/storage/media/100/local/files/Docs/srcaa11/"; + string desturi = "file://docs/storage/media/100/local/files/Docs/dstaa11/"; + string srcpath = "/storage/media/100/local/files/Docs/srcaa11/"; + string destpath = "/storage/media/100/local/files/Docs/dstaa11/"; std::error_code errCode; if (!std::filesystem::exists(srcpath, errCode) && errCode.value() == E_OK) { int res = Storage::DistributedFile::FileCopyManager::GetInstance()->MakeDir(srcpath); @@ -245,41 +310,39 @@ HWTEST_F(FileCopyManagerTest, FileCopyManager_Copy_0006, TestSize.Level0) infos->destUri = desturi; infos->srcPath = srcpath; infos->destPath = destpath; - auto ret = Storage::DistributedFile::FileCopyManager::GetInstance()->ExecLocal(infos); - EXPECT_EQ(ret, 2); - ProcessCallback processCallback = [](uint64_t processSize, uint64_t totalSize) -> void {}; infos->localListener = FileCopyLocalListener::GetLocalListener(infos->srcPath, infos->srcUriIsFile, processCallback); - ret = Storage::DistributedFile::FileCopyManager::GetInstance()->ExecLocal(infos); - EXPECT_EQ(ret, 2); - - infos->srcUriIsFile = true; - ret = Storage::DistributedFile::FileCopyManager::GetInstance()->ExecLocal(infos); - EXPECT_NE(ret, 0); + auto ret = Storage::DistributedFile::FileCopyManager::GetInstance()->ExecLocal(infos); + // destpath not exist + EXPECT_EQ(ret, ENOENT); - infos->localListener = nullptr; + if (!std::filesystem::exists(destpath, errCode) && errCode.value() == E_OK) { + int res = Storage::DistributedFile::FileCopyManager::GetInstance()->MakeDir(destpath); + EXPECT_EQ(res, E_OK); + } + // dir copy to dir ret = Storage::DistributedFile::FileCopyManager::GetInstance()->ExecLocal(infos); - EXPECT_NE(ret, 0); + EXPECT_EQ(ret, 0); ASSERT_EQ(remove(srcpath.c_str()), 0); - ASSERT_EQ(ForceRemoveDirectory(destpath.c_str()), 0); - GTEST_LOG_(INFO) << "FileCopyManager_Copy_0006 End"; + ASSERT_EQ(ForceRemoveDirectory(destpath.c_str()), true); + GTEST_LOG_(INFO) << "FileCopyManager_ExecLocal_0002 End"; } /** -* @tc.name: FileCopyManager_Copy_0007 +* @tc.name: FileCopyManager_ExecLocal_0003 * @tc.desc: The execution of the execlocal failed. * @tc.type: FUNC * @tc.require: I7TDJK */ -HWTEST_F(FileCopyManagerTest, FileCopyManager_Copy_0007, TestSize.Level1) +HWTEST_F(FileCopyManagerTest, FileCopyManager_ExecLocal_0003, TestSize.Level0) { - //无destpath赋值,stat检查返回2 - GTEST_LOG_(INFO) << "FileCopyManager_Copy_0006 Start"; - string srcuri = "file://docs/storage/media/100/local/files/Docs/aa/"; - string desturi = "file://docs/storage/media/100/local/files/Docs/aa1/"; - string srcpath = "/storage/media/100/local/files/Docs/aa/"; + GTEST_LOG_(INFO) << "FileCopyManager_ExecLocal_0003 Start"; + string srcuri = "file://docs/storage/media/100/local/files/Docs/srcaa12/"; + string desturi = "file://docs/storage/media/100/local/files/Docs/dstaa12/"; + string srcpath = "/storage/media/100/local/files/Docs/srcaa12/"; + string destpath = "/storage/media/100/local/files/Docs/dstaa12/"; std::error_code errCode; if (!std::filesystem::exists(srcpath, errCode) && errCode.value() == E_OK) { int res = Storage::DistributedFile::FileCopyManager::GetInstance()->MakeDir(srcpath); @@ -294,82 +357,118 @@ HWTEST_F(FileCopyManagerTest, FileCopyManager_Copy_0007, TestSize.Level1) infos->srcUri = srcuri; infos->destUri = desturi; infos->srcPath = srcpath; + infos->destPath = destpath; + infos->srcUriIsFile = true; + ProcessCallback processCallback = [](uint64_t processSize, uint64_t totalSize) -> void {}; + infos->localListener = FileCopyLocalListener::GetLocalListener(infos->srcPath, + infos->srcUriIsFile, processCallback); + // srcUriIsFile is true, destpath not exist auto ret = Storage::DistributedFile::FileCopyManager::GetInstance()->ExecLocal(infos); - EXPECT_EQ(ret, 2); + EXPECT_EQ(ret, ENOTDIR); ASSERT_EQ(remove(srcpath.c_str()), 0); - GTEST_LOG_(INFO) << "FileCopyManager_Copy_0007 End"; + ASSERT_EQ(remove(destpath.c_str()), 0); + GTEST_LOG_(INFO) << "FileCopyManager_ExecLocal_0003 End"; } /** -* @tc.name: FileCopyManager_Copy_0008 -* @tc.desc: The execution of the Copy succeed. +* @tc.name: FileCopyManager_ExecLocal_0004 +* @tc.desc: The execution of the execlocal failed. * @tc.type: FUNC * @tc.require: I7TDJK */ -HWTEST_F(FileCopyManagerTest, FileCopyManager_Copy_0008, TestSize.Level0) +HWTEST_F(FileCopyManagerTest, FileCopyManager_ExecLocal_0004, TestSize.Level0) { - //same uri - GTEST_LOG_(INFO) << "FileCopyManager_Copy_0008 Start"; - string srcUri = "file://docs/storage/media/100/local/files/Docs/1.txt"; - string destUri = "file://docs/storage/media/100/local/files/Docs/1.txt"; - string srcPath = "/storage/media/100/local/files/Docs/1.txt"; - int fd = open(srcPath.c_str(), O_RDWR | O_CREAT); - ASSERT_TRUE(fd != -1) <<"Failed to open file in FileCopyManager_Copy_0002!" << errno; - close(fd); + //无对应子文件夹,errno返回2 + GTEST_LOG_(INFO) << "FileCopyManager_ExecLocal_0004 Start"; + string srcuri = "file://docs/storage/media/100/local/files/Docs/srcaa13/"; + string desturi = "file://docs/storage/media/100/local/files/Docs/dstaa13/"; + string srcpath = "/storage/media/100/local/files/Docs/srcaa13/"; + string destpath = "/storage/media/100/local/files/Docs/dstaa13/"; + std::error_code errCode; + auto infos = std::make_shared(); + infos->srcUri = srcuri; + infos->destUri = desturi; + infos->srcPath = srcpath; + infos->destPath = destpath; + ProcessCallback processCallback = [](uint64_t processSize, uint64_t totalSize) -> void {}; + infos->localListener = FileCopyLocalListener::GetLocalListener(infos->srcPath, + infos->srcUriIsFile, processCallback); - auto ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Copy(srcUri, destUri, listener_); - EXPECT_EQ(ret, EINVAL); - ASSERT_EQ(remove(srcPath.c_str()), 0); - GTEST_LOG_(INFO) << "FileCopyManager_Copy_0008 End"; + if (!std::filesystem::exists(destpath, errCode) && errCode.value() == E_OK) { + int res = Storage::DistributedFile::FileCopyManager::GetInstance()->MakeDir(destpath); + EXPECT_EQ(res, E_OK); + } + auto ret = Storage::DistributedFile::FileCopyManager::GetInstance()->ExecLocal(infos); + // src path not exist + EXPECT_EQ(ret, E_OK); + ASSERT_EQ(ForceRemoveDirectory(destpath.c_str()), true); + GTEST_LOG_(INFO) << "FileCopyManager_ExecLocal_0004 End"; } /** -* @tc.name: FileCopyManager_Copy_0009 -* @tc.desc: The execution of the Copy succeed. +* @tc.name: FileCopyManager_ExecLocal_0005 +* @tc.desc: ExecLocal * @tc.type: FUNC * @tc.require: I7TDJK */ -HWTEST_F(FileCopyManagerTest, FileCopyManager_Copy_0009, TestSize.Level0) +HWTEST_F(FileCopyManagerTest, FileCopyManager_ExecLocal_0005, TestSize.Level0) { - GTEST_LOG_(INFO) << "FileCopyManager_Copy_0009 Start"; - string srcUri = "file://docs/storage/media/100/local/files/Docs/1.txt"; - string destUri = "file://docs/storage/media/100/local/files/Docs/a1.txt"; - string srcPath = "/storage/media/100/local/files/Docs/1.txt"; - int fd = open(srcPath.c_str(), O_RDWR | O_CREAT); - ASSERT_TRUE(fd != -1) <<"Failed to open file in FileCopyManager_Copy_0009!" << errno; + GTEST_LOG_(INFO) << "FileCopyManager_ExecLocal_0005 Start"; + string srcuri = "file://docs/storage/media/100/local/files/Docs/11.txt"; + string desturi = "file://docs/storage/media/100/local/files/Docs/aa/"; + string srcpath = "/storage/media/100/local/files/Docs/11.txt"; + string destpath = "/storage/media/100/local/files/Docs/aa/"; + int fd = open(srcpath.c_str(), O_RDWR | O_CREAT); + ASSERT_TRUE(fd != -1) <<"Failed to open file in FileCopyManager_ExecLocal_0005!" << errno; close(fd); - auto ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Copy(srcUri, destUri, listener_); - EXPECT_EQ(ret, E_OK); - ASSERT_EQ(remove(srcPath.c_str()), 0); - GTEST_LOG_(INFO) << "FileCopyManager_Copy_0009 End"; + std::error_code errCode; + if (!std::filesystem::exists(destpath, errCode) && errCode.value() == E_OK) { + int res = Storage::DistributedFile::FileCopyManager::GetInstance()->MakeDir(destpath); + ASSERT_EQ(res, E_OK); + } + + auto infos = std::make_shared(); + infos->localListener = std::make_shared("", + true, [](uint64_t processSize, uint64_t totalSize) -> void {}); + infos->srcUri = srcuri; + infos->destUri = desturi; + infos->srcPath = srcpath; + infos->destPath = destpath; + infos->srcUriIsFile = true; + // file to dir + auto ret = Storage::DistributedFile::FileCopyManager::GetInstance()->ExecLocal(infos); + EXPECT_EQ(ret, EINVAL); + ASSERT_EQ(remove(srcpath.c_str()), 0); + EXPECT_TRUE(ForceRemoveDirectory(destpath)); + GTEST_LOG_(INFO) << "FileCopyManager_ExecLocal_0005 End"; } /** -* @tc.name: FileCopyManager_Copy_0010 -* @tc.desc: The execution of the Copy failed. +* @tc.name: FileCopyManager_ExecLocal_0006 +* @tc.desc: ExecLocal * @tc.type: FUNC * @tc.require: I7TDJK */ -HWTEST_F(FileCopyManagerTest, FileCopyManager_Copy_0010, TestSize.Level0) +HWTEST_F(FileCopyManagerTest, FileCopyManager_ExecLocal_0006, TestSize.Level0) { - GTEST_LOG_(INFO) << "FileCopyManager_Copy_0010 Start"; - string localUri = "/data/test/test.txt"; - string dstUri = "/data/test/test.txt"; - - auto ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Copy("", localUri, emptyCallback_); - EXPECT_EQ(ret, EINVAL); - - ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Copy(localUri, "", listener_); - EXPECT_EQ(ret, EINVAL); - - ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Copy(localUri, dstUri, listener_); - EXPECT_EQ(ret, EINVAL); - - ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Copy(localUri, dstUri, emptyCallback_); - EXPECT_EQ(ret, EINVAL); + GTEST_LOG_(INFO) << "FileCopyManager_ExecLocal_0006 Start"; + string srcuri = "file://docs/storage/media/100/local/files/Docs/11.txt"; + string desturi = "file://docs/storage/media/100/local/files/Docs/dest11.txt"; + string srcpath = "/storage/media/100/local/files/Docs/11.txt"; + string destpath = "/aa/dest11.txt"; - GTEST_LOG_(INFO) << "FileCopyManager_Copy_0010 End"; + auto infos = std::make_shared(); + infos->srcUriIsFile = true; + infos->srcPath = srcpath; + infos->destPath = destpath; + infos->localListener = FileCopyLocalListener::GetLocalListener(infos->srcPath, + infos->srcUriIsFile, listener_); + + // destpath is invalid + auto ret = Storage::DistributedFile::FileCopyManager::GetInstance()->ExecLocal(infos); + EXPECT_EQ(ret, ENOENT); + GTEST_LOG_(INFO) << "FileCopyManager_ExecLocal_0006 End"; } /** @@ -635,22 +734,6 @@ HWTEST_F(FileCopyManagerTest, FileCopyManager_CheckOrCreateLPath_0001, TestSize. GTEST_LOG_(INFO) << "FileCopyManager_CheckOrCreateLPath_0001 End"; } -/** -* @tc.name: FileCopyManager_CreateFileInfos_0001 -* @tc.desc: CreateFileInfos -* @tc.type: FUNC -* @tc.require: I7TDJK -*/ -HWTEST_F(FileCopyManagerTest, FileCopyManager_CreateFileInfos_0001, TestSize.Level0) -{ - GTEST_LOG_(INFO) << "FileCopyManager_CreateFileInfos_0001 Start"; - auto infos = std::make_shared(); - infos->srcUri = ""; - int32_t ret = Storage::DistributedFile::FileCopyManager::GetInstance()->CreateFileInfos("", "", infos); - EXPECT_EQ(ret, ERR_BAD_VALUE); - GTEST_LOG_(INFO) << "FileCopyManager_CreateFileInfos_0001 End"; -} - /** * @tc.name: FileCopyManager_RemoveFileInfos_0001 * @tc.desc: RemoveFileInfos @@ -885,6 +968,44 @@ HWTEST_F(FileCopyManagerTest, FileCopyManager_Cancel_0003, TestSize.Level0) GTEST_LOG_(INFO) << "FileCopyManager_Cancel_0003 End"; } +/** +* @tc.name: FileCopyManager_Cancel_0004 +* @tc.desc: The execution of the cancel succeed. +* @tc.type: FUNC +* @tc.require: I7TDJK + */ +HWTEST_F(FileCopyManagerTest, FileCopyManager_Cancel_0004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "FileCopyManager_Cancel_0004 Start"; + auto infos1 = std::make_shared(); + infos1->srcUri = "srcUri1"; + infos1->destUri = "destUri1"; + infos1->transListener = nullptr; + infos1->localListener = std::make_shared("", + true, [](uint64_t processSize, uint64_t totalSize) -> void {}); + std::string srcUri = "srcUri1"; + std::string destUri = "destUri3"; + + Storage::DistributedFile::FileCopyManager::GetInstance()->FileInfosVec_.emplace_back(infos1); + auto ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Cancel(srcUri, destUri); + EXPECT_EQ(ret, E_OK); + srcUri = "srcUri2"; + destUri = "destUri1"; + ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Cancel(srcUri, destUri); + EXPECT_EQ(ret, E_OK); + + srcUri = "srcUri2"; + destUri = "destUri2"; + ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Cancel(srcUri, destUri); + EXPECT_EQ(ret, E_OK); + + srcUri = "srcUri1"; + destUri = "destUri1"; + ret = Storage::DistributedFile::FileCopyManager::GetInstance()->Cancel(srcUri, destUri); + EXPECT_EQ(ret, E_OK); + GTEST_LOG_(INFO) << "FileCopyManager_Cancel_0004 End"; +} + /** * @tc.name: FileCopyManager_MakeDir_0001 * @tc.desc: test MakeDir function. @@ -898,44 +1019,7 @@ HWTEST_F(FileCopyManagerTest, FileCopyManager_MakeDir_0001, TestSize.Level1) std::error_code errCode; int res = Storage::DistributedFile::FileCopyManager::GetInstance()->MakeDir(srcpath); EXPECT_EQ(res, E_OK); + ASSERT_EQ(ForceRemoveDirectory(srcpath.c_str()), true); GTEST_LOG_(INFO) << "FileCopyManager_MakeDir_0001 End"; } - -/** -* @tc.name: FileCopyManager_ExecLocal_0001 -* @tc.desc: ExecLocal -* @tc.type: FUNC -* @tc.require: I7TDJK - */ -HWTEST_F(FileCopyManagerTest, FileCopyManager_ExecLocal_0001, TestSize.Level0) -{ - GTEST_LOG_(INFO) << "FileCopyManager_ExecLocal_0001 Start"; - string srcuri = "file://docs/storage/media/100/local/files/Docs/11.txt"; - string desturi = "file://docs/storage/media/100/local/files/Docs/aa/"; - string srcpath = "/storage/media/100/local/files/Docs/11.txt"; - string destpath = "/storage/media/100/local/files/Docs/aa/"; - int fd = open(srcpath.c_str(), O_RDWR | O_CREAT); - ASSERT_TRUE(fd != -1) <<"Failed to open file in FileCopyManager_ExecLocal_0001!" << errno; - close(fd); - - std::error_code errCode; - if (!std::filesystem::exists(destpath, errCode) && errCode.value() == E_OK) { - int res = Storage::DistributedFile::FileCopyManager::GetInstance()->MakeDir(destpath); - ASSERT_EQ(res, E_OK); - } - - auto infos = std::make_shared(); - infos->localListener = std::make_shared("", - true, [](uint64_t processSize, uint64_t totalSize) -> void {}); - infos->srcUri = srcuri; - infos->destUri = desturi; - infos->srcPath = srcpath; - infos->destPath = destpath; - auto ret = Storage::DistributedFile::FileCopyManager::GetInstance()->ExecLocal(infos); - EXPECT_EQ(ret, E_OK); - EXPECT_TRUE(std::filesystem::exists("/storage/media/100/local/files/Docs/aa/11.txt")); - ASSERT_EQ(remove(srcpath.c_str()), 0); - EXPECT_TRUE(ForceRemoveDirectory(destpath)); - GTEST_LOG_(INFO) << "FileCopyManager_ExecLocal_0001 End"; -} } \ No newline at end of file diff --git a/test/unittests/distributed_file_inner/copy/remote_file_copy_manager_test.cpp b/test/unittests/distributed_file_inner/copy/remote_file_copy_manager_test.cpp index 6d5c743af847c2629b42bc25a366ec6100ee441f..4ee604018d08c19f43ecb8afb4632718e8825233 100644 --- a/test/unittests/distributed_file_inner/copy/remote_file_copy_manager_test.cpp +++ b/test/unittests/distributed_file_inner/copy/remote_file_copy_manager_test.cpp @@ -25,8 +25,8 @@ #include "file_copy_listener.h" #include "file_copy_manager.h" #include "file_size_utils.h" -#include "trans_listener.h" #include "sandbox_helper.h" +#include "trans_listener.h" std::string g_physicalPath = "/test/test"; int32_t g_getPhysicalPath = 0; @@ -37,7 +37,7 @@ int32_t SandboxHelper::GetPhysicalPath(const std::string &fileUri, const std::st physicalPath = g_physicalPath; return g_getPhysicalPath; } -} +} // namespace OHOS::AppFileService namespace OHOS::Storage::DistributedFile::Test { using namespace OHOS::FileManagement; @@ -107,9 +107,6 @@ HWTEST_F(RemoteFileCopyManagerTest, RemoteFileCopyManager_Copy_0001, TestSize.Le ret = Storage::DistributedFile::RemoteFileCopyManager::GetInstance()->RemoteCopy("", "", listenerCallback, userId, copyPath); EXPECT_EQ(ret, EINVAL); - ret = Storage::DistributedFile::RemoteFileCopyManager::GetInstance()->RemoteCopy(localUri, dstUri, listenerCallback, userId, copyPath); - EXPECT_EQ(ret, ENOENT); - string remoteUri = "/data/test/Copy/?networkid=/"; if (!ForceCreateDirectory(remoteUri)) { GTEST_LOG_(INFO) << "RemoteFileCopyManager_Copy_0001 create dir err"; @@ -135,7 +132,7 @@ HWTEST_F(RemoteFileCopyManagerTest, RemoteFileCopyManager_Copy_0002, TestSize.Le string destUri = "file://docs/storage/media/100/local/files/Docs/dest1.txt"; string srcPath = "/storage/media/100/local/files/Docs/1.txt"; int32_t userId = 100; - string copyPath = "/data/storage/el2/distributedfiles/123412345/dest1.txt"; + string copyPath = "/data/storage/el2/distributedfiles/123412345"; sptr listenerCallback; int fd = open(srcPath.c_str(), O_RDWR | O_CREAT); @@ -237,7 +234,7 @@ HWTEST_F(RemoteFileCopyManagerTest, RemoteFileCopyManager_CreateFileInfos_0001, int32_t userId = 100; string copyPath = "/data/storage/el2/distributedfiles/123412345/test.txt"; int32_t ret = Storage::DistributedFile::RemoteFileCopyManager::GetInstance()->CreateFileInfos("", "", infos, userId, copyPath); - EXPECT_EQ(ret, ENOENT); + EXPECT_EQ(ret, E_OK); GTEST_LOG_(INFO) << "RemoteFileCopyManager_CreateFileInfos_0001 End"; } diff --git a/test/unittests/services_daemon/BUILD.gn b/test/unittests/services_daemon/BUILD.gn index 6a7e0a1b48a99c65c1bb2cc2779f9a47fd715b8b..56cd110061b7a793e10cf908c7460cff83d77580 100644 --- a/test/unittests/services_daemon/BUILD.gn +++ b/test/unittests/services_daemon/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (C) 2023-2025 Huawei Device Co., Ltd. +# Copyright (C) 2023-2024 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 @@ -20,6 +20,7 @@ ohos_unittest("fuse_manager_test") { sources = [ "${distributedfile_path}/services/cloudfiledaemon/src/fuse_manager/cloud_daemon_statistic.cpp", "${distributedfile_path}/services/cloudfiledaemon/src/fuse_manager/fuse_manager.cpp", + "${services_path}/cloudfiledaemon/src/utils/setting_data_helper.cpp", "fuse_manager_test.cpp", "mock/libfuse_mock.cpp", "mock/system_function_mock.cpp", @@ -41,6 +42,7 @@ ohos_unittest("fuse_manager_test") { "${distributedfile_path}/services/cloudfiledaemon/include/fuse_manager", "${distributedfile_path}/utils/ioctl/include", "${services_path}/cloudfiledaemon/include/cloud_disk/", + "${services_path}/cloudfiledaemon/include/utils/", "${services_path}/cloudfiledaemon/src/fuse_manager", "${distributedfile_path}/adapter/cloud_adapter_example/include", "${clouddisk_database_path}/include", @@ -53,7 +55,6 @@ ohos_unittest("fuse_manager_test") { "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", "${utils_path}:libdistributedfiledentry", "${utils_path}:libdistributedfileutils", - "${utils_path}:libdistributedfileutils_lite", ] external_deps = [ @@ -61,6 +62,7 @@ ohos_unittest("fuse_manager_test") { "ability_runtime:dataobs_manager", "bounds_checking_function:libsec_shared", "c_utils:utils", + "data_share:datashare_consumer", "ffrt:libffrt", "googletest:gmock_main", "googletest:gtest_main", @@ -191,7 +193,6 @@ ohos_unittest("cloud_daemon_statistic_test") { "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit", "${utils_path}:libdistributedfiledentry", "${utils_path}:libdistributedfileutils", - "${utils_path}:libdistributedfileutils_lite", ] external_deps = [ @@ -234,6 +235,7 @@ ohos_unittest("cloud_daemon_test") { "${distributedfile_path}/services/cloudfiledaemon/src/fuse_manager/fuse_manager.cpp", "${distributedfile_path}/services/cloudfiledaemon/src/ipc/cloud_daemon.cpp", "${distributedfile_path}/services/cloudfiledaemon/src/ipc/cloud_daemon_stub.cpp", + "${services_path}/cloudfiledaemon/src/utils/setting_data_helper.cpp", "cloud_daemon_test.cpp", "mock/system_function_mock.cpp", ] @@ -271,6 +273,7 @@ ohos_unittest("cloud_daemon_test") { "${innerkits_native_path}/cloud_file_kit_inner/big_data_statistics", "${services_path}/cloudfiledaemon/include/fuse_manager/", "${services_path}/cloudfiledaemon/include/ipc/", + "${services_path}/cloudfiledaemon/include/utils/", "${services_path}/cloudsyncservice/include/data_sync/", ] @@ -280,7 +283,6 @@ ohos_unittest("cloud_daemon_test") { "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit_core", "${utils_path}:libdistributedfiledentry", "${utils_path}:libdistributedfileutils", - "${utils_path}:libdistributedfileutils_lite", ] external_deps = [ @@ -288,6 +290,7 @@ ohos_unittest("cloud_daemon_test") { "ability_runtime:dataobs_manager", "c_utils:utils", "common_event_service:cesfwk_innerkits", + "data_share:datashare_consumer", "ffrt:libffrt", "googletest:gmock_main", "googletest:gtest_main", @@ -320,6 +323,101 @@ ohos_unittest("cloud_daemon_test") { subsystem_name = "filemanagement" } +ohos_unittest("cloud_daemon_nomock_test") { + module_out_path = "dfs_service/dfs_service" + + sources = [ + "${distributedfile_path}/services/cloudfiledaemon/src/fuse_manager/cloud_daemon_statistic.cpp", + "${distributedfile_path}/services/cloudfiledaemon/src/fuse_manager/fuse_manager.cpp", + "${distributedfile_path}/services/cloudfiledaemon/src/ipc/cloud_daemon.cpp", + "${distributedfile_path}/services/cloudfiledaemon/src/ipc/cloud_daemon_stub.cpp", + "${services_path}/cloudfiledaemon/src/utils/setting_data_helper.cpp", + "cloud_daemon_nomock_test.cpp", + ] + + cloud_disk = [ + "${services_path}/cloudfiledaemon/src/cloud_disk/database_manager.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_base.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_cloud.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/file_operations_local.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/fuse_operations.cpp", + "${distributedfile_path}/services/cloudfiledaemon/src/cloud_disk/file_operations_helper.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/account_status.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/account_status_listener.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/appstate_observer.cpp", + "${services_path}/cloudfiledaemon/src/cloud_disk/io_message_listener.cpp", + ] + + sources += cloud_disk + + include_dirs = [ + "${distributedfile_path}/services/cloudfiledaemon/include", + "${services_path}/cloudfiledaemon/include/cloud_disk/", + "${distributedfile_path}/adapter/cloud_adapter_example/include", + "${clouddisk_database_path}/include", + "${distributedfile_path}/test/unittests/services_daemon/mock", + "${distributedfile_path}/services/cloudfiledaemon/include/fuse_manager", + "${distributedfile_path}/interfaces/inner_api/native", + "${distributedfile_path}/interfaces/inner_api/native/cloud_file_kit_inner/big_data_statistics", + "${distributedfile_path}/utils/ioctl/include", + "${utils_path}/cloud_disk/include", + "${utils_path}/dentry/include", + "${utils_path}/log/include", + "${utils_path}/system/include", + "${innerkits_native_path}/cloud_daemon_kit_inner", + "${innerkits_native_path}/cloud_file_kit_inner/big_data_statistics", + "${services_path}/cloudfiledaemon/include/fuse_manager/", + "${services_path}/cloudfiledaemon/include/ipc/", + "${services_path}/cloudfiledaemon/include/utils/", + "${services_path}/cloudsyncservice/include/data_sync/", + ] + + deps = [ + "${clouddisk_database_path}:clouddisk_database", + "${innerkits_native_path}/cloud_daemon_kit_inner:cloud_daemon_kit_inner", + "${innerkits_native_path}/cloud_file_kit_inner:cloudfile_kit_core", + "${utils_path}:libdistributedfiledentry", + "${utils_path}:libdistributedfileutils", + "${utils_path}:libdistributedfileutils_lite", + ] + + external_deps = [ + "ability_base:zuri", + "ability_runtime:dataobs_manager", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "data_share:datashare_consumer", + "ffrt:libffrt", + "googletest:gmock_main", + "googletest:gtest_main", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_single", + "libfuse:libfuse", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "ability_runtime:app_manager", + ] + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"CloudFileDaemon\"", + ] + + if (cloudsync_service_hicollie_enable) { + external_deps += [ "hicollie:libhicollie" ] + defines += [ "HICOLLIE_ENABLE" ] + } + + use_exceptions = true + part_name = "dfs_service" + subsystem_name = "filemanagement" +} + ohos_unittest("cloud_daemon_stub_test") { module_out_path = "dfs_service/dfs_service" @@ -389,6 +487,7 @@ ohos_unittest("fuse_manager_static_test") { "${distributedfile_path}/services/cloudfiledaemon/include/fuse_manager", "${distributedfile_path}/utils/ioctl/include", "${services_path}/cloudfiledaemon/include/cloud_disk/", + "${services_path}/cloudfiledaemon/include/utils/", "${services_path}/cloudfiledaemon/src/fuse_manager", "${distributedfile_path}/adapter/cloud_adapter_example/include", "${clouddisk_database_path}/include", @@ -437,6 +536,72 @@ ohos_unittest("fuse_manager_static_test") { subsystem_name = "filemanagement" } +ohos_unittest("setting_data_helper_test") { + module_out_path = "dfs_service/dfs_service" + + sources = [ + "${services_path}/cloudfiledaemon/src/utils/setting_data_helper.cpp", + "mock/data_helper_mock.cpp", + "setting_data_helper_test.cpp", + ] + + include_dirs = [ + "${clouddisk_database_path}/include", + "${distributedfile_path}/interfaces/inner_api/native/cloudsync_kit_inner", + "${distributedfile_path}/services/cloudfiledaemon/include", + "${distributedfile_path}/services/cloudfiledaemon/include/cloud_disk", + "${distributedfile_path}/services/cloudfiledaemon/include/fuse_manager", + "${distributedfile_path}/services/cloudfiledaemon/include/utils", + "${innerkits_native_path}/cloud_daemon_kit_inner", + "${innerkits_native_path}/cloud_file_kit_inner", + "${innerkits_native_path}/cloud_file_kit_inner/big_data_statistics", + "${services_path}/cloudfiledaemon/include/ipc/", + "${services_path}/cloudfiledaemon/src/fuse_manager", + "${services_path}/cloudsyncservice/include/data_sync/", + "${utils_path}/cloud_disk/include", + "${utils_path}/dentry/include", + "${utils_path}/log/include", + "mock" + ] + + deps = [ + "${utils_path}:libdistributedfileutils_lite", + ] + + external_deps = [ + "ability_base:zuri", + "ability_runtime:dataobs_manager", + "bounds_checking_function:libsec_shared", + "c_utils:utils", + "data_share:datashare_consumer", + "ffrt:libffrt", + "googletest:gmock_main", + "googletest:gtest_main", + "hilog:libhilog", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + "init:libbegetutil", + "ipc:ipc_single", + "libfuse:libfuse", + "relational_store:native_rdb", + ] + + defines = [ + "private=public", + "LOG_DOMAIN=0xD004308", + "LOG_TAG=\"SettingDataHelperTest\"", + ] + + if (cloudsync_service_hicollie_enable) { + external_deps += [ "hicollie:libhicollie" ] + defines += [ "HICOLLIE_ENABLE" ] + } + + use_exceptions = true + part_name = "dfs_service" + subsystem_name = "filemanagement" +} + group("services_daemon_test") { testonly = true @@ -447,5 +612,7 @@ group("services_daemon_test") { ":cloud_daemon_test", ":fuse_manager_test", ":fuse_manager_static_test", + ":setting_data_helper_test", + ":cloud_daemon_nomock_test", ] } diff --git a/test/unittests/services_daemon/cloud_daemon_nomock_test.cpp b/test/unittests/services_daemon/cloud_daemon_nomock_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e2b57ddde98ff66a27d66b07a838bd7fb5f01d35 --- /dev/null +++ b/test/unittests/services_daemon/cloud_daemon_nomock_test.cpp @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "dfs_error.h" +#include "fuse_assistant.h" +#include "fuse_manager/fuse_manager.h" +#include "ipc/cloud_daemon.h" +#include "iremote_object.h" +#include "setting_data_helper.h" +#include "system_ability_definition.h" +#include "utils_log.h" + +namespace OHOS::FileManagement::CloudFile::Test { +using namespace testing; +using namespace testing::ext; +constexpr int32_t USER_ID = 100; +constexpr int32_t DEV_FD = 10; + +class CloudDaemonTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + std::shared_ptr cloudDaemon_; +}; + +void CloudDaemonTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void CloudDaemonTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void CloudDaemonTest::SetUp(void) +{ + int32_t saID = FILEMANAGEMENT_CLOUD_DAEMON_SERVICE_SA_ID; + bool runOnCreate = true; + cloudDaemon_ = std::make_shared(saID, runOnCreate); + GTEST_LOG_(INFO) << "SetUp"; +} + +void CloudDaemonTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: OnAddSystemAbilityTest001 + * @tc.desc: Verify the OnStart function + * @tc.type: FUNC + * @tc.require: issuesIB538J + */ +HWTEST_F(CloudDaemonTest, OnAddSystemAbility001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnAddSystemAbility001 start"; + try { + const int32_t systemAbilityId = 100; + const std::string deviceId = "device_test"; + cloudDaemon_->OnAddSystemAbility(systemAbilityId, deviceId); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnAddSystemAbilityTest001 failed"; + } + GTEST_LOG_(INFO) << "OnAddSystemAbilityTest001 end"; +} + +/** + * @tc.name: OnAddSystemAbilityTest002 + * @tc.desc: Verify the OnAddSystemAbility function + * @tc.type: FUNC + */ +HWTEST_F(CloudDaemonTest, OnAddSystemAbilityTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnAddSystemAbilityTest002 start"; + try { + const int32_t systemAbilityId = DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID; + const std::string deviceId = "device_test"; + SettingDataHelper::GetInstance().isBundleInited_ = true; + cloudDaemon_->OnAddSystemAbility(systemAbilityId, deviceId); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnAddSystemAbilityTest002 failed"; + } + GTEST_LOG_(INFO) << "OnAddSystemAbilityTest002 end"; +} +} // namespace OHOS::FileManagement::CloudSync::Test \ No newline at end of file diff --git a/test/unittests/services_daemon/cloud_daemon_test.cpp b/test/unittests/services_daemon/cloud_daemon_test.cpp index 1525544778a6d4bc3786551685c5146831df844b..b102f0aebefb6ab5fbf0c203081dc0a71f158039 100644 --- a/test/unittests/services_daemon/cloud_daemon_test.cpp +++ b/test/unittests/services_daemon/cloud_daemon_test.cpp @@ -21,6 +21,7 @@ #include "fuse_manager/fuse_manager.h" #include "ipc/cloud_daemon.h" #include "iremote_object.h" +#include "setting_data_helper.h" #include "system_ability_definition.h" #include "utils_log.h" @@ -256,4 +257,24 @@ HWTEST_F(CloudDaemonTest, OnAddSystemAbility001, TestSize.Level1) } GTEST_LOG_(INFO) << "OnAddSystemAbilityTest001 end"; } + +/** + * @tc.name: OnAddSystemAbilityTest002 + * @tc.desc: Verify the OnAddSystemAbility function + * @tc.type: FUNC + */ +HWTEST_F(CloudDaemonTest, OnAddSystemAbilityTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OnAddSystemAbilityTest002 start"; + try { + const int32_t systemAbilityId = DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID; + const std::string deviceId = "device_test"; + SettingDataHelper::GetInstance().isBundleInited_ = true; + cloudDaemon_->OnAddSystemAbility(systemAbilityId, deviceId); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "OnAddSystemAbilityTest002 failed"; + } + GTEST_LOG_(INFO) << "OnAddSystemAbilityTest002 end"; +} } // namespace OHOS::FileManagement::CloudSync::Test \ No newline at end of file diff --git a/test/unittests/services_daemon/fuse_manager_static_test.cpp b/test/unittests/services_daemon/fuse_manager_static_test.cpp index 446d88dbbc56518091dc94e05d8e6103a6789bb8..a7c718843e57b918e4bd34f54e6211f8fc0250a3 100644 --- a/test/unittests/services_daemon/fuse_manager_static_test.cpp +++ b/test/unittests/services_daemon/fuse_manager_static_test.cpp @@ -372,4 +372,46 @@ HWTEST_F(FuseManagerStaticTest, DeleteFdsanTest003, TestSize.Level1) } GTEST_LOG_(INFO) << "DeleteFdsanTest003 end"; } + +/** + * @tc.name: IsHdc001 + * @tc.desc: Verify the IsHdc function + * @tc.type: FUNC + */ +HWTEST_F(FuseManagerStaticTest, IsHdc001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsHdc001 Begin"; + try { + struct FuseData data; + data.activeBundle = CloudSync::GALLERY_BUNDLE_NAME; + bool ret = IsHdc(&data); + + EXPECT_EQ(ret, false); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "IsHdc001 Error"; + } + GTEST_LOG_(INFO) << "IsHdc001 End"; +} + +/** + * @tc.name: IsHdc002 + * @tc.desc: Verify the IsHdc function + * @tc.type: FUNC + */ +HWTEST_F(FuseManagerStaticTest, IsHdc002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsHdc002 Begin"; + try { + struct FuseData data; + data.activeBundle = CloudSync::HDC_BUNDLE_NAME; + bool ret = IsHdc(&data); + + EXPECT_EQ(ret, true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "IsHdc002 Error"; + } + GTEST_LOG_(INFO) << "IsHdc002 End"; +} } // namespace OHOS::FileManagement::CloudSync::Test \ No newline at end of file diff --git a/utils/ffrt/src/concurrent_queue.cpp b/test/unittests/services_daemon/mock/data_helper_mock.cpp similarity index 37% rename from utils/ffrt/src/concurrent_queue.cpp rename to test/unittests/services_daemon/mock/data_helper_mock.cpp index ebcbd482018132f967bd03a9b75e9b1a44df5735..8c2bfc79c75f56ef8c643425e3b2b86dc5cb4440 100644 --- a/utils/ffrt/src/concurrent_queue.cpp +++ b/test/unittests/services_daemon/mock/data_helper_mock.cpp @@ -12,44 +12,35 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "concurrent_queue.h" -#include "utils_log.h" +#include "data_helper_mock.h" -namespace OHOS { -namespace FileManagement { -ConcurrentQueue &ConcurrentQueue::GetInstance() +namespace OHOS::DataShare { +using namespace OHOS::FileManagement::CloudFile; +std::shared_ptr DataShareHelper::Creator(const std::string &strUri, + const CreateOptions &options, + const std::string &bundleName, + const int waitTime, + bool isSystem) { - static ConcurrentQueue instance_; - return instance_; + return IDataHelper::ins->Creator(); } +} // namespace OHOS::DataShare -void ConcurrentQueue::Init(int32_t qos, int32_t maxConcurrencyNum) -{ - queue_ = std::make_unique(ffrt::queue_concurrent, "ConcurrencyQueue", - ffrt::queue_attr().qos(qos).max_concurrency(maxConcurrencyNum)); -} +namespace OHOS::FileManagement::CloudSync { +using namespace OHOS::FileManagement::CloudFile; -void ConcurrentQueue::Deinit() +SwitchStatus SettingsDataManager::GetSwitchStatus() { - queue_ = nullptr; + return IDataHelper::ins->GetSwitchStatus(); } -void ConcurrentQueue::Submit(std::function &&func, const ffrt::task_attr &attr) +int32_t SettingsDataManager::QuerySwitchStatus() { - if (queue_ == nullptr) { - LOGE("concurrent queue instance is null, submit task failed."); - return; - } - queue_->submit_h(func, attr); + return IDataHelper::ins->QuerySwitchStatus(); } -void ConcurrentQueue::Submit(const std::function &func, const ffrt::task_attr &attr) +void SettingsDataManager::RegisterObserver(const std::string &key, sptr dataObserver) { - if (queue_ == nullptr) { - LOGE("concurrent queue instance is null, submit task failed."); - return; - } - queue_->submit_h(func, attr); + return; } -} // namespace FileManagement -} // namespace OHOS \ No newline at end of file +} // namespace OHOS::FileManagement::CloudSync \ No newline at end of file diff --git a/test/unittests/services_daemon/mock/data_helper_mock.h b/test/unittests/services_daemon/mock/data_helper_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..87afdd7df869f7a2c0db04c7bacd2bcaec641c4b --- /dev/null +++ b/test/unittests/services_daemon/mock/data_helper_mock.h @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef DATA_HELPER_MOCK_H +#define DATA_HELPER_MOCK_H +#include +#include +#include + +#include "datashare_helper.h" +#include "settings_data_manager.h" + +namespace OHOS::FileManagement::CloudFile { +using namespace OHOS::DataShare; +using namespace OHOS::FileManagement::CloudSync; + +class DataShareHelperMock : public DataShareHelper { +public: + MOCK_METHOD5(Creator, + std::shared_ptr(const std::string &strUri, + const CreateOptions &options, + const std::string &bundleName, + const int waitTime, + bool isSystem)); + MOCK_METHOD0(Release, bool()); + MOCK_METHOD2(GetFileTypes, std::vector(Uri &uri, const std::string &mimeTypeFilter)); + MOCK_METHOD2(OpenFile, int(Uri &uri, const std::string &mode)); + MOCK_METHOD3(OpenFileWithErrCode, int(Uri &uri, const std::string &mode, int32_t &errCode)); + MOCK_METHOD2(OpenRawFile, int(Uri &uri, const std::string &mode)); + MOCK_METHOD2(Insert, int(Uri &uri, const DataShareValuesBucket &value)); + MOCK_METHOD3(InsertExt, int(Uri &uri, const DataShareValuesBucket &value, std::string &result)); + MOCK_METHOD3(Update, int(Uri &uri, const DataSharePredicates &predicates, const DataShareValuesBucket &value)); + MOCK_METHOD2(BatchUpdate, int(const UpdateOperations &operations, std::vector &results)); + MOCK_METHOD2(Delete, int(Uri &uri, const DataSharePredicates &predicates)); + MOCK_METHOD4(Query, + std::shared_ptr(Uri &uri, + const DataSharePredicates &predicates, + std::vector &columns, + DatashareBusinessError *businessError)); + MOCK_METHOD1(GetType, std::string(Uri &uri)); + MOCK_METHOD2(BatchInsert, int(Uri &uri, const std::vector &values)); + MOCK_METHOD2(ExecuteBatch, int(const std::vector &statements, ExecResultSet &result)); + MOCK_METHOD2(RegisterObserver, int(const Uri &uri, const sptr &dataObserver)); + MOCK_METHOD2(UnregisterObserver, int(const Uri &uri, const sptr &dataObserver)); + MOCK_METHOD1(NotifyChange, void(const Uri &uri)); + MOCK_METHOD3(RegisterObserverExtProvider, + int(const Uri &uri, std::shared_ptr dataObserver, bool isDescendants)); + MOCK_METHOD2(UnregisterObserverExtProvider, int(const Uri &uri, std::shared_ptr dataObserver)); + MOCK_METHOD1(NotifyChangeExtProvider, void(const DataShareObserver::ChangeInfo &changeInfo)); + MOCK_METHOD1(NormalizeUri, Uri(Uri &uri)); + MOCK_METHOD1(DenormalizeUri, Uri(Uri &uri)); + MOCK_METHOD3(AddQueryTemplate, int(const std::string &uri, int64_t subscriberId, Template &tpl)); + MOCK_METHOD2(DelQueryTemplate, int(const std::string &uri, int64_t subscriberId)); + MOCK_METHOD2(Publish, std::vector(const Data &data, const std::string &bundleName)); + MOCK_METHOD2(GetPublishedData, Data(const std::string &bundleName, int &resultCode)); + MOCK_METHOD3(SubscribeRdbData, + std::vector(const std::vector &uris, + const TemplateId &templateId, + const std::function &callback)); + MOCK_METHOD2(UnsubscribeRdbData, + std::vector(const std::vector &uris, const TemplateId &templateId)); + MOCK_METHOD2(EnableRdbSubs, + std::vector(const std::vector &uris, const TemplateId &templateId)); + MOCK_METHOD2(DisableRdbSubs, + std::vector(const std::vector &uris, const TemplateId &templateId)); + MOCK_METHOD3( + SubscribePublishedData, + std::vector(const std::vector &uris, + int64_t subscriberId, + const std::function &callback)); + MOCK_METHOD2(UnsubscribePublishedData, + std::vector(const std::vector &uris, int64_t subscriberId)); + MOCK_METHOD2(EnablePubSubs, + std::vector(const std::vector &uris, int64_t subscriberId)); + MOCK_METHOD2(DisablePubSubs, + std::vector(const std::vector &uris, int64_t subscriberId)); + MOCK_METHOD2(InsertEx, std::pair(Uri &uri, const DataShareValuesBucket &value)); + MOCK_METHOD3(UpdateEx, + std::pair(Uri &uri, + const DataSharePredicates &predicates, + const DataShareValuesBucket &value)); + MOCK_METHOD2(DeleteEx, std::pair(Uri &uri, const DataSharePredicates &predicates)); + MOCK_METHOD3(UserDefineFunc, int32_t(MessageParcel &data, MessageParcel &reply, MessageOption &option)); +}; + +class IDataHelper { +public: + virtual ~IDataHelper() = default; + virtual std::shared_ptr Creator() = 0; + virtual SwitchStatus GetSwitchStatus() = 0; + virtual int32_t QuerySwitchStatus() = 0; + +public: + static inline std::shared_ptr ins = nullptr; +}; + +class DataHelperMock : public IDataHelper { +public: + MOCK_METHOD0(Creator, std::shared_ptr()); + MOCK_METHOD0(GetSwitchStatus, SwitchStatus()); + MOCK_METHOD0(QuerySwitchStatus, int32_t()); +}; +} // namespace OHOS::FileManagement::CloudFile +#endif \ No newline at end of file diff --git a/test/unittests/services_daemon/setting_data_helper_test.cpp b/test/unittests/services_daemon/setting_data_helper_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6c85941bae6b55ca6eaf97296081d7099275fbae --- /dev/null +++ b/test/unittests/services_daemon/setting_data_helper_test.cpp @@ -0,0 +1,382 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include + +#include "fuse_manager.cpp" + +#include "data_helper_mock.h" +#include "data_sync_const.h" +#include "dfs_error.h" +#include "setting_data_helper.h" + +namespace OHOS::FileManagement::CloudFile { +using namespace std; +using namespace testing; +using namespace testing::ext; +using namespace OHOS::DataShare; + +class SettingDataHelperTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr mock_ = nullptr; +}; + +void SettingDataHelperTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void SettingDataHelperTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void SettingDataHelperTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; + mock_ = make_shared(); + DataHelperMock::ins = mock_; +} + +void SettingDataHelperTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; + DataHelperMock::ins = nullptr; + mock_ = nullptr; +} + +/** + * @tc.name: GetInstanceTest + * @tc.desc: Verify the GetInstance function + * @tc.type: FUNC + */ +HWTEST_F(SettingDataHelperTest, GetInstanceTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetInstanceTest start"; + try { + SettingDataHelper::GetInstance(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetInstanceTest failed"; + } + GTEST_LOG_(INFO) << "GetInstanceTest end"; +} + +/** + * @tc.name: SetUserDataTest + * @tc.desc: Verify the SetUserData function + * @tc.type: FUNC + */ +HWTEST_F(SettingDataHelperTest, SetUserDataTest, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetUserDataTest start"; + try { + SettingDataHelper::GetInstance().SetUserData(nullptr); + EXPECT_EQ(SettingDataHelper::GetInstance().data_, nullptr); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetUserDataTest failed"; + } + GTEST_LOG_(INFO) << "SetUserDataTest end"; +} + + +/** + * @tc.name: IsDataShareReadyTest001 + * @tc.desc: Verify the IsDataShareReady function + * @tc.type: FUNC + */ +HWTEST_F(SettingDataHelperTest, IsDataShareReadyTest001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsDataShareReadyTest001 start"; + try { + SettingDataHelper::GetInstance().isDataShareReady_ = true; + bool ret = SettingDataHelper::GetInstance().IsDataShareReady(); + EXPECT_EQ(ret, true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "IsDataShareReadyTest001 failed"; + } + GTEST_LOG_(INFO) << "IsDataShareReadyTest001 end"; +} + +/** + * @tc.name: IsDataShareReadyTest002 + * @tc.desc: Verify the IsDataShareReady function + * @tc.type: FUNC + */ +HWTEST_F(SettingDataHelperTest, IsDataShareReadyTest002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsDataShareReadyTest002 start"; + try { + EXPECT_CALL(*mock_, Creator()).WillOnce(Return(nullptr)); + SettingDataHelper::GetInstance().isDataShareReady_ = false; + bool ret = SettingDataHelper::GetInstance().IsDataShareReady(); + EXPECT_EQ(ret, false); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "IsDataShareReadyTest002 failed"; + } + GTEST_LOG_(INFO) << "IsDataShareReadyTest002 end"; +} + +/** + * @tc.name: IsDataShareReadyTest003 + * @tc.desc: Verify the IsDataShareReady function + * @tc.type: FUNC + */ +HWTEST_F(SettingDataHelperTest, IsDataShareReadyTest003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "IsDataShareReadyTest003 start"; + try { + shared_ptr helper = std::make_shared();; + EXPECT_CALL(*helper, Release()).WillOnce(Return(true)); + EXPECT_CALL(*mock_, Creator()).WillOnce(Return(helper)); + SettingDataHelper::GetInstance().isDataShareReady_ = false; + bool ret = SettingDataHelper::GetInstance().IsDataShareReady(); + EXPECT_EQ(ret, true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "IsDataShareReadyTest003 failed"; + } + GTEST_LOG_(INFO) << "IsDataShareReadyTest003 end"; +} + +/** + * @tc.name: GetSwitchStatus001 + * @tc.desc: Verify the GetSwitchStatus function + * @tc.type: FUNC + */ +HWTEST_F(SettingDataHelperTest, GetSwitchStatus001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetSwitchStatus001 start"; + try { + EXPECT_CALL(*mock_, GetSwitchStatus()).WillOnce(Return(AI_FAMILY)); + string bundle = SettingDataHelper::GetInstance().GetActiveBundle(); + EXPECT_EQ(bundle, HDC_BUNDLE_NAME); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetSwitchStatus001 failed"; + } + GTEST_LOG_(INFO) << "GetSwitchStatus001 end"; +} + +/** + * @tc.name: GetSwitchStatus002 + * @tc.desc: Verify the GetSwitchStatus function + * @tc.type: FUNC + */ +HWTEST_F(SettingDataHelperTest, GetSwitchStatus002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetSwitchStatus002 start"; + try { + EXPECT_CALL(*mock_, GetSwitchStatus()).WillOnce(Return(CLOUD_SPACE)); + string bundle = SettingDataHelper::GetInstance().GetActiveBundle(); + EXPECT_EQ(bundle, GALLERY_BUNDLE_NAME); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetSwitchStatus002 failed"; + } + GTEST_LOG_(INFO) << "GetSwitchStatus002 end"; +} + +/** + * @tc.name: GetSwitchStatus003 + * @tc.desc: Verify the GetSwitchStatus function + * @tc.type: FUNC + */ +HWTEST_F(SettingDataHelperTest, GetSwitchStatus003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "GetSwitchStatus003 start"; + try { + EXPECT_CALL(*mock_, GetSwitchStatus()).WillOnce(Return(SwitchStatus::NONE)); + string bundle = SettingDataHelper::GetInstance().GetActiveBundle(); + EXPECT_EQ(bundle, ""); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "GetSwitchStatus003 failed"; + } + GTEST_LOG_(INFO) << "GetSwitchStatus003 end"; +} + +/** + * @tc.name: InitActiveBundle001 + * @tc.desc: Verify the InitActiveBundle function + * @tc.type: FUNC + */ +HWTEST_F(SettingDataHelperTest, InitActiveBundle001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "InitActiveBundle001 start"; + try { + SettingDataHelper::GetInstance().isBundleInited_ = true; + bool ret = SettingDataHelper::GetInstance().InitActiveBundle(); + EXPECT_EQ(ret, true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "InitActiveBundle001 failed"; + } + GTEST_LOG_(INFO) << "InitActiveBundle001 end"; +} + +/** + * @tc.name: InitActiveBundle002 + * @tc.desc: Verify the InitActiveBundle function + * @tc.type: FUNC + */ +HWTEST_F(SettingDataHelperTest, InitActiveBundle002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "InitActiveBundle002 start"; + try { + SettingDataHelper::GetInstance().isBundleInited_ = false; + SettingDataHelper::GetInstance().isDataShareReady_ = false; + + EXPECT_CALL(*mock_, Creator()).WillOnce(Return(nullptr)); + + bool ret = SettingDataHelper::GetInstance().InitActiveBundle(); + EXPECT_EQ(ret, false); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "InitActiveBundle002 failed"; + } + GTEST_LOG_(INFO) << "InitActiveBundle002 end"; +} + +/** + * @tc.name: InitActiveBundle003 + * @tc.desc: Verify the InitActiveBundle function + * @tc.type: FUNC + */ +HWTEST_F(SettingDataHelperTest, InitActiveBundle003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "InitActiveBundle003 start"; + try { + SettingDataHelper::GetInstance().isBundleInited_ = false; + SettingDataHelper::GetInstance().isDataShareReady_ = false; + + shared_ptr helper = std::make_shared(); + EXPECT_CALL(*helper, Release()).WillOnce(Return(true)); + EXPECT_CALL(*mock_, Creator()).WillOnce(Return(helper)); + EXPECT_CALL(*mock_, QuerySwitchStatus()).WillOnce(Return(E_OK)); + EXPECT_CALL(*mock_, GetSwitchStatus()).WillOnce(Return(CLOUD_SPACE)); + + bool ret = SettingDataHelper::GetInstance().InitActiveBundle(); + EXPECT_EQ(ret, true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "InitActiveBundle003 failed"; + } + GTEST_LOG_(INFO) << "InitActiveBundle003 end"; +} + +/** + * @tc.name: UpdateActiveBundle001 + * @tc.desc: Verify the UpdateActiveBundle function + * @tc.type: FUNC + */ +HWTEST_F(SettingDataHelperTest, UpdateActiveBundle001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "UpdateActiveBundle001 start"; + try { + EXPECT_CALL(*mock_, QuerySwitchStatus()).WillOnce(Return(E_OK)); + EXPECT_CALL(*mock_, GetSwitchStatus()).WillOnce(Return(CLOUD_SPACE)); + + SettingDataHelper::GetInstance().UpdateActiveBundle(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "UpdateActiveBundle001 failed"; + } + GTEST_LOG_(INFO) << "UpdateActiveBundle001 end"; +} + +/** + * @tc.name: RegisterObserver001 + * @tc.desc: Verify the RegisterObserver function + * @tc.type: FUNC + */ +HWTEST_F(SettingDataHelperTest, RegisterObserver001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "RegisterObserver001 start"; + try { + SettingDataHelper::GetInstance().RegisterObserver(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "RegisterObserver001 failed"; + } + GTEST_LOG_(INFO) << "RegisterObserver001 end"; +} + +/** + * @tc.name: SetActiveBundle001 + * @tc.desc: Verify the SetActiveBundle function + * @tc.type: FUNC + */ +HWTEST_F(SettingDataHelperTest, SetActiveBundle001, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetActiveBundle001 start"; + try { + SettingDataHelper::GetInstance().data_ = nullptr; + SettingDataHelper::GetInstance().SetActiveBundle(GALLERY_BUNDLE_NAME); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetActiveBundle001 failed"; + } + GTEST_LOG_(INFO) << "SetActiveBundle001 end"; +} + +/** + * @tc.name: SetActiveBundle002 + * @tc.desc: Verify the SetActiveBundle function + * @tc.type: FUNC + */ +HWTEST_F(SettingDataHelperTest, SetActiveBundle002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetActiveBundle002 start"; + try { + struct FuseData data; + data.activeBundle = GALLERY_BUNDLE_NAME; + SettingDataHelper::GetInstance().data_ = &data; + SettingDataHelper::GetInstance().SetActiveBundle(HDC_BUNDLE_NAME); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetActiveBundle002 failed"; + } + GTEST_LOG_(INFO) << "SetActiveBundle002 end"; +} + +/** + * @tc.name: SetActiveBundle003 + * @tc.desc: Verify the SetActiveBundle function + * @tc.type: FUNC + */ +HWTEST_F(SettingDataHelperTest, SetActiveBundle003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SetActiveBundle003 start"; + try { + struct FuseData data; + data.activeBundle = GALLERY_BUNDLE_NAME; + SettingDataHelper::GetInstance().data_ = &data; + SettingDataHelper::GetInstance().SetActiveBundle(GALLERY_BUNDLE_NAME); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SetActiveBundle003 failed"; + } + GTEST_LOG_(INFO) << "SetActiveBundle003 end"; +} +} // namespace OHOS::FileManagement::CloudFile \ No newline at end of file diff --git a/utils/BUILD.gn b/utils/BUILD.gn index dfad5dc11f696cc412cdf2ef0903944d027db64c..abb87cfe6cb346797143db61e41e2e9559466b9c 100755 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2021-2025 Huawei Device Co., Ltd. +# Copyright (c) 2021 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -130,6 +130,7 @@ ohos_shared_library("libdistributedfileutils") { "ipc:ipc_core", "json:nlohmann_json_static", "napi:ace_napi", + "os_account:os_account_innerkits", "preferences:native_preferences", ] @@ -203,7 +204,6 @@ ohos_shared_library("libdistributedfiledentry") { config("utils_lite_public_config") { include_dirs = [ "dentry/include", - "ffrt/include", "inner_api", "ioctl/include", "load/include", @@ -230,7 +230,6 @@ ohos_shared_library("libdistributedfileutils_lite") { "dentry/src/meta_file.cpp", "dentry/src/meta_file_clouddisk.cpp", "dfx/src/xcollie_helper.cpp", - "ffrt/src/concurrent_queue.cpp", "ffrt/src/ffrt_timer.cpp", "load/src/plugin_loader.cpp", "log/src/dfs_error.cpp", diff --git a/utils/cloud_disk/src/cloud_file_utils.cpp b/utils/cloud_disk/src/cloud_file_utils.cpp index 7e738ef7225ccae4bcaed914c8ba24421e853e78..64539f19f42e800fe6940c26e578a955a34f4357 100644 --- a/utils/cloud_disk/src/cloud_file_utils.cpp +++ b/utils/cloud_disk/src/cloud_file_utils.cpp @@ -282,6 +282,12 @@ bool CloudFileUtils::LocalWriteOpen(const string &dfsPath) return false; } int fd = fileno(file); + /* + * In the implementation of fopen, if the contained fd < 0, reutrn nullptr. + * There is no case where the fd < 0 when the pointer is non-null. + * This is to judge the exception where the file carrying the fd has been closed. + * In such cases, fclose is not needed. + */ if (fd < 0) { LOGE("get fd failed, errno:%{public}d", errno); return false; @@ -316,6 +322,12 @@ static bool ClearHmdfsCache(const string &dfsPath) return false; } int fd = fileno(file); + /* + * In the implementation of fopen, if the contained fd < 0, reutrn nullptr. + * There is no case where the fd < 0 when the pointer is non-null. + * This is to judge the exception where the file carrying the fd has been closed. + * In such cases, fclose is not needed. + */ if (fd < 0) { LOGE("get fd failed, errno:%{public}d", errno); return false; diff --git a/utils/dentry/include/meta_file.h b/utils/dentry/include/meta_file.h index f1476dfb6c09ad5fbd9920b43e710d3f1d7a6aa6..beddc82fc07299027dacd4b539fb9bc77f4851a6 100644 --- a/utils/dentry/include/meta_file.h +++ b/utils/dentry/include/meta_file.h @@ -135,8 +135,8 @@ class MetaFileMgr { public: static MetaFileMgr& GetInstance(); /* recordId is hex string of 256 bits, convert to u8 cloudId[32] to kernel */ - static std::string RecordIdToCloudId(const std::string hexStr); - static std::string CloudIdToRecordId(const std::string cloudId); + static std::string RecordIdToCloudId(const std::string hexStr, bool isHdc = false); + static std::string CloudIdToRecordId(const std::string cloudId, bool isHdc = false); std::shared_ptr GetMetaFile(uint32_t userId, const std::string &path); std::shared_ptr GetCloudDiskMetaFile(uint32_t userId, const std::string &bundleName, const std::string &cloudId); diff --git a/utils/dentry/src/meta_file.cpp b/utils/dentry/src/meta_file.cpp index 0820e0fa3ae603e2122fc530fb2923eb3a1419fd..c8d3c11b07deb7ce10046ccdb9bac5e2fc403fd3 100644 --- a/utils/dentry/src/meta_file.cpp +++ b/utils/dentry/src/meta_file.cpp @@ -45,6 +45,9 @@ constexpr uint32_t BUCKET_BLOCKS = 2; constexpr uint32_t BITS_PER_BYTE = 8; constexpr uint32_t HMDFS_SLOT_LEN_BITS = 3; constexpr uint32_t DIR_SIZE = 4096; +constexpr uint32_t EVEN_NUM_FLAG = 2; +const char HDC_ID_START = '0'; +const std::string HDC_ID_END = "ff"; #pragma pack(push, 1) struct HmdfsDentry { @@ -293,6 +296,7 @@ static bool UpdateDentry(HmdfsDentryGroup &d, const MetaBase &base, uint32_t nam de->fileType = base.fileType; de->size = base.size; de->mode = base.mode; + (void)memset_s(de->recordId, CLOUD_RECORD_ID_LEN, 0, CLOUD_RECORD_ID_LEN); ret = memcpy_s(de->recordId, CLOUD_RECORD_ID_LEN, base.cloudId.c_str(), base.cloudId.length()); if (ret != EOK) { LOGE("memcpy_s failed, dstLen = %{public}d, srcLen = %{public}zu", CLOUD_RECORD_ID_LEN, base.cloudId.length()); @@ -704,18 +708,26 @@ void MetaFileMgr::ClearAll() metaFileList_.clear(); } -std::string MetaFileMgr::RecordIdToCloudId(const std::string hexStr) +std::string MetaFileMgr::RecordIdToCloudId(const std::string hexStr, bool isHdc) { + std::string srcStr = hexStr; + if (isHdc) { + if (srcStr.size() % EVEN_NUM_FLAG != 0) { + srcStr = HDC_ID_START + srcStr + HDC_ID_END; + } else { + srcStr = srcStr + HDC_ID_END; + } + } std::string result; constexpr std::size_t offset = 2; constexpr int changeBase = 16; - for (std::size_t i = 0; i < hexStr.length(); i += offset) { - std::string hexByte = hexStr.substr(i, offset); + for (std::size_t i = 0; i < srcStr.length(); i += offset) { + std::string hexByte = srcStr.substr(i, offset); char *endPtr; unsigned long hexValue = std::strtoul(hexByte.c_str(), &endPtr, changeBase); if (endPtr != hexByte.c_str() + hexByte.length()) { - LOGE("Invalid hexadecimal string: %{public}s", hexStr.c_str()); + LOGE("Invalid hexadecimal string: %{public}s", srcStr.c_str()); return ""; } result += static_cast(hexValue); @@ -728,7 +740,15 @@ std::string MetaFileMgr::RecordIdToCloudId(const std::string hexStr) return result; } -std::string MetaFileMgr::CloudIdToRecordId(const std::string cloudId) +/** + * @brief convert cloudId to recordId + * + * @param cloudId + * @param isHdc is homedatacenter's cloudId + * @return string recordId + * @example recordId: 012345678ff -> 12345678 when isHdc=true + */ +std::string MetaFileMgr::CloudIdToRecordId(const std::string cloudId, bool isHdc) { std::stringstream result; constexpr int width = 2; @@ -736,7 +756,18 @@ std::string MetaFileMgr::CloudIdToRecordId(const std::string cloudId) uint8_t u8Byte = cloudId[i]; result << std::setw(width) << std::setfill('0') << std::hex << static_cast(u8Byte); } - return result.str(); + if (!isHdc) { + return result.str(); + } + std::string recordId = result.str(); + if (recordId.at(0) == HDC_ID_START) { + recordId = recordId.substr(1); + } + auto pos = recordId.find(HDC_ID_END); + if (pos == std::string::npos) { + return recordId; + } + return recordId.substr(0, pos); } } // namespace FileManagement diff --git a/utils/system/include/dfsu_access_token_helper.h b/utils/system/include/dfsu_access_token_helper.h index b0f4c28f01109ae2350a91dc3e25d4ae9e75d6af..3d7398930178a0ee13ac1f6bfbca8a08b7cdfc23 100644 --- a/utils/system/include/dfsu_access_token_helper.h +++ b/utils/system/include/dfsu_access_token_helper.h @@ -35,6 +35,8 @@ public: static bool IsSystemApp(); static int32_t GetUserId(); static int32_t GetPid(); + static int32_t GetAccountId(int32_t &userId); + static bool IsUserVerifyed(const int32_t userId); }; } // namespace OHOS::FileManagement diff --git a/utils/system/src/dfsu_access_token_helper.cpp b/utils/system/src/dfsu_access_token_helper.cpp index c1bbbaea8d7296334c3cd9a0e46cfc310c56481f..a8209de3aad5355b50e984d99ccf8d7121a8f526 100644 --- a/utils/system/src/dfsu_access_token_helper.cpp +++ b/utils/system/src/dfsu_access_token_helper.cpp @@ -23,6 +23,7 @@ #include "uri.h" #include "utils_log.h" #include "want.h" +#include "os_account_manager.h" namespace OHOS::FileManagement { using namespace std; @@ -122,6 +123,32 @@ int32_t DfsuAccessTokenHelper::GetUserId() return uid / BASE_USER_RANGE; } +bool DfsuAccessTokenHelper::IsUserVerifyed(const int32_t userId) +{ + bool isVerified = false; + if (AccountSA::OsAccountManager::IsOsAccountVerified(userId, isVerified) != E_OK) { + LOGE("check user verified failed"); + return false; + } + return isVerified; +} + +int32_t DfsuAccessTokenHelper::GetAccountId(int32_t &userId) +{ + vector activeUsers; + if (AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUsers) != E_OK || activeUsers.empty()) { + LOGE("query active user failed"); + return E_OSACCOUNT; + } + userId = activeUsers.front(); + if (!IsUserVerifyed(userId)) { + LOGE("userId is invalid"); + return E_INVAL_ARG; + } + LOGI("GetAccountId ok, UserId: %{public}d", userId); + return E_OK; +} + int32_t DfsuAccessTokenHelper::GetPid() { auto pid = IPCSkeleton::GetCallingPid();