diff --git a/frameworks/native/backup_ext/include/ext_backup.h b/frameworks/native/backup_ext/include/ext_backup.h index dae003248c1e2b6ff501356e91946bbe82a37834..b4d902bc92c401e7007e2d991c8c41efa0106f04 100644 --- a/frameworks/native/backup_ext/include/ext_backup.h +++ b/frameworks/native/backup_ext/include/ext_backup.h @@ -170,6 +170,8 @@ public: */ bool RestoreDataReady(); + void SetClearDataFlag(bool isClearData); + /** * @brief Invoke the extended function of the APP */ @@ -195,6 +197,7 @@ private: BConstants::ExtensionAction extAction_ {BConstants::ExtensionAction::INVALID}; ErrCode GetParament(const AAFwk::Want &want); static CreatorFunc creator_; + bool isClearData_ {true}; }; } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/include/ext_extension.h b/frameworks/native/backup_ext/include/ext_extension.h index b93bdbb3e3c7a906f7df550b377b5d8b5ad0d8d3..68184723ea589a1ec62e7e8eed9e53b6813f6448 100644 --- a/frameworks/native/backup_ext/include/ext_extension.h +++ b/frameworks/native/backup_ext/include/ext_extension.h @@ -43,12 +43,12 @@ public: UniqueFd GetFileHandle(const std::string &fileName, int32_t &errCode) override; ErrCode HandleClear() override; ErrCode PublishFile(const std::string &fileName) override; - ErrCode HandleBackup() override; - ErrCode HandleRestore() override; + ErrCode HandleBackup(bool isClearData) override; + ErrCode HandleRestore(bool isClearData) override; ErrCode GetIncrementalFileHandle(const std::string &fileName) override; ErrCode PublishIncrementalFile(const std::string &fileName) override; ErrCode HandleIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd) override; - ErrCode IncrementalOnBackup() override; + ErrCode IncrementalOnBackup(bool isClearData) override; std::tuple GetIncrementalBackupFileHandle() override; ErrCode GetBackupInfo(std::string &result) override; ErrCode UpdateFdSendRate(std::string &bundleName, int32_t sendRate) override; @@ -155,10 +155,11 @@ private: void AsyncTaskOnIncrementalBackup(); ErrCode IncrementalBigFileReady(const TarMap &pkgInfo, const vector &bigInfos, sptr proxy); - ErrCode BigFileReady(sptr proxy); + ErrCode BigFileReady(const TarMap &bigFileInfo, sptr proxy); void WaitToSendFd(std::chrono::system_clock::time_point &startTime, int &fdSendNum); void RefreshTimeInfo(std::chrono::system_clock::time_point &startTime, int &fdSendNum); void IncrementalPacket(const vector &infos, TarMap &tar, sptr proxy); + void DoPacket(const map &srcFiles, TarMap &tar, sptr proxy); /** * @brief extension incremental backup restore is done @@ -194,6 +195,11 @@ private: std::function AppDoneCallbackEx(wptr obj); std::function HandleBackupEx(wptr obj); std::function HandleTaskBackupEx(wptr obj); + void HandleSpecialVersionRestore(wptr obj); + void DeleteBackupIncrementalTars(); + void DeleteBackupTars(); + void SetClearDataFlag(bool isClearData); + private: std::shared_mutex lock_; std::shared_ptr extension_; @@ -207,6 +213,7 @@ private: std::mutex waitTimeLock_; std::string bundleName_; int32_t sendRate_ = BConstants::DEFAULT_FD_SEND_RATE; + bool isClearData_ {true}; }; } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/src/ext_backup.cpp b/frameworks/native/backup_ext/src/ext_backup.cpp index 2805185963c0be7423dfb13b6363020190c4c0c1..1a4bc1f78913a20c534f4c31e9885eb123eb20c9 100644 --- a/frameworks/native/backup_ext/src/ext_backup.cpp +++ b/frameworks/native/backup_ext/src/ext_backup.cpp @@ -189,12 +189,6 @@ sptr ExtBackup::OnConnect(const AAFwk::Want &want) auto remoteObject = sptr(new BackupExtExtension(std::static_pointer_cast(shared_from_this()))); - - // 排除特殊场景 - if (!WasFromSpecialVersion() && !RestoreDataReady()) { - remoteObject->ExtClear(); - } - return remoteObject->AsObject(); } catch (const BError &e) { return nullptr; @@ -211,6 +205,11 @@ void ExtBackup::OnDisconnect(const AAFwk::Want &want) { try { HILOGI("begin disconnect"); + if (isClearData_) { + auto remoteObject = sptr( + new BackupExtExtension(std::static_pointer_cast(shared_from_this()))); + remoteObject->ExtClear(); + } Extension::OnDisconnect(want); extAction_ = BConstants::ExtensionAction::INVALID; HILOGI("end"); @@ -253,6 +252,11 @@ bool ExtBackup::RestoreDataReady() return restoreType_ == RestoreTypeEnum::RESTORE_DATA_READDY; } +void ExtBackup::SetClearDataFlag(bool isClearData) +{ + isClearData_ = isClearData; +} + ErrCode ExtBackup::OnBackup(function callback) { HILOGI("BackupExtensionAbility(base) OnBackup."); diff --git a/frameworks/native/backup_ext/src/ext_extension.cpp b/frameworks/native/backup_ext/src/ext_extension.cpp index 071569fdddcb02111e4cac70bc71abf7ae9cfebd..c75e71b562e1e90369c7c02673d407b9beb748ed 100644 --- a/frameworks/native/backup_ext/src/ext_extension.cpp +++ b/frameworks/native/backup_ext/src/ext_extension.cpp @@ -141,14 +141,14 @@ static UniqueFd GetFileHandleForSpecialCloneCloud(const string &fileName) size_t filePathPrefix = filePath.find_last_of(BConstants::FILE_SEPARATOR_CHAR); if (filePathPrefix == string::npos) { HILOGE("GetFileHandleForSpecialCloneCloud: Invalid fileName"); - throw BError(BError::Codes::EXT_INVAL_ARG, fileName); + return UniqueFd(-1); } string path = filePath.substr(0, filePathPrefix); if (access(path.c_str(), F_OK) != 0) { bool created = ForceCreateDirectory(path.data()); if (!created) { - string str = string("Failed to create restore folder."); - throw BError(BError::Codes::EXT_INVAL_ARG, str); + HILOGE("Failed to create restore folder."); + return UniqueFd(-1); } } UniqueFd fd(open(fileName.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)); @@ -214,43 +214,47 @@ static string GetReportFileName(const string &fileName) static ErrCode GetIncreFileHandleForSpecialVersion(const string &fileName) { + HILOGI("extension:GetIncreFileHandleForSpecialVersion, filename:%{public}s", fileName.c_str()); + ErrCode errCode = ERR_OK; UniqueFd fd = GetFileHandleForSpecialCloneCloud(fileName); if (fd < 0) { HILOGE("Failed to open file = %{private}s, err = %{public}d", fileName.c_str(), errno); - throw BError(BError::Codes::EXT_INVAL_ARG, string("open tar file failed")); + errCode = errno; } string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); if (mkdir(path.data(), S_IRWXU) && errno != EEXIST) { - string str = string("Failed to create restore folder. ").append(std::generic_category().message(errno)); - throw BError(BError::Codes::EXT_INVAL_ARG, str); + HILOGE("Failed to create restore folder : %{private}s, err = %{public}d", path.c_str(), errno); + errCode = errno; } string reportName = path + BConstants::BLANK_REPORT_NAME; UniqueFd reportFd(open(reportName.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)); if (reportFd < 0) { HILOGE("Failed to open report file = %{private}s, err = %{public}d", reportName.c_str(), errno); - throw BError(BError::Codes::EXT_INVAL_ARG, string("open report file failed")); + errCode = errno; } auto proxy = ServiceProxy::GetInstance(); if (proxy == nullptr) { - throw BError(BError::Codes::EXT_BROKEN_BACKUP_SA, std::generic_category().message(errno)); + HILOGE("Failed to get file handle for special version clone"); + return BError(BError::Codes::EXT_BROKEN_BACKUP_SA).GetCode(); } - auto ret = proxy->AppIncrementalFileReady(fileName, move(fd), move(reportFd), ERR_OK); + auto ret = proxy->AppIncrementalFileReady(fileName, move(fd), move(reportFd), errCode); if (ret != ERR_OK) { HILOGE("Failed to AppIncrementalFileReady %{public}d", ret); } return ERR_OK; } -static string GetIncrementalFileHandlePath() +static string GetIncrementalFileHandlePath(const string &fileName) { string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); if (mkdir(path.data(), S_IRWXU) && errno != EEXIST) { string str = string("Failed to create restore folder. ").append(std::generic_category().message(errno)); throw BError(BError::Codes::EXT_INVAL_ARG, str); } - return path; + string tarName = path + fileName; + return tarName; } ErrCode BackupExtExtension::GetIncrementalFileHandle(const string &fileName) @@ -262,19 +266,18 @@ ErrCode BackupExtExtension::GetIncrementalFileHandle(const string &fileName) extension_->GetExtensionAction()); throw BError(BError::Codes::EXT_INVAL_ARG, "Action is invalid"); } - HILOGI("extension: Start GetIncrementalFileHandle"); VerifyCaller(); if (extension_->SpecialVersionForCloneAndCloud()) { return GetIncreFileHandleForSpecialVersion(fileName); } - HILOGI("extension: single to single fileName:%{public}s", fileName.c_str()); - string path = GetIncrementalFileHandlePath(); - string tarName = path + fileName; + HILOGI("extension: GetIncrementalFileHandle single to single Name:%{public}s", GetAnonyPath(fileName).c_str()); + string tarName = GetIncrementalFileHandlePath(fileName); + int32_t errCode = ERR_OK; if (access(tarName.c_str(), F_OK) == 0) { - throw BError(BError::Codes::EXT_INVAL_ARG, string("The file already exists")); + HILOGE("The file already exists, tarname = %{private}s, err =%{public}d", tarName.c_str(), errno); + errCode = errno; } - int32_t errCode = ERR_OK; UniqueFd fd(open(tarName.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)); if (fd < 0) { HILOGE("Failed to open tar file = %{private}s, err = %{public}d", tarName.c_str(), errno); @@ -283,7 +286,8 @@ ErrCode BackupExtExtension::GetIncrementalFileHandle(const string &fileName) // 对应的简报文件 string reportName = GetReportFileName(tarName); if (access(reportName.c_str(), F_OK) == 0) { - throw BError(BError::Codes::EXT_INVAL_ARG, string("The report file already exists")); + HILOGE("The report file already exists, Name = %{private}s, err =%{public}d", reportName.c_str(), errno); + errCode = errno; } UniqueFd reportFd(open(reportName.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)); if (reportFd < 0) { @@ -303,24 +307,29 @@ ErrCode BackupExtExtension::GetIncrementalFileHandle(const string &fileName) } catch (...) { HILOGE("Failed to get incremental file handle"); DoClear(); - return BError(BError::Codes::EXT_INVAL_ARG).GetCode(); + return BError(BError::Codes::EXT_BROKEN_IPC).GetCode(); } } ErrCode BackupExtExtension::HandleClear() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - HILOGI("begin clear"); - if (extension_ == nullptr) { - HILOGE("Failed to handle clear, extension is nullptr"); - return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode(); - } - if (extension_->GetExtensionAction() == BConstants::ExtensionAction::INVALID) { - return BError(BError::Codes::EXT_INVAL_ARG, "Action is invalid").GetCode(); + try { + HILOGI("begin clear"); + if (extension_ == nullptr) { + HILOGE("Failed to handle clear, extension is nullptr"); + return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode(); + } + if (extension_->GetExtensionAction() == BConstants::ExtensionAction::INVALID) { + return BError(BError::Codes::EXT_INVAL_ARG, "Action is invalid").GetCode(); + } + VerifyCaller(); + DoClear(); + return ERR_OK; + } catch (...) { + HILOGE("Failed to handle clear"); + return BError(BError::Codes::EXT_BROKEN_IPC).GetCode(); } - VerifyCaller(); - DoClear(); - return ERR_OK; } static ErrCode IndexFileReady(const TarMap &pkgInfo, sptr proxy) @@ -352,36 +361,26 @@ static ErrCode IndexFileReady(const TarMap &pkgInfo, sptr proxy) return ret; } -ErrCode BackupExtExtension::BigFileReady(sptr proxy) +ErrCode BackupExtExtension::BigFileReady(const TarMap &bigFileInfo, sptr proxy) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - UniqueFd fd(open(INDEX_FILE_BACKUP.data(), O_RDONLY)); - if (fd < 0) { - HILOGE("Failed to open index json file = %{private}s, err = %{public}d", INDEX_FILE_BACKUP.c_str(), errno); - return BError::GetCodeByErrno(errno); - } - BJsonCachedEntity cachedEntity(move(fd)); - auto cache = cachedEntity.Structuralize(); - auto pkgInfo = cache.GetExtManageInfo(); - HILOGI("BigFileReady Begin: pkgInfo file size is: %{public}zu", pkgInfo.size()); + HILOGI("BigFileReady Begin: bigFileInfo file size is: %{public}zu", bigFileInfo.size()); ErrCode ret {ERR_OK}; auto startTime = std::chrono::system_clock::now(); int fdNum = 0; - for (auto &item : pkgInfo) { - if (item.hashName.empty() || item.fileName.empty()) { - continue; - } + for (auto &item : bigFileInfo) { WaitToSendFd(startTime, fdNum); int32_t errCode = ERR_OK; - UniqueFd fd(open(item.fileName.data(), O_RDONLY)); + string fllePath = std::get<0>(item.second); + UniqueFd fd(open(fllePath.data(), O_RDONLY)); if (fd < 0) { - HILOGE("open file failed, file name is %{public}s, err = %{public}d", item.fileName.c_str(), errno); + HILOGE("open file failed, file name is %{public}s, err = %{public}d", fllePath.c_str(), errno); errCode = errno; } - ret = proxy->AppFileReady(item.hashName, std::move(fd), errCode); + ret = proxy->AppFileReady(item.first, std::move(fd), errCode); if (SUCCEEDED(ret)) { - HILOGI("The application is packaged successfully, package name is %{public}s", item.hashName.c_str()); + HILOGI("The application is packaged successfully, package name is %{public}s", item.first.c_str()); } else { HILOGW("Current file execute app file ready interface failed, ret is:%{public}d", ret); } @@ -466,9 +465,10 @@ ErrCode BackupExtExtension::PublishIncrementalFile(const string &fileName) } } -ErrCode BackupExtExtension::HandleBackup() +ErrCode BackupExtExtension::HandleBackup(bool isClearData) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + SetClearDataFlag(isClearData); if (extension_ == nullptr) { HILOGE("Failed to handle backup, extension is nullptr"); return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode(); @@ -482,7 +482,7 @@ ErrCode BackupExtExtension::HandleBackup() .GetCode(); } AsyncTaskOnBackup(); - return 0; + return ERR_OK; } static bool IsUserTar(const string &tarFile, const std::vector &extManageInfo) @@ -501,7 +501,7 @@ static bool IsUserTar(const string &tarFile, const std::vector &e return false; } -static pair> GetFileInfos(const vector &includes, const vector &excludes) +static pair> GetFileInfos(const vector &includes, const vector &excludes) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); auto [errCode, files, smallFiles] = BDir::GetBigFiles(includes, excludes); @@ -537,6 +537,76 @@ static pair> GetFileInfos(const vector &includes, return {bigFiles, smallFiles}; } +/** + * 全量tar包回传 + */ +static ErrCode TarFileReady(const TarMap &tarFileInfo, sptr proxy) +{ + if (tarFileInfo.empty()) { + HILOGI("TarFileReady: No tar file found"); + return ERR_OK; + } + string tarName = tarFileInfo.begin()->first; + string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_BACKUP); + string tarPath = path + tarName; + int32_t errCode = ERR_OK; + UniqueFd fd(open(tarPath.data(), O_RDONLY)); + if (fd < 0) { + HILOGE("TarFileReady open file failed, file name is %{public}s, err = %{public}d", tarName.c_str(), errno); + errCode = errno; + } + int ret = proxy->AppFileReady(tarName, std::move(fd), errCode); + if (SUCCEEDED(ret)) { + HILOGI("TarFileReady: AppFileReady success for %{public}s", tarName.c_str()); + // 删除文件 + RemoveFile(tarName); + } else { + HILOGE("TarFileReady AppFileReady fail to be invoked for %{public}s: ret = %{public}d", tarName.c_str(), ret); + } + return ret; +} + +void BackupExtExtension::DoPacket(const map &srcFiles, TarMap &tar, sptr proxy) +{ + HILOGI("DoPacket begin, infos count: %{public}zu", srcFiles.size()); + string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_BACKUP); + int64_t totalSize = 0; + uint32_t fileCount = 0; + vector packFiles; + TarFile::GetInstance().SetPacketMode(true); // 设置下打包模式 + auto startTime = std::chrono::system_clock::now(); + int fdNum = 0; + for (auto small : srcFiles) { + totalSize += small.second; + fileCount += 1; + packFiles.emplace_back(small.first); + if (totalSize >= DEFAULT_SLICE_SIZE || fileCount >= MAX_FILE_COUNT) { + TarMap tarMap {}; + TarFile::GetInstance().Packet(packFiles, "part", path, tarMap); + tar.insert(tarMap.begin(), tarMap.end()); + // 执行tar包回传功能 + WaitToSendFd(startTime, fdNum); + TarFileReady(tarMap, proxy); + totalSize = 0; + fileCount = 0; + packFiles.clear(); + fdNum += FILE_AND_MANIFEST_FD_COUNT; + RefreshTimeInfo(startTime, fdNum); + } + } + if (fileCount > 0) { + // 打包回传 + TarMap tarMap {}; + TarFile::GetInstance().Packet(packFiles, "part", path, tarMap); + TarFileReady(tarMap, proxy); + fdNum = 1; + WaitToSendFd(startTime, fdNum); + tar.insert(tarMap.begin(), tarMap.end()); + packFiles.clear(); + RefreshTimeInfo(startTime, fdNum); + } +} + int BackupExtExtension::DoBackup(const BJsonEntityExtensionConfig &usrConfig) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); @@ -557,6 +627,11 @@ int BackupExtExtension::DoBackup(const BJsonEntityExtensionConfig &usrConfig) vector includes = usrConfig.GetIncludes(); vector excludes = usrConfig.GetExcludes(); + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + throw BError(BError::Codes::EXT_BROKEN_BACKUP_SA, std::generic_category().message(errno)); + } + // 大文件处理 HILOGI("Start packet bigfiles and small files"); auto [bigFileInfo, smallFiles] = GetFileInfos(includes, excludes); @@ -567,21 +642,22 @@ int BackupExtExtension::DoBackup(const BJsonEntityExtensionConfig &usrConfig) } } + // 回传大文件 + HILOGI("Will notify BigFileReady"); + auto res = BigFileReady(bigFileInfo, proxy); + HILOGI("Start packet Tar files"); - // 分片打包 + // 分片打包, 回传tar包 TarMap tarMap {}; - TarFile::GetInstance().Packet(smallFiles, "part", path, tarMap); + DoPacket(smallFiles, tarMap, proxy); bigFileInfo.insert(tarMap.begin(), tarMap.end()); - auto proxy = ServiceProxy::GetInstance(); - if (proxy == nullptr) { - throw BError(BError::Codes::EXT_BROKEN_BACKUP_SA, std::generic_category().message(errno)); - } + HILOGI("Do backup, DoPacket end"); + HILOGI("Will notify IndexFileReady"); if (auto ret = IndexFileReady(bigFileInfo, proxy); ret) { return ret; } - HILOGI("Will notify BigFileReady"); - auto res = BigFileReady(proxy); + HILOGI("HandleBackup finish, ret = %{public}d", res); return res; } @@ -604,9 +680,17 @@ int BackupExtExtension::DoRestore(const string &fileName) // 当用户指定fullBackupOnly字段或指定版本的恢复,解压目录当前在/backup/restore if (extension_->SpecialVersionForCloneAndCloud() || extension_->UseFullBackupOnly()) { - UntarFile::GetInstance().UnPacket(tarName, path); + ErrCode err = UntarFile::GetInstance().UnPacket(tarName, path); + if (err != 0) { + HILOGE("Failed to untar file = %{public}s, err = %{public}d", tarName.c_str(), err); + return err; + } } else { - UntarFile::GetInstance().UnPacket(tarName, "/"); + ErrCode err = UntarFile::GetInstance().UnPacket(tarName, "/"); + if (err != 0) { + HILOGE("Failed to untar file = %{public}s, err = %{public}d", tarName.c_str(), err); + return err; + } } HILOGI("Application recovered successfully, package path is %{public}s", tarName.c_str()); @@ -638,6 +722,7 @@ int BackupExtExtension::DoIncrementalRestore() } auto fileSet = GetIdxFileData(); auto extManageInfo = GetExtManageInfo(); + ErrCode err = ERR_OK; for (auto item : fileSet) { // 处理要解压的tar文件 if (ExtractFileExt(item) == "tar" && !IsUserTar(item, extManageInfo)) { if (extension_->GetExtensionAction() != BConstants::ExtensionAction::RESTORE) { @@ -650,14 +735,14 @@ int BackupExtExtension::DoIncrementalRestore() // 当用户指定fullBackupOnly字段或指定版本的恢复,解压目录当前在/backup/restore if (extension_->SpecialVersionForCloneAndCloud() || extension_->UseFullBackupOnly()) { - UntarFile::GetInstance().IncrementalUnPacket(tarName, path, GetTarIncludes(tarName)); + err = UntarFile::GetInstance().IncrementalUnPacket(tarName, path, GetTarIncludes(tarName)); } else { - UntarFile::GetInstance().IncrementalUnPacket(tarName, "/", GetTarIncludes(tarName)); + err = UntarFile::GetInstance().IncrementalUnPacket(tarName, "/", GetTarIncludes(tarName)); } HILOGI("Application recovered successfully, package path is %{public}s", tarName.c_str()); } } - return ERR_OK; + return err; } void BackupExtExtension::AsyncTaskBackup(const string config) @@ -731,8 +816,11 @@ static ErrCode RestoreTarForSpecialCloneCloud(ExtManageInfo item) if (untarPath.back() != BConstants::FILE_SEPARATOR_CHAR) { untarPath += BConstants::FILE_SEPARATOR_CHAR; } - UntarFile::GetInstance().UnPacket(tarName, untarPath); - + ErrCode err = UntarFile::GetInstance().UnPacket(tarName, untarPath); + if (err != ERR_OK) { + HILOGE("Failed to untar file = %{public}s, err = %{public}d", tarName.c_str(), err); + return err; + } if (!RemoveFile(tarName)) { HILOGE("Failed to delete the backup tar %{public}s", tarName.c_str()); } @@ -860,8 +948,12 @@ static void RestoreBigFiles(bool appendTargetPath) HILOGI("End Restore Big Files"); } -static void DeleteBackupTars() +void BackupExtExtension::DeleteBackupTars() { + if (!isClearData_) { + HILOGI("configured not clear data."); + return; + } HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); UniqueFd fd(open(INDEX_FILE_RESTORE.data(), O_RDONLY)); if (fd < 0) { @@ -889,8 +981,12 @@ static void DeleteBackupTars() HILOGI("End execute DeleteBackupTars"); } -static void DeleteBackupIncrementalTars() +void BackupExtExtension::DeleteBackupIncrementalTars() { + if (!isClearData_) { + HILOGI("configured not clear data."); + return; + } UniqueFd fd(open(INDEX_FILE_RESTORE.data(), O_RDONLY)); if (fd < 0) { HILOGE("Failed to open index json file = %{private}s, err = %{public}d", INDEX_FILE_RESTORE.c_str(), errno); @@ -925,6 +1021,19 @@ static void DeleteBackupIncrementalTars() } } +void BackupExtExtension::HandleSpecialVersionRestore(wptr obj) +{ + auto ptr = obj.promote(); + BExcepUltils::BAssert(ptr, BError::Codes::EXT_BROKEN_FRAMEWORK, "Ext extension handle have been released"); + auto ret = RestoreFilesForSpecialCloneCloud(); + if (ret == ERR_OK) { + ptr->AsyncTaskRestoreForUpgrade(); + } else { + ptr->AppDone(ret); + ptr->DoClear(); + } +} + void BackupExtExtension::AsyncTaskRestore(std::set fileSet, const std::vector extManageInfo) { @@ -935,13 +1044,7 @@ void BackupExtExtension::AsyncTaskRestore(std::set fileSet, try { int ret = ERR_OK; if (ptr->extension_->SpecialVersionForCloneAndCloud()) { - ret = RestoreFilesForSpecialCloneCloud(); - if (ret == ERR_OK) { - ptr->AsyncTaskRestoreForUpgrade(); - } else { - ptr->AppDone(ret); - ptr->DoClear(); - } + ptr->HandleSpecialVersionRestore(obj); return; } // 解压 @@ -955,7 +1058,7 @@ void BackupExtExtension::AsyncTaskRestore(std::set fileSet, bool appendTargetPath = ptr->extension_->UseFullBackupOnly() && !ptr->extension_->SpecialVersionForCloneAndCloud(); RestoreBigFiles(appendTargetPath); - DeleteBackupTars(); + ptr->DeleteBackupTars(); if (ret == ERR_OK) { ptr->AsyncTaskRestoreForUpgrade(); } else { @@ -1000,7 +1103,7 @@ void BackupExtExtension::AsyncTaskIncrementalRestore() RestoreBigFiles(appendTargetPath); // delete 1.tar/manage.json - DeleteBackupIncrementalTars(); + ptr->DeleteBackupIncrementalTars(); if (ret == ERR_OK) { HILOGI("after extra, do incremental restore."); @@ -1094,7 +1197,10 @@ void BackupExtExtension::AsyncTaskRestoreForUpgrade() try { auto callBackupEx = ptr->RestoreResultCallbackEx(obj); ErrCode err = ptr->extension_->OnRestore(callBackup, callBackupEx); - HILOGI("OnRestore done err = %{public}d", err); + if (err != ERR_OK) { + ptr->AppDone(BError::GetCodeByErrno(err)); + ptr->DoClear(); + } } catch (const BError &e) { ptr->AppDone(e.GetCode()); ptr->DoClear(); @@ -1148,7 +1254,11 @@ void BackupExtExtension::AsyncTaskIncrementalRestoreForUpgrade() try { auto callBackupEx = ptr->IncRestoreResultCallbackEx(obj); ErrCode err = ptr->extension_->OnRestore(callBackup, callBackupEx); - HILOGI("OnRestore done err = %{public}d", err); + if (err != ERR_OK) { + HILOGE("OnRestore done, err = %{pubilc}d", err); + ptr->AppIncrementalDone(BError::GetCodeByErrno(err)); + ptr->DoClear(); + } } catch (const BError &e) { ptr->AppIncrementalDone(e.GetCode()); ptr->DoClear(); @@ -1179,6 +1289,10 @@ void BackupExtExtension::DoClear() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { + if (!isClearData_) { + HILOGI("configured not clear data."); + return; + } string backupCache = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_BACKUP); string restoreCache = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); @@ -1205,7 +1319,11 @@ void BackupExtExtension::AppDone(ErrCode errCode) HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("AppDone Begin."); auto proxy = ServiceProxy::GetInstance(); - BExcepUltils::BAssert(proxy, BError::Codes::EXT_BROKEN_IPC, "Failed to obtain the ServiceProxy handle"); + if (proxy == nullptr) { + HILOGE("Failed to obtain the ServiceProxy handle"); + DoClear(); + return; + } auto ret = proxy->AppDone(errCode); if (ret != ERR_OK) { HILOGE("Failed to notify the app done. err = %{public}d", ret); @@ -1246,7 +1364,11 @@ void BackupExtExtension::AsyncTaskOnBackup() BExcepUltils::BAssert(ptr->extension_, BError::Codes::EXT_INVAL_ARG, "Extension handle have been released"); try { auto callBackupEx = ptr->HandleTaskBackupEx(obj); - ptr->extension_->OnBackup(callBackup, callBackupEx); + ErrCode err = ptr->extension_->OnBackup(callBackup, callBackupEx); + if (err != ERR_OK) { + HILOGE("OnBackup done, err = %{pubilc}d", err); + ptr->AppDone(BError::GetCodeByErrno(err)); + } } catch (const BError &e) { ptr->AppDone(e.GetCode()); } catch (const exception &e) { @@ -1267,32 +1389,37 @@ void BackupExtExtension::AsyncTaskOnBackup() }); } -ErrCode BackupExtExtension::HandleRestore() +ErrCode BackupExtExtension::HandleRestore(bool isClearData) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - VerifyCaller(); - if (extension_ == nullptr) { - HILOGE("Failed to handle restore, extension is nullptr"); - throw BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr"); - } - if (extension_->GetExtensionAction() != BConstants::ExtensionAction::RESTORE) { - HILOGE("Failed to get file handle, because action is %{public}d invalid", extension_->GetExtensionAction()); - throw BError(BError::Codes::EXT_INVAL_ARG, "Action is invalid"); - } - // read backup_config is allow to backup or restore - if (!extension_->AllowToBackupRestore()) { - HILOGE("Application does not allow backup or restore"); - return BError(BError::Codes::EXT_FORBID_BACKUP_RESTORE, "Application does not allow backup or restore") - .GetCode(); - } + try { + VerifyCaller(); + SetClearDataFlag(isClearData); + if (extension_ == nullptr) { + HILOGE("Failed to handle restore, extension is nullptr"); + return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode(); + } + if (extension_->GetExtensionAction() != BConstants::ExtensionAction::RESTORE) { + HILOGE("Failed to get file handle, because action is %{public}d invalid", extension_->GetExtensionAction()); + return BError(BError::Codes::EXT_INVAL_ARG, "Action is invalid").GetCode(); + } + // read backup_config is allow to backup or restore + if (!extension_->AllowToBackupRestore()) { + HILOGE("Application does not allow backup or restore"); + return BError(BError::Codes::EXT_FORBID_BACKUP_RESTORE, "Application does not allow backup or restore") + .GetCode(); + } - // async do restore. - if (extension_->WasFromSpecialVersion() && extension_->RestoreDataReady()) { - HILOGI("Restore directly when upgrading."); - AsyncTaskRestoreForUpgrade(); + // async do restore. + if (extension_->WasFromSpecialVersion() && extension_->RestoreDataReady()) { + HILOGI("Restore directly when upgrading."); + AsyncTaskRestoreForUpgrade(); + } + return ERR_OK; + } catch (...) { + HILOGE("Failed to handle restore"); + return BError(BError::Codes::EXT_BROKEN_IPC).GetCode(); } - - return 0; } static bool CheckTar(const string &fileName) @@ -1374,27 +1501,33 @@ void BackupExtExtension::CompareFiles(UniqueFd incrementalFd, ErrCode BackupExtExtension::HandleIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd) { - HILOGI("Start HandleIncrementalBackup"); HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - if (extension_ == nullptr) { - HILOGE("Failed to handle incremental backup, extension is nullptr"); - return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode(); - } - string usrConfig = extension_->GetUsrConfig(); - BJsonCachedEntity cachedEntity(usrConfig); - auto cache = cachedEntity.Structuralize(); - if (!cache.GetAllowToBackupRestore()) { - HILOGE("Application does not allow backup or restore"); - return BError(BError::Codes::EXT_FORBID_BACKUP_RESTORE, "Application does not allow backup or restore") - .GetCode(); + try { + HILOGI("Start HandleIncrementalBackup"); + if (extension_ == nullptr) { + HILOGE("Failed to handle incremental backup, extension is nullptr"); + return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode(); + } + string usrConfig = extension_->GetUsrConfig(); + BJsonCachedEntity cachedEntity(usrConfig); + auto cache = cachedEntity.Structuralize(); + if (!cache.GetAllowToBackupRestore()) { + HILOGE("Application does not allow backup or restore"); + return BError(BError::Codes::EXT_FORBID_BACKUP_RESTORE, "Application does not allow backup or restore") + .GetCode(); + } + AsyncTaskDoIncrementalBackup(move(incrementalFd), move(manifestFd)); + return ERR_OK; + } catch (...) { + HILOGE("Failed to handle incremental backup"); + return BError(BError::Codes::EXT_INVAL_ARG).GetCode(); } - AsyncTaskDoIncrementalBackup(move(incrementalFd), move(manifestFd)); - return 0; } -ErrCode BackupExtExtension::IncrementalOnBackup() +ErrCode BackupExtExtension::IncrementalOnBackup(bool isClearData) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + SetClearDataFlag(isClearData); if (extension_ == nullptr) { HILOGE("Failed to handle incremental onBackup, extension is nullptr"); return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode(); @@ -1408,7 +1541,7 @@ ErrCode BackupExtExtension::IncrementalOnBackup() .GetCode(); } AsyncTaskOnIncrementalBackup(); - return 0; + return ERR_OK; } tuple BackupExtExtension::GetIncrementalBackupFileHandle() @@ -1616,7 +1749,11 @@ void BackupExtExtension::AsyncTaskOnIncrementalBackup() BExcepUltils::BAssert(ptr->extension_, BError::Codes::EXT_INVAL_ARG, "Extension handle have been released"); try { auto callBackupEx = ptr->HandleBackupEx(obj); - ptr->extension_->OnBackup(callBackup, callBackupEx); + ErrCode err = ptr->extension_->OnBackup(callBackup, callBackupEx); + if (err != ERR_OK) { + HILOGE("OnBackup done, err = %{pubilc}d", err); + ptr->AppIncrementalDone(BError::GetCodeByErrno(err)); + } } catch (const BError &e) { ptr->AppIncrementalDone(e.GetCode()); } catch (const exception &e) { @@ -1748,9 +1885,9 @@ int BackupExtExtension::DoIncrementalBackup(const vector if (smallFiles.size() == 0 && bigFiles.size() == 0) { // 没有增量,则不需要上传 TarMap tMap; - IncrementalAllFileReady(tMap, allFiles, proxy); + ErrCode err = IncrementalAllFileReady(tMap, allFiles, proxy); HILOGI("Do increment backup, IncrementalAllFileReady end, file empty"); - return ERR_OK; + return err; } // tar包数据 TarMap tarMap; @@ -1762,17 +1899,21 @@ int BackupExtExtension::DoIncrementalBackup(const vector HILOGI("Do increment backup, IncrementalBigFileReady end"); bigMap.insert(tarMap.begin(), tarMap.end()); // 回传manage.json和全量文件 - IncrementalAllFileReady(bigMap, allFiles, proxy); + ErrCode err = IncrementalAllFileReady(bigMap, allFiles, proxy); HILOGI("End, bigFiles num:%{public}zu, smallFiles num:%{public}zu, allFiles num:%{public}zu", bigFiles.size(), smallFiles.size(), allFiles.size()); - return ERR_OK; + return err; } void BackupExtExtension::AppIncrementalDone(ErrCode errCode) { HILOGI("Begin"); auto proxy = ServiceProxy::GetInstance(); - BExcepUltils::BAssert(proxy, BError::Codes::EXT_BROKEN_IPC, "Failed to obtain the ServiceProxy handle"); + if (proxy == nullptr) { + HILOGE("Failed to obtain the ServiceProxy handle"); + DoClear(); + return; + } auto ret = proxy->AppIncrementalDone(errCode); if (ret != ERR_OK) { HILOGE("Failed to notify the app done. err = %{public}d", ret); @@ -1813,15 +1954,20 @@ ErrCode BackupExtExtension::GetBackupInfo(std::string &result) ErrCode BackupExtExtension::UpdateFdSendRate(std::string &bundleName, int32_t sendRate) { - std::lock_guard lock(updateSendRateLock_); - HILOGI("Update SendRate, bundleName:%{public}s, sendRate:%{public}d", bundleName.c_str(), sendRate); - VerifyCaller(); - bundleName_ = bundleName; - sendRate_ = sendRate; - if (sendRate > 0) { - startSendFdRateCon_.notify_one(); + try { + std::lock_guard lock(updateSendRateLock_); + HILOGI("Update SendRate, bundleName:%{public}s, sendRate:%{public}d", bundleName.c_str(), sendRate); + VerifyCaller(); + bundleName_ = bundleName; + sendRate_ = sendRate; + if (sendRate > 0) { + startSendFdRateCon_.notify_one(); + } + return ERR_OK; + } catch (...) { + HILOGE("Failed to UpdateFdSendRate"); + return BError(BError::Codes::EXT_BROKEN_IPC).GetCode(); } - return ERR_OK; } std::function BackupExtExtension::RestoreResultCallbackEx(wptr obj) @@ -1988,4 +2134,18 @@ void BackupExtExtension::RefreshTimeInfo(std::chrono::system_clock::time_point & fdSendNum = 0; } } + +void BackupExtExtension::SetClearDataFlag(bool isClearData) +{ + isClearData_ = isClearData; + HILOGI("set clear data flag:%{public}d", isClearData); + if (extension_ == nullptr) { + HILOGE("Extension handle have been released"); + return; + } + extension_->SetClearDataFlag(isClearData); + if (!extension_->WasFromSpecialVersion() && !extension_->RestoreDataReady()) { + DoClear(); + } +} } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/src/ext_extension_stub.cpp b/frameworks/native/backup_ext/src/ext_extension_stub.cpp index 6930c2982442cc28ec4a863fde44fee1ac5d4be0..1589df3b4de70f8e3a88d588194667b5efc3ae51 100644 --- a/frameworks/native/backup_ext/src/ext_extension_stub.cpp +++ b/frameworks/native/backup_ext/src/ext_extension_stub.cpp @@ -106,7 +106,9 @@ ErrCode ExtExtensionStub::CmdHandleClear(MessageParcel &data, MessageParcel &rep ErrCode ExtExtensionStub::CmdHandleBackup(MessageParcel &data, MessageParcel &reply) { - ErrCode res = HandleBackup(); + bool isClearData = true; + isClearData = data.ReadBool(); + ErrCode res = HandleBackup(isClearData); if (!reply.WriteInt32(res)) { stringstream ss; ss << "Failed to send the result " << res; @@ -133,7 +135,9 @@ ErrCode ExtExtensionStub::CmdPublishFile(MessageParcel &data, MessageParcel &rep ErrCode ExtExtensionStub::CmdHandleRestore(MessageParcel &data, MessageParcel &reply) { - ErrCode res = HandleRestore(); + bool isClearData = true; + isClearData = data.ReadBool(); + ErrCode res = HandleRestore(isClearData); if (!reply.WriteInt32(res)) { stringstream ss; ss << "Failed to send the result " << res; @@ -187,7 +191,9 @@ ErrCode ExtExtensionStub::CmdHandleIncrementalBackup(MessageParcel &data, Messag ErrCode ExtExtensionStub::CmdIncrementalOnBackup(MessageParcel &data, MessageParcel &reply) { - ErrCode res = IncrementalOnBackup(); + bool isClearData = true; + isClearData = data.ReadBool(); + ErrCode res = IncrementalOnBackup(isClearData); if (!reply.WriteInt32(res)) { stringstream ss; ss << "Failed to send the result " << res; diff --git a/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp b/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp index f747d28c7662c0b22edf870320e7253fee023ee2..28928068bef5fb4332ac48c3f9e492f3ad6689f7 100644 --- a/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp +++ b/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp @@ -113,6 +113,11 @@ ErrCode BIncrementalBackupSession::Release() if (proxy == nullptr) { return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); } + auto remoteObject = proxy->AsObject(); + if (remoteObject != nullptr) { + remoteObject->RemoveDeathRecipient(deathRecipient_); + } + deathRecipient_ = nullptr; return proxy->Release(); } diff --git a/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp b/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp index 000241ad00fa33ddcf07acdfb1e09ba657c34a52..68f48d2ab10e6c9b0ac3d0f553014b0dfdceecf4 100644 --- a/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp +++ b/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp @@ -119,6 +119,11 @@ ErrCode BIncrementalRestoreSession::Release() if (proxy == nullptr) { return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); } + auto remoteObject = proxy->AsObject(); + if (remoteObject != nullptr) { + remoteObject->RemoveDeathRecipient(deathRecipient_); + } + deathRecipient_ = nullptr; return proxy->Release(); } diff --git a/frameworks/native/backup_kit_inner/src/b_incremental_session_restore_async.cpp b/frameworks/native/backup_kit_inner/src/b_incremental_session_restore_async.cpp index 84f75d66efc567dbca2fd01b5de3c13ab20f57d3..109350dece423db076785fa25231d0f0a7c18a8a 100644 --- a/frameworks/native/backup_kit_inner/src/b_incremental_session_restore_async.cpp +++ b/frameworks/native/backup_kit_inner/src/b_incremental_session_restore_async.cpp @@ -125,6 +125,11 @@ ErrCode BIncrementalSessionRestoreAsync::Release() if (proxy == nullptr) { return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); } + auto remoteObject = proxy->AsObject(); + if (remoteObject != nullptr) { + remoteObject->RemoveDeathRecipient(deathRecipient_); + } + deathRecipient_ = nullptr; return proxy->Release(); } diff --git a/frameworks/native/backup_kit_inner/src/b_session_backup.cpp b/frameworks/native/backup_kit_inner/src/b_session_backup.cpp index 04176686bd8da61518fe2d153cc41f938d62503d..78c19fec88d42b3ba79b2a763513cb0a2b6ea21d 100644 --- a/frameworks/native/backup_kit_inner/src/b_session_backup.cpp +++ b/frameworks/native/backup_kit_inner/src/b_session_backup.cpp @@ -132,6 +132,11 @@ ErrCode BSessionBackup::Release() if (proxy == nullptr) { return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); } + auto remoteObject = proxy->AsObject(); + if (remoteObject != nullptr) { + remoteObject->RemoveDeathRecipient(deathRecipient_); + } + deathRecipient_ = nullptr; return proxy->Release(); } diff --git a/frameworks/native/backup_kit_inner/src/b_session_restore.cpp b/frameworks/native/backup_kit_inner/src/b_session_restore.cpp index 250d68bc7f24b8124536264115c5d79964f7599a..e2063e27edc88acfc1bc683a0bdb3800170c8d29 100644 --- a/frameworks/native/backup_kit_inner/src/b_session_restore.cpp +++ b/frameworks/native/backup_kit_inner/src/b_session_restore.cpp @@ -130,6 +130,11 @@ ErrCode BSessionRestore::Release() if (proxy == nullptr) { return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); } + auto remoteObject = proxy->AsObject(); + if (remoteObject != nullptr) { + remoteObject->RemoveDeathRecipient(deathRecipient_); + } + deathRecipient_ = nullptr; return proxy->Release(); } diff --git a/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp b/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp index 10c388fb58b468f1ea7bf402fa39527ec0d55a50..e44e65b6fd471aaf1aaed2ba4c1a6dd2e70ae4ca 100644 --- a/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp +++ b/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp @@ -125,6 +125,11 @@ ErrCode BSessionRestoreAsync::Release() if (proxy == nullptr) { return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); } + auto remoteObject = proxy->AsObject(); + if (remoteObject != nullptr) { + remoteObject->RemoveDeathRecipient(deathRecipient_); + } + deathRecipient_ = nullptr; return proxy->Release(); } diff --git a/interfaces/common/src/json_utils.cpp b/interfaces/common/src/json_utils.cpp index 30523ac779f81b5cc879cab00070e1403bc08dc1..3a401b5bb96f472ab1951dd288f0eecdff664258 100644 --- a/interfaces/common/src/json_utils.cpp +++ b/interfaces/common/src/json_utils.cpp @@ -39,7 +39,7 @@ int32_t JsonUtils::GetJsonObjFromPath(nlohmann::json& jsonObj, const std::string jsonFileStream.close(); jsonObj = nlohmann::json::parse(buf.str(), nullptr, false); - if (!jsonObj.is_discarded()) { + if (jsonObj.is_discarded()) { LOGE("Parse json file path %{public}s failed", jsonPath.c_str()); } return 0; diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_extension.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_extension.h index 364214d2d0c1b70b45b61062c23b6ba20b9358b5..387ec3b0ecb43e4bc1c925c6e77e007262698b9e 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_extension.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_extension.h @@ -30,13 +30,13 @@ public: virtual ~IExtension() = default; virtual UniqueFd GetFileHandle(const std::string &fileName, int32_t &errCode) = 0; virtual ErrCode HandleClear() = 0; - virtual ErrCode HandleBackup() = 0; + virtual ErrCode HandleBackup(bool isClearData) = 0; virtual ErrCode PublishFile(const std::string &fileName) = 0; - virtual ErrCode HandleRestore() = 0; + virtual ErrCode HandleRestore(bool isClearData) = 0; virtual ErrCode GetIncrementalFileHandle(const std::string &fileName) = 0; virtual ErrCode PublishIncrementalFile(const std::string &fileName) = 0; virtual ErrCode HandleIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd) = 0; - virtual ErrCode IncrementalOnBackup() = 0; + virtual ErrCode IncrementalOnBackup(bool isClearData) = 0; virtual std::tuple GetIncrementalBackupFileHandle() = 0; virtual ErrCode GetBackupInfo(std::string &result) = 0; virtual ErrCode UpdateFdSendRate(std::string &bundleName, int32_t sendRate) = 0; diff --git a/interfaces/innerkits/native/file_uri/src/file_uri.cpp b/interfaces/innerkits/native/file_uri/src/file_uri.cpp index 11fb261c6e7149035d616d5cccae4802df690925..3050f29a5b6e204dde8ca13893b5aa0a549d46ce 100644 --- a/interfaces/innerkits/native/file_uri/src/file_uri.cpp +++ b/interfaces/innerkits/native/file_uri/src/file_uri.cpp @@ -59,7 +59,7 @@ string FileUri::GetName() return ""; } - if (posLast == sandboxPath.size()) { + if (posLast == (sandboxPath.size() - 1)) { return ""; } diff --git a/interfaces/kits/js/backup/prop_n_operation.cpp b/interfaces/kits/js/backup/prop_n_operation.cpp index d059dc95f201b774a0e0e800ce46a7ecca384723..593c67a597cf7d0d1da81c8f7fcbeab8950c75ae 100644 --- a/interfaces/kits/js/backup/prop_n_operation.cpp +++ b/interfaces/kits/js/backup/prop_n_operation.cpp @@ -17,6 +17,7 @@ #include "b_error/b_error.h" #include "b_incremental_data.h" #include "b_resources/b_constants.h" +#include "b_sa/b_sa_utils.h" #include "filemgmt_libhilog.h" #include "filemgmt_libn.h" #include "incremental_backup_data.h" @@ -32,19 +33,6 @@ using namespace LibN; const int32_t H_TO_MS = 3600 * 1000; -static bool CheckPermission(const string &permission) -{ - Security::AccessToken::AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); - return Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, permission) == - Security::AccessToken::PermissionState::PERMISSION_GRANTED; -} - -static bool IsSystemApp() -{ - uint64_t fullTokenId = OHOS::IPCSkeleton::GetCallingFullTokenID(); - return Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId); -} - static napi_value AsyncCallback(napi_env env, const NFuncArg& funcArg) { HILOGD("called LocalCapabilities::AsyncCallback begin"); @@ -182,6 +170,16 @@ static napi_value AsyncDataList(napi_env env, const NFuncArg& funcArg) napi_value PropNOperation::Async(napi_env env, napi_callback_info info) { HILOGD("called LocalCapabilities::Async begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } NFuncArg funcArg(env, info); if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { HILOGE("Number of arguments unmatched."); @@ -203,6 +201,16 @@ napi_value PropNOperation::Async(napi_env env, napi_callback_info info) napi_value PropNOperation::DoGetBackupInfo(napi_env env, napi_callback_info info) { HILOGD("called DoGetBackupInfo begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } std::string result; NFuncArg funcArg(env, info); if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { @@ -278,12 +286,12 @@ bool PropNOperation::UpdateSendRate(std::string &bundleName, int32_t sendRate) napi_value PropNOperation::DoUpdateTimer(napi_env env, napi_callback_info info) { HILOGD("called DoUpdateTimer begin"); - if (!CheckPermission("ohos.permission.BACKUP")) { - HILOGE("has not permission!"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); NError(E_PERMISSION).ThrowErr(env); return nullptr; } - if (!IsSystemApp()) { + if (!SAUtils::IsSystemApp()) { HILOGE("System App check fail!"); NError(E_PERMISSION_SYS).ThrowErr(env); return nullptr; @@ -326,12 +334,12 @@ napi_value PropNOperation::DoUpdateTimer(napi_env env, napi_callback_info info) napi_value PropNOperation::DoUpdateSendRate(napi_env env, napi_callback_info info) { HILOGD("called DoUpdateSendRate begin"); - if (!CheckPermission("ohos.permission.BACKUP")) { - HILOGE("has not permission!"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); NError(E_PERMISSION).ThrowErr(env); return nullptr; } - if (!IsSystemApp()) { + if (!SAUtils::IsSystemApp()) { HILOGE("System App check fail!"); NError(E_PERMISSION_SYS).ThrowErr(env); return nullptr; diff --git a/interfaces/kits/js/backup/session_backup_n_exporter.cpp b/interfaces/kits/js/backup/session_backup_n_exporter.cpp index 0d84c030833a28891d5f0c1de5ca0ccd484ecd7f..3198e00c8a54eb4b3b012367abd28c2cefcf1222 100644 --- a/interfaces/kits/js/backup/session_backup_n_exporter.cpp +++ b/interfaces/kits/js/backup/session_backup_n_exporter.cpp @@ -251,6 +251,16 @@ static void OnBackupServiceDied(weak_ptr pCallbacks) napi_value SessionBackupNExporter::Constructor(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionBackup::Constructor begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } NFuncArg funcArg(env, cbinfo); if (!funcArg.InitArgs(NARG_CNT::ONE)) { HILOGE("Number of arguments unmatched."); @@ -326,6 +336,16 @@ static bool VerifyParamSuccess(NFuncArg &funcArg, std::vector &bund napi_value SessionBackupNExporter::AppendBundles(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionBackup::AppendBundles begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } std::vector bundleNames; std::vector bundleInfos; NFuncArg funcArg(env, cbinfo); @@ -369,6 +389,16 @@ napi_value SessionBackupNExporter::AppendBundles(napi_env env, napi_callback_inf napi_value SessionBackupNExporter::Release(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionBackup::Release begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } NFuncArg funcArg(env, cbinfo); if (!funcArg.InitArgs(NARG_CNT::ZERO)) { HILOGE("Number of arguments unmatched."); diff --git a/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp b/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp index 8d386e094d8806deb24bc1a724e6d76b531f0eb8..69bfc17687842669923b8c728aa85d9684fc80d8 100644 --- a/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp +++ b/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp @@ -22,6 +22,7 @@ #include "b_incremental_backup_session.h" #include "b_incremental_data.h" #include "b_resources/b_constants.h" +#include "b_sa/b_sa_utils.h" #include "backup_kit_inner.h" #include "directory_ex.h" #include "filemgmt_libhilog.h" @@ -257,6 +258,16 @@ static void OnBackupServiceDied(weak_ptr pCallbacks) napi_value SessionIncrementalBackupNExporter::Constructor(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionIncrementalBackup::Constructor begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } NFuncArg funcArg(env, cbinfo); if (!funcArg.InitArgs(NARG_CNT::ONE)) { HILOGE("Number of arguments unmatched"); @@ -391,6 +402,16 @@ static bool VerifyParamSuccess(NFuncArg &funcArg, std::vector napi_value SessionIncrementalBackupNExporter::AppendBundles(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionIncrementalBackup::AppendBundles begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } std::vector backupBundles; std::vector bundleInfos; NFuncArg funcArg(env, cbinfo); @@ -431,6 +452,16 @@ napi_value SessionIncrementalBackupNExporter::AppendBundles(napi_env env, napi_c napi_value SessionIncrementalBackupNExporter::Release(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionIncrementalBackup::Release begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } NFuncArg funcArg(env, cbinfo); if (!funcArg.InitArgs(NARG_CNT::ZERO)) { HILOGE("Number of arguments unmatched."); diff --git a/interfaces/kits/js/backup/session_restore_n_exporter.cpp b/interfaces/kits/js/backup/session_restore_n_exporter.cpp index 71d362b8d3c33947f8ddfebf01cec256f3bea86d..dd3ccf163b0113fa46510c2946485d29a38e2410 100644 --- a/interfaces/kits/js/backup/session_restore_n_exporter.cpp +++ b/interfaces/kits/js/backup/session_restore_n_exporter.cpp @@ -371,6 +371,16 @@ static bool VerifyNarg(napi_env env, NVal &callbacks) napi_value SessionRestoreNExporter::Constructor(napi_env env, napi_callback_info cbinfo) { HILOGI("called SessionRestore::Constructor begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } NFuncArg funcArg(env, cbinfo); if (VerifyNapiObject(env, funcArg)) { return nullptr; @@ -405,23 +415,16 @@ napi_value SessionRestoreNExporter::Constructor(napi_env env, napi_callback_info return funcArg.GetThisVar(); } -napi_value SessionRestoreNExporter::AppendBundles(napi_env env, napi_callback_info cbinfo) +static NContextCBExec GetAppendBundlesCBExec(napi_env env, NFuncArg &funcArg, const int32_t fdRestore, + const std::vector &bundleNames, const std::vector &bundleInfos) { - HILOGI("called SessionRestore::AppendBundles begin"); - int32_t fdRestore = BConstants::INVALID_FD_NUM; - std::vector bundleNames; - std::vector bundleInfos; - NFuncArg funcArg(env, cbinfo); - if (!VerifyAppendBundlesParam(funcArg, fdRestore, bundleNames, bundleInfos, env)) { - return nullptr; - } auto restoreEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); if (!(restoreEntity && (restoreEntity->sessionWhole || restoreEntity->sessionSheet))) { HILOGE("Failed to get RestoreSession entity."); NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to get RestoreSession entity.").GetCode()).ThrowErr(env); return nullptr; } - auto cbExec = [entity {restoreEntity}, fd {fdRestore}, bundles {bundleNames}, infos {bundleInfos}]() -> NError { + return [entity {restoreEntity}, fd {fdRestore}, bundles {bundleNames}, infos {bundleInfos}]() -> NError { if (!(entity && (entity->sessionWhole || entity->sessionSheet))) { return NError(BError(BError::Codes::SDK_INVAL_ARG, "restore session is nullptr").GetCode()); } @@ -440,10 +443,38 @@ napi_value SessionRestoreNExporter::AppendBundles(napi_env env, napi_callback_in } return NError(entity->sessionSheet->AppendBundles(UniqueFd(fd), bundles)); }; +} + +napi_value SessionRestoreNExporter::AppendBundles(napi_env env, napi_callback_info cbinfo) +{ + HILOGI("called SessionRestore::AppendBundles begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } + int32_t fdRestore = BConstants::INVALID_FD_NUM; + std::vector bundleNames; + std::vector bundleInfos; + NFuncArg funcArg(env, cbinfo); + if (!VerifyAppendBundlesParam(funcArg, fdRestore, bundleNames, bundleInfos, env)) { + return nullptr; + } + auto cbExec = GetAppendBundlesCBExec(env, funcArg, fdRestore, bundleNames, bundleInfos); + if (cbExec == nullptr) { + HILOGE("GetAppendBundlesCBExec fail!"); + return nullptr; + } auto cbCompl = [](napi_env env, NError err) -> NVal { return err ? NVal {env, err.GetNapiErr(env)} : NVal::CreateUndefined(env); }; HILOGD("Called SessionRestore::AppendBundles end."); + NVal thisVar(env, funcArg.GetThisVar()); if (funcArg.GetArgc() == NARG_CNT::TWO) { return NAsyncWorkPromise(env, thisVar).Schedule(className, cbExec, cbCompl).val_; @@ -457,24 +488,16 @@ napi_value SessionRestoreNExporter::AppendBundles(napi_env env, napi_callback_in } } -napi_value SessionRestoreNExporter::PublishFile(napi_env env, napi_callback_info cbinfo) +static NContextCBExec GetPublishFileCBExec(napi_env env, NFuncArg &funcArg, const std::string &bundleName, + const std::string &fileName) { - HILOGD("called SessionRestore::PublishFile begin"); - std::string bundleName; - std::string fileName; - NFuncArg funcArg(env, cbinfo); - if (!VerifyPublishFileParam(funcArg, bundleName, fileName, env)) { - return nullptr; - } - auto restoreEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); if (!(restoreEntity && (restoreEntity->sessionWhole || restoreEntity->sessionSheet))) { HILOGE("Failed to get RestoreSession entity."); NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to get RestoreSession entity.").GetCode()).ThrowErr(env); return nullptr; } - - auto cbExec = [entity {restoreEntity}, bundleName {bundleName}, fileName {fileName}]() -> NError { + return [entity {restoreEntity}, bundleName {bundleName}, fileName {fileName}]() -> NError { if (!(entity && (entity->sessionWhole || entity->sessionSheet))) { return NError(BError(BError::Codes::SDK_INVAL_ARG, "restore session is nullptr").GetCode()); } @@ -492,10 +515,35 @@ napi_value SessionRestoreNExporter::PublishFile(napi_env env, napi_callback_info } return NError(entity->sessionSheet->PublishFile(fileInfo)); }; +} + +napi_value SessionRestoreNExporter::PublishFile(napi_env env, napi_callback_info cbinfo) +{ + HILOGD("called SessionRestore::PublishFile begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } + std::string bundleName; + std::string fileName; + NFuncArg funcArg(env, cbinfo); + if (!VerifyPublishFileParam(funcArg, bundleName, fileName, env)) { + return nullptr; + } + auto cbExec = GetPublishFileCBExec(env, funcArg, bundleName, fileName); + if (cbExec == nullptr) { + HILOGE("GetPublishFileCBExec fail!"); + return nullptr; + } auto cbCompl = [](napi_env env, NError err) -> NVal { return err ? NVal {env, err.GetNapiErr(env)} : NVal::CreateUndefined(env); }; - HILOGD("Called SessionRestore::PublishFile end."); NVal thisVar(env, funcArg.GetThisVar()); @@ -507,9 +555,42 @@ napi_value SessionRestoreNExporter::PublishFile(napi_env env, napi_callback_info } } +static NContextCBExec GetFileHandleCBExec(napi_env env, NFuncArg &funcArg, std::unique_ptr bundleName, + std::unique_ptr fileName) +{ + auto restoreEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!(restoreEntity && (restoreEntity->sessionWhole || restoreEntity->sessionSheet))) { + HILOGE("Failed to get RestoreSession entity."); + NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to get RestoreSession entity.").GetCode()).ThrowErr(env); + return nullptr; + } + return [entity {restoreEntity}, bundleName {string(bundleName.get())}, + fileName {string(fileName.get())}]() -> NError { + if (!(entity && (entity->sessionWhole || entity->sessionSheet))) { + return NError(BError(BError::Codes::SDK_INVAL_ARG, "restore session is nullptr").GetCode()); + } + string bundle = bundleName; + string file = fileName; + if (entity->sessionWhole) { + return NError(entity->sessionWhole->GetFileHandle(bundle, file)); + } + return NError(entity->sessionSheet->GetFileHandle(bundle, file)); + }; +} + napi_value SessionRestoreNExporter::GetFileHandle(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionRestore::GetFileHandle begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } NFuncArg funcArg(env, cbinfo); if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { HILOGE("Number of arguments unmatched."); @@ -531,29 +612,14 @@ napi_value SessionRestoreNExporter::GetFileHandle(napi_env env, napi_callback_in return nullptr; } - auto restoreEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!(restoreEntity && (restoreEntity->sessionWhole || restoreEntity->sessionSheet))) { - HILOGE("Failed to get RestoreSession entity."); - NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to get RestoreSession entity.").GetCode()).ThrowErr(env); + auto cbExec = GetFileHandleCBExec(env, funcArg, move(bundleName), move(fileName)); + if (cbExec == nullptr) { + HILOGE("GetFileHandleCBExec fail!"); return nullptr; } - - auto cbExec = [entity {restoreEntity}, bundleName {string(bundleName.get())}, - fileName {string(fileName.get())}]() -> NError { - if (!(entity && (entity->sessionWhole || entity->sessionSheet))) { - return NError(BError(BError::Codes::SDK_INVAL_ARG, "restore session is nullptr").GetCode()); - } - string bundle = bundleName; - string file = fileName; - if (entity->sessionWhole) { - return NError(entity->sessionWhole->GetFileHandle(bundle, file)); - } - return NError(entity->sessionSheet->GetFileHandle(bundle, file)); - }; auto cbCompl = [](napi_env env, NError err) -> NVal { return err ? NVal {env, err.GetNapiErr(env)} : NVal::CreateUndefined(env); }; - HILOGD("Called SessionRestore::GetFileHandle end."); NVal thisVar(env, funcArg.GetThisVar()); @@ -568,6 +634,16 @@ napi_value SessionRestoreNExporter::GetFileHandle(napi_env env, napi_callback_in napi_value SessionRestoreNExporter::Release(napi_env env, napi_callback_info cbinfo) { HILOGI("called SessionRestore::Release begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } NFuncArg funcArg(env, cbinfo); if (!funcArg.InitArgs(NARG_CNT::ZERO)) { HILOGE("Number of arguments unmatched."); @@ -594,7 +670,6 @@ napi_value SessionRestoreNExporter::Release(napi_env env, napi_callback_info cbi auto cbCompl = [](napi_env env, NError err) -> NVal { return err ? NVal {env, err.GetNapiErr(env)} : NVal::CreateUndefined(env); }; - HILOGI("Called SessionRestore::Release end."); NVal thisVar(env, funcArg.GetThisVar()); diff --git a/interfaces/kits/ndk/fileshare/src/oh_file_share.cpp b/interfaces/kits/ndk/fileshare/src/oh_file_share.cpp index 53a0b79887cfe7b0ba672af38cce548198aaeefd..1b115fc1d6c2536fedb097a32d78ccc15eeca165 100644 --- a/interfaces/kits/ndk/fileshare/src/oh_file_share.cpp +++ b/interfaces/kits/ndk/fileshare/src/oh_file_share.cpp @@ -29,29 +29,9 @@ #include "tokenid_kit.h" const int32_t FOO_MAX_LEN = sizeof(FileShare_PolicyErrorResult) * OHOS::AppFileService::MAX_ARRAY_SIZE; -const std::string FILE_ACCESS_PERSIST_PERMISSION = "ohos.permission.FILE_ACCESS_PERSIST"; -const std::string FULL_MOUNT_ENABLE_PARAMETER = "const.filemanager.full_mount.enable"; using Exec = std::function &uriPolicies, std::deque &errorResults)>; -static bool CheckPermission(const std::string &permission) -{ - OHOS::Security::AccessToken::AccessTokenID tokenCaller = OHOS::IPCSkeleton::GetCallingTokenID(); - return OHOS::Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, permission) == - OHOS::Security::AccessToken::PermissionState::PERMISSION_GRANTED; -} - -static bool CheckFileManagerFullMountEnable() -{ - char value[] = "false"; - int retSystem = GetParameter(FULL_MOUNT_ENABLE_PARAMETER.c_str(), "false", value, sizeof(value)); - if (retSystem > 0 && !strcmp(value, "true")) { - LOGI("The full mount enable parameter is true"); - return true; - } - LOGI("The full mount enable parameter is false"); - return false; -} static bool ConvertPolicyInfo(const FileShare_PolicyInfo *policies, int policyNum, @@ -173,12 +153,6 @@ static FileManagement_ErrCode ExecAction(const FileShare_PolicyInfo *policies, Exec exec) { (*resultNum) = 0; - if (!CheckFileManagerFullMountEnable()) { - return E_DEVICE_NOT_SUPPORT; - } - if (!CheckPermission(FILE_ACCESS_PERSIST_PERMISSION)) { - return E_PERMISSION; - } std::vector uriPolicies; if (!ConvertPolicyInfo(policies, policyNum, uriPolicies)) { return E_PARAMS; @@ -274,12 +248,6 @@ FileManagement_ErrCode OH_FileShare_CheckPersistentPermission(const FileShare_Po return E_PARAMS; } *resultNum = 0; - if (!CheckFileManagerFullMountEnable()) { - return E_DEVICE_NOT_SUPPORT; - } - if (!CheckPermission(FILE_ACCESS_PERSIST_PERMISSION)) { - return E_PERMISSION; - } std::vector uriPolicies; if (!ConvertPolicyInfo(policies, policyNum, uriPolicies)) { return E_PARAMS; diff --git a/interfaces/kits/ndk/fileuri/src/oh_file_uri.cpp b/interfaces/kits/ndk/fileuri/src/oh_file_uri.cpp index db175595eff1a8c27f5684fc99e3797c21da34b4..e471696ab96f0ee7d4c44c2e79a70ee1497133a2 100644 --- a/interfaces/kits/ndk/fileuri/src/oh_file_uri.cpp +++ b/interfaces/kits/ndk/fileuri/src/oh_file_uri.cpp @@ -84,7 +84,7 @@ FileManagement_ErrCode OH_FileUri_GetFullDirectoryUri(const char *uri, unsigned bool OH_FileUri_IsValidUri(const char *uri, unsigned int length) { if (uri == nullptr || strlen(uri) != length) { - return ERR_PARAMS; + return false; } std::string uriStr(uri, length); OHOS::AppFileService::ModuleFileUri::FileUri fileUri(uriStr); diff --git a/services/backup_sa/BUILD.gn b/services/backup_sa/BUILD.gn index 5bf8af4f0b7e9cbf0969c91096f98810ece90515..027216afec711a3d02b3a8d4491d79a0f572ddbd 100644 --- a/services/backup_sa/BUILD.gn +++ b/services/backup_sa/BUILD.gn @@ -66,6 +66,7 @@ ohos_shared_library("backup_sa") { "ability_runtime:ability_connect_callback_stub", "ability_runtime:ability_manager", "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", diff --git a/services/backup_sa/include/module_external/bms_adapter.h b/services/backup_sa/include/module_external/bms_adapter.h index 5f106294c5aaaa772ef420eb703849c2eb79ca28..e56ec31dd1506c877bc6b6249796385bf29d3a4b 100644 --- a/services/backup_sa/include/module_external/bms_adapter.h +++ b/services/backup_sa/include/module_external/bms_adapter.h @@ -63,6 +63,10 @@ public: static std::vector GetBundleInfosForSA(); static void GetBundleInfoForSA(std::string bundleName, std::vector &bundleInfos); +private: + static bool GetCurBundleExtenionInfo(AppExecFwk::BundleInfo &installedBundle, const std::string &bundleName, + std::vector &extensionInfos, sptr bms, + int32_t userId); }; } // namespace OHOS::FileManagement::Backup #endif // OHOS_FILEMGMT_BACKUP_BUNDLE_MGR_ADAPTER_H diff --git a/services/backup_sa/include/module_ipc/service.h b/services/backup_sa/include/module_ipc/service.h index 7f81017326ff54077016134af12535c32b098248..45a9393e5a3bd987ec3eda79f67aa9377b924302 100644 --- a/services/backup_sa/include/module_ipc/service.h +++ b/services/backup_sa/include/module_ipc/service.h @@ -173,6 +173,13 @@ public: * */ void SessionDeactive(); + + /** + * @brief 卸载服务 + * + */ + void UnloadService(); + /** * @brief 构造拉起应用所需的want * @@ -311,12 +318,23 @@ private: * @param restoreBundleInfos 待恢复的应用 * @param restoreBundleNames 待恢复的应用包信息 * @param bundleNameDetailMap bundle和detail的对应关系 + * @param isClearDataFlags 清理数据标志集合 * @param restoreType 任务类型 */ void SetCurrentSessProperties(std::vector &restoreBundleInfos, std::vector &restoreBundleNames, std::map> &bundleNameDetailMap, - RestoreTypeEnum restoreType); + std::map &isClearDataFlags, RestoreTypeEnum restoreType); + + /** + * @brief set session info + * + * @param restoreBundleInfos: bundles to be restored + * @param restoreBundleNames: bundles info to be restored + * @param restoreType: retore type + */ + void SetCurrentSessProperties(std::vector &restoreBundleInfos, + std::vector &restoreBundleNames, RestoreTypeEnum restoreType); /** * @brief 通知权限模块 @@ -362,6 +380,17 @@ private: */ void NotifyCallerCurAppIncrementDone(ErrCode errCode, const std::string &callerName); + void SetWant(AAFwk::Want &want, const BundleName &bundleName, const BConstants::ExtensionAction &action); + + /** + * @brief GetBackupInfo 任务执行 + * + * @param bundleName 应用名称 + * @param result 业务结果出参 + * + */ + ErrCode GetBackupInfoCmdHandle(BundleName &bundleName, std::string &result); + private: static sptr instance_; static std::mutex instanceLock_; @@ -369,6 +398,7 @@ private: std::condition_variable getBackupInfoCondition_; static inline std::atomic seed {1}; std::atomic isConnectDied_ {false}; + std::atomic isUnloadService_ {false}; sptr session_; sptr sched_; diff --git a/services/backup_sa/include/module_ipc/svc_backup_connection.h b/services/backup_sa/include/module_ipc/svc_backup_connection.h index 379721abd3dbbb7b6608f5ba3a51aeda5f1fb8d7..1958fcb8cd3c639ea8c0b71aef5cad17e8aeb4a4 100644 --- a/services/backup_sa/include/module_ipc/svc_backup_connection.h +++ b/services/backup_sa/include/module_ipc/svc_backup_connection.h @@ -76,7 +76,7 @@ public: * @param callConnected */ void SetCallback(std::function callConnected); - + /** * @brief Set the CallDied object * @@ -84,23 +84,32 @@ public: */ void SetCallDied(std::function callDied); + /** + * @brief wait disconnect done + */ + bool WaitDisconnectDone(); + public: SvcBackupConnection(std::function callDied, - std::function callConnected) - : callDied_(callDied), callConnected_(callConnected) + std::function callConnected, + std::string bundleNameIndexInfo) + : callDied_(callDied), callConnected_(callConnected), bundleNameIndexInfo_(bundleNameIndexInfo) { } ~SvcBackupConnection() override {}; private: std::mutex mutex_; + std::mutex waitMutex_; std::condition_variable condition_; + std::condition_variable waitCondition_; std::atomic isConnected_ = {false}; std::atomic isConnectedDone_ = {false}; sptr backupProxy_; std::function callDied_; std::function callConnected_; + std::string bundleNameIndexInfo_; }; } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/include/module_ipc/svc_extension_proxy.h b/services/backup_sa/include/module_ipc/svc_extension_proxy.h index e817810ae7d36c609b20e2af954357235def8d2f..a20ef511212b97add80fd42bff88d18e4e458043 100644 --- a/services/backup_sa/include/module_ipc/svc_extension_proxy.h +++ b/services/backup_sa/include/module_ipc/svc_extension_proxy.h @@ -25,13 +25,13 @@ class SvcExtensionProxy : public IRemoteProxy { public: UniqueFd GetFileHandle(const std::string &fileName, int32_t &errCode) override; ErrCode HandleClear() override; - ErrCode HandleBackup() override; + ErrCode HandleBackup(bool isClearData) override; ErrCode PublishFile(const std::string &fileName) override; - ErrCode HandleRestore() override; + ErrCode HandleRestore(bool isClearData) override; ErrCode GetIncrementalFileHandle(const std::string &fileName) override; ErrCode PublishIncrementalFile(const std::string &fileName) override; ErrCode HandleIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd) override; - ErrCode IncrementalOnBackup() override; + ErrCode IncrementalOnBackup(bool isClearData) override; std::tuple GetIncrementalBackupFileHandle() override; ErrCode GetBackupInfo(std::string &result) override; ErrCode UpdateFdSendRate(std::string &bundleName, int32_t sendRate) override; diff --git a/services/backup_sa/include/module_ipc/svc_session_manager.h b/services/backup_sa/include/module_ipc/svc_session_manager.h index 737116a6c84041c2f5729054eb4e53b9c0204df7..7baf1cabb497f8fae39e39ea406e3adae9220071 100644 --- a/services/backup_sa/include/module_ipc/svc_session_manager.h +++ b/services/backup_sa/include/module_ipc/svc_session_manager.h @@ -65,6 +65,8 @@ struct BackupExtInfo { std::string backupParameters; int32_t backupPriority; std::string extInfo; + int32_t appendNum {1}; + bool isClearData {true}; }; class Service; @@ -475,6 +477,10 @@ public: bool ValidRestoreDataType(RestoreTypeEnum restoreType); Impl GetImpl(); + int GetSessionCnt(); + + void SetClearDataFlag(const std::string &bundleName, bool isClearData); + bool GetClearDataFlag(const std::string &bundleName); private: /** @@ -541,6 +547,7 @@ private: uint32_t extConnectNum_ {0}; Utils::Timer extBundleTimer {"backupBundleExtTimer"}; std::atomic sessionCnt_ {0}; + bool unloadSAFlag_ {false}; int32_t memoryParaCurSize_ {BConstants::DEFAULT_VFS_CACHE_PRESSURE}; }; } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_app_gallery/app_gallery_dispose_proxy.cpp b/services/backup_sa/src/module_app_gallery/app_gallery_dispose_proxy.cpp index 34f60aed333205220e16870eace44006c9b9af1a..f49ed5bd306f00f7e545f4441814dc09b4cc5a30 100644 --- a/services/backup_sa/src/module_app_gallery/app_gallery_dispose_proxy.cpp +++ b/services/backup_sa/src/module_app_gallery/app_gallery_dispose_proxy.cpp @@ -94,6 +94,11 @@ DisposeErr AppGalleryDisposeProxy::DoDispose(const std::string &bundleName, Disp } MessageParcel data; + const auto interfaceToken = APP_FOUNDATION_SERVICE; + if (!data.WriteInterfaceToken(interfaceToken)) { + HILOGI("write WriteInterfaceToken failed"); + return DisposeErr::IPC_FAIL; + } if (!data.WriteString16(Str8ToStr16(bundleName))) { HILOGI("write ownerInfo and bundleName failed"); return DisposeErr::IPC_FAIL; @@ -103,11 +108,6 @@ DisposeErr AppGalleryDisposeProxy::DoDispose(const std::string &bundleName, Disp HILOGI("write RemoteObject failed"); return DisposeErr::IPC_FAIL; } - const auto interfaceToken = APP_FOUNDATION_SERVICE; - if (!data.WriteInterfaceToken(interfaceToken)) { - HILOGI("write WriteInterfaceToken failed"); - return DisposeErr::IPC_FAIL; - } MessageParcel reply; MessageOption option(MessageOption::TF_ASYNC); diff --git a/services/backup_sa/src/module_external/bms_adapter.cpp b/services/backup_sa/src/module_external/bms_adapter.cpp index 87b1cfda47483c7014681a2048df70ddc83ef0ff..09a0d132ac82817a43829a226c7d2562fd7e6011 100644 --- a/services/backup_sa/src/module_external/bms_adapter.cpp +++ b/services/backup_sa/src/module_external/bms_adapter.cpp @@ -22,6 +22,7 @@ #include "b_error/b_error.h" #include "b_file_info.h" +#include "b_jsonutil/b_jsonutil.h" #include "b_json/b_json_entity_extension_config.h" #include "b_resources/b_constants.h" #include "b_sa/b_sa_utils.h" @@ -47,7 +48,6 @@ const string LINUX_HAP_CODE_PATH = "2"; const string MEDIA_LIBRARY_HAP = "com.ohos.medialibrary.medialibrarydata"; const string EXTERNAL_FILE_HAP = "com.ohos.UserFile.ExternalFileManager"; const int E_ERR = -1; -const int SINGLE_BUNDLE_NUM = 1; const vector dataDir = {"app", "local", "distributed", "database", "cache"}; } // namespace @@ -95,7 +95,8 @@ static int64_t GetBundleStats(const string &bundleName, int32_t userId) } auto bms = GetBundleManager(); vector bundleStats; - bool res = bms->GetBundleStats(bundleName, userId, bundleStats); + BJsonUtil::BundleDetailInfo bundleDetailInfo = BJsonUtil::ParseBundleNameIndexStr(bundleName); + bool res = bms->GetBundleStats(bundleDetailInfo.bundleName, userId, bundleStats, bundleDetailInfo.bundleIndex); if (!res || bundleStats.size() != dataDir.size()) { HILOGE("An error occurred in querying bundle stats. name:%{public}s", bundleName.c_str()); return 0; @@ -122,25 +123,20 @@ vector BundleMgrAdapter::GetBundleInfos(const vecto continue; } AppExecFwk::BundleInfo installedBundle; - if (!bms->GetBundleInfo(bundleName, AppExecFwk::GET_BUNDLE_WITH_EXTENSION_INFO, installedBundle, userId)) { - if (bundleNames.size() != SINGLE_BUNDLE_NUM) { - HILOGE("bundleName:%{public}s, current bundle info for backup/restore is empty", bundleName.c_str()); - continue; - } - throw BError(BError::Codes::SA_BUNDLE_INFO_EMPTY, "Failed to get bundle info"); - } - if (installedBundle.applicationInfo.codePath == HMOS_HAP_CODE_PATH || - installedBundle.applicationInfo.codePath == LINUX_HAP_CODE_PATH) { - HILOGI("Unsupported applications, name : %{public}s", installedBundle.name.data()); + std::vector extensionInfos; + bool getBundleSuccess = GetCurBundleExtenionInfo(installedBundle, bundleName, extensionInfos, bms, userId); + if (!getBundleSuccess) { + HILOGE("Get current extension failed"); continue; } auto [allToBackup, fullBackupOnly, extName, restoreDeps, supportScene, extraInfo] = - GetAllowAndExtName(installedBundle.extensionInfos); + GetAllowAndExtName(extensionInfos); int64_t dataSize = 0; if (allToBackup) { dataSize = GetBundleStats(installedBundle.name, userId); } - bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.versionCode, + bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.appIndex, + installedBundle.versionCode, installedBundle.versionName, dataSize, 0, allToBackup, fullBackupOnly, extName, restoreDeps, supportScene, extraInfo}); @@ -258,6 +254,7 @@ static bool GenerateBundleStatsIncrease(int32_t userId, const vector &bu std::string curBundleName = bundleInfos[i].name; HILOGD("BundleMgrAdapter name for %{public}s", curBundleName.c_str()); BJsonEntityCaps::BundleInfo newBundleInfo = {.name = curBundleName, + .appIndex = bundleInfos[i].appIndex, .versionCode = bundleInfos[i].versionCode, .versionName = bundleInfos[i].versionName, .spaceOccupied = pkgFileSizes[i], @@ -284,16 +281,14 @@ vector BundleMgrAdapter::GetBundleInfosForIncrement auto bundleName = bundleNameTime.bundleName; HILOGD("Begin get bundleName:%{private}s", bundleName.c_str()); AppExecFwk::BundleInfo installedBundle; - if (!bms->GetBundleInfo(bundleName, AppExecFwk::GET_BUNDLE_WITH_EXTENSION_INFO, installedBundle, userId)) { - throw BError(BError::Codes::SA_BROKEN_IPC, "Failed to get bundle info"); - } - if (installedBundle.applicationInfo.codePath == HMOS_HAP_CODE_PATH || - installedBundle.applicationInfo.codePath == LINUX_HAP_CODE_PATH) { - HILOGI("Unsupported applications, name : %{private}s", installedBundle.name.data()); + std::vector extensionInfos; + bool getBundleSuccess = GetCurBundleExtenionInfo(installedBundle, bundleName, extensionInfos, bms, userId); + if (!getBundleSuccess) { + HILOGE("Failed to get bundle info from bms, bundleName:%{public}s", bundleName.c_str()); continue; } struct BJsonEntityCaps::BundleBackupConfigPara backupPara; - if (!GetBackupExtConfig(installedBundle.extensionInfos, backupPara)) { + if (!GetBackupExtConfig(extensionInfos, backupPara)) { HILOGE("No backup extension ability found"); continue; } @@ -301,7 +296,8 @@ vector BundleMgrAdapter::GetBundleInfosForIncrement backupPara.excludes)) { continue; } - bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.versionCode, + bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.appIndex, + installedBundle.versionCode, installedBundle.versionName, 0, 0, backupPara.allToBackup, backupPara.fullBackupOnly, backupPara.extensionName, @@ -342,9 +338,9 @@ vector BundleMgrAdapter::GetBundleInfosForIncrement auto [allToBackup, fullBackupOnly, extName, restoreDeps, supportScene, extraInfo] = GetAllowAndExtName(installedBundle.extensionInfos); if (!allToBackup) { - bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.versionCode, - installedBundle.versionName, 0, 0, allToBackup, fullBackupOnly, extName, restoreDeps, supportScene, - extraInfo}); + bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.appIndex, + installedBundle.versionCode, installedBundle.versionName, 0, 0, allToBackup, fullBackupOnly, extName, + restoreDeps, supportScene, extraInfo}); continue; } auto it = std::find_if(extraIncreData.begin(), extraIncreData.end(), @@ -405,7 +401,7 @@ std::vector BundleMgrAdapter::GetBundleInfosForSA() int32_t ret = samgrProxy->GetExtensionSaIds(BConstants::EXTENSION_BACKUP, saIds); HILOGI("GetExtensionSaIds ret: %{public}d", ret); for (auto saId : saIds) { - saBundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {std::to_string(saId), 0, "", 0, 0, true, false, + saBundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {std::to_string(saId), 0, 0, "", 0, 0, true, false, "", "", "", ""}); } return saBundleInfos; @@ -435,7 +431,38 @@ void BundleMgrAdapter::GetBundleInfoForSA(std::string bundleName, std::vector &extensionInfos, + sptr bms, int32_t userId) +{ + BJsonUtil::BundleDetailInfo bundleDetailInfo = BJsonUtil::ParseBundleNameIndexStr(bundleName); + int32_t flags = static_cast(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE) | + static_cast(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY) | + static_cast(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_METADATA); + ErrCode ret = bms->GetCloneBundleInfo(bundleDetailInfo.bundleName, flags, bundleDetailInfo.bundleIndex, + installedBundle, userId); + if (ret != ERR_OK) { + HILOGE("bundleName:%{public}s, ret:%{public}d, current bundle info for backup/restore is empty", + bundleName.c_str(), ret); + return false; + } + if (installedBundle.applicationInfo.codePath == HMOS_HAP_CODE_PATH || + installedBundle.applicationInfo.codePath == LINUX_HAP_CODE_PATH) { + HILOGE("Unsupported applications, name : %{public}s", installedBundle.name.data()); + return false; + } + HILOGI("bundleName:%{public}s, hapMoudleInfos size:%{public}zu", bundleName.c_str(), + installedBundle.hapModuleInfos.size()); + std::vector hapModuleInfos = installedBundle.hapModuleInfos; + for (auto &hapModuleInfo : hapModuleInfos) { + extensionInfos.insert(extensionInfos.end(), hapModuleInfo.extensionInfos.begin(), + hapModuleInfo.extensionInfos.end()); + } + HILOGI("bundleName:%{public}s, extensionInfos size:%{public}zu", bundleName.c_str(), extensionInfos.size()); + return true; +} } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_ipc/service.cpp b/services/backup_sa/src/module_ipc/service.cpp index 952aeefa0aaf082835e66a5fa900ea53edd3703d..8f65b2178ea21c37dd667fcfed57bb84392eeb38 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -54,6 +54,8 @@ #include "hisysevent.h" #include "hitrace_meter.h" #include "ipc_skeleton.h" +#include "access_token.h" +#include "tokenid_kit.h" #include "module_app_gallery/app_gallery_dispose_proxy.h" #include "module_external/bms_adapter.h" #include "module_external/sms_adapter.h" @@ -80,6 +82,7 @@ const int32_t CONNECT_WAIT_TIME_S = 15; const std::string BACKUPSERVICE_WORK_STATUS_KEY = "persist.backupservice.workstatus"; const std::string BACKUPSERVICE_WORK_STATUS_ON = "true"; const std::string BACKUPSERVICE_WORK_STATUS_OFF = "false"; +const std::string BACKUP_PERMISSION = "ohos.permission.BACKUP"; } // namespace /* Shell/Xts user id equal to 0/1, we need set default 100 */ @@ -144,6 +147,10 @@ UniqueFd Service::GetLocalCapabilities() so there must be set init userId. */ HILOGI("Begin"); + if (session_ == nullptr) { + HILOGE("GetLocalCapabilities error, session is empty."); + return UniqueFd(-EPERM); + } session_->IncreaseSessionCnt(); session_->SetSessionUserId(GetUserIdDefault()); VerifyCaller(); @@ -152,7 +159,8 @@ UniqueFd Service::GetLocalCapabilities() UniqueFd fd(open(path.data(), O_TMPFILE | O_RDWR, S_IRUSR | S_IWUSR)); if (fd < 0) { HILOGE("Failed to open config file = %{private}s, err = %{public}d", path.c_str(), errno); - return UniqueFd(-1); + session_->DecreaseSessionCnt(); + return UniqueFd(-EPERM); } BJsonCachedEntity cachedEntity(std::move(fd)); @@ -197,8 +205,10 @@ string Service::VerifyCallerAndGetCallerName() if (Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenCaller, hapTokenInfo) != 0) { throw BError(BError::Codes::SA_INVAL_ARG, "Get hap token info failed"); } - session_->VerifyBundleName(hapTokenInfo.bundleName); - return hapTokenInfo.bundleName; + std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(hapTokenInfo.bundleName, + hapTokenInfo.instIndex); + session_->VerifyBundleName(bundleNameIndexInfo); + return bundleNameIndexInfo; } else { string str = to_string(tokenCaller); HILOGE("tokenID = %{private}s", GetAnonyString(str).c_str()); @@ -212,23 +222,34 @@ void Service::VerifyCaller() uint32_t tokenCaller = IPCSkeleton::GetCallingTokenID(); int tokenType = Security::AccessToken::AccessTokenKit::GetTokenType(tokenCaller); switch (tokenType) { - case Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE: /* Update Service */ + case Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE: { /* Update Service */ + if (Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, BACKUP_PERMISSION) != + Security::AccessToken::PermissionState::PERMISSION_GRANTED) { + throw BError(BError::Codes::SA_REFUSED_ACT, + string("Permission denied, token type is ").append(to_string(tokenType))); + } + break; + } case Security::AccessToken::ATokenTypeEnum::TOKEN_HAP: { - const string permission = "ohos.permission.BACKUP"; - if (Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, permission) == - Security::AccessToken::TypePermissionState::PERMISSION_DENIED) { - throw BError(BError::Codes::SA_INVAL_ARG, - string("Permission denied, token type is ").append(to_string(tokenType))); + if (Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, BACKUP_PERMISSION) != + Security::AccessToken::PermissionState::PERMISSION_GRANTED) { + throw BError(BError::Codes::SA_REFUSED_ACT, + string("Permission denied, token type is ").append(to_string(tokenType))); + } + uint64_t fullTokenId = OHOS::IPCSkeleton::GetCallingFullTokenID(); + if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId)) { + throw BError(BError::Codes::SA_REFUSED_ACT, + string("Permission denied, token type is ").append(to_string(tokenType))); } break; } case Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL: if (IPCSkeleton::GetCallingUid() != BConstants::SYSTEM_UID) { - throw BError(BError::Codes::SA_INVAL_ARG, "Calling uid is invalid"); + throw BError(BError::Codes::SA_REFUSED_ACT, "Calling uid is invalid"); } break; default: - throw BError(BError::Codes::SA_INVAL_ARG, string("Invalid token type ").append(to_string(tokenType))); + throw BError(BError::Codes::SA_REFUSED_ACT, string("Invalid token type ").append(to_string(tokenType))); break; } } @@ -280,16 +301,27 @@ ErrCode Service::InitBackupSession(sptr remote) } catch (const BError &e) { StopAll(nullptr, true); return e.GetCode(); + } catch (const exception &e) { + HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); + return EPERM; + } catch (...) { + HILOGI("Unexpected exception"); + return EPERM; } } ErrCode Service::Start() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - VerifyCaller(session_->GetScenario()); - session_->Start(); - OnStartSched(); - return BError(BError::Codes::OK); + try { + VerifyCaller(session_->GetScenario()); + session_->Start(); + OnStartSched(); + return BError(BError::Codes::OK); + } catch (const BError &e) { + HILOGE("Failde to Start"); + return e.GetCode(); + } } static bool SpecialVersion(const string &versionName) @@ -333,6 +365,7 @@ static vector GetRestoreBundleNames(UniqueFd fd, for (auto &restoreInfo : restoreInfos) { if (SAUtils::IsSABundleName(restoreInfo.name)) { BJsonEntityCaps::BundleInfo info = {.name = restoreInfo.name, + .appIndex = restoreInfo.appIndex, .versionCode = restoreInfo.versionCode, .versionName = restoreInfo.versionName, .spaceOccupied = restoreInfo.spaceOccupied, @@ -350,6 +383,7 @@ static vector GetRestoreBundleNames(UniqueFd fd, continue; } BJsonEntityCaps::BundleInfo info = {.name = (*it).name, + .appIndex = (*it).appIndex, .versionCode = (*it).versionCode, .versionName = (*it).versionName, .spaceOccupied = (*it).spaceOccupied, @@ -367,7 +401,8 @@ static void HandleExceptionOnAppendBundles(sptr session, const vector &appendBundleNames, const vector &restoreBundleNames) { if (appendBundleNames.size() != restoreBundleNames.size()) { - HILOGE("AppendBundleNames not equal restoreBundleNames."); + HILOGE("AppendBundleNames not equal restoreBundleNames, appendBundleNames size:%{public}zu," + "restoreBundleNames size:%{public}zu", appendBundleNames.size(), restoreBundleNames.size()); for (auto bundleName : appendBundleNames) { auto it = find_if(restoreBundleNames.begin(), restoreBundleNames.end(), [&bundleName](const auto &obj) { return obj == bundleName; }); @@ -391,9 +426,10 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, const vector bundleNamesOnly; + std::map isClearDataFlags; std::map> bundleNameDetailMap = - BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); - auto restoreInfos = GetRestoreBundleNames(move(fd), session_, bundleNamesOnly); + BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId, isClearDataFlags); + auto restoreInfos = GetRestoreBundleNames(move(fd), session_, bundleNames); auto restoreBundleNames = SvcRestoreDepsManager::GetInstance().GetRestoreBundleNames(restoreInfos, restoreType); HandleExceptionOnAppendBundles(session_, bundleNames, restoreBundleNames); if (restoreBundleNames.empty()) { @@ -402,7 +438,8 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, const vectorAppendBundles(restoreBundleNames); - SetCurrentSessProperties(restoreInfos, restoreBundleNames, bundleNameDetailMap, restoreType); + SetCurrentSessProperties(restoreInfos, restoreBundleNames, bundleNameDetailMap, + isClearDataFlags, restoreType); OnStartSched(); session_->DecreaseSessionCnt(); HILOGI("End"); @@ -420,6 +457,33 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, const vector &restoreBundleInfos, + std::vector &restoreBundleNames, RestoreTypeEnum restoreType) +{ + HILOGI("Start"); + for (auto restoreInfo : restoreBundleInfos) { + auto it = find_if(restoreBundleNames.begin(), restoreBundleNames.end(), + [&restoreInfo](const auto &bundleName) { return bundleName == restoreInfo.name; }); + if (it == restoreBundleNames.end()) { + throw BError(BError::Codes::SA_BUNDLE_INFO_EMPTY, "Can't find bundle name"); + } + HILOGI("bundleName: %{public}s, extensionName: %{public}s", restoreInfo.name.c_str(), + restoreInfo.extensionName.c_str()); + if ((restoreInfo.allToBackup == false && !SpecialVersion(restoreInfo.versionName)) || + (restoreInfo.extensionName.empty() && !SAUtils::IsSABundleName(restoreInfo.name))) { + OnBundleStarted(BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), session_, restoreInfo.name); + session_->RemoveExtInfo(restoreInfo.name); + continue; + } + session_->SetBundleRestoreType(restoreInfo.name, restoreType); + session_->SetBundleVersionCode(restoreInfo.name, restoreInfo.versionCode); + session_->SetBundleVersionName(restoreInfo.name, restoreInfo.versionName); + session_->SetBundleDataSize(restoreInfo.name, restoreInfo.spaceOccupied); + session_->SetBackupExtName(restoreInfo.name, restoreInfo.extensionName); + } + HILOGI("End"); +} + ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, const vector &bundleNames, RestoreTypeEnum restoreType, @@ -434,83 +498,78 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, VerifyCaller(IServiceReverse::Scenario::RESTORE); auto restoreInfos = GetRestoreBundleNames(move(fd), session_, bundleNames); auto restoreBundleNames = SvcRestoreDepsManager::GetInstance().GetRestoreBundleNames(restoreInfos, restoreType); + HandleExceptionOnAppendBundles(session_, bundleNames, restoreBundleNames); if (restoreBundleNames.empty()) { session_->DecreaseSessionCnt(); HILOGW("RestoreBundleNames is empty."); return BError(BError::Codes::OK); } session_->AppendBundles(restoreBundleNames); - for (auto restoreInfo : restoreInfos) { - auto it = find_if(restoreBundleNames.begin(), restoreBundleNames.end(), - [&restoreInfo](const auto &bundleName) { return bundleName == restoreInfo.name; }); - if (it == restoreBundleNames.end()) { - throw BError(BError::Codes::SA_BUNDLE_INFO_EMPTY, "Can't find bundle name"); - } - HILOGI("bundleName: %{public}s, extensionName: %{public}s", restoreInfo.name.c_str(), - restoreInfo.extensionName.c_str()); - if ((restoreInfo.allToBackup == false && !SpecialVersion(restoreInfo.versionName)) || - (restoreInfo.extensionName.empty() && !SAUtils::IsSABundleName(restoreInfo.name))) { - OnBundleStarted(BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), session_, restoreInfo.name); - session_->RemoveExtInfo(restoreInfo.name); - continue; - } - session_->SetBundleRestoreType(restoreInfo.name, restoreType); - session_->SetBundleVersionCode(restoreInfo.name, restoreInfo.versionCode); - session_->SetBundleVersionName(restoreInfo.name, restoreInfo.versionName); - session_->SetBundleDataSize(restoreInfo.name, restoreInfo.spaceOccupied); - session_->SetBackupExtName(restoreInfo.name, restoreInfo.extensionName); - } + SetCurrentSessProperties(restoreInfos, restoreBundleNames, restoreType); OnStartSched(); session_->DecreaseSessionCnt(); return BError(BError::Codes::OK); } catch (const BError &e) { + HILOGE("Catch exception"); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); session_->DecreaseSessionCnt(); return e.GetCode(); } catch (...) { + HILOGE("Unexpected exception"); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); session_->DecreaseSessionCnt(); - HILOGI("Unexpected exception"); return EPERM; } } void Service::SetCurrentSessProperties(std::vector &restoreBundleInfos, std::vector &restoreBundleNames, - std::map> &bundleNameDetailMap, RestoreTypeEnum restoreType) + std::map> &bundleNameDetailMap, + std::map &isClearDataFlags, RestoreTypeEnum restoreType) { HILOGI("Start"); for (auto restoreInfo : restoreBundleInfos) { auto it = find_if(restoreBundleNames.begin(), restoreBundleNames.end(), - [&restoreInfo](const auto &bundleName) { return bundleName == restoreInfo.name; }); + [&restoreInfo](const auto &bundleName) { + std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(restoreInfo.name, + restoreInfo.appIndex); + return bundleName == bundleNameIndexInfo; + }); if (it == restoreBundleNames.end()) { throw BError(BError::Codes::SA_BUNDLE_INFO_EMPTY, "Can't find bundle name"); } HILOGD("bundleName: %{public}s, extensionName: %{public}s", restoreInfo.name.c_str(), restoreInfo.extensionName.c_str()); + std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(restoreInfo.name, restoreInfo.appIndex); if ((restoreInfo.allToBackup == false && !SpecialVersion(restoreInfo.versionName)) || (restoreInfo.extensionName.empty() && !SAUtils::IsSABundleName(restoreInfo.name))) { OnBundleStarted(BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), session_, restoreInfo.name); - session_->RemoveExtInfo(restoreInfo.name); + session_->RemoveExtInfo(bundleNameIndexInfo); continue; } - session_->SetBundleRestoreType(restoreInfo.name, restoreType); - session_->SetBundleVersionCode(restoreInfo.name, restoreInfo.versionCode); - session_->SetBundleVersionName(restoreInfo.name, restoreInfo.versionName); - session_->SetBundleDataSize(restoreInfo.name, restoreInfo.spaceOccupied); - session_->SetBackupExtName(restoreInfo.name, restoreInfo.extensionName); + session_->SetBundleRestoreType(bundleNameIndexInfo, restoreType); + session_->SetBundleVersionCode(bundleNameIndexInfo, restoreInfo.versionCode); + session_->SetBundleVersionName(bundleNameIndexInfo, restoreInfo.versionName); + session_->SetBundleDataSize(bundleNameIndexInfo, restoreInfo.spaceOccupied); + session_->SetBackupExtName(bundleNameIndexInfo, restoreInfo.extensionName); + auto iter = isClearDataFlags.find(bundleNameIndexInfo); + if (iter != isClearDataFlags.end()) { + session_->SetClearDataFlag(bundleNameIndexInfo, iter->second); + } BJsonUtil::BundleDetailInfo broadCastInfo; BJsonUtil::BundleDetailInfo uniCastInfo; - bool broadCastRet = BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, restoreInfo.name, BROADCAST_TYPE, + bool broadCastRet = BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, bundleNameIndexInfo, BROADCAST_TYPE, broadCastInfo); if (broadCastRet) { bool notifyRet = DelayedSingleton::GetInstance()->NotifyBundleDetail(broadCastInfo); HILOGI("Publish event end, notify result is:%{public}d", notifyRet); } - bool uniCastRet = BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, restoreInfo.name, UNICAST_TYPE, + bool uniCastRet = BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, bundleNameIndexInfo, UNICAST_TYPE, uniCastInfo); if (uniCastRet) { HILOGI("current bundle, unicast info:%{public}s", GetAnonyString(uniCastInfo.detail).c_str()); - session_->SetBackupExtInfo(restoreInfo.name, uniCastInfo.detail); + session_->SetBackupExtInfo(bundleNameIndexInfo, uniCastInfo.detail); } } HILOGI("End"); @@ -537,16 +596,19 @@ ErrCode Service::AppendBundlesBackupSession(const vector &bundleName session_->DecreaseSessionCnt(); return BError(BError::Codes::OK); } catch (const BError &e) { + HandleExceptionOnAppendBundles(session_, bundleNames, {}); session_->DecreaseSessionCnt(); HILOGE("Failed, errCode = %{public}d", e.GetCode()); return e.GetCode(); } catch (const exception &e) { + HandleExceptionOnAppendBundles(session_, bundleNames, {}); session_->DecreaseSessionCnt(); - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); + HILOGE("Catched an unexpected low-level exception %{public}s", e.what()); return EPERM; } catch (...) { + HandleExceptionOnAppendBundles(session_, bundleNames, {}); session_->DecreaseSessionCnt(); - HILOGI("Unexpected exception"); + HILOGE("Unexpected exception"); return EPERM; } } @@ -559,22 +621,26 @@ ErrCode Service::AppendBundlesDetailsBackupSession(const vector &bun session_->IncreaseSessionCnt(); // BundleMgrAdapter::GetBundleInfos可能耗时 VerifyCaller(IServiceReverse::Scenario::BACKUP); std::vector bundleNamesOnly; + std::map isClearDataFlags; std::map> bundleNameDetailMap = - BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, session_->GetSessionUserId()); + BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + session_->GetSessionUserId(), isClearDataFlags); auto backupInfos = BundleMgrAdapter::GetBundleInfos(bundleNames, session_->GetSessionUserId()); session_->AppendBundles(bundleNames); for (auto info : backupInfos) { session_->SetBundleDataSize(info.name, info.spaceOccupied); session_->SetBackupExtName(info.name, info.extensionName); + auto iter = isClearDataFlags.find(info.name); + if (iter != isClearDataFlags.end()) { + session_->SetClearDataFlag(info.name, iter->second); + } if (info.allToBackup == false) { session_->GetServiceReverseProxy()->BackupOnBundleStarted( BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), info.name); session_->RemoveExtInfo(info.name); } BJsonUtil::BundleDetailInfo uniCastInfo; - bool uniCastRet = BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, info.name, UNICAST_TYPE, - uniCastInfo); - if (uniCastRet) { + if (BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, info.name, UNICAST_TYPE, uniCastInfo)) { HILOGI("current bundle, unicast info:%{public}s", GetAnonyString(uniCastInfo.detail).c_str()); session_->SetBackupExtInfo(info.name, uniCastInfo.detail); } @@ -583,16 +649,19 @@ ErrCode Service::AppendBundlesDetailsBackupSession(const vector &bun session_->DecreaseSessionCnt(); return BError(BError::Codes::OK); } catch (const BError &e) { - session_->DecreaseSessionCnt(); HILOGE("Failed, errCode = %{public}d", e.GetCode()); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(); return e.GetCode(); } catch (const exception &e) { - session_->DecreaseSessionCnt(); HILOGE("Catched an unexpected low-level exception %{public}s", e.what()); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(); return EPERM; } catch(...) { - session_->DecreaseSessionCnt(); HILOGE("Unexpected exception"); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(); return EPERM; } } @@ -600,10 +669,15 @@ ErrCode Service::AppendBundlesDetailsBackupSession(const vector &bun ErrCode Service::Finish() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - VerifyCaller(session_->GetScenario()); - session_->Finish(); - OnAllBundlesFinished(BError(BError::Codes::OK)); - return BError(BError::Codes::OK); + try { + VerifyCaller(session_->GetScenario()); + session_->Finish(); + OnAllBundlesFinished(BError(BError::Codes::OK)); + return BError(BError::Codes::OK); + } catch (const BError &e) { + HILOGE("Failde to Finish"); + return e.GetCode(); + } } ErrCode Service::PublishFile(const BFileInfo &fileInfo) @@ -797,6 +871,27 @@ void Service::NotifyCloneBundleFinish(std::string bundleName) OnAllBundlesFinished(BError(BError::Codes::OK)); } +void Service::SetWant(AAFwk::Want &want, const BundleName &bundleName, const BConstants::ExtensionAction &action) +{ + BJsonUtil::BundleDetailInfo bundleDetail = BJsonUtil::ParseBundleNameIndexStr(bundleName); + string backupExtName = session_->GetBackupExtName(bundleName); /* new device app ext name */ + HILOGI("BackupExtName: %{public}s, bundleName: %{public}s", backupExtName.data(), bundleName.data()); + string versionName = session_->GetBundleVersionName(bundleName); /* old device app version name */ + int64_t versionCode = session_->GetBundleVersionCode(bundleName); /* old device app version code */ + RestoreTypeEnum restoreType = session_->GetBundleRestoreType(bundleName); /* app restore type */ + string bundleExtInfo = session_->GetBackupExtInfo(bundleName); + HILOGI("BundleExtInfo is:%{public}s", GetAnonyString(bundleExtInfo).c_str()); + + want.SetElementName(bundleDetail.bundleName, backupExtName); + want.SetParam(BConstants::EXTENSION_ACTION_PARA, static_cast(action)); + want.SetParam(BConstants::EXTENSION_VERSION_CODE_PARA, static_cast(versionCode)); + want.SetParam(BConstants::EXTENSION_RESTORE_TYPE_PARA, static_cast(restoreType)); + want.SetParam(BConstants::EXTENSION_VERSION_NAME_PARA, versionName); + want.SetParam(BConstants::EXTENSION_RESTORE_EXT_INFO_PARA, bundleExtInfo); + want.SetParam(BConstants::EXTENSION_BACKUP_EXT_INFO_PARA, bundleExtInfo); + want.SetParam(BConstants::EXTENSION_APP_CLONE_INDEX_PARA, bundleDetail.bundleIndex); +} + ErrCode Service::LaunchBackupExtension(const BundleName &bundleName) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); @@ -815,29 +910,22 @@ ErrCode Service::LaunchBackupExtension(const BundleName &bundleName) return LaunchBackupSAExtension(bundleName); } AAFwk::Want want; - string backupExtName = session_->GetBackupExtName(bundleName); /* new device app ext name */ - HILOGD("backupExtName: %{public}s, bundleName: %{public}s", backupExtName.data(), bundleName.data()); - string versionName = session_->GetBundleVersionName(bundleName); /* old device app version name */ - int64_t versionCode = session_->GetBundleVersionCode(bundleName); /* old device app version code */ - RestoreTypeEnum restoreType = session_->GetBundleRestoreType(bundleName); /* app restore type */ - string bundleExtInfo = session_->GetBackupExtInfo(bundleName); - HILOGI("bundleExtInfo is:%{public}s", GetAnonyString(bundleExtInfo).c_str()); - - want.SetElementName(bundleName, backupExtName); - want.SetParam(BConstants::EXTENSION_ACTION_PARA, static_cast(action)); - want.SetParam(BConstants::EXTENSION_VERSION_CODE_PARA, static_cast(versionCode)); - want.SetParam(BConstants::EXTENSION_RESTORE_TYPE_PARA, static_cast(restoreType)); - want.SetParam(BConstants::EXTENSION_VERSION_NAME_PARA, versionName); - want.SetParam(BConstants::EXTENSION_RESTORE_EXT_INFO_PARA, bundleExtInfo); - want.SetParam(BConstants::EXTENSION_BACKUP_EXT_INFO_PARA, bundleExtInfo); - + SetWant(want, bundleName, action); auto backUpConnection = session_->GetExtConnection(bundleName); if (backUpConnection == nullptr) { HILOGE("LaunchBackupExtension error, backUpConnection is empty"); return BError(BError::Codes::SA_INVAL_ARG); } + if (backUpConnection->IsExtAbilityConnected() && !backUpConnection->WaitDisconnectDone()) { + HILOGE("LaunchBackupExtension error, WaitDisconnectDone failed"); + return BError(BError::Codes::SA_INVAL_ARG); + } ErrCode ret = backUpConnection->ConnectBackupExtAbility(want, session_->GetSessionUserId()); - return ret; + if (ret) { + HILOGE("ConnectBackupExtAbility faild, bundleName:%{public}s, ret:%{public}d", bundleName.c_str(), ret); + return BError(BError::Codes::SA_BOOT_EXT_FAIL); + } + return BError(BError::Codes::OK); } catch (const BError &e) { return e.GetCode(); } catch (const exception &e) { @@ -999,7 +1087,7 @@ void Service::ExtStart(const string &bundleName) throw BError(BError::Codes::SA_INVAL_ARG, "ExtStart bundle task error, Extension backup Proxy is empty"); } if (scenario == IServiceReverse::Scenario::BACKUP) { - auto ret = proxy->HandleBackup(); + auto ret = proxy->HandleBackup(session_->GetClearDataFlag(bundleName)); session_->GetServiceReverseProxy()->BackupOnBundleStarted(ret, bundleName); if (ret) { ClearSessionAndSchedInfo(bundleName); @@ -1010,7 +1098,7 @@ void Service::ExtStart(const string &bundleName) if (scenario != IServiceReverse::Scenario::RESTORE) { throw BError(BError::Codes::SA_INVAL_ARG, "Failed to scenario"); } - auto ret = proxy->HandleRestore(); + auto ret = proxy->HandleRestore(session_->GetClearDataFlag(bundleName)); session_->GetServiceReverseProxy()->RestoreOnBundleStarted(ret, bundleName); auto fileNameVec = session_->GetExtFileNameRequest(bundleName); for (auto &fileName : fileNameVec) { @@ -1348,6 +1436,18 @@ void Service::DeleteDisConfigFile() } } +void Service::UnloadService() +{ + if (sched_ == nullptr) { + HILOGE("Unload Service error, sched is empty"); + return; + } + if (!isUnloadService_.load()) { + isUnloadService_.store(true); + sched_->TryUnloadService(); + } +} + void Service::SessionDeactive() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); @@ -1368,8 +1468,12 @@ void Service::SessionDeactive() return; } session_->ClearSessionData(); - // 卸载服务 - sched_->TryUnloadService(); + // close session + StopAll(nullptr, true); + if (session_->GetSessionCnt() <= 0) { + HILOGI("do unload Service."); + sched_->TryUnloadService(); + } } catch (...) { HILOGE("Unexpected exception"); return; @@ -1403,51 +1507,66 @@ std::function Service::GetBackupInfoConnectDied(wptr }; } +ErrCode Service::GetBackupInfoCmdHandle(BundleName &bundleName, std::string &result) +{ + if (session_ == nullptr) { + HILOGE("Get BackupInfo error, session is empty."); + return BError(BError::Codes::SA_INVAL_ARG); + } + session_->SetSessionUserId(GetUserIdDefault()); + auto backupConnection = session_->CreateBackupConnection(bundleName); + if (backupConnection == nullptr) { + HILOGE("backupConnection is null. bundleName: %{public}s", bundleName.c_str()); + return BError(BError::Codes::SA_INVAL_ARG); + } + auto callConnected = GetBackupInfoConnectDone(wptr(this), bundleName); + auto callDied = GetBackupInfoConnectDied(wptr(this), bundleName); + backupConnection->SetCallback(callConnected); + backupConnection->SetCallDied(callDied); + AAFwk::Want want = CreateConnectWant(bundleName); + auto ret = backupConnection->ConnectBackupExtAbility(want, session_->GetSessionUserId()); + if (ret) { + HILOGE("ConnectBackupExtAbility faild, bundleName:%{public}s, ret:%{public}d", bundleName.c_str(), ret); + return BError(BError::Codes::SA_BOOT_EXT_FAIL); + } + std::unique_lock lock(getBackupInfoMutx_); + getBackupInfoCondition_.wait_for(lock, std::chrono::seconds(CONNECT_WAIT_TIME_S)); + if (isConnectDied_.load()) { + HILOGE("GetBackupInfoConnectDied, please check bundleName: %{public}s", bundleName.c_str()); + isConnectDied_.store(false); + return BError(BError::Codes::EXT_ABILITY_DIED); + } + auto proxy = backupConnection->GetBackupExtProxy(); + if (!proxy) { + HILOGE("Extension backup Proxy is empty."); + return BError(BError::Codes::SA_INVAL_ARG); + } + ret = proxy->GetBackupInfo(result); + backupConnection->DisconnectBackupExtAbility(); + if (ret != ERR_OK) { + HILOGE("Call Ext GetBackupInfo faild."); + return BError(BError::Codes::SA_INVAL_ARG); + } + + return BError(BError::Codes::OK); +} + ErrCode Service::GetBackupInfo(BundleName &bundleName, std::string &result) { try { HILOGI("Service::GetBackupInfo begin."); + if (session_ == nullptr) { + HILOGE("Get BackupInfo error, session is empty."); + return BError(BError::Codes::SA_INVAL_ARG); + } if (session_->GetImpl().clientToken) { return BError(BError::Codes::SA_REFUSED_ACT, "Already have an active session"); } session_->IncreaseSessionCnt(); - session_->SetSessionUserId(GetUserIdDefault()); - auto backupConnection = session_->CreateBackupConnection(bundleName); - if (backupConnection == nullptr) { - HILOGE("backupConnection is null. bundleName: %{public}s", bundleName.c_str()); - return BError(BError::Codes::SA_INVAL_ARG); - } - auto callConnected = GetBackupInfoConnectDone(wptr(this), bundleName); - auto callDied = GetBackupInfoConnectDied(wptr(this), bundleName); - backupConnection->SetCallback(callConnected); - backupConnection->SetCallDied(callDied); - AAFwk::Want want = CreateConnectWant(bundleName); - auto ret = backupConnection->ConnectBackupExtAbility(want, session_->GetSessionUserId()); - if (ret) { - HILOGE("ConnectBackupExtAbility faild, please check bundleName: %{public}s", bundleName.c_str()); - return BError(BError::Codes::EXT_ABILITY_DIED); - } - std::unique_lock lock(getBackupInfoMutx_); - getBackupInfoCondition_.wait_for(lock, std::chrono::seconds(CONNECT_WAIT_TIME_S)); - if (isConnectDied_.load()) { - HILOGE("GetBackupInfoConnectDied, please check bundleName: %{public}s", bundleName.c_str()); - isConnectDied_.store(false); - return BError(BError::Codes::EXT_ABILITY_DIED); - } - auto proxy = backupConnection->GetBackupExtProxy(); - if (!proxy) { - HILOGE("Extension backup Proxy is empty."); - return BError(BError::Codes::SA_INVAL_ARG); - } - ret = proxy->GetBackupInfo(result); - backupConnection->DisconnectBackupExtAbility(); - if (ret != ERR_OK) { - HILOGE("Call Ext GetBackupInfo faild."); - return BError(BError::Codes::SA_INVAL_ARG); - } + auto ret = GetBackupInfoCmdHandle(bundleName, result); HILOGI("Service::GetBackupInfo end. result: %s", result.c_str()); session_->DecreaseSessionCnt(); - return BError(BError::Codes::OK); + return ret; } catch (...) { session_->DecreaseSessionCnt(); HILOGI("Unexpected exception"); @@ -1483,8 +1602,13 @@ ErrCode Service::UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &res }; try { HILOGI("Service::UpdateTimer begin."); - VerifyCaller(); + if (session_ == nullptr) { + HILOGE("Update Timer error, session is empty."); + result = false; + return BError(BError::Codes::SA_INVAL_ARG); + } session_->IncreaseSessionCnt(); + VerifyCaller(); result = session_->UpdateTimer(bundleName, timeOut, timeoutCallback); session_->DecreaseSessionCnt(); return BError(BError::Codes::OK); @@ -1498,25 +1622,42 @@ ErrCode Service::UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &res ErrCode Service::UpdateSendRate(std::string &bundleName, int32_t sendRate, bool &result) { - HILOGI("Begin, bundle name:%{public}s, sendRate is:%{public}d", bundleName.c_str(), sendRate); - VerifyCaller(); - IServiceReverse::Scenario scenario = session_ -> GetScenario(); - if (scenario != IServiceReverse::Scenario::BACKUP) { - HILOGE("This method is applicable to the backup scenario"); - return BError(BError::Codes::SA_INVAL_ARG); - } - auto backupConnection = session_->GetExtConnection(bundleName); - auto proxy = backupConnection->GetBackupExtProxy(); - if (!proxy) { - throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); - } - auto ret = proxy->UpdateFdSendRate(bundleName, sendRate); - if (ret != NO_ERROR) { + try { + HILOGI("Begin, bundle name:%{public}s, sendRate is:%{public}d", bundleName.c_str(), sendRate); + if (session_ == nullptr) { + HILOGE("Update Send Rate error, session is empty."); + result = false; + return BError(BError::Codes::SA_INVAL_ARG); + } + session_->IncreaseSessionCnt(); + VerifyCaller(); + IServiceReverse::Scenario scenario = session_ -> GetScenario(); + if (scenario != IServiceReverse::Scenario::BACKUP) { + HILOGE("This method is applicable to the backup scenario"); + result = false; + session_->DecreaseSessionCnt(); + return BError(BError::Codes::SA_INVAL_ARG); + } + auto backupConnection = session_->GetExtConnection(bundleName); + auto proxy = backupConnection->GetBackupExtProxy(); + if (!proxy) { + throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); + } + auto ret = proxy->UpdateFdSendRate(bundleName, sendRate); + if (ret != NO_ERROR) { + result = false; + session_->DecreaseSessionCnt(); + return BError(BError::Codes::EXT_BROKEN_IPC); + } + result = true; + session_->DecreaseSessionCnt(); + return BError(BError::Codes::OK); + } catch (...) { result = false; - return BError(BError::Codes::EXT_BROKEN_IPC); + session_->DecreaseSessionCnt(); + HILOGI("Unexpected exception"); + return EPERM; } - result = true; - return BError(BError::Codes::OK); } AAFwk::Want Service::CreateConnectWant (BundleName &bundleName) diff --git a/services/backup_sa/src/module_ipc/service_incremental.cpp b/services/backup_sa/src/module_ipc/service_incremental.cpp index 07c6f6f87fca4c4faf3a9a15925f0158964ead74..7df256035fad13833d418ac4cea476cc2edeba3b 100644 --- a/services/backup_sa/src/module_ipc/service_incremental.cpp +++ b/services/backup_sa/src/module_ipc/service_incremental.cpp @@ -293,22 +293,26 @@ ErrCode Service::AppendBundlesIncrementalBackupSession(const std::vector bundleNamesOnly; + std::map isClearDataFlags; std::map> bundleNameDetailMap = - BJsonUtil::BuildBundleInfos(bundleNames, infos, bundleNamesOnly, session_->GetSessionUserId()); + BJsonUtil::BuildBundleInfos(bundleNames, infos, bundleNamesOnly, + session_->GetSessionUserId(), isClearDataFlags); auto backupInfos = BundleMgrAdapter::GetBundleInfos(bundleNames, session_->GetSessionUserId()); session_->AppendBundles(bundleNames); for (auto info : backupInfos) { session_->SetBundleDataSize(info.name, info.spaceOccupied); session_->SetBackupExtName(info.name, info.extensionName); + auto iter = isClearDataFlags.find(info.name); + if (iter != isClearDataFlags.end()) { + session_->SetClearDataFlag(info.name, iter->second); + } if (info.allToBackup == false) { session_->GetServiceReverseProxy()->IncrementalBackupOnBundleStarted( BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), info.name); session_->RemoveExtInfo(info.name); } BJsonUtil::BundleDetailInfo uniCastInfo; - bool uniCastRet = BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, info.name, UNICAST_TYPE, - uniCastInfo); - if (uniCastRet) { + if (BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, info.name, UNICAST_TYPE, uniCastInfo)) { HILOGI("current bundle, unicast info:%{public}s", GetAnonyString(uniCastInfo.detail).c_str()); session_->SetBackupExtInfo(info.name, uniCastInfo.detail); } @@ -519,7 +523,7 @@ bool Service::IncrementalBackup(const string &bundleName) throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); } if (scenario == IServiceReverse::Scenario::BACKUP && session_->GetIsIncrementalBackup()) { - auto ret = proxy->IncrementalOnBackup(); + auto ret = proxy->IncrementalOnBackup(session_->GetClearDataFlag(bundleName)); session_->GetServiceReverseProxy()->IncrementalBackupOnBundleStarted(ret, bundleName); if (ret) { ClearSessionAndSchedInfo(bundleName); @@ -528,7 +532,7 @@ bool Service::IncrementalBackup(const string &bundleName) return true; } else if (scenario == IServiceReverse::Scenario::RESTORE && BackupPara().GetBackupOverrideIncrementalRestore() && session_->ValidRestoreDataType(RestoreTypeEnum::RESTORE_DATA_WAIT_SEND)) { - auto ret = proxy->HandleRestore(); + auto ret = proxy->HandleRestore(session_->GetClearDataFlag(bundleName)); session_->GetServiceReverseProxy()->IncrementalRestoreOnBundleStarted(ret, bundleName); auto fileNameVec = session_->GetExtFileNameRequest(bundleName); for (auto &fileName : fileNameVec) { diff --git a/services/backup_sa/src/module_ipc/svc_backup_connection.cpp b/services/backup_sa/src/module_ipc/svc_backup_connection.cpp index a44451272684c93085e4468067b75608543c35e3..f9dc891c68e4e3a66a3c688717c2df9aab531e34 100644 --- a/services/backup_sa/src/module_ipc/svc_backup_connection.cpp +++ b/services/backup_sa/src/module_ipc/svc_backup_connection.cpp @@ -63,7 +63,12 @@ void SvcBackupConnection::OnAbilityConnectDone(const AppExecFwk::ElementName &el "PID", getpid(), "TIME", strTime.str() ); - callConnected_(move(bundleName)); + if (bundleNameIndexInfo_.find(bundleName) == string::npos) { + HILOGE("Current bundle name is wrong, bundleNameIndexInfo:%{public}s, bundleName:%{public}s", + bundleNameIndexInfo_.c_str(), bundleName.c_str()); + return; + } + callConnected_(move(bundleNameIndexInfo_)); HILOGI("called end"); } @@ -79,6 +84,7 @@ void SvcBackupConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName callDied_(move(bundleName)); } condition_.notify_all(); + waitCondition_.notify_all(); HILOGI("called end, name: %{public}s", bundleName.c_str()); } @@ -112,6 +118,17 @@ ErrCode SvcBackupConnection::DisconnectBackupExtAbility() return ret; } +bool SvcBackupConnection::WaitDisconnectDone() +{ + std::unique_lock lock(waitMutex_); + if (waitCondition_.wait_for(lock, std::chrono::seconds(WAIT_TIME), + [this]() { return isConnected_.load() == false; })) { + HILOGI("Wait disconnected done success"); + return true; + } + return false; +} + bool SvcBackupConnection::IsExtAbilityConnected() { return isConnected_.load(); diff --git a/services/backup_sa/src/module_ipc/svc_extension_incremental_proxy.cpp b/services/backup_sa/src/module_ipc/svc_extension_incremental_proxy.cpp index c4355e6aa43a0cc28a328383abbd922a1ec295d8..434ac777cd4af3dfc0be8b29b6ee15f76600743e 100644 --- a/services/backup_sa/src/module_ipc/svc_extension_incremental_proxy.cpp +++ b/services/backup_sa/src/module_ipc/svc_extension_incremental_proxy.cpp @@ -101,13 +101,15 @@ ErrCode SvcExtensionProxy::HandleIncrementalBackup(UniqueFd incrementalFd, Uniqu return reply.ReadInt32(); } -ErrCode SvcExtensionProxy::IncrementalOnBackup() +ErrCode SvcExtensionProxy::IncrementalOnBackup(bool isClearData) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGD("Start"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; - data.WriteInterfaceToken(GetDescriptor()); + if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteBool(isClearData)) { + return BError(BError::Codes::SDK_INVAL_ARG, "build param fail."); + } MessageParcel reply; MessageOption option; diff --git a/services/backup_sa/src/module_ipc/svc_extension_proxy.cpp b/services/backup_sa/src/module_ipc/svc_extension_proxy.cpp index 57e126eb35275538bcb63f56b1928035df7e478a..ce2bfcc36b75865ade94bba5f7cac9cd889af247 100644 --- a/services/backup_sa/src/module_ipc/svc_extension_proxy.cpp +++ b/services/backup_sa/src/module_ipc/svc_extension_proxy.cpp @@ -79,13 +79,15 @@ ErrCode SvcExtensionProxy::HandleClear() return reply.ReadInt32(); } -ErrCode SvcExtensionProxy::HandleBackup() +ErrCode SvcExtensionProxy::HandleBackup(bool isClearData) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Start"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; - data.WriteInterfaceToken(GetDescriptor()); + if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteBool(isClearData)) { + return BError(BError::Codes::SDK_INVAL_ARG, "build param fail."); + } MessageParcel reply; MessageOption option; @@ -126,13 +128,15 @@ ErrCode SvcExtensionProxy::PublishFile(const string &fileName) return reply.ReadInt32(); } -ErrCode SvcExtensionProxy::HandleRestore() +ErrCode SvcExtensionProxy::HandleRestore(bool isClearData) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Start"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; - data.WriteInterfaceToken(GetDescriptor()); + if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteBool(isClearData)) { + return BError(BError::Codes::SDK_INVAL_ARG, "build param fail."); + } MessageParcel reply; MessageOption option; diff --git a/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp b/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp index 115db71c495443b2d8149ecec32c30ac24481fba..5907c0ecce900f98c8584e0341fa7bdfe3d7fb35 100644 --- a/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp +++ b/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp @@ -15,6 +15,7 @@ #include "module_ipc/svc_restore_deps_manager.h" +#include "b_jsonutil/b_jsonutil.h" #include "filemgmt_libhilog.h" namespace OHOS::FileManagement::Backup { @@ -28,23 +29,16 @@ vector SvcRestoreDepsManager::GetRestoreBundleNames(const vector &bundleInfos) { for (auto &bundleInfo : bundleInfos) { - if (depsMap_.find(bundleInfo.name) != depsMap_.end()) { + std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(bundleInfo.name, bundleInfo.appIndex); + if (depsMap_.find(bundleNameIndexInfo) != depsMap_.end()) { continue; } allBundles_.emplace_back(bundleInfo); @@ -100,7 +95,7 @@ void SvcRestoreDepsManager::BuildDepsMap(const vector lock(lock_); if (impl_.scenario != scenario) { + HILOGE("Inconsistent scenario, impl scenario:%{public}d", impl_.scenario); throw BError(BError::Codes::SDK_MIXED_SCENARIO); } if (impl_.clientToken != clientToken) { @@ -53,6 +54,11 @@ SvcSessionManager::Impl SvcSessionManager::GetImpl() return impl_; } +int SvcSessionManager::GetSessionCnt() +{ + return sessionCnt_.load(); +} + ErrCode SvcSessionManager::Active(Impl newImpl) { unique_lock lock(lock_); @@ -71,6 +77,7 @@ ErrCode SvcSessionManager::Active(Impl newImpl) InitClient(newImpl); impl_ = newImpl; + unloadSAFlag_ = false; return BError(BError::Codes::OK); } @@ -92,6 +99,7 @@ void SvcSessionManager::Deactive(const wptr &remoteInAction, bool deathRecipient_ = nullptr; HILOGI("Succeed to deactive a session"); impl_ = {}; + unloadSAFlag_ = true; extConnectNum_ = 0; } @@ -205,12 +213,18 @@ void SvcSessionManager::RemoveExtInfo(const string &bundleName) unique_lock lock(lock_); auto it = impl_.backupExtNameMap.find(bundleName); if (it == impl_.backupExtNameMap.end()) { + HILOGI("BackupExtNameMap not contain %{public}s", bundleName.c_str()); return; } - impl_.backupExtNameMap.erase(it); if (extConnectNum_) { extConnectNum_--; } + int32_t &appendNum = impl_.backupExtNameMap[bundleName].appendNum; + if (--appendNum > 0) { + HILOGI("No need remove bundleName:%{public}s, appendNum=%{public}d", bundleName.c_str(), appendNum); + return; + } + impl_.backupExtNameMap.erase(it); } wptr SvcSessionManager::GetExtConnection(const BundleName &bundleName) @@ -267,7 +281,7 @@ sptr SvcSessionManager::GetBackupAbilityExt(const string &b revPtrStrong->ExtConnectDone(move(bundleName)); }; - return sptr(new SvcBackupConnection(callDied, callConnected)); + return sptr(new SvcBackupConnection(callDied, callConnected, bundleName)); } std::shared_ptr SvcSessionManager::GetBackupSAExt(const std::string &bundleName) @@ -483,6 +497,14 @@ void SvcSessionManager::AppendBundles(const vector &bundleNames) for (auto &&bundleName : bundleNames) { HILOGD("bundleName: %{public}s", bundleName.c_str()); BackupExtInfo info {}; + auto it = impl_.backupExtNameMap.find(bundleName); + if (it != impl_.backupExtNameMap.end()) { + HILOGI("BackupExtNameMap already contain %{public}s", bundleName.c_str()); + info.backUpConnection = impl_.backupExtNameMap[bundleName].backUpConnection; + info.appendNum = impl_.backupExtNameMap[bundleName].appendNum + 1; + impl_.backupExtNameMap[bundleName] = info; + continue; + } if (SAUtils::IsSABundleName(bundleName)) { info.saBackupConnection = GetBackupSAExt(bundleName); } else { @@ -729,6 +751,15 @@ void SvcSessionManager::DecreaseSessionCnt() sessionCnt_--; } else { HILOGE("Invalid sessionCount."); + return; + } + if (reversePtr_ == nullptr) { + HILOGE("Service reverse pointer is empty."); + return; + } + if (sessionCnt_.load() <= 0 && unloadSAFlag_ == true) { + HILOGI("do unload Service."); + reversePtr_->UnloadService(); } } @@ -816,6 +847,26 @@ void SvcSessionManager::SetMemParaCurSize(int32_t size) memoryParaCurSize_ = size; } +void SvcSessionManager::SetClearDataFlag(const std::string &bundleName, bool isClearData) +{ + unique_lock lock(lock_); + if (!impl_.clientToken) { + throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + } + auto it = GetBackupExtNameMap(bundleName); + it->second.isClearData = isClearData; + HILOGI("bundleName:%{public}s, set clear data flag:%{public}d.", bundleName.c_str(), isClearData); +} +bool SvcSessionManager::GetClearDataFlag(const std::string &bundleName) +{ + unique_lock lock(lock_); + if (!impl_.clientToken) { + throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + } + auto it = GetBackupExtNameMap(bundleName); + return it->second.isClearData; +} + bool SvcSessionManager::ValidRestoreDataType(RestoreTypeEnum restoreDataType) { return impl_.restoreDataType == restoreDataType; diff --git a/services/backup_sa/src/module_sched/sched_scheduler.cpp b/services/backup_sa/src/module_sched/sched_scheduler.cpp index 726c742d466df94cb84b64c6a2ba80cff02bdf2b..20f7e530c92930aab08ef5a689a7787286526cfb 100644 --- a/services/backup_sa/src/module_sched/sched_scheduler.cpp +++ b/services/backup_sa/src/module_sched/sched_scheduler.cpp @@ -72,28 +72,30 @@ void SchedScheduler::Sched(string bundleName) void SchedScheduler::ExecutingQueueTasks(const string &bundleName) { - HILOGE("start"); if (sessionPtr_ == nullptr) { HILOGE("ExecutingQueueTasks bundle %{public}s error, sessionPtr is empty", bundleName.c_str()); return; } BConstants::ServiceSchedAction action = sessionPtr_->GetServiceSchedAction(bundleName); if (action == BConstants::ServiceSchedAction::START) { - // 注册启动定时器 + // register timer for connect extension auto callStart = [reversePtr {reversePtr_}, bundleName]() { HILOGE("Extension connect failed = %{public}s", bundleName.data()); auto ptr = reversePtr.promote(); if (ptr) { - ptr->ExtConnectFailed(bundleName, BError(BError::Codes::SA_BOOT_TIMEOUT)); + ptr->ExtConnectFailed(bundleName, BError(BError::Codes::SA_BOOT_EXT_TIMEOUT)); } }; auto iTime = extTime_.Register(callStart, BConstants::EXT_CONNECT_MAX_TIME, true); unique_lock lock(lock_); bundleTimeVec_.emplace_back(make_tuple(bundleName, iTime)); lock.unlock(); - // 启动extension + // launch extension if (reversePtr_ != nullptr) { - reversePtr_->LaunchBackupExtension(bundleName); + ErrCode errCode = reversePtr_->LaunchBackupExtension(bundleName); + if (errCode) { + reversePtr_->ExtConnectFailed(bundleName, errCode); + } } } else if (action == BConstants::ServiceSchedAction::RUNNING) { HILOGI("Current bundle %{public}s process is running", bundleName.data()); @@ -106,12 +108,10 @@ void SchedScheduler::ExecutingQueueTasks(const string &bundleName) throw BError(BError::Codes::SA_INVAL_ARG, "Failed to find timer"); } auto &[bName, iTime] = *iter; - // 移除启动定时器 当前逻辑无启动成功后的ext心跳检测 + // unregister timer extTime_.Unregister(iTime); lock.unlock(); - // 开始执行备份恢复流程 - HILOGI("Current bundle %{public}s extension start", bundleName.data()); - //通知应用市场设置处置 + //notify AppGallery to start restore if (reversePtr_ != nullptr) { reversePtr_->SendStartAppGalleryNotify(bundleName); reversePtr_->ExtStart(bundleName); diff --git a/test/unittest/file_permission_native/BUILD.gn b/test/unittest/file_permission_native/BUILD.gn index 96a4bbf5b40fbfbc9e30ddcc2f488af4365952f0..bb3fff721a10bb3853ee8f5d13a04e5419eb122a 100644 --- a/test/unittest/file_permission_native/BUILD.gn +++ b/test/unittest/file_permission_native/BUILD.gn @@ -50,7 +50,7 @@ ohos_unittest("file_permission_test") { "ipc:ipc_core", "samgr:samgr_proxy", ] - defines = [] + defines = [ "private = public" ] if (sandbox_manarer) { external_deps += [ "sandbox_manager:libsandbox_manager_sdk" ] defines += [ "SANDBOX_MANAGER" ] diff --git a/test/unittest/file_permission_native/src/file_permission_test.cpp b/test/unittest/file_permission_native/src/file_permission_test.cpp index ee998d1d1cab31a6ad5cd090bfc04c6ea1ab799e..ac5fd86474e920862bd9ca6d13d8a0e2bb930dac 100644 --- a/test/unittest/file_permission_native/src/file_permission_test.cpp +++ b/test/unittest/file_permission_native/src/file_permission_test.cpp @@ -600,6 +600,117 @@ HWTEST_F(FilePermissionTest, CheckPersistentPermission_test_0003, testing::ext:: }; GTEST_LOG_(INFO) << "FileShareTest-end CheckPersistentPermission_test_0003"; } + +/** + * @tc.name: GetPathPolicyInfoFromUriPolicyInfo_test_0001 + * @tc.desc: Test function of GetPathPolicyInfoFromUriPolicyInfo() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(FilePermissionTest, GetPathPolicyInfoFromUriPolicyInfo_test_0001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FileShareTest-begin GetPathPolicyInfoFromUriPolicyInfo_test_0001"; + UriPolicyInfo infoB = {.uri = BUNDLE_NAME_A + "/storage/001.txt"}; + UriPolicyInfo infoC = {.uri = "file://media/Photo/10/1.jpeg"}; + UriPolicyInfo infoD = {.uri = "file://" + BUNDLE_NAME_A + "/storage/001.txt?networkid=5454541547878787878748748"}; + UriPolicyInfo infoE = {.uri = "file://" + BUNDLE_NAME_A + "/storage"}; + std::vector uriPolicies; + uriPolicies.emplace_back(infoB); + uriPolicies.emplace_back(infoC); + uriPolicies.emplace_back(infoD); + uriPolicies.emplace_back(infoE); + vector errorResult; + auto pathPolicies = FilePermission::GetPathPolicyInfoFromUriPolicyInfo(uriPolicies, errorResult); + EXPECT_EQ(pathPolicies.size(), 1); + ASSERT_TRUE(errorResult.size() == 4); + EXPECT_EQ(errorResult[3], true); + GTEST_LOG_(INFO) << "FileShareTest-end GetPathPolicyInfoFromUriPolicyInfo_test_0001"; +} + +/** + * @tc.name: ParseErrorResults_test_0001 + * @tc.desc: Test function of ParseErrorResults() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(FilePermissionTest, ParseErrorResults_test_0001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FileShareTest-begin ParseErrorResults_test_0001"; + vector resultCodes; + vector errorResults; + FilePermission::ParseErrorResults(resultCodes, errorResults); + EXPECT_EQ(errorResults.size(), 0); + + resultCodes.push_back(false); + FilePermission::ParseErrorResults(resultCodes, errorResults); + EXPECT_EQ(errorResults.size(), 0); + + resultCodes.push_back(false); + errorResults.push_back(true); + FilePermission::ParseErrorResults(resultCodes, errorResults); + ASSERT_TRUE(errorResults.size() == 1); + EXPECT_EQ(errorResults[0], false); + + errorResults.push_back(true); + errorResults.push_back(true); + FilePermission::ParseErrorResults(resultCodes, errorResults); + ASSERT_TRUE(errorResults.size() == 3); + EXPECT_EQ(errorResults[0], false); + EXPECT_EQ(errorResults[1], false); + EXPECT_EQ(errorResults[2], false); + GTEST_LOG_(INFO) << "FileShareTest-end ParseErrorResults_test_0001"; +} + +/** + * @tc.name: ParseErrorResults_test_002 + * @tc.desc: Test function of ParseErrorResults() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(FilePermissionTest, ParseErrorResults_test_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "FileShareTest-begin ParseErrorResults_test_002"; + PolicyInfo infoA = {.path = "file://" + BUNDLE_NAME_A + "/storage/001.txt"}; + PolicyInfo infoB = {.path = BUNDLE_NAME_A + "/storage/001.txt"}; + PolicyInfo infoC = {.path = "file://media/Photo/10/1.jpeg"}; + PolicyInfo infoD = {.path = "file://" + BUNDLE_NAME_A + "/storage/001.txt?networkid=5454541547878787878748748"}; + PolicyInfo infoE = {.path = "file://" + BUNDLE_NAME_A + "/storage"}; + std::vector uriPolicies; + uriPolicies.emplace_back(infoA); + uriPolicies.emplace_back(infoB); + uriPolicies.emplace_back(infoC); + uriPolicies.emplace_back(infoD); + uriPolicies.emplace_back(infoE); + vector resultCodes; + resultCodes.emplace_back(static_cast(PolicyErrorCode::PERSISTENCE_FORBIDDEN)); + resultCodes.emplace_back(static_cast(PolicyErrorCode::INVALID_MODE)); + resultCodes.emplace_back(static_cast(PolicyErrorCode::INVALID_PATH)); + resultCodes.emplace_back(static_cast(PolicyErrorCode::PERMISSION_NOT_PERSISTED)); + + deque errorResults; + FilePermission::ParseErrorResults(resultCodes, uriPolicies, errorResults); + ASSERT_TRUE(errorResults.size() == 0); + + resultCodes.emplace_back(5); + FilePermission::ParseErrorResults(resultCodes, uriPolicies, errorResults); + ASSERT_TRUE(errorResults.size() == 4); + EXPECT_EQ(errorResults[0].uri, infoA.path); + EXPECT_EQ(errorResults[0].code, PolicyErrorCode::PERSISTENCE_FORBIDDEN); + EXPECT_EQ(errorResults[1].uri, infoB.path); + EXPECT_EQ(errorResults[1].code, PolicyErrorCode::INVALID_MODE); + EXPECT_EQ(errorResults[2].uri, infoC.path); + EXPECT_EQ(errorResults[2].code, PolicyErrorCode::INVALID_PATH); + EXPECT_EQ(errorResults[3].uri, infoD.path); + EXPECT_EQ(errorResults[3].code, PolicyErrorCode::PERMISSION_NOT_PERSISTED); + GTEST_LOG_(INFO) << "FileShareTest-end ParseErrorResults_test_002"; +} + #endif } // namespace AppFileService } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/file_share_ndk_test/BUILD.gn b/test/unittest/file_share_ndk_test/BUILD.gn index 75128bd0b0da90becbaf11378c2467913364f0fd..f1007eed397633175a5a59b2ee108bd3c8e2222e 100644 --- a/test/unittest/file_share_ndk_test/BUILD.gn +++ b/test/unittest/file_share_ndk_test/BUILD.gn @@ -16,7 +16,7 @@ import("//build/test.gni") group("unittest") { testonly = true deps = [ - "file_share_nopermission_test:file_share_no_permission_ndk_test", + "file_share_permission_sup_test:file_share_permission_ndk_sup_test", "file_share_permission_test:file_share_permission_ndk_test", ] } diff --git a/test/unittest/file_share_ndk_test/file_share_nopermission_test/file_share_nopermission_test.cpp b/test/unittest/file_share_ndk_test/file_share_nopermission_test/file_share_nopermission_test.cpp deleted file mode 100644 index 1689a45579409ffe810e4ee41162b3db8307d761..0000000000000000000000000000000000000000 --- a/test/unittest/file_share_ndk_test/file_share_nopermission_test/file_share_nopermission_test.cpp +++ /dev/null @@ -1,214 +0,0 @@ -/* - * 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 - -#include "common_func.h" -#include "error_code.h" -#include "oh_file_share.h" -#include "parameter.h" - -using namespace testing::ext; -using namespace OHOS::AppFileService; -namespace { -const std::string FILE_MANAGER_FULL_MOUNT_ENABLE_PARAMETER_STR = "const.filemanager.full_mount.enable"; -} // namespace - -static bool CheckFileManagerFullMountEnable() -{ - char value[] = "false"; - int retSystem = GetParameter(FILE_MANAGER_FULL_MOUNT_ENABLE_PARAMETER_STR.c_str(), "false", value, sizeof(value)); - if (retSystem > 0 && !std::strcmp(value, "true")) { - return true; - } - GTEST_LOG_(INFO) << "Not supporting all mounts"; - return false; -} - -namespace OHOS::AppFileService::ModuleFileShareNoPermission { - -class NDKFileShareNoPermissionTest : public testing::Test { -public: - static void SetUpTestCase(void) {}; - static void TearDownTestCase(void) {}; - void SetUp() {}; - void TearDown() {}; -}; - -/** - * @tc.name: OH_FileShare_PersistPermission_test - * @tc.desc: Test function of OH_FileShare_PersistPermission() interface for no permission. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: - */ -HWTEST_F(NDKFileShareNoPermissionTest, OH_FileShare_PersistPermission_test, TestSize.Level1) -{ - GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test start"; - char policyUriChar[] = "file://com.example.filesharea/storage"; - FileShare_PolicyInfo policy = { - .uri = policyUriChar, - .length = sizeof(policyUriChar) - 1, - .operationMode = FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE - }; - FileShare_PolicyInfo policies[] = {policy}; - unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); - FileShare_PolicyErrorResult *result = nullptr; - unsigned int resultNum; - FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT); - } else { - EXPECT_EQ(ret, E_PERMISSION); - } - if (result != nullptr) { - OH_FileShare_ReleasePolicyErrorResult(result, resultNum); - } - GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test end"; -} - -/** - * @tc.name: OH_FileShare_RevokePermission_test - * @tc.desc: Test function of OH_FileShare_RevokePermission() interface for no permission. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: - */ -HWTEST_F(NDKFileShareNoPermissionTest, OH_FileShare_RevokePermission_test, TestSize.Level1) -{ - GTEST_LOG_(INFO) << "OH_FileShare_RevokePermission_test start"; - char policyUriChar[] = "file://com.example.filesharea/storage"; - FileShare_PolicyInfo policy = {.uri = policyUriChar, - .length = sizeof(policyUriChar) - 1, - .operationMode = - FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; - FileShare_PolicyInfo policies[] = {policy}; - unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); - FileShare_PolicyErrorResult *result = nullptr; - unsigned int resultNum; - FileManagement_ErrCode ret = OH_FileShare_RevokePermission(policies, policiesNum, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT); - } else { - EXPECT_EQ(ret, E_PERMISSION); - } - if (result != nullptr) { - OH_FileShare_ReleasePolicyErrorResult(result, resultNum); - } - GTEST_LOG_(INFO) << "OH_FileShare_RevokePermission_test end"; -} - -/** - * @tc.name: OH_FileShare_ActivatePermission_test - * @tc.desc: Test function of OH_FileShare_ActivatePermission() interface for no permission. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: - */ -HWTEST_F(NDKFileShareNoPermissionTest, OH_FileShare_ActivatePermission_test, TestSize.Level1) -{ - GTEST_LOG_(INFO) << "OH_FileShare_ActivatePermission_test start"; - char policyUriChar[] = "file://com.example.filesharea/storage"; - FileShare_PolicyInfo policy = {.uri = policyUriChar, - .length = sizeof(policyUriChar) - 1, - .operationMode = - FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; - FileShare_PolicyInfo policies[] = {policy}; - unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); - FileShare_PolicyErrorResult *result = nullptr; - unsigned int resultNum; - FileManagement_ErrCode ret = OH_FileShare_ActivatePermission(policies, policiesNum, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT); - } else { - EXPECT_EQ(ret, E_PERMISSION); - } - if (result != nullptr) { - OH_FileShare_ReleasePolicyErrorResult(result, resultNum); - } - GTEST_LOG_(INFO) << "OH_FileShare_ActivatePermission_test end"; -} - -/** - * @tc.name: OH_FileShare_DeactivatePermission_test - * @tc.desc: Test function of OH_FileShare_DeactivatePermission() interface for no permission. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: - */ -HWTEST_F(NDKFileShareNoPermissionTest, OH_FileShare_DeactivatePermission_test, TestSize.Level1) -{ - GTEST_LOG_(INFO) << "OH_FileShare_DeactivatePermission_test start"; - char policyUriChar[] = "file://com.example.filesharea/storage"; - FileShare_PolicyInfo policy = {.uri = policyUriChar, - .length = sizeof(policyUriChar) - 1, - .operationMode = - FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; - FileShare_PolicyInfo policies[] = {policy}; - unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); - FileShare_PolicyErrorResult *result = nullptr; - unsigned int resultNum; - FileManagement_ErrCode ret = OH_FileShare_DeactivatePermission(policies, policiesNum, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT); - } else { - EXPECT_EQ(ret, E_PERMISSION); - } - if (result != nullptr) { - OH_FileShare_ReleasePolicyErrorResult(result, resultNum); - } - GTEST_LOG_(INFO) << "OH_FileShare_DeactivatePermission_test end"; -} - -/** - * @tc.name: OH_FileShare_CheckPersistentPermission_test - * @tc.desc: Test function of OH_FileShare_CheckPersistentPermission() interface for no permission. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: - */ -HWTEST_F(NDKFileShareNoPermissionTest, OH_FileShare_CheckPersistentPermission_test, TestSize.Level1) -{ - GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test start"; - char policyUriChar[] = "file://com.example.filesharea/storage"; - FileShare_PolicyInfo policy = {.uri = policyUriChar, - .length = sizeof(policyUriChar) - 1, - .operationMode = - FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; - FileShare_PolicyInfo policies[] = {policy}; - unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); - bool *result = nullptr; - unsigned int resultNum; - FileManagement_ErrCode ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT); - } else { - EXPECT_EQ(ret, E_PERMISSION); - } - if (result != nullptr) { - free(result); - } - GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test end"; -} - -} // namespace OHOS::AppFileService::ModuleFileShareNoPermission \ No newline at end of file diff --git a/test/unittest/file_share_ndk_test/file_share_nopermission_test/BUILD.gn b/test/unittest/file_share_ndk_test/file_share_permission_sup_test/BUILD.gn similarity index 62% rename from test/unittest/file_share_ndk_test/file_share_nopermission_test/BUILD.gn rename to test/unittest/file_share_ndk_test/file_share_permission_sup_test/BUILD.gn index ec3710413082204f4b9560a9ef644dc41f3452c1..5d75c18f5210be980fdfb5302a06606300896bb4 100644 --- a/test/unittest/file_share_ndk_test/file_share_nopermission_test/BUILD.gn +++ b/test/unittest/file_share_ndk_test/file_share_permission_sup_test/BUILD.gn @@ -14,34 +14,46 @@ import("//build/test.gni") import("//foundation/filemanagement/app_file_service/app_file_service.gni") -ohos_unittest("file_share_no_permission_ndk_test") { +ohos_unittest("file_share_permission_ndk_sup_test") { branch_protector_ret = "pac_ret" sanitize = { integer_overflow = true cfi = true cfi_cross_dso = true debug = false + blocklist = "${app_file_service_path}/cfi_blocklist.txt" } module_out_path = "filemanagement/app_file_service" include_dirs = [ "include", "${app_file_service_path}/interfaces/kits/ndk/fileshare/include", + "${app_file_service_path}/tests/mock/file_permission_native_mock/include", + "${app_file_service_path}/tests/mock/parameter_mock/include", "//third_party/googletest/include", ] - - sources = [ "file_share_nopermission_test.cpp" ] + resource_config_file = "../../resource/ohos_test.xml" + sources = [ + "${app_file_service_path}/interfaces/kits/ndk/fileshare/src/oh_file_share.cpp", + "${app_file_service_path}/tests/mock/file_permission_native_mock/src/file_permission_mock.cpp", + "file_share_permission_sup_test.cpp", + ] external_deps = [ + "ability_base:base", + "ability_base:want", "ability_base:zuri", + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", "c_utils:utils", - "file_api:filemgmt_libn", + "common_event_service:cesfwk_innerkits", "hilog:libhilog", "init:libbegetutil", + "ipc:ipc_core", + "samgr:samgr_proxy", ] - deps = [ "${app_file_service_path}/interfaces/innerkits/native:fileshare_native", - "${app_file_service_path}/interfaces/kits/ndk/fileshare/src:ohfileshare", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", ] diff --git a/test/unittest/file_share_ndk_test/file_share_permission_sup_test/file_share_permission_sup_test.cpp b/test/unittest/file_share_ndk_test/file_share_permission_sup_test/file_share_permission_sup_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9d988473c32fb61e80d7a644eb6eec073c31aa66 --- /dev/null +++ b/test/unittest/file_share_ndk_test/file_share_permission_sup_test/file_share_permission_sup_test.cpp @@ -0,0 +1,339 @@ +/* + * 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 "oh_file_share.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "accesstoken_kit.h" +#include "nativetoken_kit.h" +#include "permission_def.h" +#include "permission_state_full.h" +#include "securec.h" +#include "token_setproc.h" +#include "uri.h" + +#include "error_code.h" +#include "file_permission_mock.h" + +using namespace testing::ext; +using namespace testing; +using namespace OHOS::AppFileService; +using namespace OHOS::Security::AccessToken; + +namespace OHOS::AppFileService::ModuleFileSharePermission { +void GrantNativePermission() +{ + const char **perms = new const char *[1]; + perms[0] = "ohos.permission.FILE_ACCESS_PERSIST"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 1, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "app_file_service", + .aplStr = "system_core", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + +class NDKFileSharePermissionSupTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp() {}; + void TearDown() {}; + static inline shared_ptr filePermMoc_ = nullptr; +}; + +void NDKFileSharePermissionSupTest::SetUpTestCase() +{ + GrantNativePermission(); + + filePermMoc_ = make_shared(); + FilePermissionMock::filePermissionMock = filePermMoc_; +} + +void NDKFileSharePermissionSupTest::TearDownTestCase() +{ + FilePermissionMock::filePermissionMock = nullptr; + filePermMoc_ = nullptr; +} + +/** + * @tc.name: OH_FileShare_PersistPermission_test_002 + * @tc.desc: Test function of OH_FileShare_PersistPermission() interface for invalid path. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_PersistPermission_test_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_002 start"; + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = nullptr, + .length = 0, + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policies[] = {policy}; + unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); + FileShare_PolicyErrorResult *result = nullptr; + unsigned int resultNum; + FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + OH_FileShare_ReleasePolicyErrorResult(result, resultNum); + + policies[0].uri = policyUriChar; + ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + OH_FileShare_ReleasePolicyErrorResult(result, resultNum); + + policies[0].length = sizeof(policyUriChar); + ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + OH_FileShare_ReleasePolicyErrorResult(result, resultNum); + GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_002 end"; +} + +/** + * @tc.name: OH_FileShare_PersistPermission_test_003 + * @tc.desc: Test function of OH_FileShare_PersistPermission() interface for invalid path. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_PersistPermission_test_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_003 start"; + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = strlen(policyUriChar), + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policies[] = {policy}; + unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); + FileShare_PolicyErrorResult *result = nullptr; + unsigned int resultNum; + + EXPECT_CALL(*filePermMoc_, PersistPermission(_, _)).WillOnce(Return(E_PERMISSION)); + FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_ENOMEM); + OH_FileShare_ReleasePolicyErrorResult(result, resultNum); + + std::deque errorResults; + for (int i = 0; i <= MAX_ARRAY_SIZE; i++) { + PolicyErrorResult rlt; + errorResults.push_back(rlt); + } + + EXPECT_CALL(*filePermMoc_, PersistPermission(_, _)) + .WillOnce(DoAll(SetArgReferee<1>(errorResults), Return(E_PARAMS))); + ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_ENOMEM); + OH_FileShare_ReleasePolicyErrorResult(result, resultNum); + GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_003 end"; +} + +/** + * @tc.name: OH_FileShare_PersistPermission_test_004 + * @tc.desc: Test function of OH_FileShare_PersistPermission() interface for invalid path. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_PersistPermission_test_004, TestSize.Level1) +{ + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = strlen(policyUriChar), + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policies[] = {policy}; + unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); + FileShare_PolicyErrorResult *result = nullptr; + unsigned int resultNum; + + PolicyErrorResult rltOne = {.uri = string(policy.uri)}; + std::deque errorResults; + errorResults.push_back(rltOne); + EXPECT_CALL(*filePermMoc_, PersistPermission(_, _)) + .WillOnce(DoAll(SetArgReferee<1>(errorResults), Return(EPERM))); + FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_EPERM); + OH_FileShare_ReleasePolicyErrorResult(result, resultNum); + + EXPECT_CALL(*filePermMoc_, PersistPermission(_, _)) + .WillOnce(DoAll(SetArgReferee<1>(errorResults), Return(E_EPERM))); + ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_UNKNOWN_ERROR); + OH_FileShare_ReleasePolicyErrorResult(result, resultNum); + GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_004 end"; +} + +/** + * @tc.name: OH_FileShare_PersistPermission_test_005 + * @tc.desc: Test function of OH_FileShare_PersistPermission() interface for invalid path. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_PersistPermission_test_005, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_005 start"; + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = strlen(policyUriChar), + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policies[] = {policy}; + unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); + FileShare_PolicyErrorResult *result = nullptr; + unsigned int resultNum; + + EXPECT_CALL(*filePermMoc_, PersistPermission(_, _)).WillOnce(Return(E_NO_ERROR)); + FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_NO_ERROR); + OH_FileShare_ReleasePolicyErrorResult(result, resultNum); + GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_005 end"; +} + +/** + * @tc.name: OH_FileShare_CheckPersistentPermission_test_002 + * @tc.desc: Test function of OH_FileShare_CheckPersistentPermission() interface for FAILURE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_CheckPersistentPermission_test_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test_002 start"; + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = 0, + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policies[] = {policy}; + unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); + bool *result = nullptr; + unsigned int resultNum; + FileManagement_ErrCode ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + if (result != nullptr) { + free(result); + } + + policies[0].length = strlen(policyUriChar); + EXPECT_CALL(*filePermMoc_, CheckPersistentPermission(_, _)).WillOnce(Return(EPERM)); + ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_EPERM); + if (result != nullptr) { + free(result); + } + GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test_002 end"; +} + +/** + * @tc.name: OH_FileShare_CheckPersistentPermission_test_003 + * @tc.desc: Test function of OH_FileShare_CheckPersistentPermission() interface for FAILURE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_CheckPersistentPermission_test_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test_003 start"; + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = strlen(policyUriChar), + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policies[] = {policy}; + unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); + bool *result = nullptr; + unsigned int resultNum; + EXPECT_CALL(*filePermMoc_, CheckPersistentPermission(_, _)).WillOnce(Return(E_NO_ERROR)); + FileManagement_ErrCode ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_ENOMEM); + if (result != nullptr) { + free(result); + } + + std::vector errorResults; + for (int i = 0; i <= sizeof(FileShare_PolicyErrorResult) * MAX_ARRAY_SIZE; i++) { + errorResults.push_back(false); + } + + EXPECT_CALL(*filePermMoc_, CheckPersistentPermission(_, _)) + .WillOnce(DoAll(SetArgReferee<1>(errorResults), Return(E_NO_ERROR))); + ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_ENOMEM); + if (result != nullptr) { + free(result); + } + GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test_003 end"; +} + +/** + * @tc.name: OH_FileShare_CheckPersistentPermission_test_004 + * @tc.desc: Test function of OH_FileShare_CheckPersistentPermission() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_CheckPersistentPermission_test_004, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test_004 start"; + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = strlen(policyUriChar), + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policies[] = {policy}; + unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); + bool *result = nullptr; + unsigned int resultNum; + + std::vector errorResults; + errorResults.push_back(false); + + EXPECT_CALL(*filePermMoc_, CheckPersistentPermission(_, _)) + .WillOnce(DoAll(SetArgReferee<1>(errorResults), Return(E_NO_ERROR))); + FileManagement_ErrCode ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_NO_ERROR); + + if (result != nullptr) { + free(result); + } + GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test_004 end"; +} +} // namespace OHOS::AppFileService::ModuleFileSharePermission diff --git a/test/unittest/file_share_ndk_test/file_share_permission_test/BUILD.gn b/test/unittest/file_share_ndk_test/file_share_permission_test/BUILD.gn index a35a2c810c95047fca2088b4f95219806263306f..88e9a42ec5921fa56ea9eb766d01ca3ba0e2f9dc 100644 --- a/test/unittest/file_share_ndk_test/file_share_permission_test/BUILD.gn +++ b/test/unittest/file_share_ndk_test/file_share_permission_test/BUILD.gn @@ -27,6 +27,7 @@ ohos_unittest("file_share_permission_ndk_test") { include_dirs = [ "include", "${app_file_service_path}/interfaces/kits/ndk/fileshare/include", + "${app_file_service_path}/interfaces/kits/ndk/fileshare/src", "//third_party/googletest/include", ] resource_config_file = "../../resource/ohos_test.xml" diff --git a/test/unittest/file_share_ndk_test/file_share_permission_test/file_share_permission_test.cpp b/test/unittest/file_share_ndk_test/file_share_permission_test/file_share_permission_test.cpp index d7c5a1c2dfe1753f9ba6000f38b8ff3e2b2c047a..e5634aa6d8474250f1c3e14fda3239f26f4f31f3 100644 --- a/test/unittest/file_share_ndk_test/file_share_permission_test/file_share_permission_test.cpp +++ b/test/unittest/file_share_ndk_test/file_share_permission_test/file_share_permission_test.cpp @@ -27,9 +27,10 @@ #include "accesstoken_kit.h" #include "common_func.h" #include "error_code.h" +#include "file_permission.h" #include "ipc_skeleton.h" #include "log.h" -#include "oh_file_share.h" +#include "oh_file_share.cpp" #include "parameter.h" #include "sandbox_helper.h" #include "uri.h" @@ -69,17 +70,6 @@ void GrantNativePermission() delete[] perms; } -static bool CheckFileManagerFullMountEnable() -{ - char value[] = "false"; - int retSystem = GetParameter(FILE_MANAGER_FULL_MOUNT_ENABLE_PARAMETER_STR.c_str(), "false", value, sizeof(value)); - if (retSystem > 0 && !std::strcmp(value, "true")) { - return true; - } - GTEST_LOG_(INFO) << "Not supporting all mounts"; - return false; -} - class NDKFileSharePermissionTest : public testing::Test { public: static void SetUpTestCase(void); @@ -114,11 +104,7 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_PersistPermission_test_001, Te FileShare_PolicyErrorResult *result = nullptr; unsigned int resultNum; FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT); - } else { - EXPECT_EQ(ret, E_NO_ERROR); - } + EXPECT_EQ(ret, E_EPERM); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_001 end"; } @@ -144,15 +130,11 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_PersistPermission_test_002, Te FileShare_PolicyErrorResult *result = nullptr; unsigned int resultNum; FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT); + EXPECT_EQ(ret, E_EPERM); + if (result != nullptr) { + EXPECT_EQ(FileShare_PolicyErrorCode::INVALID_PATH, result[0].code); } else { - EXPECT_EQ(ret, E_EPERM); - if (result != nullptr) { - EXPECT_EQ(INVALID_PATH, result[0].code); - } else { - EXPECT_FALSE(true); - } + EXPECT_FALSE(true); } OH_FileShare_ReleasePolicyErrorResult(result, resultNum); GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_002 end"; @@ -169,11 +151,29 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_PersistPermission_test_002, Te HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_PersistPermission_test_003, TestSize.Level1) { GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_003 start"; - FileShare_PolicyInfo *policies = nullptr; unsigned int policiesNum = SET_ZERO; FileShare_PolicyErrorResult *result = nullptr; unsigned int resultNum; - FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); + FileManagement_ErrCode ret = OH_FileShare_PersistPermission(nullptr, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = sizeof(policyUriChar) - 1, + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policies[] = {policy}; + ret = OH_FileShare_PersistPermission(policies, policiesNum, nullptr, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + + ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, nullptr); + EXPECT_EQ(ret, E_PARAMS); + + ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + + policiesNum = OHOS::AppFileService::MAX_ARRAY_SIZE + 1; + ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); EXPECT_EQ(ret, E_PARAMS); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_003 end"; @@ -205,15 +205,11 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_PersistPermission_test_004, Te FileShare_PolicyErrorResult *result = nullptr; unsigned int resultNum; FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT); + EXPECT_EQ(ret, E_EPERM); + if (result != nullptr) { + EXPECT_EQ(FileShare_PolicyErrorCode::INVALID_PATH, result[0].code); } else { - EXPECT_EQ(ret, E_EPERM); - if (result != nullptr) { - EXPECT_EQ(INVALID_PATH, result[0].code); - } else { - EXPECT_FALSE(true); - } + EXPECT_FALSE(true); } OH_FileShare_ReleasePolicyErrorResult(result, resultNum); GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_004 end"; @@ -240,18 +236,10 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_RevokePermission_test_001, Tes FileShare_PolicyErrorResult *result = nullptr; unsigned int resultNum; FileManagement_ErrCode retPersist = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(retPersist, E_DEVICE_NOT_SUPPORT); - } else { - EXPECT_EQ(retPersist, E_NO_ERROR); - } + EXPECT_EQ(retPersist, E_EPERM); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); FileManagement_ErrCode ret = OH_FileShare_RevokePermission(policies, policiesNum, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT); - } else { - EXPECT_EQ(ret, E_NO_ERROR); - } + EXPECT_EQ(ret, E_EPERM); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); GTEST_LOG_(INFO) << "OH_FileShare_RevokePermission_test_001 end"; } @@ -277,15 +265,11 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_RevokePermission_test_002, Tes FileShare_PolicyErrorResult *result = nullptr; unsigned int resultNum; FileManagement_ErrCode ret = OH_FileShare_RevokePermission(policies, policiesNum, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT); + EXPECT_EQ(ret, E_EPERM); + if (result != nullptr) { + EXPECT_EQ(FileShare_PolicyErrorCode::INVALID_PATH, result[0].code); } else { - EXPECT_EQ(ret, E_EPERM); - if (result != nullptr) { - EXPECT_EQ(INVALID_PATH, result[0].code); - } else { - EXPECT_FALSE(true); - } + EXPECT_FALSE(true); } OH_FileShare_ReleasePolicyErrorResult(result, resultNum); GTEST_LOG_(INFO) << "OH_FileShare_RevokePermission_test_002 end"; @@ -308,6 +292,25 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_RevokePermission_test_003, Tes unsigned int resultNum; FileManagement_ErrCode ret = OH_FileShare_RevokePermission(policies, policiesNum, &result, &resultNum); EXPECT_EQ(ret, E_PARAMS); + + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = sizeof(policyUriChar) - 1, + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policiesTwo[] = {policy}; + ret = OH_FileShare_RevokePermission(policiesTwo, policiesNum, nullptr, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + + ret = OH_FileShare_RevokePermission(policiesTwo, policiesNum, &result, nullptr); + EXPECT_EQ(ret, E_PARAMS); + + ret = OH_FileShare_RevokePermission(policiesTwo, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + + policiesNum = OHOS::AppFileService::MAX_ARRAY_SIZE + 1; + ret = OH_FileShare_RevokePermission(policiesTwo, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); GTEST_LOG_(INFO) << "OH_FileShare_RevokePermission_test_003 end"; } @@ -333,11 +336,7 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_RevokePermission_test_004, Tes FileShare_PolicyErrorResult *result = nullptr; unsigned int resultNum; FileManagement_ErrCode retPersist = OH_FileShare_PersistPermission(policiesA, policiesNumA, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(retPersist, E_DEVICE_NOT_SUPPORT); - } else { - EXPECT_EQ(retPersist, E_NO_ERROR); - } + EXPECT_EQ(retPersist, E_EPERM); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); char policyUriCharB[] = "file://com.example.filesharea/data/storage/fileShare04.txt"; FileShare_PolicyInfo policyB = {.uri = policyUriCharB, @@ -347,15 +346,11 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_RevokePermission_test_004, Tes FileShare_PolicyInfo policies[] = {policyA, policyB}; unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); FileManagement_ErrCode ret = OH_FileShare_RevokePermission(policies, policiesNum, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT); + EXPECT_EQ(ret, E_EPERM); + if (result != nullptr) { + EXPECT_EQ(FileShare_PolicyErrorCode::INVALID_PATH, result[0].code); } else { - EXPECT_EQ(ret, E_EPERM); - if (result != nullptr) { - EXPECT_EQ(INVALID_PATH, result[0].code); - } else { - EXPECT_FALSE(true); - } + EXPECT_FALSE(true); } OH_FileShare_ReleasePolicyErrorResult(result, resultNum); GTEST_LOG_(INFO) << "OH_FileShare_RevokePermission_test_004 end"; @@ -382,18 +377,10 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ActivatePermission_test_001, T FileShare_PolicyErrorResult *result = nullptr; unsigned int resultNum; FileManagement_ErrCode retPersist = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(retPersist, E_DEVICE_NOT_SUPPORT); - } else { - EXPECT_EQ(retPersist, E_NO_ERROR); - } + EXPECT_EQ(retPersist, E_EPERM); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); FileManagement_ErrCode ret = OH_FileShare_ActivatePermission(policies, policiesNum, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT); - } else { - EXPECT_EQ(ret, E_NO_ERROR); - } + EXPECT_EQ(ret, E_EPERM); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); GTEST_LOG_(INFO) << "OH_FileShare_ActivatePermission_test_001 end"; } @@ -419,15 +406,11 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ActivatePermission_test_002, T FileShare_PolicyErrorResult *result = nullptr; unsigned int resultNum; FileManagement_ErrCode ret = OH_FileShare_ActivatePermission(policies, policiesNum, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT); + EXPECT_EQ(ret, E_EPERM); + if (result != nullptr) { + EXPECT_EQ(FileShare_PolicyErrorCode::INVALID_PATH, result[0].code); } else { - EXPECT_EQ(ret, E_EPERM); - if (result != nullptr) { - EXPECT_EQ(INVALID_PATH, result[0].code); - } else { - EXPECT_FALSE(true); - } + EXPECT_FALSE(true); } OH_FileShare_ReleasePolicyErrorResult(result, resultNum); GTEST_LOG_(INFO) << "OH_FileShare_ActivatePermission_test_002 end"; @@ -450,6 +433,25 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ActivatePermission_test_003, T unsigned int resultNum; FileManagement_ErrCode ret = OH_FileShare_ActivatePermission(policies, policiesNum, &result, &resultNum); EXPECT_EQ(ret, E_PARAMS); + + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = sizeof(policyUriChar) - 1, + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policiesTwo[] = {policy}; + ret = OH_FileShare_ActivatePermission(policiesTwo, policiesNum, nullptr, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + + ret = OH_FileShare_ActivatePermission(policiesTwo, policiesNum, &result, nullptr); + EXPECT_EQ(ret, E_PARAMS); + + ret = OH_FileShare_ActivatePermission(policiesTwo, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + + policiesNum = OHOS::AppFileService::MAX_ARRAY_SIZE + 1; + ret = OH_FileShare_ActivatePermission(policiesTwo, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); GTEST_LOG_(INFO) << "OH_FileShare_ActivatePermission_test_003 end"; } @@ -475,11 +477,7 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ActivatePermission_test_004, T FileShare_PolicyErrorResult *result = nullptr; unsigned int resultNum; FileManagement_ErrCode retPersist = OH_FileShare_PersistPermission(policiesA, policiesNumA, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(retPersist, E_DEVICE_NOT_SUPPORT); - } else { - EXPECT_EQ(retPersist, E_NO_ERROR); - } + EXPECT_EQ(retPersist, E_EPERM); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); char policyUriCharB[] = "file://com.example.filesharea/data/storage/fileShare04.txt"; FileShare_PolicyInfo policyB = {.uri = policyUriCharB, @@ -489,15 +487,11 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ActivatePermission_test_004, T FileShare_PolicyInfo policies[] = {policyA, policyB}; unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); FileManagement_ErrCode ret = OH_FileShare_ActivatePermission(policies, policiesNum, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT); + EXPECT_EQ(ret, E_EPERM); + if (result != nullptr) { + EXPECT_EQ(FileShare_PolicyErrorCode::INVALID_PATH, result[0].code); } else { - EXPECT_EQ(ret, E_EPERM); - if (result != nullptr) { - EXPECT_EQ(INVALID_PATH, result[0].code); - } else { - EXPECT_FALSE(true); - } + EXPECT_FALSE(true); } OH_FileShare_ReleasePolicyErrorResult(result, resultNum); GTEST_LOG_(INFO) << "OH_FileShare_ActivatePermission_test_004 end"; @@ -524,25 +518,13 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_DeactivatePermission_test_001, FileShare_PolicyErrorResult *result = nullptr; unsigned int resultNum; FileManagement_ErrCode retPersist = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(retPersist, E_DEVICE_NOT_SUPPORT); - } else { - EXPECT_EQ(retPersist, E_NO_ERROR); - } + EXPECT_EQ(retPersist, E_EPERM); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); FileManagement_ErrCode retActivate = OH_FileShare_ActivatePermission(policies, policiesNum, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(retActivate, E_DEVICE_NOT_SUPPORT); - } else { - EXPECT_EQ(retActivate, E_NO_ERROR); - } + EXPECT_EQ(retActivate, E_EPERM); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); FileManagement_ErrCode ret = OH_FileShare_DeactivatePermission(policies, policiesNum, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT); - } else { - EXPECT_EQ(ret, E_NO_ERROR); - } + EXPECT_EQ(ret, E_EPERM); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); GTEST_LOG_(INFO) << "OH_FileShare_DeactivatePermission_test_001 end"; } @@ -569,15 +551,11 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_DeactivatePermission_test_002, FileShare_PolicyErrorResult *result = nullptr; unsigned int resultNum; FileManagement_ErrCode ret = OH_FileShare_DeactivatePermission(policies, policiesNum, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT); + EXPECT_EQ(ret, E_EPERM); + if (result != nullptr) { + EXPECT_EQ(FileShare_PolicyErrorCode::INVALID_PATH, result[0].code); } else { - EXPECT_EQ(ret, E_EPERM); - if (result != nullptr) { - EXPECT_EQ(INVALID_PATH, result[0].code); - } else { - EXPECT_FALSE(true); - } + EXPECT_FALSE(true); } OH_FileShare_ReleasePolicyErrorResult(result, resultNum); GTEST_LOG_(INFO) << "OH_FileShare_DeactivatePermission_test_002 end"; @@ -600,6 +578,25 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_DeactivatePermission_test_003, unsigned int resultNum; FileManagement_ErrCode ret = OH_FileShare_DeactivatePermission(policies, policiesNum, &result, &resultNum); EXPECT_EQ(ret, E_PARAMS); + + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = sizeof(policyUriChar) - 1, + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policiesTwo[] = {policy}; + ret = OH_FileShare_DeactivatePermission(policiesTwo, policiesNum, nullptr, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + + ret = OH_FileShare_DeactivatePermission(policiesTwo, policiesNum, &result, nullptr); + EXPECT_EQ(ret, E_PARAMS); + + ret = OH_FileShare_DeactivatePermission(policiesTwo, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + + policiesNum = OHOS::AppFileService::MAX_ARRAY_SIZE + 1; + ret = OH_FileShare_DeactivatePermission(policiesTwo, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); GTEST_LOG_(INFO) << "OH_FileShare_DeactivatePermission_test_003 end"; } @@ -625,18 +622,10 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_DeactivatePermission_test_004, FileShare_PolicyErrorResult *result = nullptr; unsigned int resultNum; FileManagement_ErrCode retPersist = OH_FileShare_PersistPermission(policiesA, policiesNumA, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(retPersist, E_DEVICE_NOT_SUPPORT); - } else { - EXPECT_EQ(retPersist, E_NO_ERROR); - } + EXPECT_EQ(retPersist, E_EPERM); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); FileManagement_ErrCode retActivate = OH_FileShare_ActivatePermission(policiesA, policiesNumA, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(retActivate, E_DEVICE_NOT_SUPPORT); - } else { - EXPECT_EQ(retActivate, E_NO_ERROR); - } + EXPECT_EQ(retActivate, E_EPERM); OH_FileShare_ReleasePolicyErrorResult(result, resultNum); char policyUriCharB[] = "file://com.example.filesharea/data/storage/fileShare04.txt"; FileShare_PolicyInfo policyB = {.uri = policyUriCharB, @@ -646,15 +635,11 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_DeactivatePermission_test_004, FileShare_PolicyInfo policies[] = {policyA, policyB}; unsigned int policiesNum = sizeof(policies) / sizeof(policies[0]); FileManagement_ErrCode ret = OH_FileShare_DeactivatePermission(policies, policiesNum, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT); + EXPECT_EQ(ret, E_EPERM); + if (result != nullptr) { + EXPECT_EQ(FileShare_PolicyErrorCode::INVALID_PATH, result[0].code); } else { - EXPECT_EQ(ret, E_EPERM); - if (result != nullptr) { - EXPECT_EQ(INVALID_PATH, result[0].code); - } else { - EXPECT_FALSE(true); - } + EXPECT_FALSE(true); } OH_FileShare_ReleasePolicyErrorResult(result, resultNum); GTEST_LOG_(INFO) << "OH_FileShare_DeactivatePermission_test_004 end"; @@ -682,24 +667,16 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_CheckPersistentPermission_test unsigned int resultPersistNum; FileManagement_ErrCode retPersist = OH_FileShare_PersistPermission(policies, policiesNum, &resultPersist, &resultPersistNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(retPersist, E_DEVICE_NOT_SUPPORT); - } else { - EXPECT_EQ(retPersist, E_NO_ERROR); - } + EXPECT_EQ(retPersist, E_EPERM); OH_FileShare_ReleasePolicyErrorResult(resultPersist, resultPersistNum); bool *result = nullptr; unsigned int resultNum; FileManagement_ErrCode ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT); + EXPECT_EQ(ret, E_NO_ERROR); + if (result != nullptr) { + EXPECT_EQ(result[0], false); } else { - EXPECT_EQ(ret, E_NO_ERROR); - if (result != nullptr) { - EXPECT_EQ(result[0], true); - } else { - EXPECT_FALSE(true); - } + EXPECT_FALSE(true); } if (result != nullptr) { free(result); @@ -728,15 +705,11 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_CheckPersistentPermission_test bool *result = nullptr; unsigned int resultNum; FileManagement_ErrCode ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT); + EXPECT_EQ(ret, E_NO_ERROR); + if (result != nullptr) { + EXPECT_EQ(result[0], false); } else { - EXPECT_EQ(ret, E_NO_ERROR); - if (result != nullptr) { - EXPECT_EQ(result[0], false); - } else { - EXPECT_FALSE(true); - } + EXPECT_FALSE(true); } if (result != nullptr) { free(result); @@ -761,6 +734,25 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_CheckPersistentPermission_test unsigned int resultNum; FileManagement_ErrCode ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum); EXPECT_EQ(ret, E_PARAMS); + + char policyUriChar[] = "file://com.example.filesharea/data/storage/fileShare02.txt"; + FileShare_PolicyInfo policy = {.uri = policyUriChar, + .length = sizeof(policyUriChar) - 1, + .operationMode = + FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE}; + FileShare_PolicyInfo policiesTwo[] = {policy}; + ret = OH_FileShare_CheckPersistentPermission(policiesTwo, policiesNum, nullptr, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + + ret = OH_FileShare_CheckPersistentPermission(policiesTwo, policiesNum, &result, nullptr); + EXPECT_EQ(ret, E_PARAMS); + + ret = OH_FileShare_CheckPersistentPermission(policiesTwo, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); + + policiesNum = OHOS::AppFileService::MAX_ARRAY_SIZE + 1; + ret = OH_FileShare_CheckPersistentPermission(policiesTwo, policiesNum, &result, &resultNum); + EXPECT_EQ(ret, E_PARAMS); if (result != nullptr) { free(result); } @@ -789,11 +781,7 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_CheckPersistentPermission_test unsigned int resultPersistNum; FileManagement_ErrCode retPersist = OH_FileShare_PersistPermission(policiesA, policiesNumA, &resultPersist, &resultPersistNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(retPersist, E_DEVICE_NOT_SUPPORT); - } else { - EXPECT_EQ(retPersist, E_NO_ERROR); - } + EXPECT_EQ(retPersist, E_EPERM); OH_FileShare_ReleasePolicyErrorResult(resultPersist, resultPersistNum); char policyUriCharB[] = "file://com.example.filesharea/data/storage/fileShare04.txt"; FileShare_PolicyInfo policyB = {.uri = policyUriCharB, @@ -805,20 +793,295 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_CheckPersistentPermission_test bool *result = nullptr; unsigned int resultNum; FileManagement_ErrCode ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum); - if (!CheckFileManagerFullMountEnable()) { - EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT); + EXPECT_EQ(ret, E_NO_ERROR); + if (result != nullptr && resultNum == 2) { + EXPECT_EQ(result[0], false); + EXPECT_EQ(result[1], false); } else { - EXPECT_EQ(ret, E_NO_ERROR); - if (result != nullptr && resultNum == 2) { - EXPECT_EQ(result[0], true); - EXPECT_EQ(result[1], false); - } else { - EXPECT_FALSE(true); - } + EXPECT_FALSE(true); } if (result != nullptr) { free(result); } GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test_004 end"; } + +/** + * @tc.name: OH_FileShare_ConvertPolicyInfo_0100 + * @tc.desc: Test function of OH_FileShare_ConvertPolicyInfo_0100() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ConvertPolicyInfo_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyInfo_0100 start"; + char policyUriChar[] = "file://com.example.filesharea/storage"; + FileShare_PolicyInfo policy = { + .uri = policyUriChar, + .length = sizeof(policyUriChar) - 1, + .operationMode = FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE + }; + FileShare_PolicyInfo policies[] = {policy}; + int policiesNum = sizeof(policies) / sizeof(policies[0]); + std::vector uriPolicies; + bool ret = ConvertPolicyInfo(policies, policiesNum, uriPolicies); + EXPECT_TRUE(ret); + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyInfo_0100 end"; +} + +/** + * @tc.name: OH_FileShare_ConvertPolicyInfo_0200 + * @tc.desc: Test function of OH_FileShare_ConvertPolicyInfo_0200() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ConvertPolicyInfo_0200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyInfo_0200 start"; + FileShare_PolicyInfo policy = { + .uri = nullptr, + .length = 1, + .operationMode = FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE + }; + FileShare_PolicyInfo policies[] = {policy}; + int policiesNum = 1; + std::vector uriPolicies; + bool ret = ConvertPolicyInfo(policies, policiesNum, uriPolicies); + EXPECT_FALSE(ret); + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyInfo_0200 end"; +} + +/** + * @tc.name: OH_FileShare_ConvertPolicyInfo_0300 + * @tc.desc: Test function of OH_FileShare_ConvertPolicyInfo_0300() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ConvertPolicyInfo_0300, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyInfo_0300 start"; + char policyUriChar[] = "file://com.example.filesharea/storage"; + FileShare_PolicyInfo policy = { + .uri = policyUriChar, + .length = 0, + .operationMode = FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE + }; + FileShare_PolicyInfo policies[] = {policy}; + int policiesNum = 1; + std::vector uriPolicies; + bool ret = ConvertPolicyInfo(policies, policiesNum, uriPolicies); + EXPECT_FALSE(ret); + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyInfo_0300 end"; +} + +/** + * @tc.name: OH_FileShare_ConvertPolicyInfo_0400 + * @tc.desc: Test function of OH_FileShare_ConvertPolicyInfo_0400() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ConvertPolicyInfo_0400, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyInfo_0400 start"; + char policyUriChar[] = "file://com.example.filesharea/storage"; + FileShare_PolicyInfo policy = { + .uri = policyUriChar, + .length = sizeof(policyUriChar) + 1, + .operationMode = FileShare_OperationMode::READ_MODE | FileShare_OperationMode::WRITE_MODE + }; + FileShare_PolicyInfo policies[] = {policy}; + int policiesNum = sizeof(policies) / sizeof(policies[0]); + std::vector uriPolicies; + bool ret = ConvertPolicyInfo(policies, policiesNum, uriPolicies); + EXPECT_FALSE(ret); + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyInfo_0400 end"; +} + +/** + * @tc.name: OH_FileShare_ConvertPolicyErrorResult_0100 + * @tc.desc: Test function of OH_FileShare_ConvertPolicyErrorResult_0100() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ConvertPolicyErrorResult_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResult_0100 start"; + std::deque errorResults; + FileShare_PolicyErrorResult *result = nullptr; + unsigned int resultNum = 0; + bool ret = ConvertPolicyErrorResult(errorResults, &result, resultNum); + EXPECT_FALSE(ret); + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResult_0100 end"; +} + +/** + * @tc.name: OH_FileShare_ConvertPolicyErrorResult_0200 + * @tc.desc: Test function of OH_FileShare_ConvertPolicyErrorResult_0200() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ConvertPolicyErrorResult_0200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResult_0200 start"; + std::deque errorResults; + for (int32_t i = 0; i <= FOO_MAX_LEN + 1; i++) { + OHOS::AppFileService::PolicyErrorResult errorResult; + errorResults.push_back(errorResult); + } + FileShare_PolicyErrorResult *result = nullptr; + unsigned int resultNum = 0; + bool ret = ConvertPolicyErrorResult(errorResults, &result, resultNum); + EXPECT_FALSE(ret); + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResult_0200 end"; +} + +/** + * @tc.name: OH_FileShare_ConvertPolicyErrorResult_0300 + * @tc.desc: Test function of OH_FileShare_ConvertPolicyErrorResult_0300() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ConvertPolicyErrorResult_0300, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResult_0300 start"; + std::deque errorResults; + OHOS::AppFileService::PolicyErrorResult errorResult; + errorResults.push_back(errorResult); + FileShare_PolicyErrorResult *result = nullptr; + unsigned int resultNum = 0; + bool ret = ConvertPolicyErrorResult(errorResults, &result, resultNum); + EXPECT_TRUE(ret); + if (result[0].uri != nullptr) { + free(result[0].uri); + } + if (result[0].message != nullptr) { + free(result[0].message); + } + if (result != nullptr) { + free(result); + } + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResult_0300 end"; +} + +/** + * @tc.name: OH_FileShare_ConvertPolicyErrorResult_0400 + * @tc.desc: Test function of OH_FileShare_ConvertPolicyErrorResult_0400() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ConvertPolicyErrorResult_0400, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResult_0400 start"; + std::deque errorResults; + OHOS::AppFileService::PolicyErrorResult errorResult; + errorResult.uri = "uri"; + errorResult.message = "message"; + errorResults.push_back(errorResult); + FileShare_PolicyErrorResult *result = nullptr; + unsigned int resultNum = 0; + bool ret = ConvertPolicyErrorResult(errorResults, &result, resultNum); + EXPECT_TRUE(ret); + if (result[0].uri != nullptr) { + free(result[0].uri); + } + if (result[0].message != nullptr) { + free(result[0].message); + } + if (result != nullptr) { + free(result); + } + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResult_0400 end"; +} + +/** + * @tc.name: OH_FileShare_ConvertPolicyErrorResultBool_0100 + * @tc.desc: Test function of OH_FileShare_ConvertPolicyErrorResultBool_0100() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ConvertPolicyErrorResultBool_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResultBool_0100 start"; + std::vector errorResults; + bool *result = nullptr; + bool ret = ConvertPolicyErrorResultBool(errorResults, &result); + EXPECT_FALSE(ret); + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResultBool_0100 end"; +} + +/** + * @tc.name: OH_FileShare_ConvertPolicyErrorResultBool_0200 + * @tc.desc: Test function of OH_FileShare_ConvertPolicyErrorResultBool_0200() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ConvertPolicyErrorResultBool_0200, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResultBool_0200 start"; + std::vector errorResults(FOO_MAX_LEN + 1, true); + bool *result = nullptr; + bool ret = ConvertPolicyErrorResultBool(errorResults, &result); + EXPECT_FALSE(ret); + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResultBool_0200 end"; +} + +/** + * @tc.name: OH_FileShare_ConvertPolicyErrorResultBool_0300 + * @tc.desc: Test function of OH_FileShare_ConvertPolicyErrorResultBool_0300() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ConvertPolicyErrorResultBool_0300, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResultBool_0300 start"; + std::vector errorResults(1, true); + bool *result = nullptr; + bool ret = ConvertPolicyErrorResultBool(errorResults, &result); + EXPECT_TRUE(ret); + if (result != nullptr) { + free(result); + } + GTEST_LOG_(INFO) << "OH_FileShare_ConvertPolicyErrorResultBool_0300 end"; +} + +/** + * @tc.name: OH_FileShare_ErrorCodeConversion_0100 + * @tc.desc: Test function of OH_FileShare_ErrorCodeConversion_0100() interface for no permission. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ +HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_ErrorCodeConversion_0100, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "OH_FileShare_ErrorCodeConversion_0100 start"; + EXPECT_EQ(ErrorCodeConversion(static_cast(E_NO_ERROR)), E_NO_ERROR); + EXPECT_EQ(ErrorCodeConversion(static_cast(E_PERMISSION)), E_PERMISSION); + EXPECT_EQ(ErrorCodeConversion(static_cast(E_PARAMS)), E_PARAMS); + EXPECT_EQ(ErrorCodeConversion(EPERM), E_EPERM); + EXPECT_EQ(ErrorCodeConversion(-EPERM), E_UNKNOWN_ERROR); + GTEST_LOG_(INFO) << "OH_FileShare_ErrorCodeConversion_0100 end"; +} } // namespace OHOS::AppFileService::ModuleFileSharePermission diff --git a/test/unittest/file_uri_native/file_uri_test.cpp b/test/unittest/file_uri_native/file_uri_test.cpp index d02975a69b832afa24b4a19ca48117819f8c57f8..8e84576ff4722215074b5dfe9a1e711cf7dcf6b0 100644 --- a/test/unittest/file_uri_native/file_uri_test.cpp +++ b/test/unittest/file_uri_native/file_uri_test.cpp @@ -106,6 +106,11 @@ namespace OHOS::AppFileService::ModuleFileUri { FileUri fileUri(fileStr); string name = fileUri.GetName(); EXPECT_EQ(name, "test.txt"); + + string fileStr2 = "/data/storage/el2/base/files/test.txt/"; + string uri2 = "file://" + BUNDLE_A + fileStr; + FileUri fileUri2(fileStr2); + EXPECT_EQ(fileUri2.GetName(), ""); GTEST_LOG_(INFO) << "FileUriTest-end File_uri_GetName_0000"; } @@ -130,6 +135,10 @@ namespace OHOS::AppFileService::ModuleFileUri { FileUri fileUri2(uri2); path = fileUri2.GetPath(); EXPECT_EQ(path, "/Photo/12/IMG_12345_999999"); + + string uri4 = "file://media/Photo/12/IMG_12345_999999"; + FileUri fileUri4(uri4); + EXPECT_EQ(fileUri2.GetPath(), "/Photo/12/IMG_12345_999999"); GTEST_LOG_(INFO) << "FileUriTest-end File_uri_GetPath_0000"; } @@ -268,4 +277,33 @@ namespace OHOS::AppFileService::ModuleFileUri { EXPECT_EQ(folderUriObject.GetFullDirectoryUri(), folderDirectoryUri); GTEST_LOG_(INFO) << "FileUriTest-end File_uri_GetPath_0000"; } + + /** + * @tc.name: File_uri_IsRemoteUri_0000 + * @tc.desc: Test function of IsRemoteUri() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: + */ + HWTEST_F(FileUriTest, File_uri_IsRemoteUri_0000, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "FileUriTest-begin File_uri_GetFullDirectoryUri_0000"; + string fileStr = "file://" + BUNDLE_A + "/data/test"; + FileUri fileUriObject(fileStr); + EXPECT_EQ(fileUriObject.IsRemoteUri(), false); + + string fileStr2 = "file://" + BUNDLE_A + "/data/test?networkid="; + FileUri fileUriObject2(fileStr2); + EXPECT_EQ(fileUriObject2.IsRemoteUri(), false); + + string fileStr3 = "file://" + BUNDLE_A + "/data/test?networkid=123456/"; + FileUri fileUriObject3(fileStr3); + EXPECT_EQ(fileUriObject3.IsRemoteUri(), false); + + string fileStr4 = "file://" + BUNDLE_A + "/data/test?networkid=123456"; + FileUri fileUriObject4(fileStr4); + EXPECT_EQ(fileUriObject4.IsRemoteUri(), true); + GTEST_LOG_(INFO) << "FileUriTest-end File_uri_GetPath_0000"; + } } \ No newline at end of file diff --git a/test/unittest/file_uri_ndk_test/file_uri_ndk_test.cpp b/test/unittest/file_uri_ndk_test/file_uri_ndk_test.cpp index 307dfb9f7127aea1c8c1c382686238355bd29106..7344bf7cf1229e86138e678421930c5389b22279 100644 --- a/test/unittest/file_uri_ndk_test/file_uri_ndk_test.cpp +++ b/test/unittest/file_uri_ndk_test/file_uri_ndk_test.cpp @@ -223,6 +223,33 @@ HWTEST_F(NDKFileUriTest, get_path_from_uri_test_006, TestSize.Level1) GTEST_LOG_(INFO) << "get_path_from_uri_test_006 end"; } +/** + * @tc.number: get_path_from_uri_test_007 + * @tc.name: Test function of OH_FileUri_GetPathFromUri() interface for distributed files uri + * @tc.desc: Set uri and get path + * @tc.type: FUNC + */ +HWTEST_F(NDKFileUriTest, get_path_from_uri_test_007, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "get_path_from_uri_test_007 start"; + std::string bundleB = "com.example.fileshareb"; + std::string fileUriStr = "file://" + bundleB + "/data/storage/el2/distributedfiles/.remote_share/"; + fileUriStr += "data/storage/el2/base/haps/entry/files/GetPathFromUri006.txt"; + fileUriStr += "?networkid=64799ecdf70788e396f454ff4a6e6ae4b09e20227c39c21f6e67a2aacbcef7b9"; + const char *fileUri = fileUriStr.c_str(); + char *result = nullptr; + unsigned int length = fileUriStr.size(); + FileManagement_ErrCode ret = OH_FileUri_GetPathFromUri(nullptr, length, &result); + EXPECT_EQ(ret, ERR_PARAMS); + + ret = OH_FileUri_GetPathFromUri(fileUri, length - 1, &result); + EXPECT_EQ(ret, ERR_PARAMS); + + ret = OH_FileUri_GetPathFromUri(fileUri, length, nullptr); + EXPECT_EQ(ret, ERR_PARAMS); + GTEST_LOG_(INFO) << "get_path_from_uri_test_007 end"; +} + /** * @tc.number: get_uri_from_path_test_001 * @tc.name: Test function of OH_FileUri_GetUriFromPath() interface for document uri @@ -246,6 +273,29 @@ HWTEST_F(NDKFileUriTest, get_uri_from_path_test_001, TestSize.Level1) GTEST_LOG_(INFO) << "get_uri_from_path_test_001 end"; } +/** + * @tc.number: get_uri_from_path_test_002 + * @tc.name: Test function of OH_FileUri_GetUriFromPath() interface for document uri + * @tc.desc: Set path and get uri + * @tc.type: FUNC + */ +HWTEST_F(NDKFileUriTest, get_uri_from_path_test_002, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "get_uri_from_path_test_002 start"; + const char filePath[] = "storage/Users/currentUser/Documents/GetPathFromUri001.txt"; + char *result = nullptr; + unsigned int length = strlen(filePath); + FileManagement_ErrCode ret = OH_FileUri_GetUriFromPath(nullptr, length, &result); + EXPECT_EQ(ret, ERR_PARAMS); + + ret = OH_FileUri_GetUriFromPath(filePath, length - 1, &result); + EXPECT_EQ(ret, ERR_PARAMS); + + ret = OH_FileUri_GetUriFromPath(filePath, length, nullptr); + EXPECT_EQ(ret, ERR_PARAMS); + GTEST_LOG_(INFO) << "get_uri_from_path_test_002 end"; +} + /** * @tc.number: get_full_directory_uri_test_001 * @tc.name: Test function of OH_FileUri_GetFullDirectoryUri() interface for unknown path @@ -287,6 +337,30 @@ HWTEST_F(NDKFileUriTest, get_full_directory_uri_test_002, TestSize.Level1) GTEST_LOG_(INFO) << "get_full_directory_uri_test_002 end"; } +/** + * @tc.number: get_full_directory_uri_test_003 + * @tc.name: Test function of OH_FileUri_GetFullDirectoryUri() interface for success + * @tc.desc: Set uri and get full directory uri + * @tc.type: FUNC + */ +HWTEST_F(NDKFileUriTest, get_full_directory_uri_test_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "get_full_directory_uri_test_003 start"; + const char fileUri[] = "file://com.example.filesharea/data/test/file_uri_test.txt"; + char *result = nullptr; + unsigned int length = strlen(fileUri); + FileManagement_ErrCode ret = OH_FileUri_GetFullDirectoryUri(nullptr, length, &result); + EXPECT_EQ(ret, ERR_PARAMS); + + ret = OH_FileUri_GetFullDirectoryUri(fileUri, length - 1, &result); + EXPECT_EQ(ret, ERR_PARAMS); + + ret = OH_FileUri_GetFullDirectoryUri(fileUri, length, nullptr); + EXPECT_EQ(ret, ERR_PARAMS); + FreeResult(&result); + GTEST_LOG_(INFO) << "get_full_directory_uri_test_003 end"; +} + /** * @tc.number: is_valid_uri_test_001 * @tc.name: Test function of OH_FileUri_IsValidUri() interface for real uri @@ -319,4 +393,22 @@ HWTEST_F(NDKFileUriTest, is_valid_uri_test_002, TestSize.Level1) GTEST_LOG_(INFO) << "is_valid_uri_test_002"; } +/** + * @tc.number: is_valid_uri_test_003 + * @tc.name: Test function of OH_FileUri_IsValidUri() interface for unreal uri + * @tc.desc: Set URI and make a judgment + * @tc.type: FUNC + */ +HWTEST_F(NDKFileUriTest, is_valid_uri_test_003, TestSize.Level1) +{ + GTEST_LOG_(INFO) << "is_valid_uri_test_003"; + const char fileUri[] = "com.demo.a/data/storage/el2/base/files/IsValidUriTest002.txt"; + unsigned int length = strlen(fileUri); + bool flags = OH_FileUri_IsValidUri(nullptr, length); + EXPECT_EQ(flags, false); + + flags = OH_FileUri_IsValidUri(fileUri, length - 1); + EXPECT_EQ(flags, false); + GTEST_LOG_(INFO) << "is_valid_uri_test_003"; +} } // namespace OHOS::AppFileService::ModuleFileUri \ No newline at end of file diff --git a/test/unittest/remote_file_share/BUILD.gn b/test/unittest/remote_file_share/BUILD.gn index b3663db5ac0fd3d077dc0c0379f41fdde1984c4f..13ca80d731ae785ee3a156467c9e5a0abb6e8815 100644 --- a/test/unittest/remote_file_share/BUILD.gn +++ b/test/unittest/remote_file_share/BUILD.gn @@ -33,6 +33,7 @@ ohos_unittest("remote_file_share_test") { include_dirs = [ "include", "../../../interfaces/innerkits/native/remote_file_share/include", + "../../../interfaces/innerkits/native/remote_file_share/src", "${utils_system_safwk_path}/native/include", "${path_base}/include", ] @@ -41,4 +42,15 @@ ohos_unittest("remote_file_share_test") { "../../../interfaces/innerkits/native:remote_file_share_native", "//third_party/googletest:gtest_main", ] + + external_deps = [ + "ability_base:zuri", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "hilog:libhilog", + "init:libbegetutil", + "ipc:ipc_core", + "samgr:samgr_proxy", + ] } diff --git a/test/unittest/remote_file_share/remote_file_share_test.cpp b/test/unittest/remote_file_share/remote_file_share_test.cpp index 5559074bae1035d63a2b7826adbf6a67ec37029f..3f9bf5e9acedc3c7cb3e95ee3369d21cc1e6292a 100644 --- a/test/unittest/remote_file_share/remote_file_share_test.cpp +++ b/test/unittest/remote_file_share/remote_file_share_test.cpp @@ -24,6 +24,7 @@ #include #include "remote_file_share.h" +#include "remote_file_share.cpp" namespace { using namespace std; @@ -396,6 +397,74 @@ namespace { GTEST_LOG_(INFO) << "RemoteFileShareTest-end Remote_file_share_GetDfsUriFromLocal_0011"; } + /** + * @tc.name: Remote_file_share_GetDfsUriFromLocal_0012 + * @tc.desc: Test function of GetDfsUriFromLocal() interface for FAILURE. + * the file name is chinese which has been encoded + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I7KDF7 + */ + HWTEST_F(RemoteFileShareTest, Remote_file_share_GetDfsUriFromLocal_0012, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "RemoteFileShareTest-begin Remote_file_share_GetDfsUriFromLocal_0012"; + string uriStr = "datashare://media/Photo/12/IMG_12345_0011/test.jpg"; + const int userId = 100; + + HmdfsUriInfo hui; + auto ret = RemoteFileShare::GetDfsUriFromLocal(uriStr, userId, hui); + EXPECT_EQ(ret, -EINVAL); + + uriStr = "datashare://media/Photo/12/IMG_12345_0011/test.jpg/others"; + ret = RemoteFileShare::GetDfsUriFromLocal(uriStr, userId, hui); + EXPECT_EQ(ret, -EINVAL); + GTEST_LOG_(INFO) << "RemoteFileShareTest-end Remote_file_share_GetDfsUriFromLocal_0012"; + } + + /** + * @tc.name: Remote_file_share_GetDfsUriFromLocal_0013 + * @tc.desc: Test function of GetDfsUriFromLocal() interface for SUCCESS. + * the file name is chinese which has been encoded + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I7KDF7 + */ + HWTEST_F(RemoteFileShareTest, Remote_file_share_GetDfsUriFromLocal_0013, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "RemoteFileShareTest-begin Remote_file_share_GetDfsUriFromLocal_0013"; + const string uriStr = "file://media/Photo/12/IMG_12345_0011/test.jpg"; + const int userId = 100; + + HmdfsUriInfo hui; + auto ret = RemoteFileShare::GetDfsUriFromLocal(uriStr, userId, hui); + EXPECT_NE(ret, 0); + GTEST_LOG_(INFO) << "RemoteFileShareTest-end Remote_file_share_GetDfsUriFromLocal_0013"; + } + + /** + * @tc.name: Remote_file_share_GetDfsUriFromLocal_0014 + * @tc.desc: Test function of GetDfsUriFromLocal() interface for SUCCESS. + * the file name is chinese which has been encoded + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I7KDF7 + */ + HWTEST_F(RemoteFileShareTest, Remote_file_share_GetDfsUriFromLocal_0014, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "RemoteFileShareTest-begin Remote_file_share_GetDfsUriFromLocal_0014"; + const string uriStr = "file://docs/storage/Users/currentUser/Documents/1.txt"; + const int userId = 100; + + HmdfsUriInfo hui; + auto ret = RemoteFileShare::GetDfsUriFromLocal(uriStr, userId, hui); + EXPECT_EQ(ret, E_OK); + EXPECT_EQ(hui.fileSize, 0); + GTEST_LOG_(INFO) << "RemoteFileShareTest-end Remote_file_share_GetDfsUriFromLocal_0014"; + } + /** * @tc.name: remote_file_share_test_0012 * @tc.desc: Test function of TransRemoteUriToLocal() interface for SUCCESS. @@ -502,4 +571,96 @@ namespace { GTEST_LOG_(INFO) << "RemoteFileShareTest-end Remote_file_share_TransRemoteUriToLocal_0015"; } + + /** + * @tc.name: remote_file_share_test_0016 + * @tc.desc: Test function of TransRemoteUriToLocal() interface for FAILURE. + * the inpute param is invalid + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I7KDF7 + */ + HWTEST_F(RemoteFileShareTest, Remote_file_share_TransRemoteUriToLocal_0016, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "RemoteFileShareTest-begin Remote_file_share_TransRemoteUriToLocal_0016"; + const vector uriList = {"FILE://docs/storage/Users/currentUser/Document/1.txt", + "file://docs/storage/Users/currentUser/Download/Subject/2.jpg", + "file://docs/storage/Users/currentUser/Document/Subject1/Subject2/1.txt", + "file://docs/storage/100/account/Document/Subject1/Subject2/1.txt"}; + string networkId = ""; + string deviceId = "001"; + vector resultList; + int ret = RemoteFileShare::TransRemoteUriToLocal(uriList, networkId, deviceId, resultList); + EXPECT_EQ(ret, EINVAL); + + networkId = "100"; + deviceId = ""; + ret = RemoteFileShare::TransRemoteUriToLocal(uriList, networkId, deviceId, resultList); + EXPECT_EQ(ret, EINVAL); + + networkId = ""; + deviceId = ""; + ret = RemoteFileShare::TransRemoteUriToLocal(uriList, networkId, deviceId, resultList); + EXPECT_EQ(ret, EINVAL); + GTEST_LOG_(INFO) << "RemoteFileShareTest-end Remote_file_share_TransRemoteUriToLocal_0016"; + } + + /** + * @tc.name: remote_file_share_test_0017 + * @tc.desc: Test function of TransRemoteUriToLocal() interface for FAILURE. + * the inpute param is invalid + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I7KDF7 + */ + HWTEST_F(RemoteFileShareTest, remote_file_share_test_0017, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "RemoteFileShareTest-begin remote_file_share_test_0017"; + vector uriList = {"file://docs/storage/Users/currentUser/./Document/1.txt"}; + const string networkId = "100"; + const string deviceId = "001"; + vector resultList; + int ret = RemoteFileShare::TransRemoteUriToLocal(uriList, networkId, deviceId, resultList); + EXPECT_NE(ret, EINVAL); + + uriList[0].clear(); + uriList[0] = "datashare://docs/storage/Users/currentUser/Document/1.txt"; + ret = RemoteFileShare::TransRemoteUriToLocal(uriList, networkId, deviceId, resultList); + EXPECT_NE(ret, EINVAL); + + uriList[0].clear(); + uriList[0] = "file://media/Photo/12/IMG_12345_0011/test.jpg"; + ret = RemoteFileShare::TransRemoteUriToLocal(uriList, networkId, deviceId, resultList); + EXPECT_NE(ret, EINVAL); + + uriList[0].clear(); + uriList[0] = "file://docs/test/"; + ret = RemoteFileShare::TransRemoteUriToLocal(uriList, networkId, deviceId, resultList); + EXPECT_NE(ret, EINVAL); + + uriList[0].clear(); + uriList[0] = "file://docs/storage/"; + ret = RemoteFileShare::TransRemoteUriToLocal(uriList, networkId, deviceId, resultList); + EXPECT_NE(ret, EINVAL); + GTEST_LOG_(INFO) << "RemoteFileShareTest-end remote_file_share_test_0017"; + } + + /** + * @tc.name: remote_file_share_test_0000 + * @tc.desc: Test function of RemoteFileShare() interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: SR000H63TL + */ + HWTEST_F(RemoteFileShareTest, Remote_file_share_DeleteShareDir_0000, testing::ext::TestSize.Level1) + { + GTEST_LOG_(INFO) << "RemoteFileShareTest-begin Remote_file_share_DeleteShareDir_0000"; + string packagePath = "/data/filetest"; + string sharePath = "/data/filetest"; + EXPECT_EQ(true, DeleteShareDir(packagePath, sharePath)); + GTEST_LOG_(INFO) << "RemoteFileShareTest-end Remote_file_share_DeleteShareDir_0000"; +} } diff --git a/tests/mock/accesstoken/accesstoken_kit_mock.cpp b/tests/mock/accesstoken/accesstoken_kit_mock.cpp index 1531837704a37124fc2d4f1f7bb08ae806b07081..f2c5795cc147ff1ce70e97cd0ba0b5561a790999 100644 --- a/tests/mock/accesstoken/accesstoken_kit_mock.cpp +++ b/tests/mock/accesstoken/accesstoken_kit_mock.cpp @@ -14,6 +14,7 @@ */ #include "accesstoken_kit.h" +#include "tokenid_kit.h" namespace OHOS::Security::AccessToken { ATokenTypeEnum AccessTokenKit::GetTokenType(AccessTokenID tokenID) @@ -31,4 +32,9 @@ int AccessTokenKit::VerifyAccessToken(AccessTokenID tokenID, const std::string & { return 0; } + +bool TokenIdKit::IsSystemAppByFullTokenID(uint64_t tokenId) +{ + return true; +} } // namespace OHOS::Security::AccessToken diff --git a/tests/mock/file_permission_native_mock/include/file_permission_mock.h b/tests/mock/file_permission_native_mock/include/file_permission_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..19942181585f0a66f16005f1d8c938068170715b --- /dev/null +++ b/tests/mock/file_permission_native_mock/include/file_permission_mock.h @@ -0,0 +1,55 @@ +/* + * 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 FILEMANAGEMENT_FILE_PERMISSION_MOCK_MOCK_H +#define FILEMANAGEMENT_FILE_PERMISSION_MOCK_MOCK_H +#include + +#include "file_permission.h" +namespace OHOS { +namespace AppFileService { +class IFilePermissionMock { +public: + virtual ~IFilePermissionMock() = default; + virtual int32_t PersistPermission(const vector &uriPolicies, + deque &errorResults) = 0; + virtual int32_t RevokePermission(const vector &uriPolicies, + deque &errorResults) = 0; + virtual int32_t ActivatePermission(const vector &uriPolicies, + deque &errorResults) = 0; + virtual int32_t DeactivatePermission(const vector &uriPolicies, + deque &errorResults) = 0; + virtual int32_t CheckPersistentPermission(const vector &uriPolicies, + vector &errorResults) = 0; +public: + static inline std::shared_ptr filePermissionMock = nullptr; +}; + +class FilePermissionMock : public IFilePermissionMock { +public: + MOCK_METHOD2(PersistPermission, + int32_t(const vector &uriPolicies, deque &errorResults)); + MOCK_METHOD2(RevokePermission, int32_t(const vector &uriPolicies, + deque &errorResults)); + MOCK_METHOD2(ActivatePermission, int32_t(const vector &uriPolicies, + deque &errorResults)); + MOCK_METHOD2(DeactivatePermission, int32_t(const vector &uriPolicies, + deque &errorResults)); + MOCK_METHOD2(CheckPersistentPermission, int32_t(const vector &uriPolicies, + vector &errorResults)); +}; +} +} +#endif diff --git a/tests/mock/file_permission_native_mock/src/file_permission_mock.cpp b/tests/mock/file_permission_native_mock/src/file_permission_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f46fb424383137acf99e3c50dc3d8a0c60cf4b7d --- /dev/null +++ b/tests/mock/file_permission_native_mock/src/file_permission_mock.cpp @@ -0,0 +1,65 @@ +/* + * 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 "file_permission_mock.h" + +namespace OHOS { +using namespace AppFileService; +int32_t FilePermission::PersistPermission(const vector &uriPolicies, + deque &errorResults) +{ + if (IFilePermissionMock::filePermissionMock == nullptr) { + return 0; + } + + return IFilePermissionMock::filePermissionMock->PersistPermission(uriPolicies, errorResults); +} + +int32_t FilePermission::RevokePermission(const vector &uriPolicies, + deque &errorResults) +{ + if (IFilePermissionMock::filePermissionMock == nullptr) { + return 0; + } + + return IFilePermissionMock::filePermissionMock->RevokePermission(uriPolicies, errorResults); +} + +int32_t FilePermission::ActivatePermission(const vector &uriPolicies, + deque &errorResults) +{ + if (IFilePermissionMock::filePermissionMock == nullptr) { + return 0; + } + + return IFilePermissionMock::filePermissionMock->ActivatePermission(uriPolicies, errorResults); +} +int32_t FilePermission::DeactivatePermission(const vector &uriPolicies, + deque &errorResults) +{ + if (IFilePermissionMock::filePermissionMock == nullptr) { + return 0; + } + + return IFilePermissionMock::filePermissionMock->DeactivatePermission(uriPolicies, errorResults); +} +int32_t FilePermission::CheckPersistentPermission(const vector &uriPolicies, vector &errorResults) +{ + if (IFilePermissionMock::filePermissionMock == nullptr) { + return 0; + } + + return IFilePermissionMock::filePermissionMock->CheckPersistentPermission(uriPolicies, errorResults); +} +} \ No newline at end of file diff --git a/tests/mock/module_external/bms_adapter_mock.cpp b/tests/mock/module_external/bms_adapter_mock.cpp index cef59d5f1921af0494ce638b98d1fe311cb02154..fd6b866a656d8790dcaea77485a19f553fb75264 100644 --- a/tests/mock/module_external/bms_adapter_mock.cpp +++ b/tests/mock/module_external/bms_adapter_mock.cpp @@ -32,7 +32,8 @@ vector BundleMgrAdapter::GetBundleInfos(const vecto { vector bundleInfos; bundleInfos.emplace_back( - BJsonEntityCaps::BundleInfo {"com.example.app2backup", {}, {}, 0, 0, true, false, "com.example.app2backup"}); + BJsonEntityCaps::BundleInfo {"com.example.app2backup", 0, {}, {}, 0, 0, true, false, + "com.example.app2backup"}); return bundleInfos; } @@ -46,7 +47,8 @@ vector BundleMgrAdapter::GetBundleInfosForIncrement { vector bundleInfos; bundleInfos.emplace_back( - BJsonEntityCaps::BundleInfo {"com.example.app2backup", {}, {}, 0, 0, true, false, "com.example.app2backup"}); + BJsonEntityCaps::BundleInfo {"com.example.app2backup", 0, {}, {}, 0, 0, true, false, + "com.example.app2backup"}); return bundleInfos; } @@ -55,7 +57,8 @@ vector BundleMgrAdapter::GetBundleInfosForIncrement { vector bundleInfos; bundleInfos.emplace_back( - BJsonEntityCaps::BundleInfo {"com.example.app2backup", {}, {}, 0, 0, true, false, "com.example.app2backup"}); + BJsonEntityCaps::BundleInfo {"com.example.app2backup", 0, {}, {}, 0, 0, true, false, + "com.example.app2backup"}); return bundleInfos; } diff --git a/tests/mock/module_ipc/svc_backup_connection_mock.cpp b/tests/mock/module_ipc/svc_backup_connection_mock.cpp index 1d007fa7c4cb0baad931ed09c09b08a3a9a8d477..0af352b4e188d2f89e68547ec3ac03775b6bac0e 100644 --- a/tests/mock/module_ipc/svc_backup_connection_mock.cpp +++ b/tests/mock/module_ipc/svc_backup_connection_mock.cpp @@ -55,6 +55,11 @@ ErrCode SvcBackupConnection::DisconnectBackupExtAbility() return 0; } +bool SvcBackupConnection::WaitDisconnectDone() +{ + return true; +} + bool SvcBackupConnection::IsExtAbilityConnected() { bool bFlag = g_bExtAbilityConnected; diff --git a/tests/mock/module_ipc/svc_extension_proxy_mock.cpp b/tests/mock/module_ipc/svc_extension_proxy_mock.cpp index bd20c461fc5470db4ea6772b7349e89a44991845..c7032836b63a73d090c9cba5f1e3be58bc90421d 100644 --- a/tests/mock/module_ipc/svc_extension_proxy_mock.cpp +++ b/tests/mock/module_ipc/svc_extension_proxy_mock.cpp @@ -28,7 +28,7 @@ ErrCode SvcExtensionProxy::HandleClear() return 0; } -ErrCode SvcExtensionProxy::HandleBackup() +ErrCode SvcExtensionProxy::HandleBackup(bool isClearData) { return 0; } @@ -38,7 +38,7 @@ ErrCode SvcExtensionProxy::PublishFile(const string &fileName) return 0; } -ErrCode SvcExtensionProxy::HandleRestore() +ErrCode SvcExtensionProxy::HandleRestore(bool isClearData) { return 0; } @@ -63,7 +63,7 @@ ErrCode SvcExtensionProxy::HandleIncrementalBackup(UniqueFd incrementalFd, Uniqu return 0; } -ErrCode SvcExtensionProxy::IncrementalOnBackup() +ErrCode SvcExtensionProxy::IncrementalOnBackup(bool isClearData) { return 0; } diff --git a/tests/mock/module_ipc/svc_session_manager_mock.cpp b/tests/mock/module_ipc/svc_session_manager_mock.cpp index 320bdd66cd0b298fe6873337d3f87cbc6899116f..53b97b777bb8e73a97fb4ebefb3839d0b1e679d6 100644 --- a/tests/mock/module_ipc/svc_session_manager_mock.cpp +++ b/tests/mock/module_ipc/svc_session_manager_mock.cpp @@ -104,7 +104,8 @@ wptr SvcSessionManager::GetExtConnection(const BundleName & if (!it->second.backUpConnection) { auto callDied = [](const string &&bundleName) {}; auto callConnected = [](const string &&bundleName) {}; - it->second.backUpConnection = sptr(new SvcBackupConnection(callDied, callConnected)); + it->second.backUpConnection = sptr(new SvcBackupConnection(callDied, callConnected, + bundleName)); sptr mock = sptr(new BackupExtExtensionMock()); it->second.backUpConnection->OnAbilityConnectDone({}, mock->AsObject(), 0); } @@ -114,7 +115,7 @@ wptr SvcSessionManager::GetExtConnection(const BundleName & sptr SvcSessionManager::GetBackupAbilityExt(const string &bundleName) { GTEST_LOG_(INFO) << "GetBackupAbilityExt"; - return sptr(new SvcBackupConnection(nullptr, nullptr)); + return sptr(new SvcBackupConnection(nullptr, nullptr, bundleName)); } void SvcSessionManager::DumpInfo(const int fd, const std::vector &args) @@ -393,6 +394,18 @@ SvcSessionManager::Impl SvcSessionManager::GetImpl() return impl_; } +int SvcSessionManager::GetSessionCnt() +{ + return sessionCnt_.load(); +} + +void SvcSessionManager::SetClearDataFlag(const std::string &bundleName, bool isNotClear) {} + +bool SvcSessionManager::GetClearDataFlag(const std::string &bundleName) +{ + return true; +} + void SvcSessionManager::SetIncrementalData(const BIncrementalData &incrementalData) {} int32_t SvcSessionManager::GetIncrementalManifestFd(const string &bundleName) diff --git a/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp b/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp index 9ba4687b8fa3a87246f3cb89c89a259c7f5dab32..80acd08fcab61190243b8bcf8b9ca84c17845f1a 100644 --- a/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp +++ b/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp @@ -275,6 +275,21 @@ SvcSessionManager::Impl SvcSessionManager::GetImpl() return BackupSvcSessionManager::session->GetImpl(); } +int SvcSessionManager::GetSessionCnt() +{ + return BackupSvcSessionManager::session->GetSessionCnt(); +} + +void SvcSessionManager::SetClearDataFlag(const std::string &bundleName, bool isNotClear) +{ + BackupSvcSessionManager::session->SetClearDataFlag(bundleName, isNotClear); +} + +bool SvcSessionManager::GetClearDataFlag(const std::string &bundleName) +{ + return BackupSvcSessionManager::session->GetClearDataFlag(bundleName); +} + void SvcSessionManager::SetIncrementalData(const BIncrementalData &incrementalData) { BackupSvcSessionManager::session->SetIncrementalData(incrementalData); diff --git a/tests/mock/module_ipc/svc_session_manager_throw_mock.h b/tests/mock/module_ipc/svc_session_manager_throw_mock.h index 670bef53b5a5f69288fc3c03c021f0c6e0b716a3..f00d6e93d4d97c69f78c75855a6aa1151799b0f8 100644 --- a/tests/mock/module_ipc/svc_session_manager_throw_mock.h +++ b/tests/mock/module_ipc/svc_session_manager_throw_mock.h @@ -78,6 +78,9 @@ public: virtual bool GetIsIncrementalBackup() = 0; virtual bool ValidRestoreDataType(RestoreTypeEnum) = 0; virtual SvcSessionManager::Impl GetImpl() = 0; + virtual int GetSessionCnt() = 0; + virtual void SetClearDataFlag(const std::string &bundleName, bool isNotClear) = 0; + virtual bool GetClearDataFlag(const std::string &bundleName) = 0; virtual void SetIncrementalData(const BIncrementalData &) = 0; virtual int32_t GetIncrementalManifestFd(const std::string &) = 0; virtual int64_t GetLastIncrementalTime(const std::string &) = 0; @@ -138,6 +141,9 @@ public: MOCK_METHOD(bool, GetIsIncrementalBackup, ()); MOCK_METHOD(bool, ValidRestoreDataType, (RestoreTypeEnum)); MOCK_METHOD(SvcSessionManager::Impl, GetImpl, ()); + MOCK_METHOD(int, GetSessionCnt, ()); + MOCK_METHOD(void, SetClearDataFlag, (const std::string &, bool)); + MOCK_METHOD(bool, GetClearDataFlag, (const std::string &)); MOCK_METHOD(void, SetIncrementalData, (const BIncrementalData &)); MOCK_METHOD(int32_t, GetIncrementalManifestFd, (const std::string &)); MOCK_METHOD(int64_t, GetLastIncrementalTime, (const std::string &)); diff --git a/tests/mock/napi/include/napi_mock.h b/tests/mock/napi/include/napi_mock.h index bc699b791d8ba1548bcf6abc11f318245c9546d1..5f70f4f022c00af96c55e54410330bc2f22a0541 100644 --- a/tests/mock/napi/include/napi_mock.h +++ b/tests/mock/napi/include/napi_mock.h @@ -60,6 +60,7 @@ public: virtual napi_status napi_create_function(napi_env, const char*, size_t, napi_callback, void*, napi_value*) = 0; virtual napi_status napi_open_handle_scope(napi_env, napi_handle_scope*) = 0; virtual napi_status napi_close_handle_scope(napi_env, napi_handle_scope) = 0; + virtual napi_status napi_is_exception_pending(napi_env, bool*) = 0; public: static inline std::shared_ptr napi = nullptr; }; @@ -96,6 +97,7 @@ public: MOCK_METHOD6(napi_create_function, napi_status(napi_env, const char*, size_t, napi_callback, void*, napi_value*)); MOCK_METHOD2(napi_open_handle_scope, napi_status(napi_env, napi_handle_scope*)); MOCK_METHOD2(napi_close_handle_scope, napi_status(napi_env, napi_handle_scope)); + MOCK_METHOD2(napi_is_exception_pending, napi_status(napi_env, bool*)); }; } // namespace OHOS::FileManagement::Backup #endif // TEST_UNITTEST_MOCK_NAPI_H \ No newline at end of file diff --git a/tests/mock/napi/src/napi_mock.cpp b/tests/mock/napi/src/napi_mock.cpp index 0310429d36660f0c13e192b167aa541ec70dd138..5b672ce665a256f232ce8cfa4b2bb3360c68aa84 100644 --- a/tests/mock/napi/src/napi_mock.cpp +++ b/tests/mock/napi/src/napi_mock.cpp @@ -18,12 +18,6 @@ int uv_queue_work(uv_loop_t* loop, uv_work_t* req, uv_work_cb work_cb, uv_after_work_cb after_work_cb) { - if (work_cb) { - work_cb(req); - } - if (after_work_cb) { - after_work_cb(req, 0); - } return OHOS::FileManagement::Backup::Napi::napi->uv_queue_work(loop, req, work_cb, after_work_cb); } @@ -163,4 +157,9 @@ NAPI_EXTERN napi_status napi_open_handle_scope(napi_env env, napi_handle_scope* NAPI_EXTERN napi_status napi_close_handle_scope(napi_env env, napi_handle_scope scope) { return OHOS::FileManagement::Backup::Napi::napi->napi_close_handle_scope(env, scope); +} + +napi_status napi_is_exception_pending(napi_env env, bool* result) +{ + return OHOS::FileManagement::Backup::Napi::napi->napi_is_exception_pending(env, result); } \ No newline at end of file diff --git a/tests/mock/parameter_mock/include/parameter_mock.h b/tests/mock/parameter_mock/include/parameter_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..76136ae9aad7c03d9ec10561c3875c6d690732ab --- /dev/null +++ b/tests/mock/parameter_mock/include/parameter_mock.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2022-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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MOCK_OHOS_MOCK_PARAMETER_H +#define MOCK_OHOS_MOCK_PARAMETER_H + +#include +#include + +namespace OHOS { +namespace AppFileService { +class IParamMoc { +public: + virtual ~IParamMoc() = default; +public: + virtual int GetParameter(const char *key, const char *def, char *value, uint32_t len) = 0; +public: + static inline std::shared_ptr paramMoc = nullptr; +}; + +class ParamMoc : public IParamMoc { +public: + MOCK_METHOD4(GetParameter, int(const char *key, const char *def, char *value, uint32_t len)); +}; +} +} +#endif \ No newline at end of file diff --git a/tests/mock/parameter_mock/src/parameter_mock.cpp b/tests/mock/parameter_mock/src/parameter_mock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..106ce53d8c2f0a0ea52a627967039167a6930562 --- /dev/null +++ b/tests/mock/parameter_mock/src/parameter_mock.cpp @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2022-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 + * + * 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 "parameter_mock.h" + +#include "parameter.h" + +using namespace OHOS::AppFileService; +int GetParameter(const char *key, const char *def, char *value, uint32_t len) +{ + if (IParamMoc::paramMoc == nullptr) { + return -1; + } + return IParamMoc::paramMoc->GetParameter(key, def, value, len); +} \ No newline at end of file diff --git a/tests/unittests/backup_api/backup_impl/include/ext_extension_mock.h b/tests/unittests/backup_api/backup_impl/include/ext_extension_mock.h index 7484d1b8c64bf208e376adaf37dc8998a8fc84fc..6ff7362e0797b6fb22c1bce3680df5dcefc93ee5 100644 --- a/tests/unittests/backup_api/backup_impl/include/ext_extension_mock.h +++ b/tests/unittests/backup_api/backup_impl/include/ext_extension_mock.h @@ -79,7 +79,7 @@ public: return BError(BError::Codes::OK); }; - ErrCode HandleBackup() override + ErrCode HandleBackup(bool isClearData) override { GTEST_LOG_(INFO) << "HandleBackup"; if (nHandleBackupNum_ == 1) { @@ -99,7 +99,7 @@ public: return BError(BError::Codes::OK); }; - ErrCode HandleRestore() override + ErrCode HandleRestore(bool isClearData) override { return BError(BError::Codes::OK); }; @@ -119,7 +119,7 @@ public: return BError(BError::Codes::OK); }; - ErrCode IncrementalOnBackup() override + ErrCode IncrementalOnBackup(bool isClearData) override { return BError(BError::Codes::OK); }; diff --git a/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp b/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp index f95584e61d204e60609cb74b85bad115a9010f73..b93201d1a174305efb3e8dab2f13d7d59b02407a 100644 --- a/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp +++ b/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp @@ -271,6 +271,36 @@ HWTEST_F(ServiceProxyTest, SUB_Service_proxy_AppDone_0100, testing::ext::TestSiz GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_AppDone_0100"; } +/** + * @tc.number: SUB_Service_proxy_ServiceResultReport_0100 + * @tc.name: SUB_Service_proxy_ServiceResultReport_0100 + * @tc.desc: 测试 ServiceResultReport + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceProxyTest, SUB_Service_proxy_ServiceResultReport_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_ServiceResultReport_0100"; + if (proxy_ == nullptr) { + GTEST_LOG_(INFO) << "SUB_Service_proxy_ServiceResultReport_0100 proxy_ == nullptr"; + return; + } + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) + .Times(2) + .WillOnce(Invoke(mock_.GetRefPtr(), &IServiceMock::InvokeSendRequest)) + .WillOnce(Return(EPERM)); + std::string restoreRetInfo = "test_restoreRetInfo"; + BackupRestoreScenario scenario = FULL_BACKUP; + int32_t result = proxy_->ServiceResultReport(restoreRetInfo, scenario, BError(BError::Codes::OK)); + EXPECT_EQ(result, BError(BError::Codes::OK)); + + result = proxy_->ServiceResultReport(restoreRetInfo, scenario, BError(BError::Codes::OK)); + EXPECT_NE(result, BError(BError::Codes::OK)); + GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_ServiceResultReport_0100"; +} + /** * @tc.number: SUB_Service_proxy_GetFileHandle_0100 * @tc.name: SUB_Service_proxy_GetFileHandle_0100 @@ -394,6 +424,38 @@ HWTEST_F(ServiceProxyTest, SUB_Service_proxy_AppendBundlesBackupSession_0100, te GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_AppendBundlesBackupSession_0100"; } +/** + * @tc.number: SUB_Service_proxy_AppendBundlesDetailsBackupSession_0100 + * @tc.name: SUB_Service_proxy_AppendBundlesDetailsBackupSession_0100 + * @tc.desc: 测试 AppendBundlesDetailsBackupSession + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6URNZ + */ +HWTEST_F(ServiceProxyTest, SUB_Service_proxy_AppendBundlesDetailsBackupSession_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_AppendBundlesDetailsBackupSession_0100"; + if (proxy_ == nullptr) { + GTEST_LOG_(INFO) << "SUB_Service_proxy_AppendBundlesDetailsBackupSession_0100 proxy_ == nullptr"; + return; + } + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) + .Times(2) + .WillOnce(Invoke(mock_.GetRefPtr(), &IServiceMock::InvokeSendRequest)) + .WillOnce(Return(EPERM)); + + std::vector bundleNames; + std::vector detailInfos; + + int32_t result = proxy_->AppendBundlesDetailsBackupSession(bundleNames, detailInfos); + EXPECT_EQ(result, BError(BError::Codes::OK)); + + result = proxy_->AppendBundlesDetailsBackupSession(bundleNames, detailInfos); + EXPECT_NE(result, BError(BError::Codes::OK)); + GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_AppendBundlesDetailsBackupSession_0100"; +} + /** * @tc.number: SUB_Service_proxy_Finish_0100 * @tc.name: SUB_Service_proxy_Finish_0100 diff --git a/tests/unittests/backup_ext/BUILD.gn b/tests/unittests/backup_ext/BUILD.gn index 7ab377141aaaf2f03300b45dd6d8184fb8552e5b..5b41aab979c26d6053ae1b78fd8e796d0c6ff287 100644 --- a/tests/unittests/backup_ext/BUILD.gn +++ b/tests/unittests/backup_ext/BUILD.gn @@ -325,12 +325,13 @@ ohos_unittest("ext_backup_js_test") { group("backup_ext_test") { testonly = true - - deps = [ - ":ext_backup_js_test", - ":ext_extension_stub_test", - ":ext_extension_test", - ":tar_file_test", - ":untar_file_test", - ] + if (!use_libfuzzer) { + deps = [ + ":ext_backup_js_test", + ":ext_extension_stub_test", + ":ext_extension_test", + ":tar_file_test", + ":untar_file_test", + ] + } } diff --git a/tests/unittests/backup_ext/ext_backup_js_test.cpp b/tests/unittests/backup_ext/ext_backup_js_test.cpp index 4e23ad233323ae150ed7387390ff2538d3fb61ef..bb76737d11f36ed9a40bdb84aad8368617338f84 100644 --- a/tests/unittests/backup_ext/ext_backup_js_test.cpp +++ b/tests/unittests/backup_ext/ext_backup_js_test.cpp @@ -38,6 +38,7 @@ namespace OHOS::FileManagement::Backup { using namespace std; using namespace testing; +const int ARG_INDEX_FIRST = 1; const int ARG_INDEX_SECOND = 2; const int ARG_INDEX_FOURTH = 4; const int ARG_INDEX_FIFTH = 5; @@ -782,11 +783,18 @@ HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_ExportJsContext_0100, testing::ext:: extBackupJs->ExportJsContext(); EXPECT_TRUE(extBackupJs->jsObj_ == nullptr); + extBackupJs->jsObj_ = make_unique(); + auto refMock = static_cast(extBackupJs->jsObj_.get()); EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); - extBackupJs->jsObj_ = unique_ptr(); + EXPECT_CALL(*refMock, GetNapiValue()).WillOnce(Return(nullptr)); extBackupJs->ExportJsContext(); - EXPECT_TRUE(true); - extBackupJs->jsObj_ = nullptr; + EXPECT_TRUE(extBackupJs->jsObj_ != nullptr); + + int value = 0; + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*refMock, GetNapiValue()).WillOnce(Return(reinterpret_cast(&value))); + extBackupJs->ExportJsContext(); + EXPECT_TRUE(extBackupJs->jsObj_ != nullptr); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by ExportJsContext."; @@ -812,16 +820,18 @@ HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_CallJsMethod_0100, testing::ext::Tes auto ret = extBackupJs->CallJsMethod("", *jsRuntime, nullptr, nullptr, nullptr); EXPECT_EQ(ret, EINVAL); - EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)).WillOnce(Return(nullptr)); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(Return(1)); - EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce(Return(napi_ok)); ret = extBackupJs->CallJsMethod("", *jsRuntime, nullptr, nullptr, nullptr); EXPECT_EQ(ret, EINVAL); EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)).WillOnce(Return(nullptr)); EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); - EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(Return(0)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(DoAll(WithArgs<1, 3>(Invoke( + [](uv_work_t* req, uv_after_work_cb after_work_cb) { + after_work_cb(req, 0); + })), Return(0))); EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce(Return(napi_ok)); ret = extBackupJs->CallJsMethod("", *jsRuntime, nullptr, nullptr, nullptr); EXPECT_EQ(ret, ERR_OK); @@ -831,4 +841,594 @@ HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_CallJsMethod_0100, testing::ext::Tes } GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_CallJsMethod_0100"; } + +/** + * @tc.number: SUB_backup_ext_js_DoCallJsMethod_0100 + * @tc.name: SUB_backup_ext_js_DoCallJsMethod_0100 + * @tc.desc: 测试 DoCallJsMethod 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_DoCallJsMethod_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_DoCallJsMethod_0100"; + try { + string funcName = ""; + InputArgsParser argParserIn = {}; + ResultValueParser retParserIn = {}; + auto param = make_shared(funcName, nullptr, nullptr, argParserIn, retParserIn); + auto ret = DoCallJsMethod(param.get()); + EXPECT_EQ(ret, EINVAL); + + param->jsRuntime = jsRuntime.get(); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce(Return(napi_ok)); + ret = DoCallJsMethod(param.get()); + EXPECT_EQ(ret, EINVAL); + + int scope = 0; + param->argParser = [](napi_env, std::vector &){ return false; }; + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce( + DoAll(SetArgPointee(reinterpret_cast(&scope)), Return(napi_ok))); + EXPECT_CALL(*napiMock, napi_close_handle_scope(_, _)).WillOnce(Return(napi_ok)); + ret = DoCallJsMethod(param.get()); + EXPECT_EQ(ret, EINVAL); + + auto ref = make_shared(); + param->argParser = [](napi_env, std::vector &){ return true; }; + param->jsObj = ref.get(); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce( + DoAll(SetArgPointee(reinterpret_cast(&scope)), Return(napi_ok))); + EXPECT_CALL(*ref, GetNapiValue()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_close_handle_scope(_, _)).WillOnce(Return(napi_ok)); + ret = DoCallJsMethod(param.get()); + EXPECT_EQ(ret, EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by DoCallJsMethod."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_DoCallJsMethod_0100"; +} + +/** + * @tc.number: SUB_backup_ext_js_DoCallJsMethod_0200 + * @tc.name: SUB_backup_ext_js_DoCallJsMethod_0200 + * @tc.desc: 测试 DoCallJsMethod 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_DoCallJsMethod_0200, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_DoCallJsMethod_0200"; + try { + string funcName = ""; + InputArgsParser argParserIn = {}; + ResultValueParser retParserIn = {}; + auto param = make_shared(funcName, nullptr, nullptr, argParserIn, retParserIn); + auto ref = make_shared(); + param->argParser = nullptr; + param->retParser = nullptr; + param->jsObj = ref.get(); + + int scope = 0; + napi_value value = nullptr; + param->jsRuntime = jsRuntime.get(); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce( + DoAll(SetArgPointee(reinterpret_cast(&scope)), Return(napi_ok))); + EXPECT_CALL(*ref, GetNapiValue()).WillOnce(Return(reinterpret_cast(&value))); + EXPECT_CALL(*napiMock, napi_get_named_property(_, _, _, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, napi_close_handle_scope(_, _)).WillOnce(Return(napi_ok)); + auto ret = DoCallJsMethod(param.get()); + EXPECT_EQ(ret, EINVAL); + + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce( + DoAll(SetArgPointee(reinterpret_cast(&scope)), Return(napi_ok))); + EXPECT_CALL(*ref, GetNapiValue()).WillOnce(Return(reinterpret_cast(&value))); + EXPECT_CALL(*napiMock, napi_get_named_property(_, _, _, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_close_handle_scope(_, _)).WillOnce(Return(napi_ok)); + ret = DoCallJsMethod(param.get()); + EXPECT_EQ(ret, EINVAL); + + param->retParser = [](napi_env, napi_value){ return false; }; + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce( + DoAll(SetArgPointee(reinterpret_cast(&scope)), Return(napi_ok))); + EXPECT_CALL(*ref, GetNapiValue()).WillOnce(Return(reinterpret_cast(&value))); + EXPECT_CALL(*napiMock, napi_get_named_property(_, _, _, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_call_function(_, _, _, _, _, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_escape_handle(_, _, _, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_close_handle_scope(_, _)).WillOnce(Return(napi_ok)); + ret = DoCallJsMethod(param.get()); + EXPECT_EQ(ret, EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by DoCallJsMethod."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_DoCallJsMethod_0200"; +} + +/** + * @tc.number: SUB_backup_ext_js_DoCallJsMethod_0300 + * @tc.name: SUB_backup_ext_js_DoCallJsMethod_0300 + * @tc.desc: 测试 DoCallJsMethod 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_DoCallJsMethod_0300, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_DoCallJsMethod_0300"; + try { + string funcName = ""; + InputArgsParser argParserIn = {}; + ResultValueParser retParserIn = {}; + auto param = make_shared(funcName, nullptr, nullptr, argParserIn, retParserIn); + auto ref = make_shared(); + param->argParser = nullptr; + param->retParser = nullptr; + param->jsObj = ref.get(); + + int scope = 0; + napi_value value = nullptr; + param->jsRuntime = jsRuntime.get(); + param->retParser = [](napi_env, napi_value){ return true; }; + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce( + DoAll(SetArgPointee(reinterpret_cast(&scope)), Return(napi_ok))); + EXPECT_CALL(*ref, GetNapiValue()).WillOnce(Return(reinterpret_cast(&value))); + EXPECT_CALL(*napiMock, napi_get_named_property(_, _, _, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_call_function(_, _, _, _, _, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_escape_handle(_, _, _, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_close_handle_scope(_, _)).WillOnce(Return(napi_ok)); + auto ret = DoCallJsMethod(param.get()); + EXPECT_EQ(ret, ERR_OK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by DoCallJsMethod."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_DoCallJsMethod_0300"; +} + +/** + * @tc.number: SUB_backup_ext_js_InvokeAppExtMethod_0100 + * @tc.name: SUB_backup_ext_js_InvokeAppExtMethod_0100 + * @tc.desc: 测试 InvokeAppExtMethod 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_InvokeAppExtMethod_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_InvokeAppExtMethod_0100"; + try { + ErrCode errCode = BError(BError::Codes::OK); + string result = ""; + auto ret = extBackupJs->InvokeAppExtMethod(errCode, result); + EXPECT_EQ(ret, ERR_OK); + + result = "test"; + ret = extBackupJs->InvokeAppExtMethod(errCode, result); + EXPECT_EQ(ret, ERR_OK); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by InvokeAppExtMethod."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_InvokeAppExtMethod_0100"; +} + +/** + * @tc.number: SUB_backup_ext_js_CallJsOnBackupEx_0100 + * @tc.name: SUB_backup_ext_js_CallJsOnBackupEx_0100 + * @tc.desc: 测试 CallJsOnBackupEx 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_CallJsOnBackupEx_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_CallJsOnBackupEx_0100"; + try { + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_invalid_arg)); + auto ret = extBackupJs->CallJsOnBackupEx(); + EXPECT_EQ(ret, EINVAL); + + extBackupJs->callbackInfoEx_ = std::make_shared([](ErrCode, std::string){}); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_exception_pending(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_get_value_string_utf8(_, _, _, _, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, nullptr); + return -1; + }))); + ret = extBackupJs->CallJsOnBackupEx(); + EXPECT_EQ(ret, EINVAL); + + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_exception_pending(_, _)) + .WillOnce(DoAll(SetArgPointee(true), Return(napi_ok))); + EXPECT_CALL(*napiMock, napi_get_and_clear_last_exception(_, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, nullptr); + return -1; + }))); + ret = extBackupJs->CallJsOnBackupEx(); + EXPECT_EQ(ret, EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by CallJsOnBackupEx."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_CallJsOnBackupEx_0100"; +} + +/** + * @tc.number: SUB_backup_ext_js_CallJsOnBackupEx_0200 + * @tc.name: SUB_backup_ext_js_CallJsOnBackupEx_0200 + * @tc.desc: 测试 CallJsOnBackupEx 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_CallJsOnBackupEx_0200, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_CallJsOnBackupEx_0200"; + try { + extBackupJs->callbackInfoEx_ = std::make_shared([](ErrCode, std::string){}); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_promise(_, _, _)) + .WillOnce(DoAll(SetArgPointee(true), Return(napi_ok))); + EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_close_handle_scope(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_get_named_property(_, _, _, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + int value = 0; + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, reinterpret_cast(&value)); + return -1; + }))); + auto ret = extBackupJs->CallJsOnBackupEx(); + EXPECT_EQ(ret, EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by CallJsOnBackupEx."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_CallJsOnBackupEx_0200"; +} + +/** + * @tc.number: SUB_backup_ext_js_CallJsOnBackup_0100 + * @tc.name: SUB_backup_ext_js_CallJsOnBackup_0100 + * @tc.desc: 测试 CallJsOnBackup 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_CallJsOnBackup_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_CallJsOnBackup_0100"; + try { + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_invalid_arg)); + auto ret = extBackupJs->CallJsOnBackup(); + EXPECT_EQ(ret, EINVAL); + + extBackupJs->callbackInfo_ = std::make_shared([](ErrCode, std::string){}); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_exception_pending(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, nullptr); + return -1; + }))); + ret = extBackupJs->CallJsOnBackup(); + EXPECT_EQ(ret, EINVAL); + + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_exception_pending(_, _)) + .WillOnce(DoAll(SetArgPointee(true), Return(napi_ok))); + EXPECT_CALL(*napiMock, napi_get_and_clear_last_exception(_, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, nullptr); + return -1; + }))); + ret = extBackupJs->CallJsOnBackup(); + EXPECT_EQ(ret, EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by CallJsOnBackup."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_CallJsOnBackup_0100"; +} + +/** + * @tc.number: SUB_backup_ext_js_CallJsOnBackup_0200 + * @tc.name: SUB_backup_ext_js_CallJsOnBackup_0200 + * @tc.desc: 测试 CallJsOnBackup 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_CallJsOnBackup_0200, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_CallJsOnBackup_0200"; + try { + extBackupJs->callbackInfo_ = std::make_shared([](ErrCode, std::string){}); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_promise(_, _, _)) + .WillOnce(DoAll(SetArgPointee(true), Return(napi_ok))); + EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_close_handle_scope(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_get_named_property(_, _, _, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + int value = 0; + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, reinterpret_cast(&value)); + return -1; + }))); + auto ret = extBackupJs->CallJsOnBackup(); + EXPECT_EQ(ret, EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by CallJsOnBackup."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_CallJsOnBackup_0200"; +} + +/** + * @tc.number: SUB_backup_ext_js_CallJSRestoreEx_0100 + * @tc.name: SUB_backup_ext_js_CallJSRestoreEx_0100 + * @tc.desc: 测试 CallJSRestoreEx 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_CallJSRestoreEx_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_CallJSRestoreEx_0100"; + try { + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_invalid_arg)); + auto ret = extBackupJs->CallJSRestoreEx(); + EXPECT_EQ(ret, EINVAL); + + extBackupJs->callbackInfoEx_ = std::make_shared([](ErrCode, std::string){}); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_exception_pending(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_get_value_string_utf8(_, _, _, _, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, nullptr); + return -1; + }))); + ret = extBackupJs->CallJSRestoreEx(); + EXPECT_EQ(ret, EINVAL); + + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_exception_pending(_, _)) + .WillOnce(DoAll(SetArgPointee(true), Return(napi_ok))); + EXPECT_CALL(*napiMock, napi_get_and_clear_last_exception(_, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, nullptr); + return -1; + }))); + ret = extBackupJs->CallJSRestoreEx(); + EXPECT_EQ(ret, EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by CallJSRestoreEx."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_CallJSRestoreEx_0100"; +} + +/** + * @tc.number: SUB_backup_ext_js_CallJSRestoreEx_0200 + * @tc.name: SUB_backup_ext_js_CallJSRestoreEx_0200 + * @tc.desc: 测试 CallJSRestoreEx 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_CallJSRestoreEx_0200, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_CallJSRestoreEx_0200"; + try { + extBackupJs->callbackInfoEx_ = std::make_shared([](ErrCode, std::string){}); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_promise(_, _, _)) + .WillOnce(DoAll(SetArgPointee(true), Return(napi_ok))); + EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_close_handle_scope(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_get_named_property(_, _, _, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + int value = 0; + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, reinterpret_cast(&value)); + return -1; + }))); + auto ret = extBackupJs->CallJSRestoreEx(); + EXPECT_EQ(ret, EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by CallJSRestoreEx."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_CallJSRestoreEx_0200"; +} + +/** + * @tc.number: SUB_backup_ext_js_CallJSRestore_0100 + * @tc.name: SUB_backup_ext_js_CallJSRestore_0100 + * @tc.desc: 测试 CallJSRestore 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_CallJSRestore_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_CallJSRestore_0100"; + try { + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_invalid_arg)); + auto ret = extBackupJs->CallJSRestore(); + EXPECT_EQ(ret, EINVAL); + + extBackupJs->callbackInfo_ = std::make_shared([](ErrCode, std::string){}); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_exception_pending(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, nullptr); + return -1; + }))); + ret = extBackupJs->CallJSRestore(); + EXPECT_EQ(ret, EINVAL); + + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_exception_pending(_, _)) + .WillOnce(DoAll(SetArgPointee(true), Return(napi_ok))); + EXPECT_CALL(*napiMock, napi_get_and_clear_last_exception(_, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, nullptr); + return -1; + }))); + ret = extBackupJs->CallJSRestore(); + EXPECT_EQ(ret, EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by CallJSRestore."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_CallJSRestore_0100"; +} + +/** + * @tc.number: SUB_backup_ext_js_CallJSRestore_0200 + * @tc.name: SUB_backup_ext_js_CallJSRestore_0200 + * @tc.desc: 测试 CallJSRestore 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_CallJSRestore_0200, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_CallJSRestore_0200"; + try { + extBackupJs->callbackInfo_ = std::make_shared([](ErrCode, std::string){}); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_promise(_, _, _)) + .WillOnce(DoAll(SetArgPointee(true), Return(napi_ok))); + EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_close_handle_scope(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_get_named_property(_, _, _, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + int value = 0; + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, reinterpret_cast(&value)); + return -1; + }))); + auto ret = extBackupJs->CallJSRestore(); + EXPECT_EQ(ret, EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by CallJSRestore."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_CallJSRestore_0200"; +} + +/** + * @tc.number: SUB_backup_ext_js_GetBackupInfo_0100 + * @tc.name: SUB_backup_ext_js_GetBackupInfo_0100 + * @tc.desc: 测试 GetBackupInfo 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesIAFBOS + */ +HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_GetBackupInfo_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtBackupJsTest-begin SUB_backup_ext_js_GetBackupInfo_0100"; + try { + extBackupJs->jsObj_ = make_unique(); + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_invalid_arg)); + auto ret = extBackupJs->GetBackupInfo([](ErrCode, std::string){}); + EXPECT_EQ(ret, EINVAL); + + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_get_value_string_utf8(_, _, _, _, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, nullptr); + return -1; + }))); + ret = extBackupJs->GetBackupInfo([](ErrCode, std::string){}); + EXPECT_EQ(ret, EINVAL); + + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_get_value_string_utf8(_, _, _, _, _)).WillOnce(Return(napi_ok)) + .WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, nullptr); + return -1; + }))); + ret = extBackupJs->GetBackupInfo([](ErrCode, std::string){}); + EXPECT_EQ(ret, EINVAL); + + EXPECT_CALL(*extBackupMock, GetNapiEnv()).WillOnce(Return(nullptr)).WillOnce(Return(nullptr)); + EXPECT_CALL(*napiMock, napi_get_uv_event_loop(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_is_promise(_, _, _)) + .WillOnce(DoAll(SetArgPointee(true), Return(napi_ok))); + EXPECT_CALL(*napiMock, napi_open_handle_scope(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_close_handle_scope(_, _)).WillOnce(Return(napi_ok)); + EXPECT_CALL(*napiMock, napi_get_named_property(_, _, _, _)).WillOnce(Return(napi_invalid_arg)); + EXPECT_CALL(*napiMock, uv_queue_work(_, _, _, _)).WillOnce(WithArgs<1>(Invoke([](uv_work_t* work) { + int value = 0; + CallJsParam *param = reinterpret_cast(work->data); + param->retParser(nullptr, reinterpret_cast(&value)); + return -1; + }))); + ret = extBackupJs->GetBackupInfo([](ErrCode, std::string){}); + EXPECT_EQ(ret, EINVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtBackupJsTest-an exception occurred by GetBackupInfo."; + } + GTEST_LOG_(INFO) << "ExtBackupJsTest-end SUB_backup_ext_js_GetBackupInfo_0200"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_ext/ext_extension_stub_test.cpp b/tests/unittests/backup_ext/ext_extension_stub_test.cpp index 413212265d6d6ff246ebc15e8eb3b9e4c1ee673a..ba73c7db635f495a3bc2f6c9f07ed3762939bf11 100644 --- a/tests/unittests/backup_ext/ext_extension_stub_test.cpp +++ b/tests/unittests/backup_ext/ext_extension_stub_test.cpp @@ -28,13 +28,13 @@ class ExtExtensionStubMock : public ExtExtensionStub { public: MOCK_METHOD(UniqueFd, GetFileHandle, (const std::string &fileName, int32_t &errCode)); MOCK_METHOD(ErrCode, HandleClear, ()); - MOCK_METHOD(ErrCode, HandleBackup, ()); + MOCK_METHOD(ErrCode, HandleBackup, (bool isClearData)); MOCK_METHOD(ErrCode, PublishFile, (const std::string &fileName)); - MOCK_METHOD(ErrCode, HandleRestore, ()); + MOCK_METHOD(ErrCode, HandleRestore, (bool isClearData)); MOCK_METHOD(ErrCode, GetIncrementalFileHandle, (const std::string &fileName)); MOCK_METHOD(ErrCode, PublishIncrementalFile, (const std::string &fileName)); MOCK_METHOD(ErrCode, HandleIncrementalBackup, (UniqueFd incrementalFd, UniqueFd manifestFd)); - MOCK_METHOD(ErrCode, IncrementalOnBackup, ()); + MOCK_METHOD(ErrCode, IncrementalOnBackup, (bool isClearData)); MOCK_METHOD((std::tuple), GetIncrementalBackupFileHandle, ()); MOCK_METHOD(ErrCode, GetBackupInfo, (std::string &result)); MOCK_METHOD(ErrCode, UpdateFdSendRate, (std::string &bundleName, int32_t sendRate)); @@ -201,13 +201,13 @@ HWTEST_F(ExtExtensionStubTest, SUB_backup_ext_ExtExtensionStub_CmdHandleBackup_0 try { MessageParcel data; MessageParcel reply; - EXPECT_CALL(*stub, HandleBackup()).WillOnce(Return(0)); + EXPECT_CALL(*stub, HandleBackup(_)).WillOnce(Return(0)); EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(false)); EXPECT_TRUE(stub != nullptr); auto err = stub->CmdHandleBackup(data, reply); EXPECT_EQ(err, BError(BError::Codes::EXT_BROKEN_IPC)); - EXPECT_CALL(*stub, HandleBackup()).WillOnce(Return(0)); + EXPECT_CALL(*stub, HandleBackup(_)).WillOnce(Return(0)); EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(true)); err = stub->CmdHandleBackup(data, reply); EXPECT_EQ(err, BError(BError::Codes::OK)); @@ -271,13 +271,13 @@ HWTEST_F(ExtExtensionStubTest, SUB_backup_ext_ExtExtensionStub_CmdHandleRestore_ try { MessageParcel data; MessageParcel reply; - EXPECT_CALL(*stub, HandleRestore()).WillOnce(Return(0)); + EXPECT_CALL(*stub, HandleRestore(_)).WillOnce(Return(0)); EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(false)); EXPECT_TRUE(stub != nullptr); auto err = stub->CmdHandleRestore(data, reply); EXPECT_EQ(err, BError(BError::Codes::EXT_BROKEN_IPC)); - EXPECT_CALL(*stub, HandleRestore()).WillOnce(Return(0)); + EXPECT_CALL(*stub, HandleRestore(_)).WillOnce(Return(0)); EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(true)); err = stub->CmdHandleRestore(data, reply); EXPECT_EQ(err, BError(BError::Codes::OK)); @@ -417,13 +417,13 @@ HWTEST_F(ExtExtensionStubTest, SUB_backup_ext_ExtExtensionStub_CmdIncrementalOnB try { MessageParcel data; MessageParcel reply; - EXPECT_CALL(*stub, IncrementalOnBackup()).WillOnce(Return(0)); + EXPECT_CALL(*stub, IncrementalOnBackup(_)).WillOnce(Return(0)); EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(false)); EXPECT_TRUE(stub != nullptr); auto err = stub->CmdIncrementalOnBackup(data, reply); EXPECT_EQ(err, BError(BError::Codes::EXT_BROKEN_IPC)); - EXPECT_CALL(*stub, IncrementalOnBackup()).WillOnce(Return(0)); + EXPECT_CALL(*stub, IncrementalOnBackup(_)).WillOnce(Return(0)); EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(true)); err = stub->CmdIncrementalOnBackup(data, reply); EXPECT_EQ(err, BError(BError::Codes::OK)); diff --git a/tests/unittests/backup_ext/tar_file_test.cpp b/tests/unittests/backup_ext/tar_file_test.cpp index 5e8b37785a8742121528012e60a2a9bed153cb9d..49d094a2ffa771fe2990c94a50dff8ad97d19033 100644 --- a/tests/unittests/backup_ext/tar_file_test.cpp +++ b/tests/unittests/backup_ext/tar_file_test.cpp @@ -104,6 +104,13 @@ HWTEST_F(TarFileTest, SUB_Tar_File_Packet_0100, testing::ext::TestSize.Level1) bool ret = TarFile::GetInstance().Packet(srcFiles, tarFileName, pkPath, tarMap); EXPECT_TRUE(tarMap.empty()); EXPECT_FALSE(ret); + + TestManager tm("SUB_Tar_File_Packet_0100"); + string root = tm.GetRootDirCurTest(); + pkPath = root; + ret = TarFile::GetInstance().Packet(srcFiles, tarFileName, pkPath, tarMap); + EXPECT_TRUE(tarMap.empty()); + EXPECT_FALSE(ret); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "TarFileTest-an exception occurred by TarFile."; diff --git a/tests/unittests/backup_sa/module_ipc/BUILD.gn b/tests/unittests/backup_sa/module_ipc/BUILD.gn index 6a395d44a106d07b304d71aa687d4dc5d9ea41b3..1c9051f2749361f7cff60449008f96c859db37c7 100644 --- a/tests/unittests/backup_sa/module_ipc/BUILD.gn +++ b/tests/unittests/backup_sa/module_ipc/BUILD.gn @@ -12,6 +12,7 @@ # limitations under the License. import("//build/test.gni") +import("//foundation/filemanagement/app_file_service/app_file_service.gni") import("//foundation/filemanagement/app_file_service/backup.gni") ohos_unittest("module_ipc_test") { @@ -93,7 +94,6 @@ ohos_unittest("backup_service_test") { "${path_backup_mock}/module_ipc/app_gallery_dispose_proxy_mock.cpp", "${path_backup_mock}/timer/timer_mock.cpp", "${path_backup}/services/backup_sa/src/module_ipc/sa_backup_connection.cpp", - "${path_backup}/services/backup_sa/src/module_ipc/service.cpp", "${path_backup}/services/backup_sa/src/module_ipc/service_incremental.cpp", "${path_backup}/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp", "${path_backup}/services/backup_sa/src/module_notify/notify_work_service.cpp", @@ -107,6 +107,7 @@ ohos_unittest("backup_service_test") { include_dirs = [ "${path_backup}/services/backup_sa/include", "${path_backup}/interfaces/inner_api/native/backup_kit_inner/impl", + "${path_backup}/services/backup_sa/src/module_ipc", "${path_backup}/tests/unittests/backup_api/backup_impl/include", "${path_access_token}/interfaces/innerkits/accesstoken/include", "${path_backup_mock}/b_process/", @@ -143,7 +144,17 @@ ohos_unittest("backup_service_test") { blocklist = "${path_backup}/cfi_blocklist.txt" } + defines = [ "private=public" ] use_exceptions = true + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-Dprivate=public", + "-Dprotected=public", + ] } ohos_unittest("backup_service_throw_test") { @@ -244,6 +255,7 @@ ohos_unittest("backup_service_session_test") { ] deps = [ + "${app_file_service_path}/services/backup_sa:backup_sa", "${path_backup}/interfaces/inner_api/native/backup_kit_inner:backup_kit_inner", "${path_backup}/tests/utils:backup_test_utils", "${path_backup}/utils:backup_utils", diff --git a/tests/unittests/backup_sa/module_ipc/sched_scheduler_test.cpp b/tests/unittests/backup_sa/module_ipc/sched_scheduler_test.cpp index 27273d9cfef5c3472d0dde6fee4d1afbe4b04af2..505e0eb577076c7510f55349b957c7e1164d4034 100644 --- a/tests/unittests/backup_sa/module_ipc/sched_scheduler_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/sched_scheduler_test.cpp @@ -121,6 +121,30 @@ HWTEST_F(SchedSchedulerTest, SUB_Service_Sched_0100, testing::ext::TestSize.Leve GTEST_LOG_(INFO) << "SchedSchedulerTest-end SUB_Service_Sched_0100"; } +/** + * @tc.number: SUB_Service_Sched_0200 + * @tc.name: SUB_Service_Sched_0200 + * @tc.desc: 测试 Sched接口,sessionPtr_为空场景 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(SchedSchedulerTest, SUB_Service_Sched_0200, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SchedSchedulerTest-begin SUB_Service_Sched_0200"; + try { + sptr schedPtrNull = sptr(new SchedScheduler(wptr(servicePtr_), nullptr)); + schedPtrNull->Sched(); + schedPtrNull->ExecutingQueueTasks("test"); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SchedSchedulerTest-an exception occurred by Sched."; + } + GTEST_LOG_(INFO) << "SchedSchedulerTest-end SUB_Service_Sched_0200"; +} + /** * @tc.number: SUB_Service_ExecutingQueueTasks_0100 * @tc.name: SUB_Service_ExecutingQueueTasks_0100 @@ -168,4 +192,49 @@ HWTEST_F(SchedSchedulerTest, SUB_Service_RemoveExtConn_0100, testing::ext::TestS } GTEST_LOG_(INFO) << "SchedSchedulerTest-end SUB_Service_RemoveExtConn_0100"; } + +/** + * @tc.number: SUB_Service_TryUnloadServiceTimer_0100 + * @tc.name: SUB_Service_TryUnloadServiceTimer_0100 + * @tc.desc: 测试 TryUnloadServiceTimer 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(SchedSchedulerTest, SUB_Service_TryUnloadServiceTimer_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SchedSchedulerTest-begin SUB_Service_TryUnloadServiceTimer_0100"; + try { + EXPECT_TRUE(schedPtr_ != nullptr); + schedPtr_->TryUnloadServiceTimer(true); + schedPtr_->TryUnloadServiceTimer(false); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SchedSchedulerTest-an exception occurred by TryUnloadServiceTimer."; + } + GTEST_LOG_(INFO) << "SchedSchedulerTest-end SUB_Service_TryUnloadServiceTimer_0100"; +} + +/** + * @tc.number: SUB_Service_TryUnloadService_0100 + * @tc.name: SUB_Service_TryUnloadServicer_0100 + * @tc.desc: 测试 TryUnloadService 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(SchedSchedulerTest, SUB_Service_TryUnloadService_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SchedSchedulerTest-begin SUB_Service_TryUnloadService_0100"; + try { + EXPECT_TRUE(schedPtr_ != nullptr); + schedPtr_->TryUnloadService(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SchedSchedulerTest-an exception occurred by TryUnloadService."; + } + GTEST_LOG_(INFO) << "SchedSchedulerTest-end SUB_Service_TryUnloadService_0100"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_sa/module_ipc/service_reverse_proxy_test.cpp b/tests/unittests/backup_sa/module_ipc/service_reverse_proxy_test.cpp index 5cf98223801b041f630b4822a20e0ad63f5b8767..2dbda93dfa72d8563f147c3e0ce9fb66bd9558be 100644 --- a/tests/unittests/backup_sa/module_ipc/service_reverse_proxy_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_reverse_proxy_test.cpp @@ -2080,4 +2080,92 @@ HWTEST_F(ServiceReverseProxyTest, SUB_ServiceReverse_proxy_IncrementalRestoreOnR } GTEST_LOG_(INFO) << "ServiceReverseProxyTest-end SUB_ServiceReverse_proxy_IncrementalRestoreOnResultReport_0101"; } + +/** + * @tc.number: SUB_ServiceReverse_proxy_IncrementalBackupOnResultReport_0100 + * @tc.name: SUB_ServiceReverse_proxy_IncrementalBackupOnResultReport_0100 + * @tc.desc: Test function of IncrementalBackupOnResultReport interface for FAILURE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9OVHB + */ +HWTEST_F(ServiceReverseProxyTest, SUB_ServiceReverse_proxy_IncrementalBackupOnResultReport_0100, + testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceReverseProxyTest-begin SUB_ServiceReverse_proxy_IncrementalBackupOnResultReport_0100"; + try { + std::string bundleName = "app01"; + try { + EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(false)); + EXPECT_TRUE(proxy_ != nullptr); + proxy_->IncrementalBackupOnResultReport(RESULT_REPORT, bundleName); + EXPECT_TRUE(false); + } catch (BError &err) { + EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_BROKEN_IPC); + } + + try { + EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(false)); + proxy_->IncrementalBackupOnResultReport(RESULT_REPORT, bundleName); + EXPECT_TRUE(false); + } catch (BError &err) { + EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_BROKEN_IPC); + } + + try { + EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true)).WillOnce(Return(false)); + proxy_->IncrementalBackupOnResultReport(RESULT_REPORT, bundleName); + EXPECT_TRUE(false); + } catch (BError &err) { + EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_BROKEN_IPC); + } + + try { + EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true)).WillOnce(Return(true)); + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(-1)); + proxy_->IncrementalBackupOnResultReport(RESULT_REPORT, bundleName); + EXPECT_TRUE(false); + } catch (BError &err) { + EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_BROKEN_IPC); + } + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceReverseProxyTest-an exception occurred by IncrementalBackupOnResultReport."; + } + GTEST_LOG_(INFO) << "ServiceReverseProxyTest-end SUB_ServiceReverse_proxy_IncrementalBackupOnResultReport_0100"; +} + +/** + * @tc.number: SUB_ServiceReverse_proxy_IncrementalBackupOnResultReport_0101 + * @tc.name: SUB_ServiceReverse_proxy_IncrementalBackupOnResultReport_0101 + * @tc.desc: Test function of IncrementalBackupOnResultReport interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceReverseProxyTest, SUB_ServiceReverse_proxy_IncrementalBackupOnResultReport_0101, + testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceReverseProxyTest-begin SUB_ServiceReverse_proxy_IncrementalBackupOnResultReport_0101"; + try { + EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true)).WillOnce(Return(true)); + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) + .Times(1) + .WillOnce(Invoke(mock_.GetRefPtr(), &ServiceReverseMock::InvokeSendRequest)); + std::string bundleName = "app01"; + EXPECT_TRUE(proxy_ != nullptr); + proxy_->IncrementalBackupOnResultReport(RESULT_REPORT, bundleName); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceReverseProxyTest-an exception occurred by RestoreOnResultReport."; + } + GTEST_LOG_(INFO) << "ServiceReverseProxyTest-end SUB_ServiceReverse_proxy_IncrementalBackupOnResultReport_0101"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp b/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp index 9b9947fcbdd92014cd1c73cc32bd0e429cd56b8b..307c3c7e0eec0cb3a872148766bcde9da890d7f7 100644 --- a/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp @@ -1331,4 +1331,160 @@ HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_GetIncrementalFileHandle_010 } GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_GetIncrementalFileHandle_0100"; } + +/** + * @tc.number: SUB_backup_sa_ServiceStub_CmdResultReport_0100 + * @tc.name: SUB_backup_sa_ServiceStub_CmdResultReport_0100 + * @tc.desc: Test function of CmdResultReport interface for FAILURE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_CmdResultReport_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceStubTest-begin SUB_backup_sa_ServiceStub_CmdResultReport_0100"; + try { + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*messageParcelMock, ReadString(_)).WillOnce(Return(false)); + EXPECT_TRUE(service != nullptr); + auto err = service->CmdResultReport(data, reply); + EXPECT_EQ(err, BError(BError::Codes::SA_INVAL_ARG)); + + EXPECT_CALL(*messageParcelMock, ReadString(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock, ReadInt32(_)).WillOnce(Return(false)); + err = service->CmdResultReport(data, reply); + EXPECT_EQ(err, BError(BError::Codes::SA_INVAL_ARG)); + + EXPECT_CALL(*messageParcelMock, ReadString(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock, ReadInt32(_)).WillOnce(Return(true)).WillOnce(Return(false)); + err = service->CmdResultReport(data, reply); + EXPECT_EQ(err, BError(BError::Codes::SA_INVAL_ARG)); + + EXPECT_CALL(*messageParcelMock, ReadString(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock, ReadInt32(_)).WillOnce(Return(true)).WillOnce(Return(true)); + EXPECT_CALL(*service, ServiceResultReport(_, _, _)).WillOnce(Return(BError(BError::Codes::OK))); + EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(false)); + err = service->CmdResultReport(data, reply); + EXPECT_EQ(err, BError(BError::Codes::SA_BROKEN_IPC)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceStubTest-an exception occurred by CmdResultReport."; + } + GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_CmdResultReport_0100"; +} + +/** + * @tc.number: SUB_backup_sa_ServiceStub_CmdResultReport_0200 + * @tc.name: SUB_backup_sa_ServiceStub_CmdResultReport_0200 + * @tc.desc: Test function of GetIncrementalFileHandle interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_CmdResultReport_0200, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceStubTest-begin SUB_backup_sa_ServiceStub_CmdResultReport_0200"; + try { + MessageParcel data; + MessageParcel reply; + EXPECT_TRUE(service != nullptr); + EXPECT_CALL(*messageParcelMock, ReadString(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock, ReadInt32(_)).WillOnce(Return(true)).WillOnce(Return(true)); + EXPECT_CALL(*service, ServiceResultReport(_, _, _)).WillOnce(Return(BError(BError::Codes::OK))); + EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(true)); + auto ret = service->CmdResultReport(data, reply); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceStubTest-an exception occurred by CmdResultReport."; + } + GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_CmdResultReport_0200"; +} + +/** + * @tc.number: SUB_backup_sa_ServiceStub_CmdUpdateSendRate_0100 + * @tc.name: SUB_backup_sa_ServiceStub_CmdUpdateSendRate_0100 + * @tc.desc: Test function of CmdUpdateSendRate interface for FAILURE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_CmdUpdateSendRate_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceStubTest-begin SUB_backup_sa_ServiceStub_CmdUpdateSendRate_0100"; + try { + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*messageParcelMock, ReadString(_)).WillOnce(Return(false)); + EXPECT_TRUE(service != nullptr); + auto err = service->CmdUpdateSendRate(data, reply); + EXPECT_EQ(err, BError(BError::Codes::SA_BROKEN_IPC)); + + EXPECT_CALL(*messageParcelMock, ReadString(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock, ReadInt32(_)).WillOnce(Return(false)); + err = service->CmdUpdateSendRate(data, reply); + EXPECT_EQ(err, BError(BError::Codes::SA_BROKEN_IPC)); + + EXPECT_CALL(*messageParcelMock, ReadString(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock, ReadInt32(_)).WillOnce(Return(true)); + EXPECT_CALL(*service, UpdateSendRate(_, _, _)).WillOnce(Return(BError(BError::Codes::SA_INVAL_ARG))); + err = service->CmdUpdateSendRate(data, reply); + EXPECT_EQ(err, BError(BError::Codes::SA_BROKEN_IPC)); + + EXPECT_CALL(*messageParcelMock, ReadString(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock, ReadInt32(_)).WillOnce(Return(true)); + EXPECT_CALL(*service, UpdateSendRate(_, _, _)).WillOnce(Return(BError(BError::Codes::OK))); + EXPECT_CALL(*messageParcelMock, WriteBool(_)).WillOnce(Return(false)); + err = service->CmdUpdateSendRate(data, reply); + EXPECT_EQ(err, BError(BError::Codes::SA_BROKEN_IPC)); + + EXPECT_CALL(*messageParcelMock, ReadString(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock, ReadInt32(_)).WillOnce(Return(true)); + EXPECT_CALL(*service, UpdateSendRate(_, _, _)).WillOnce(Return(BError(BError::Codes::OK))); + EXPECT_CALL(*messageParcelMock, WriteBool(_)).WillOnce(Return(true)); + err = service->CmdUpdateSendRate(data, reply); + EXPECT_EQ(err, BError(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceStubTest-an exception occurred by CmdUpdateSendRate."; + } + GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_CmdUpdateSendRate_0100"; +} + +/** + * @tc.number: SUB_backup_sa_ServiceStub_CmdGetAppLocalListAndDoIncrementalBackup_0100 + * @tc.name: SUB_backup_sa_ServiceStub_CmdGetAppLocalListAndDoIncrementalBackup_0100 + * @tc.desc: Test function of CmdGetAppLocalListAndDoIncrementalBackup interface for FAILURE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_CmdGetAppLocalListAndDoIncrementalBackup_0100, + testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceStubTest-begin SUB_backup_sa_ServiceStub_CmdGetAppLocalListAndDoIncrementalBackup_0100"; + try { + MessageParcel data; + MessageParcel reply; + EXPECT_TRUE(service != nullptr); + EXPECT_CALL(*service, GetAppLocalListAndDoIncrementalBackup()).WillOnce(Return(BError(BError::Codes::OK))); + EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(false)); + auto err = service->CmdGetAppLocalListAndDoIncrementalBackup(data, reply); + EXPECT_EQ(err, BError(BError::Codes::SA_BROKEN_IPC)); + + EXPECT_CALL(*service, GetAppLocalListAndDoIncrementalBackup()).WillOnce(Return(BError(BError::Codes::OK))); + EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(true)); + err = service->CmdGetAppLocalListAndDoIncrementalBackup(data, reply); + EXPECT_EQ(err, BError(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceStubTest-an exception occurred by CmdGetAppLocalListAndDoIncrementalBackup."; + } + GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_CmdGetAppLocalListAndDoIncrementalBackup_0100"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_sa/module_ipc/service_test.cpp b/tests/unittests/backup_sa/module_ipc/service_test.cpp index f2e6511c836431e60978f9761538af5bdf55046a..9aad0ad61da908caf619e0c3811e3bf505577111 100644 --- a/tests/unittests/backup_sa/module_ipc/service_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_test.cpp @@ -20,6 +20,7 @@ #include #include "module_ipc/service.h" +#include "service.cpp" #include "service_reverse_mock.h" #include "test_manager.h" @@ -441,6 +442,43 @@ HWTEST_F(ServiceTest, SUB_Service_AppDone_0102, testing::ext::TestSize.Level1) GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_AppDone_0102"; } +/** + * @tc.number: SUB_Service_ServiceResultReport_0000 + * @tc.name: SUB_Service_ServiceResultReport_0000 + * @tc.desc: 测试 ServiceResultReport 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceTest, SUB_Service_ServiceResultReport_0000, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_ServiceResultReport_0000"; + try { + GTEST_LOG_(INFO) << "SUB_Service_ServiceResultReport Branches Start"; + string bundleName = ""; + EXPECT_TRUE(servicePtr_ != nullptr); + auto ret = servicePtr_->ServiceResultReport("test", BackupRestoreScenario::FULL_RESTORE, 0); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + + ret = servicePtr_->ServiceResultReport("test", BackupRestoreScenario::INCREMENTAL_RESTORE, 0); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + + ret = servicePtr_->ServiceResultReport("test", BackupRestoreScenario::FULL_BACKUP, 0); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + + ret = servicePtr_->ServiceResultReport("test", BackupRestoreScenario::INCREMENTAL_BACKUP, 0); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + + ret = servicePtr_->ServiceResultReport("test", static_cast(1000), 0); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by ServiceResultReport."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_ServiceResultReport_0000"; +} + /** * @tc.number: SUB_Service_LaunchBackupExtension_0100 * @tc.name: SUB_Service_LaunchBackupExtension_0100 @@ -523,6 +561,41 @@ HWTEST_F(ServiceTest, SUB_Service_GetFileHandle_0100, testing::ext::TestSize.Lev GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_GetFileHandle_0100"; } +/** + * @tc.number: SUB_Service_GetFileHandle_0101 + * @tc.name: SUB_Service_GetFileHandle_0101 + * @tc.desc: 测试 GetFileHandle 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceTest, SUB_Service_GetFileHandle_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_GetFileHandle_0101"; + try { + ErrCode ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + + SvcSessionManager::Impl impl_; + impl_.clientToken = 1; + BackupExtInfo extInfo {}; + auto callDied = [](const string &&bundleName) {}; + auto callConnected = [](const string &&bundleName) {}; + string bundleNameIndexInfo = "123456"; + extInfo.backUpConnection = sptr(new SvcBackupConnection(callDied, callConnected, bundleNameIndexInfo)); + extInfo.schedAction = BConstants::ServiceSchedAction::RUNNING; + impl_.backupExtNameMap[BUNDLE_NAME] = extInfo; + EXPECT_TRUE(servicePtr_ != nullptr); + ret = servicePtr_->GetFileHandle(BUNDLE_NAME, FILE_NAME); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by GetFileHandle."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_GetFileHandle_0101"; +} + /** * @tc.number: SUB_Service_OnBackupExtensionDied_0100 * @tc.name: SUB_Service_OnBackupExtensionDied_0100 @@ -554,6 +627,48 @@ HWTEST_F(ServiceTest, SUB_Service_OnBackupExtensionDied_0100, testing::ext::Test GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_OnBackupExtensionDied_0100"; } +/** + * @tc.number: SUB_Service_OnBackupExtensionDied_0101 + * @tc.name: SUB_Service_OnBackupExtensionDied_0101 + * @tc.desc: 测试 OnBackupExtensionDied 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceTest, SUB_Service_OnBackupExtensionDied_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_OnBackupExtensionDied_0101"; + try { + GTEST_LOG_(INFO) << "SUB_Service_OnBackupExtensionDied_0101 RESTORE"; + ErrCode ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + string bundleName = BUNDLE_NAME; + SvcSessionManager::Impl impl_; + impl_.clientToken = 1; + BackupExtInfo extInfo {}; + extInfo.backUpConnection = nullptr; + extInfo.versionName = "0.0.0.0-0.0.0.0"; + impl_.restoreDataType = RESTORE_DATA_WAIT_SEND; + impl_.backupExtNameMap[BUNDLE_NAME] = extInfo; + impl_.scenario = IServiceReverse::Scenario::RESTORE; + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->OnBackupExtensionDied(move(bundleName)); + GTEST_LOG_(INFO) << "SUB_Service_OnBackupExtensionDied_0101 BACKUP"; + + ret = Init(IServiceReverse::Scenario::BACKUP); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + impl_.restoreDataType = RESTORE_DATA_READDY; + bundleName = "123456789"; + impl_.backupExtNameMap[bundleName] = extInfo; + servicePtr_->OnBackupExtensionDied(move(bundleName)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by GetFileHandle."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_OnBackupExtensionDied_0101"; +} + /** * @tc.number: SUB_Service_ExtStart_0100 * @tc.name: SUB_Service_ExtStart_0100 @@ -584,6 +699,55 @@ HWTEST_F(ServiceTest, SUB_Service_ExtStart_0100, testing::ext::TestSize.Level1) GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_ExtStart_0100"; } +/** + * @tc.number: SUB_Service_ExtStart_0101 + * @tc.name: SUB_Service_ExtStart_0101 + * @tc.desc: 测试 ExtStart 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceTest, SUB_Service_ExtStart_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_ExtStart_0101"; + try { + GTEST_LOG_(INFO) << "SUB_Service_ExtStart_0101 BACKUP"; + std::string bundleName = "123456"; + ErrCode ret = Init(IServiceReverse::Scenario::BACKUP); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->ExtStart(bundleName); + + GTEST_LOG_(INFO) << "SUB_Service_ExtStart_0101 RESTORE"; + SvcSessionManager::Impl impl_; + impl_.clientToken = 1; + BackupExtInfo extInfo {}; + auto callDied = [](const string &&bundleName) {}; + auto callConnected = [](const string &&bundleName) {}; + string bundleNameIndexInfo = "123456789"; + extInfo.backUpConnection = sptr(new SvcBackupConnection(callDied, callConnected, bundleNameIndexInfo)); + extInfo.backUpConnection->backupProxy_ = nullptr; + impl_.backupExtNameMap[BUNDLE_NAME] = extInfo; + impl_.scenario = IServiceReverse::Scenario::UNDEFINED; + ret = Init(IServiceReverse::Scenario::UNDEFINED); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + servicePtr_->ExtStart(BUNDLE_NAME); + + ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + servicePtr_->ExtStart(BUNDLE_NAME); + + ret = Init(IServiceReverse::Scenario::UNDEFINED); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + servicePtr_->ExtStart(BUNDLE_NAME); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by ExtStart."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_ExtStart_0101"; +} + /** * @tc.number: SUB_Service_Dump_0100 * @tc.name: SUB_Service_Dump_0100 @@ -678,6 +842,13 @@ HWTEST_F(ServiceTest, SUB_Service_ExtConnectFailed_0100, testing::ext::TestSize. ret = Init(IServiceReverse::Scenario::BACKUP); EXPECT_EQ(ret, BError(BError::Codes::OK)); servicePtr_->ExtConnectFailed(BUNDLE_NAME, BError(BError::Codes::OK)); + + SvcSessionManager::Impl impl_; + impl_.clientToken = 1; + impl_.restoreDataType = RESTORE_DATA_READDY; + ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + servicePtr_->ExtConnectFailed(BUNDLE_NAME, BError(BError::Codes::OK)); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by ExtConnectFailed."; @@ -873,6 +1044,30 @@ HWTEST_F(ServiceTest, SUB_Service_SendStartAppGalleryNotify_0100, testing::ext:: GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SendStartAppGalleryNotify_0100"; } +/** + * @tc.number: SUB_Service_SendStartAppGalleryNotify_0101 + * @tc.name: SUB_Service_SendStartAppGalleryNotify_0101 + * @tc.desc: 测试 SendStartAppGalleryNotify 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_SendStartAppGalleryNotify_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SendStartAppGalleryNotify_0101"; + try { + ErrCode ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->SendStartAppGalleryNotify(BUNDLE_NAME); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SendStartAppGalleryNotify."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SendStartAppGalleryNotify_0101"; +} + /** * @tc.number: SUB_Service_SessionDeactive_0100 * @tc.name: SUB_Service_SessionDeactive_0100 @@ -921,6 +1116,40 @@ HWTEST_F(ServiceTest, SUB_Service_GetBackupInfo_0100, testing::ext::TestSize.Lev GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_GetBackupInfo_0100"; } +/** + * @tc.number: SUB_Service_GetBackupInfo_0101 + * @tc.name: SUB_Service_GetBackupInfo_0101 + * @tc.desc: 测试 SessionDeactive 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_GetBackupInfo_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_GetBackupInfo_0101"; + try { + std::string bundleName = "com.example.app2backup"; + std::string result = "ok"; + auto ret = Init(IServiceReverse::Scenario::BACKUP); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->session_ = nullptr; + SvcSessionManager::Impl impl_; + impl_.clientToken = 1; + ret = servicePtr_->GetBackupInfo(bundleName, result); + EXPECT_NE(ret, BError(BError::Codes::OK)); + + impl_.clientToken = 0; + ret = servicePtr_->GetBackupInfo(bundleName, result); + EXPECT_NE(ret, BError(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by GetBackupInfo."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_GetBackupInfo_0101"; +} + /** * @tc.number: SUB_Service_UpdateTimer_0100 * @tc.name: SUB_Service_UpdateTimer_0100 @@ -945,4 +1174,668 @@ HWTEST_F(ServiceTest, SUB_Service_UpdateTimer_0100, testing::ext::TestSize.Level } GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_UpdateTimer_0100"; } + +/** + * @tc.number: SUB_Service_UpdateTimer_0101 + * @tc.name: SUB_Service_UpdateTimer_0101 + * @tc.desc: 测试 UpdateTimer 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_UpdateTimer_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_UpdateTimer_0101"; + try { + std::string bundleName = "com.example.app2backup"; + bool result = true; + uint32_t timeOut = 30000; + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->session_ = nullptr; + servicePtr_->UpdateTimer(bundleName, timeOut, result); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by UpdateTimer."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_UpdateTimer_0101"; +} + +/** + * @tc.number: SUB_Service_GetBackupInfoCmdHandle_0100 + * @tc.name: SUB_Service_GetBackupInfoCmdHandle_0100 + * @tc.desc: 测试 GetBackupInfoCmdHandle 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_GetBackupInfoCmdHandle_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_GetBackupInfoCmdHandle_0100"; + try { + std::string bundleName = "com.example.app2backup"; + std::string result; + EXPECT_TRUE(servicePtr_ != nullptr); + auto ret = servicePtr_->GetBackupInfoCmdHandle(bundleName, result); + EXPECT_TRUE(ret == BError::BackupErrorCode::E_INVAL); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by GetBackupInfoCmdHandle."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_GetBackupInfoCmdHandle_0100"; +} + +/** + * @tc.number: SUB_Service_GetBackupInfoCmdHandle_0101 + * @tc.name: SUB_Service_GetBackupInfoCmdHandle_0101 + * @tc.desc: 测试 GetBackupInfoCmdHandle 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_GetBackupInfoCmdHandle_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_GetBackupInfoCmdHandle_0101"; + try { + std::string bundleName = "com.example.app2backup"; + std::string result = "ok"; + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->session_ = nullptr; + auto ret = servicePtr_->GetBackupInfoCmdHandle(bundleName, result); + EXPECT_EQ(ret, BError(BError::Codes::SA_INVAL_ARG)); + + servicePtr_->session_ = sptr(new SvcSessionManager(servicePtr_)); + ret = servicePtr_->GetBackupInfoCmdHandle(bundleName, result); + EXPECT_EQ(ret, BError(BError::Codes::EXT_ABILITY_DIED)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by GetBackupInfoCmdHandle."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_GetBackupInfoCmdHandle_0101"; +} + +/** + * @tc.number: SUB_Service_SpecialVersion_0100 + * @tc.name: SUB_Service_SpecialVersion_0100 + * @tc.desc: 测试 SpecialVersion 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_SpecialVersion_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SpecialVersion_0100"; + try { + std::string versionName = "0.0.0.0-0.0.0.0"; + EXPECT_TRUE(servicePtr_ != nullptr); + bool ret = SpecialVersion(versionName); + EXPECT_EQ(ret, true); + versionName = "1.1.1.1-1.1.1.1"; + ret = SpecialVersion(versionName); + EXPECT_EQ(ret, false); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SpecialVersion."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SpecialVersion_0100"; +} + +/** + * @tc.number: SUB_Service_OnBundleStarted_0100 + * @tc.name: SUB_Service_OnBundleStarted_0100 + * @tc.desc: 测试 OnBundleStarted 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_OnBundleStarted_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_OnBundleStarted_0100"; + try { + int32_t saID = 2503; + wptr reversePtr(new Service(saID)); + sptr session(new SvcSessionManager(reversePtr)); + EXPECT_TRUE(servicePtr_ != nullptr); + OnBundleStarted(BError(BError::Codes::SA_INVAL_ARG), session, BUNDLE_NAME); + SvcSessionManager::Impl impl_; + impl_.clientToken = 1; + impl_.scenario = IServiceReverse::Scenario::RESTORE; + OnBundleStarted(BError(BError::Codes::SA_INVAL_ARG), session, BUNDLE_NAME); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by OnBundleStarted."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_OnBundleStarted_0100"; +} + +/** + * @tc.number: SUB_Service_HandleExceptionOnAppendBundles_0100 + * @tc.name: SUB_Service_HandleExceptionOnAppendBundles_0100 + * @tc.desc: 测试 HandleExceptionOnAppendBundles 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_HandleExceptionOnAppendBundles_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_HandleExceptionOnAppendBundles_0100"; + try { + int32_t saID = 4801; + wptr reversePtr(new Service(saID)); + sptr session(new SvcSessionManager(reversePtr)); + vector appendBundleNames {"123456"}; + vector restoreBundleNames {"abcdef"}; + EXPECT_TRUE(servicePtr_ != nullptr); + HandleExceptionOnAppendBundles(session, appendBundleNames, restoreBundleNames); + + appendBundleNames.push_back("789"); + HandleExceptionOnAppendBundles(session, appendBundleNames, restoreBundleNames); + + restoreBundleNames.push_back("123456"); + restoreBundleNames.push_back("123"); + HandleExceptionOnAppendBundles(session, appendBundleNames, restoreBundleNames); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by HandleExceptionOnAppendBundles."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_HandleExceptionOnAppendBundles_0100"; +} + +/** + * @tc.number: SUB_Service_SetCurrentSessProperties_0100 + * @tc.name: SUB_Service_SetCurrentSessProperties_0100 + * @tc.desc: 测试 SetCurrentSessProperties 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_SetCurrentSessProperties_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SetCurrentSessProperties_0100"; + try { + BJsonEntityCaps::BundleInfo aInfo {}; + aInfo.name = "123456"; + aInfo.extensionName = "abcdef"; + aInfo.allToBackup = true; + std::vector restoreBundleInfos {aInfo}; + std::vector restoreBundleNames {"12345678"}; + RestoreTypeEnum restoreType = RESTORE_DATA_READDY; + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->session_ = sptr(new SvcSessionManager(servicePtr_)); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + + restoreBundleNames.push_back("123456"); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + + restoreBundleInfos.clear(); + aInfo.allToBackup = true; + aInfo.versionName = "0.0.0.0-0.0.0.0"; + aInfo.extensionName = ""; + restoreBundleInfos.push_back(aInfo); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + + restoreBundleInfos.clear(); + aInfo.name = "123456a"; + restoreBundleInfos.push_back(aInfo); + restoreBundleNames.push_back("123456a"); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + + restoreBundleInfos.clear(); + aInfo.allToBackup = false; + aInfo.extensionName = ""; + restoreBundleInfos.push_back(aInfo); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + + restoreBundleInfos.clear(); + aInfo.allToBackup = false; + aInfo.extensionName = ""; + restoreBundleInfos.push_back(aInfo); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + } catch (...) { + EXPECT_TRUE(true); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SetCurrentSessProperties."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SetCurrentSessProperties_0100"; +} + +/** + * @tc.number: SUB_Service_SetCurrentSessProperties_0101 + * @tc.name: SUB_Service_SetCurrentSessProperties_0101 + * @tc.desc: 测试 SetCurrentSessProperties 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_SetCurrentSessProperties_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SetCurrentSessProperties_0101"; + try { + BJsonEntityCaps::BundleInfo aInfo {}; + aInfo.name = "123456"; + aInfo.versionName = "0.0.0.0-0.0.0.0"; + aInfo.extensionName = "abcdef"; + aInfo.allToBackup = false; + std::vector restoreBundleInfos {aInfo}; + std::vector restoreBundleNames {"123456"}; + RestoreTypeEnum restoreType = RESTORE_DATA_READDY; + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->session_ = sptr(new SvcSessionManager(servicePtr_)); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + + restoreBundleInfos.clear(); + aInfo.extensionName = ""; + restoreBundleInfos.push_back(aInfo); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + + restoreBundleInfos.clear(); + aInfo.name = "123456a"; + restoreBundleInfos.push_back(aInfo); + restoreBundleNames.push_back("123456a"); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SetCurrentSessProperties."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SetCurrentSessProperties_0101"; +} + +/** + * @tc.number: SUB_Service_SetCurrentSessProperties_0102 + * @tc.name: SUB_Service_SetCurrentSessProperties_0102 + * @tc.desc: 测试 SetCurrentSessProperties 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_SetCurrentSessProperties_0102, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SetCurrentSessProperties_0102"; + try { + BJsonEntityCaps::BundleInfo aInfo {}; + aInfo.name = "123456"; + aInfo.versionName = "0.0.0.0-0.0.0.0"; + aInfo.extensionName = "abcdef"; + aInfo.allToBackup = false; + std::vector restoreBundleInfos {aInfo}; + std::vector restoreBundleNames {"123456"}; + RestoreTypeEnum restoreType = RESTORE_DATA_READDY; + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + + restoreBundleInfos.clear(); + aInfo.versionName = "1.1.1.1-1.1.1.1"; + aInfo.extensionName = ""; + aInfo.name = "123456"; + restoreBundleInfos.push_back(aInfo); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + + restoreBundleInfos.clear(); + aInfo.name = "123456a"; + restoreBundleInfos.push_back(aInfo); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + + restoreBundleInfos.clear(); + aInfo.extensionName = "abcdef"; + restoreBundleInfos.push_back(aInfo); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + + restoreBundleInfos.clear(); + aInfo.name = "123456"; + restoreBundleInfos.push_back(aInfo); + servicePtr_->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, restoreType); + } catch (...) { + EXPECT_TRUE(true); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SetCurrentSessProperties."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SetCurrentSessProperties_0102"; +} + +/** + * @tc.number: SUB_Service_AppendBundlesRestoreSession_0100 + * @tc.name: SUB_Service_AppendBundlesRestoreSession_0100 + * @tc.desc: 测试 AppendBundlesRestoreSession 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_AppendBundlesRestoreSession_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_AppendBundlesRestoreSession_0100"; + try { + UniqueFd fd = servicePtr_->GetLocalCapabilities(); + EXPECT_GE(fd, BError(BError::Codes::OK)); + vector bundleNames {}; + RestoreTypeEnum restoreType = RESTORE_DATA_READDY; + int32_t userId = 1; + EXPECT_TRUE(servicePtr_ != nullptr); + auto ret = servicePtr_->AppendBundlesRestoreSession(move(fd), bundleNames, restoreType, userId); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by AppendBundlesRestoreSession."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_AppendBundlesRestoreSession_0100"; +} + +/** + * @tc.number: SUB_Service_NotifyCloneBundleFinish_0100 + * @tc.name: SUB_Service_NotifyCloneBundleFinish_0100 + * @tc.desc: 测试 NotifyCloneBundleFinish 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_NotifyCloneBundleFinish_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_NotifyCloneBundleFinish_0100"; + try { + SvcSessionManager::Impl impl_; + impl_.clientToken = 1; + BackupExtInfo extInfo {}; + extInfo.backUpConnection = nullptr; + impl_.backupExtNameMap[BUNDLE_NAME] = extInfo; + impl_.scenario = IServiceReverse::Scenario::RESTORE; + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->NotifyCloneBundleFinish(BUNDLE_NAME); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by NotifyCloneBundleFinish."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_NotifyCloneBundleFinish_0100"; +} + +/** + * @tc.number: SUB_Service_LaunchBackupSAExtension_0100 + * @tc.name: SUB_Service_LaunchBackupSAExtension_0100 + * @tc.desc: 测试 LaunchBackupSAExtension 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_LaunchBackupSAExtension_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_LaunchBackupSAExtension_0100"; + try { + std::string bundleName = "123456"; + ErrCode ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_TRUE(servicePtr_ != nullptr); + ret = servicePtr_->LaunchBackupSAExtension(BUNDLE_NAME); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + + SvcSessionManager::Impl impl_; + impl_.clientToken = 1; + BackupExtInfo extInfo {}; + extInfo.backUpConnection = nullptr; + + auto callDied = [](const string &&bundleName) {}; + auto callConnected = [](const string &&bundleName) {}; + auto callBackup = [](const std::string &&bundleName, const int &&fd, const std::string &&result, + const ErrCode &&errCode) {}; + auto callRestore = [](const std::string &&bundleName, const std::string &&result, const ErrCode &&errCode) {}; + extInfo.saBackupConnection = + std::make_shared(callDied, callConnected, callBackup, callRestore); + + impl_.backupExtNameMap[BUNDLE_NAME] = extInfo; + ret = servicePtr_->LaunchBackupSAExtension(bundleName); + EXPECT_NE(ret, BError(BError::Codes::OK)); + + ret = Init(IServiceReverse::Scenario::BACKUP); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + ret = servicePtr_->LaunchBackupSAExtension(bundleName); + EXPECT_NE(ret, BError(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by LaunchBackupSAExtension."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_LaunchBackupSAExtension_0100"; +} + +/** + * @tc.number: SUB_Service_ExtConnectDied_0100 + * @tc.name: SUB_Service_ExtConnectDied_0100 + * @tc.desc: 测试 ExtConnectDied 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_ExtConnectDied_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_ExtConnectDied_0100"; + try { + std::string callName = "123456"; + ErrCode ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + SvcSessionManager::Impl impl_; + impl_.clientToken = 1; + BackupExtInfo extInfo {}; + auto callDied = [](const string &&bundleName) {}; + auto callConnected = [](const string &&bundleName) {}; + string bundleNameIndexInfo = "123456789"; + extInfo.backUpConnection = sptr(new SvcBackupConnection(callDied, callConnected, bundleNameIndexInfo)); + impl_.backupExtNameMap[BUNDLE_NAME] = extInfo; + impl_.scenario = IServiceReverse::Scenario::RESTORE; + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->ExtConnectDied(callName); + extInfo.backUpConnection->isConnected_.store(true); + servicePtr_->ExtConnectDied(callName); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by ExtConnectDied."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_ExtConnectDied_0100"; +} + +/** + * @tc.number: SUB_Service_NoticeClientFinish_0100 + * @tc.name: SUB_Service_NoticeClientFinish_0100 + * @tc.desc: 测试 NoticeClientFinish 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_NoticeClientFinish_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_NoticeClientFinish_0100"; + try { + ErrCode ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->NoticeClientFinish(BUNDLE_NAME, BError(BError::Codes::OK)); + GTEST_LOG_(INFO) << "SUB_Service_NoticeClientFinish_0100 BACKUP"; + ret = Init(IServiceReverse::Scenario::BACKUP); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + servicePtr_->NoticeClientFinish(BUNDLE_NAME, BError(BError::Codes::OK)); + + SvcSessionManager::Impl impl_; + impl_.clientToken = 1; + impl_.restoreDataType = RESTORE_DATA_READDY; + ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + servicePtr_->NoticeClientFinish(BUNDLE_NAME, BError(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by NoticeClientFinish."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_NoticeClientFinish_0100"; +} + +/** + * @tc.number: SUB_Service_OnAllBundlesFinished_0100 + * @tc.name: SUB_Service_OnAllBundlesFinished_0100 + * @tc.desc: 测试 OnAllBundlesFinished 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceTest, SUB_Service_OnAllBundlesFinished_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_OnAllBundlesFinished_0100"; + try { + ErrCode ret = Init(IServiceReverse::Scenario::BACKUP); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->session_ = sptr(new SvcSessionManager(servicePtr_)); + servicePtr_->OnAllBundlesFinished(BError(BError::Codes::OK)); + + ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + servicePtr_->OnAllBundlesFinished(BError(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by OnAllBundlesFinished."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_OnAllBundlesFinished_0100"; +} + +/** + * @tc.number: SUB_Service_SendEndAppGalleryNotify_0100 + * @tc.name: SUB_Service_SendEndAppGalleryNotify_0100 + * @tc.desc: 测试 SendEndAppGalleryNotify 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_SendEndAppGalleryNotify_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SendEndAppGalleryNotify_0100"; + try { + ErrCode ret = Init(IServiceReverse::Scenario::BACKUP); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->SendEndAppGalleryNotify(BUNDLE_NAME); + + ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + servicePtr_->SendEndAppGalleryNotify(BUNDLE_NAME); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SendEndAppGalleryNotify."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SendEndAppGalleryNotify_0100"; +} + +/** + * @tc.number: SUB_Service_SendErrAppGalleryNotify_0100 + * @tc.name: SUB_Service_SendErrAppGalleryNotify_0100 + * @tc.desc: 测试 SendErrAppGalleryNotify 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_SendErrAppGalleryNotify_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SendErrAppGalleryNotify_0100"; + try { + ErrCode ret = Init(IServiceReverse::Scenario::BACKUP); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->SendErrAppGalleryNotify(); + + ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + servicePtr_->SendErrAppGalleryNotify(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SendErrAppGalleryNotify."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SendErrAppGalleryNotify_0100"; +} + +/** + * @tc.number: SUB_Service_ClearDisposalOnSaStart_0100 + * @tc.name: SUB_Service_ClearDisposalOnSaStart_0100 + * @tc.desc: 测试 ClearDisposalOnSaStart 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_ClearDisposalOnSaStart_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_ClearDisposalOnSaStart_0100"; + try { + ErrCode ret = Init(IServiceReverse::Scenario::BACKUP); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->ClearDisposalOnSaStart(); + + ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + servicePtr_->ClearDisposalOnSaStart(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by ClearDisposalOnSaStart."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_ClearDisposalOnSaStart_0100"; +} + +/** + * @tc.number: SUB_Service_DeleteDisConfigFile_0100 + * @tc.name: SUB_Service_DeleteDisConfigFile_0100 + * @tc.desc: 测试 DeleteDisConfigFile 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_DeleteDisConfigFile_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_DeleteDisConfigFile_0100"; + try { + ErrCode ret = Init(IServiceReverse::Scenario::BACKUP); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->DeleteDisConfigFile(); + + ret = Init(IServiceReverse::Scenario::RESTORE); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + servicePtr_->DeleteDisConfigFile(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by DeleteDisConfigFile."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_DeleteDisConfigFile_0100"; +} + +/** + * @tc.number: SUB_Service_UnloadService_0100 + * @tc.name: SUB_Service_UnloadService_0100 + * @tc.desc: 测试 UnloadService 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_UnloadService_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_UnloadService_0100"; + try { + ErrCode ret = Init(IServiceReverse::Scenario::BACKUP); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_TRUE(servicePtr_ != nullptr); + servicePtr_->sched_ = nullptr; + servicePtr_->UnloadService(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by UnloadService."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_UnloadService_0100"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_sa/module_ipc/svc_backup_connection_test.cpp b/tests/unittests/backup_sa/module_ipc/svc_backup_connection_test.cpp index cfdfacc4c82a08e4edf864075401808661d4821b..772053763ae73bf6abd5b0d62bbe84ef64cf706d 100644 --- a/tests/unittests/backup_sa/module_ipc/svc_backup_connection_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/svc_backup_connection_test.cpp @@ -53,7 +53,7 @@ static void CallDone(const std::string &&name) void SvcBackupConnectionTest::SetUpTestCase() { - backupCon_ = sptr(new SvcBackupConnection(CallDied, CallDone)); + backupCon_ = sptr(new SvcBackupConnection(CallDied, CallDone, "com.example.app")); castMock = std::make_shared(); IfaceCastMock::cast = castMock; } diff --git a/tests/unittests/backup_sa/module_ipc/svc_extension_proxy_test.cpp b/tests/unittests/backup_sa/module_ipc/svc_extension_proxy_test.cpp index 0e54994bfe2084ae4db8eb254a31798a8b67ac9f..23df5b143aac2a4cef44e8847952eb5008af2c32 100644 --- a/tests/unittests/backup_sa/module_ipc/svc_extension_proxy_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/svc_extension_proxy_test.cpp @@ -148,15 +148,17 @@ HWTEST_F(SvcExtensionProxyTest, SUB_Ext_Extension_proxy_HandleBackup_0100, testi GTEST_LOG_(INFO) << "SvcExtensionProxyTest-begin SUB_Ext_Extension_proxy_HandleBackup_0100"; try { EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteBool(_)).WillOnce(Return(true)); EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(EPERM)); EXPECT_TRUE(proxy_ != nullptr); - ErrCode ret = proxy_->HandleBackup(); + ErrCode ret = proxy_->HandleBackup(true); EXPECT_EQ(EPERM, ret); EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteBool(_)).WillOnce(Return(true)); EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(0)); EXPECT_CALL(*messageParcelMock_, ReadInt32()).WillOnce(Return(0)); - ret = proxy_->HandleBackup(); + ret = proxy_->HandleBackup(true); EXPECT_EQ(BError(BError::Codes::OK), ret); } catch (...) { EXPECT_TRUE(false); @@ -218,15 +220,17 @@ HWTEST_F(SvcExtensionProxyTest, SUB_Ext_Extension_proxy_HandleRestore_0100, test GTEST_LOG_(INFO) << "SvcExtensionProxyTest-begin SUB_Ext_Extension_proxy_HandleRestore_0100"; try { EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteBool(_)).WillOnce(Return(true)); EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(EPERM)); EXPECT_TRUE(proxy_ != nullptr); - ErrCode ret = proxy_->HandleRestore(); + ErrCode ret = proxy_->HandleRestore(true); EXPECT_EQ(EPERM, ret); EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteBool(_)).WillOnce(Return(true)); EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(0)); EXPECT_CALL(*messageParcelMock_, ReadInt32()).WillOnce(Return(0)); - ret = proxy_->HandleRestore(); + ret = proxy_->HandleRestore(true); EXPECT_EQ(BError(BError::Codes::OK), ret); } catch (...) { EXPECT_TRUE(false); diff --git a/tests/unittests/backup_sa/module_ipc/svc_restore_deps_manager_test.cpp b/tests/unittests/backup_sa/module_ipc/svc_restore_deps_manager_test.cpp index 6668c0246e9ec39a457cfdc117a7b0f74d440bf8..3cb2a0082767bfbc57f06253ecaec7921afef187 100644 --- a/tests/unittests/backup_sa/module_ipc/svc_restore_deps_manager_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/svc_restore_deps_manager_test.cpp @@ -107,8 +107,8 @@ HWTEST_F(SvcRestoreDepsManagerTest, SUB_SvcRestoreDepsManager_GetRestoreBundleNa vector bundleInfos {info1, info2}; RestoreTypeEnum restoreType = RESTORE_DATA_WAIT_SEND; auto bundleNames = SvcRestoreDepsManager::GetInstance().GetRestoreBundleNames(bundleInfos, restoreType); - EXPECT_EQ(bundleNames.size(), 1); - EXPECT_FALSE(SvcRestoreDepsManager::GetInstance().IsAllBundlesRestored()); + EXPECT_EQ(bundleNames.size(), 2); + EXPECT_TRUE(SvcRestoreDepsManager::GetInstance().IsAllBundlesRestored()); ClearCache(); GTEST_LOG_(INFO) << "SvcRestoreDepsManagerTest-end SUB_SvcRestoreDepsManager_GetRestoreBundleNames_0200"; } diff --git a/tests/unittests/backup_sa/module_ipc/svc_session_manager_ex_test.cpp b/tests/unittests/backup_sa/module_ipc/svc_session_manager_ex_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..69baa543f69f2f5a71ef86e4e0e98d73aee6fbb6 --- /dev/null +++ b/tests/unittests/backup_sa/module_ipc/svc_session_manager_ex_test.cpp @@ -0,0 +1,149 @@ +/* + * 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. + */ + +/** + * @tc.number: SUB_backup_sa_session_GetLastIncrementalTime_0100 + * @tc.name: SUB_backup_sa_session_GetLastIncrementalTime_0100 + * @tc.desc: 测试 GetLastIncrementalTime + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetLastIncrementalTime_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_GetLastIncrementalTime_0100"; + try { + try { + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.clientToken = 0; + sessionManagerPtr_->GetLastIncrementalTime(BUNDLE_NAME); + EXPECT_TRUE(false); + } catch (BError &err) { + EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); + } + + sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; + sessionManagerPtr_->impl_.backupExtNameMap.clear(); + sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = {}; + sessionManagerPtr_->GetLastIncrementalTime(BUNDLE_NAME); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by GetLastIncrementalTime."; + } + GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetLastIncrementalTime_0100"; +} + +/** + * @tc.number: SUB_backup_sa_session_DecreaseSessionCnt_0100 + * @tc.name: SUB_backup_sa_session_DecreaseSessionCnt_0100 + * @tc.desc: 测试 DecreaseSessionCnt + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_DecreaseSessionCnt_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_DecreaseSessionCnt_0100"; + try { + sessionManagerPtr_->DecreaseSessionCnt(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by DecreaseSessionCnt."; + } + GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_DecreaseSessionCnt_0100"; +} + +/** + * @tc.number: SUB_backup_sa_session_DecreaseSessionCnt_0101 + * @tc.name: SUB_backup_sa_session_DecreaseSessionCnt_0101 + * @tc.desc: 测试 DecreaseSessionCnt + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_DecreaseSessionCnt_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_DecreaseSessionCnt_0101"; + try { + sessionManagerPtr_->IncreaseSessionCnt(); + sessionManagerPtr_->DecreaseSessionCnt(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by DecreaseSessionCnt."; + } + GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_DecreaseSessionCnt_0101"; +} + +/** + * @tc.number: SUB_backup_sa_session_GetServiceSchedAction_0104 + * @tc.name: SUB_backup_sa_session_GetServiceSchedAction_0104 + * @tc.desc: 测试 GetServiceSchedAction 获取状态 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetServiceSchedAction_0104, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_GetServiceSchedAction_0104"; + try { + try { + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.clientToken = 0; + sessionManagerPtr_->GetServiceSchedAction(BUNDLE_NAME); + EXPECT_TRUE(true); + } catch (BError &err) { + EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); + } + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by GetServiceSchedAction."; + } + GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetServiceSchedAction_0104"; +} + +/** + * @tc.number: SUB_backup_sa_session_GetServiceSchedAction_0105 + * @tc.name: SUB_backup_sa_session_GetServiceSchedAction_0105 + * @tc.desc: 测试 GetServiceSchedAction 获取状态 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetServiceSchedAction_0105, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_GetServiceSchedAction_0105"; + try { + try { + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.clientToken = 0; + sessionManagerPtr_->SetServiceSchedAction(BUNDLE_NAME, BConstants::ServiceSchedAction::RUNNING); + EXPECT_TRUE(true); + } catch (BError &err) { + EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); + } + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by GetServiceSchedAction."; + } + GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetServiceSchedAction_0105"; +} \ No newline at end of file diff --git a/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp b/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp index a60ac156d26b7ba0f3b9153cb248b7d331808718..411ade2de2282c038bfedaa4abb03516d5ab90a7 100644 --- a/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp @@ -627,6 +627,92 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetExtFileNameRequest_0100 GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetExtFileNameRequest_0100"; } +/** + * @tc.number: SUB_backup_sa_session_GetExtFileNameRequest_0101 + * @tc.name: SUB_backup_sa_session_GetExtFileNameRequest_0101 + * @tc.desc: 测试 GetExtFileNameRequest 获取暂存真实文件请求 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetExtFileNameRequest_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_GetExtFileNameRequest_0101"; + try { + try { + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.clientToken = 0; + sessionManagerPtr_->GetExtFileNameRequest(BUNDLE_NAME); + EXPECT_TRUE(true); + } catch (BError &err) { + EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); + } + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by GetExtFileNameRequest."; + } + GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetExtFileNameRequest_0101"; +} + +/** + * @tc.number: SUB_backup_sa_session_GetExtFileNameRequest_0102 + * @tc.name: SUB_backup_sa_session_GetExtFileNameRequest_0102 + * @tc.desc: 测试 GetExtFileNameRequest 获取暂存真实文件请求 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetExtFileNameRequest_0102, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_GetExtFileNameRequest_0102"; + try { + try { + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; + sessionManagerPtr_->impl_.scenario = IServiceReverse::Scenario::UNDEFINED; + sessionManagerPtr_->GetExtFileNameRequest(BUNDLE_NAME); + EXPECT_TRUE(true); + } catch (BError &err) { + EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); + } + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by GetExtFileNameRequest."; + } + GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetExtFileNameRequest_0102"; +} + +/** + * @tc.number: SUB_backup_sa_session_GetExtFileNameRequest_0103 + * @tc.name: SUB_backup_sa_session_GetExtFileNameRequest_0103 + * @tc.desc: 测试 GetExtFileNameRequest 获取暂存真实文件请求 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetExtFileNameRequest_0103, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_GetExtFileNameRequest_0103"; + try { + try { + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; + sessionManagerPtr_->impl_.scenario = IServiceReverse::Scenario::RESTORE; + sessionManagerPtr_->GetExtFileNameRequest(BUNDLE_NAME); + EXPECT_TRUE(true); + } catch (BError &err) { + EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); + } + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by GetExtFileNameRequest."; + } + GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetExtFileNameRequest_0103"; +} + /** * @tc.number: SUB_backup_sa_session_GetExtConnection_0100 * @tc.name: SUB_backup_sa_session_GetExtConnection_0100 @@ -668,7 +754,7 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetExtConnection_0100, tes } BackupExtInfo info; - info.backUpConnection = sptr(new SvcBackupConnection(nullptr, nullptr)); + info.backUpConnection = sptr(new SvcBackupConnection(nullptr, nullptr, BUNDLE_NAME)); sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = info; auto ret = sessionManagerPtr_->GetExtConnection(BUNDLE_NAME); @@ -1764,7 +1850,7 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_ClearSessionData_0100, tes BackupExtInfo info; info.timerStatus = true; info.schedAction = BConstants::ServiceSchedAction::RUNNING; - info.backUpConnection = sptr(new SvcBackupConnection(nullptr, nullptr)); + info.backUpConnection = sptr(new SvcBackupConnection(nullptr, nullptr, BUNDLE_NAME)); EXPECT_TRUE(sessionManagerPtr_ != nullptr); sessionManagerPtr_->impl_.backupExtNameMap.clear(); sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = info; @@ -1886,37 +1972,5 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetIncrementalManifestFd_0 GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetIncrementalManifestFd_0100"; } -/** - * @tc.number: SUB_backup_sa_session_GetLastIncrementalTime_0100 - * @tc.name: SUB_backup_sa_session_GetLastIncrementalTime_0100 - * @tc.desc: 测试 GetLastIncrementalTime - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetLastIncrementalTime_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_GetLastIncrementalTime_0100"; - try { - try { - EXPECT_TRUE(sessionManagerPtr_ != nullptr); - sessionManagerPtr_->impl_.clientToken = 0; - sessionManagerPtr_->GetLastIncrementalTime(BUNDLE_NAME); - EXPECT_TRUE(false); - } catch (BError &err) { - EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); - } - - sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; - sessionManagerPtr_->impl_.backupExtNameMap.clear(); - sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = {}; - sessionManagerPtr_->GetLastIncrementalTime(BUNDLE_NAME); - EXPECT_TRUE(true); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by GetLastIncrementalTime."; - } - GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetLastIncrementalTime_0100"; -} +#include "svc_session_manager_ex_test.cpp" } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_sa/session/b_incremental_session_test.cpp b/tests/unittests/backup_sa/session/b_incremental_session_test.cpp index 9adae7f71358b619f254981808f50a8508eb923b..d45ffbda81d35328b787fc69f470460d2326007e 100644 --- a/tests/unittests/backup_sa/session/b_incremental_session_test.cpp +++ b/tests/unittests/backup_sa/session/b_incremental_session_test.cpp @@ -168,6 +168,7 @@ HWTEST_F(IncrementalSessionTest, SUB_b_incremental_session_test_0400, testing::e EXPECT_EQ(err, BError(BError::Codes::SDK_BROKEN_IPC).GetCode()); EXPECT_CALL(*proxy, Release()).WillOnce(Return(0)); + EXPECT_CALL(*proxy, AsObject()).WillOnce(Return(nullptr)); ServiceProxy::serviceProxy_ = proxy; err = backupSession->Release(); EXPECT_EQ(err, BError(BError::Codes::OK).GetCode()); @@ -291,6 +292,7 @@ HWTEST_F(IncrementalSessionTest, SUB_b_incremental_session_test_0800, testing::e EXPECT_EQ(err, BError(BError::Codes::SDK_BROKEN_IPC).GetCode()); EXPECT_CALL(*proxy, Release()).WillOnce(Return(0)); + EXPECT_CALL(*proxy, AsObject()).WillOnce(Return(nullptr)); ServiceProxy::serviceProxy_ = proxy; err = restoreSession->Release(); EXPECT_EQ(err, BError(BError::Codes::OK).GetCode()); @@ -602,6 +604,7 @@ HWTEST_F(IncrementalSessionTest, SUB_b_incremental_session_test_1800, testing::e EXPECT_EQ(err, BError(BError::Codes::SDK_BROKEN_IPC).GetCode()); EXPECT_CALL(*proxy, Release()).WillOnce(Return(0)); + EXPECT_CALL(*proxy, AsObject()).WillOnce(Return(nullptr)); ServiceProxy::serviceProxy_ = proxy; err = restoreAsyncSession->Release(); EXPECT_EQ(err, BError(BError::Codes::OK).GetCode()); diff --git a/tests/unittests/backup_tools/BUILD.gn b/tests/unittests/backup_tools/BUILD.gn index 15fa2bced395cb897c616f5070d24ed26d312362..0a0c1d50a5090e3fa56cf0a24ab54176d2790ff6 100644 --- a/tests/unittests/backup_tools/BUILD.gn +++ b/tests/unittests/backup_tools/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Copyright (c) 2022-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 @@ -21,12 +21,16 @@ ohos_unittest("backup_tool_test") { sources = [ "${path_backup_mock}/b_filesystem/b_file_mock.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/b_incremental_data.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/service_incremental_reverse.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/service_reverse.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp", "${path_backup}/tests/mock/backup_kit_inner/b_session_backup_mock.cpp", "${path_backup}/tools/backup_tool/src/tools_op.cpp", "${path_backup}/tools/backup_tool/src/tools_op_backup.cpp", "${path_backup}/tools/backup_tool/src/tools_op_check_sa.cpp", "${path_backup}/tools/backup_tool/src/tools_op_help.cpp", - "${path_backup}/tools/backup_tool/src/tools_op_incremental_backup.cpp", "backup_tool/tools_op_backup_test.cpp", "backup_tool/tools_op_check_sa_test.cpp", "backup_tool/tools_op_help_test.cpp", @@ -37,9 +41,11 @@ ohos_unittest("backup_tool_test") { include_dirs = [ "${path_base}/include", + "${path_backup}/frameworks/native/backup_kit_inner/include", "${path_backup}/interfaces/inner_api/native/backup_kit_inner/impl", "${path_backup}/interfaces/inner_api/native/backup_kit_inner", "${path_backup}/tools/backup_tool/include", + "${path_backup}/tools/backup_tool/src", ] include_dirs += backup_mock_utils_include @@ -81,10 +87,14 @@ ohos_unittest("backup_tool_restore_test") { sources = [ "${path_backup_mock}/b_filesystem/b_file_mock.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/b_incremental_data.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/service_incremental_reverse.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/service_reverse.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp", "${path_backup}/tests/mock/backup_kit_inner/b_session_restore_async_mock.cpp", "${path_backup}/tests/mock/backup_kit_inner/b_session_restore_mock.cpp", "${path_backup}/tools/backup_tool/src/tools_op.cpp", - "${path_backup}/tools/backup_tool/src/tools_op_incremental_restore.cpp", "backup_tool/tools_op_incremental_restore_test.cpp", "backup_tool/tools_op_restore_async_test.cpp", "backup_tool/tools_op_restore_test.cpp", @@ -93,6 +103,7 @@ ohos_unittest("backup_tool_restore_test") { include_dirs = [ "${path_base}/include", + "${path_backup}/frameworks/native/backup_kit_inner/include", "${path_backup}/interfaces/inner_api/native/backup_kit_inner/impl", "${path_backup}/interfaces/inner_api/native/backup_kit_inner", "${path_backup}/tools/backup_tool/include", diff --git a/tests/unittests/backup_tools/backup_tool/tools_op_incremental_backup_test.cpp b/tests/unittests/backup_tools/backup_tool/tools_op_incremental_backup_test.cpp index a4b7542221e8ebbcbdb4634a1cf2cbfcf28be507..75727088e95476c6f2bb5dbe73e53302a028311d 100644 --- a/tests/unittests/backup_tools/backup_tool/tools_op_incremental_backup_test.cpp +++ b/tests/unittests/backup_tools/backup_tool/tools_op_incremental_backup_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-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 @@ -21,7 +21,7 @@ #include "b_resources/b_constants.h" #include "tools_op.h" -#include "tools_op_incremental_backup.h" +#include "tools_op_incremental_backup.cpp" #include "utils_mock_global_variable.h" namespace OHOS::FileManagement::Backup { @@ -178,4 +178,397 @@ HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_03 } GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_backup_0300"; } + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_0400 + * @tc.name: SUB_backup_tools_op_incremental_backup_0400 + * @tc.desc: 测试OnFileReady分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_restore_0400, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_restore_0400"; + try { + auto ctx = make_shared(); + BFileInfo fileInfo; + fileInfo.owner = "test"; + fileInfo.fileName = "/manage.json"; + fileInfo.sn = 1; + UniqueFd fd(open("textFile", O_RDONLY)); + UniqueFd manifestFd(open("textManifest", O_RDONLY)); + OnFileReady(ctx, fileInfo, move(fd), move(manifestFd)); + } catch (BError &e) { + EXPECT_EQ(e.GetCode(), BError(BError::Codes::TOOL_INVAL_ARG).GetCode()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_restore_0400"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_0500 + * @tc.name: SUB_backup_tools_op_incremental_backup_0500 + * @tc.desc: 测试OnBundleStarted分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_0500, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_0500"; + try { + auto ctx = make_shared(); + ErrCode err = 0; + BundleName name = "bundle"; + OnBundleStarted(ctx, err, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_0500"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_0501 + * @tc.name: SUB_backup_tools_op_incremental_backup_0501 + * @tc.desc: 测试OnBundleStarted分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_0501, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_0501"; + try { + auto ctx = make_shared(); + ctx->SetBundleFinishedCount(1); + ErrCode err = -1; + BundleName name = "bundle"; + OnBundleStarted(ctx, err, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_0501"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_0600 + * @tc.name: SUB_backup_tools_op_incremental_backup_0600 + * @tc.desc: 测试OnBundleFinished分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_0600, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_0600"; + try { + auto ctx = make_shared(); + ctx->SetBundleFinishedCount(1); + ErrCode err = 0; + BundleName name = "bundle"; + OnBundleFinished(ctx, err, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_0600"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_0700 + * @tc.name: SUB_backup_tools_op_incremental_backup_0700 + * @tc.desc: 测试OnAllBundlesFinished分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_0700, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_0700"; + try { + auto ctx = make_shared(); + ErrCode err = 0; + OnAllBundlesFinished(ctx, err); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_0700"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_0701 + * @tc.name: SUB_backup_tools_op_incremental_backup_0701 + * @tc.desc: 测试OnAllBundlesFinished分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_0701, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_0701"; + try { + auto ctx = make_shared(); + ErrCode err = -1; + OnAllBundlesFinished(ctx, err); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_0701"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_0800 + * @tc.name: SUB_backup_tools_op_incremental_backup_0800 + * @tc.desc: 测试OnBackupServiceDied分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_0800, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_0800"; + try { + auto ctx = make_shared(); + OnBackupServiceDied(ctx); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_0800"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_0900 + * @tc.name: SUB_backup_tools_op_incremental_backup_0900 + * @tc.desc: 测试BackupToolDirSoftlinkToBackupDir分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_0900, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_0900"; + try { + BackupToolDirSoftlinkToBackupDir(); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_0900"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_1000 + * @tc.name: SUB_backup_tools_op_incremental_backup_1000 + * @tc.desc: 测试GetLocalCapabilitiesIncremental分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_1000, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_1000"; + try { + auto ctx = make_shared(); + string pathCapFile = ""; + vector bundleNames; + bundleNames.push_back("bundle1"); + bundleNames.push_back("bundle2"); + vector times = {"100"}; + int32_t ret = GetLocalCapabilitiesIncremental(ctx, pathCapFile, bundleNames, times); + EXPECT_EQ(-EPERM, ret); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_1000"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_1001 + * @tc.name: SUB_backup_tools_op_incremental_backup_1001 + * @tc.desc: 测试GetLocalCapabilitiesIncremental分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_1001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_1001"; + try { + auto ctx = make_shared(); + string pathCapFile = "/data/backup"; + vector bundleNames; + bundleNames.push_back("bundle1"); + bundleNames.push_back("bundle2"); + vector times; + times.push_back("100"); + times.push_back("200"); + int32_t ret = GetLocalCapabilitiesIncremental(ctx, pathCapFile, bundleNames, times); + EXPECT_EQ(-EPERM, ret); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_1001"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_1100 + * @tc.name: SUB_backup_tools_op_incremental_backup_1100 + * @tc.desc: 测试Init分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_1100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_1100"; + try { + string pathCapFile = "/data/backup"; + vector bundleNames; + bundleNames.push_back("bundle1"); + bundleNames.push_back("bundle2"); + vector times; + times.push_back("100"); + times.push_back("200"); + int32_t ret = Init(pathCapFile, bundleNames, times); + EXPECT_EQ(-EPERM, ret); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_1100"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_1200 + * @tc.name: SUB_backup_tools_op_incremental_backup_1200 + * @tc.desc: 测试Exec分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_1200, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_1200"; + try { + map> mapArgToVal = { + {"pathCapFile", {"path"}}, + {"bundles", {"bundle1", "bundle2"}}, + {"incrementalTime", {"time"}} + }; + int ret = g_exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_1200"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_1201 + * @tc.name: SUB_backup_tools_op_incremental_backup_1201 + * @tc.desc: 测试Exec分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_1201, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_1201"; + try { + map> mapArgToVal = { + {"bundles", {"bundle1"}}, + {"incrementalTime", {"time"}} + }; + int ret = g_exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_1201"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_1202 + * @tc.name: SUB_backup_tools_op_incremental_backup_1202 + * @tc.desc: 测试Exec分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_1202, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_1202"; + try { + map> mapArgToVal = { + {"pathCapFile", {"path"}}, + {"incrementalTime", {"time"}} + }; + int ret = g_exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_1202"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_backup_1203 + * @tc.name: SUB_backup_tools_op_incremental_backup_1203 + * @tc.desc: 测试Exec分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalBackupTest, SUB_backup_tools_op_incremental_backup_1203, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-begin SUB_backup_tools_op_incremental_backup_1203"; + try { + map> mapArgToVal = { + {"pathCapFile", {"path"}}, + {"bundles", {"bundle1"}} + }; + int ret = g_exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalBackupTest-end SUB_backup_tools_op_incremental_backup_1203"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_tools/backup_tool/tools_op_incremental_restore_test.cpp b/tests/unittests/backup_tools/backup_tool/tools_op_incremental_restore_test.cpp index a5f8038a86e12ef98b2aca2acec51a54f144b8e0..94de5082106d9c699c1b2a846b27812cf913bb5a 100644 --- a/tests/unittests/backup_tools/backup_tool/tools_op_incremental_restore_test.cpp +++ b/tests/unittests/backup_tools/backup_tool/tools_op_incremental_restore_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-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 @@ -21,7 +21,7 @@ #include "b_resources/b_constants.h" #include "tools_op.h" -#include "tools_op_incremental_restore.h" +#include "tools_op_incremental_restore.cpp" namespace OHOS::FileManagement::Backup { using namespace std; @@ -195,4 +195,655 @@ HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_ } GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_restore_0300"; } + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_0400 + * @tc.name: SUB_backup_tools_op_incremental_restore_0400 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_0400, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_0400"; + try { + auto ctx = make_shared(); + BFileInfo fileInfo; + fileInfo.owner = "test"; + fileInfo.fileName = "/manage.json"; + fileInfo.sn = 1; + UniqueFd fd(open("textFile", O_RDONLY)); + UniqueFd manifestFd(open("textManifest", O_RDONLY)); + OnFileReady(ctx, fileInfo, move(fd), move(manifestFd), 0); + } catch (BError &e) { + EXPECT_EQ(e.GetCode(), BError(BError::Codes::TOOL_INVAL_ARG).GetCode()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_0400"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_0500 + * @tc.name: SUB_backup_tools_op_incremental_restore_0500 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_0500, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_0500"; + try { + auto ctx = make_shared(); + vector bundleNames; + bundleNames.push_back("bundle1"); + bundleNames.push_back("bundle2"); + vector times = {"100"}; + int32_t ret = InitRestoreSession(ctx, bundleNames, times); + EXPECT_EQ(-EPERM, ret); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_0500"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_0501 + * @tc.name: SUB_backup_tools_op_incremental_restore_0501 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_0501, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_0501"; + try { + auto ctx = make_shared(); + vector bundleNames; + bundleNames.push_back("bundle1"); + bundleNames.push_back("bundle2"); + vector times; + times.push_back("100"); + times.push_back("200"); + int32_t ret = InitRestoreSession(nullptr, bundleNames, times); + EXPECT_EQ(-EPERM, ret); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_0501"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_0502 + * @tc.name: SUB_backup_tools_op_incremental_restore_0502 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_0502, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_0502"; + try { + auto ctx = make_shared(); + vector bundleNames; + bundleNames.push_back("bundle1"); + bundleNames.push_back("bundle2"); + vector times; + times.push_back("10"); + times.push_back("20"); + int32_t ret = InitRestoreSession(ctx, bundleNames, times); + EXPECT_EQ(0, ret); + + BFileInfo fileInfo; + fileInfo.owner = "test"; + fileInfo.fileName = "manage.json"; + fileInfo.sn = 1; + UniqueFd fd(open("textFile", O_RDONLY)); + UniqueFd manifestFd(open("textManifest", O_RDONLY)); + OnFileReady(ctx, fileInfo, move(fd), move(manifestFd), 0); + } catch (BError &e) { + EXPECT_EQ(e.GetCode(), BError(BError::Codes::TOOL_INVAL_ARG).GetCode()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_0502"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_0600 + * @tc.name: SUB_backup_tools_op_incremental_restore_0600 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_0600, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_0600"; + try { + auto ctx = make_shared(); + ErrCode err = 0; + BundleName name = "bundle"; + OnBundleStarted(ctx, err, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_0600"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_0601 + * @tc.name: SUB_backup_tools_op_incremental_restore_0601 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_0601, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_0601"; + try { + auto ctx = make_shared(); + ctx->cnt_ = 1; + ErrCode err = -1; + BundleName name = "bundle"; + OnBundleStarted(ctx, err, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_0601"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_0700 + * @tc.name: SUB_backup_tools_op_incremental_restore_0700 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_0700, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_0700"; + try { + auto ctx = make_shared(); + ctx->cnt_ = 1; + ErrCode err = 0; + BundleName name = "bundle"; + OnBundleFinished(ctx, err, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_0700"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_0701 + * @tc.name: SUB_backup_tools_op_incremental_restore_0701 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_0701, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_0701"; + try { + auto ctx = make_shared(); + ctx->cnt_ = 1; + ErrCode err = -1; + BundleName name = "bundle"; + OnBundleFinished(ctx, err, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_0701"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_0800 + * @tc.name: SUB_backup_tools_op_incremental_restore_0800 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_0800, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_0800"; + try { + auto ctx = make_shared(); + ErrCode err = 0; + OnAllBundlesFinished(ctx, err); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_0800"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_0801 + * @tc.name: SUB_backup_tools_op_incremental_restore_0801 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_0801, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_0801"; + try { + auto ctx = make_shared(); + ErrCode err = -1; + OnAllBundlesFinished(ctx, err); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_0801"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_0900 + * @tc.name: SUB_backup_tools_op_incremental_restore_0900 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_0900, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_0900"; + try { + auto ctx = make_shared(); + OnBackupServiceDied(ctx); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_0900"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1000 + * @tc.name: SUB_backup_tools_op_incremental_restore_1000 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1000, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1000"; + try { + shared_ptr restore = nullptr; + RestoreApp(restore); + } catch (BError &e) { + EXPECT_EQ(e.GetCode(), BError(BError::Codes::TOOL_INVAL_ARG).GetCode()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1000"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1001 + * @tc.name: SUB_backup_tools_op_incremental_restore_1001 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1001"; + try { + shared_ptr restore = make_shared(); + restore->session_ = nullptr; + RestoreApp(restore); + } catch (BError &e) { + EXPECT_EQ(e.GetCode(), BError(BError::Codes::TOOL_INVAL_ARG).GetCode()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1001"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1002 + * @tc.name: SUB_backup_tools_op_incremental_restore_1002 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1002"; + try { + shared_ptr restore = make_shared(); + restore->session_ = {}; + BIncrementalData data("text", 1); + restore->lastIncrementalData = {data}; + RestoreApp(restore); + EXPECT_TRUE(true); + } catch (BError &e) { + EXPECT_EQ(e.GetCode(), BError(BError::Codes::TOOL_INVAL_ARG).GetCode()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1002"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1003 + * @tc.name: SUB_backup_tools_op_incremental_restore_1003 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1003"; + try { + auto ctx = make_shared(); + vector bundleNames; + bundleNames.push_back("bundle1"); + bundleNames.push_back("bundle2"); + vector times; + times.push_back("10"); + times.push_back("20"); + int32_t ret = InitRestoreSession(ctx, bundleNames, times); + EXPECT_EQ(0, ret); + + RestoreApp(ctx); + EXPECT_TRUE(ctx); + } catch (BError &e) { + EXPECT_EQ(e.GetCode(), BError(BError::Codes::TOOL_INVAL_ARG).GetCode()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1003"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1100 + * @tc.name: SUB_backup_tools_op_incremental_restore_1100 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1100"; + try { + string pathCapFile = ""; + vector bundleNames = {"com.example.app2backup/"}; + bool depMode = true; + vector times = {"10"}; + int32_t ret = Init(pathCapFile, bundleNames, depMode, times); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1100"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1101 + * @tc.name: SUB_backup_tools_op_incremental_restore_1101 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1101"; + try { + string pathCapFile = "/data/backup"; + vector bundleNames = {"com.example.app2backup/"}; + bool depMode = true; + vector times = {"1"}; + int32_t ret = Init(pathCapFile, bundleNames, depMode, times); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1101"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1102 + * @tc.name: SUB_backup_tools_op_incremental_restore_1102 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1102, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1102"; + try { + string pathCapFile = ""; + vector bundleNames = {"com.example.app2backup/"}; + bool depMode = false; + vector times = {"10"}; + int32_t ret = Init(pathCapFile, bundleNames, depMode, times); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1102"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1200 + * @tc.name: SUB_backup_tools_op_incremental_restore_1200 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1200, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1200"; + try { + map> mapArgToVal; + mapArgToVal["depMode"] = {"false"}; + g_exec(mapArgToVal); + EXPECT_EQ(mapArgToVal["depMode"][0], "false"); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1200"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1201 + * @tc.name: SUB_backup_tools_op_incremental_restore_1201 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1201, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1201"; + try { + map> mapArgToVal = { + {"pathCapFile", {"path"}}, + {"bundles", {"bundle1"}}, + {"incrementalTime", {"time"}} + }; + int ret = g_exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1201"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1202 + * @tc.name: SUB_backup_tools_op_incremental_restore_1202 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1202, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1202"; + try { + map> mapArgToVal = { + {"bundles", {"bundle1"}}, + {"incrementalTime", {"time"}} + }; + int ret = g_exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1202"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1203 + * @tc.name: SUB_backup_tools_op_incremental_restore_1203 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1203, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1203"; + try { + map> mapArgToVal = { + {"pathCapFile", {"path"}}, + {"bundles", {"bundle1"}}, + {"incrementalTime", {"time"}}, + {"depMode", {"true"}} + }; + int ret = g_exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1203"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1204 + * @tc.name: SUB_backup_tools_op_incremental_restore_1204 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1204, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1204"; + try { + map> mapArgToVal = { + {"pathCapFile", {"path"}}, + {"incrementalTime", {"time"}} + }; + int ret = g_exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1204"; +} + +/** + * @tc.number: SUB_backup_tools_op_incremental_restore_1205 + * @tc.name: SUB_backup_tools_op_incremental_restore_1205 + * @tc.desc: 测试 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ToolsOpIncrementalRestoreTest, SUB_backup_tools_op_incremental_restore_1205, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-begin SUB_backup_tools_op_incremental_restore_1205"; + try { + map> mapArgToVal = { + {"pathCapFile", {"path"}}, + {"bundles", {"bundle1"}} + }; + int ret = g_exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpIncrementalRestoreTest-end SUB_backup_tools_op_incremental_restore_1205"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_tools/backup_tool/tools_op_restore_async_test.cpp b/tests/unittests/backup_tools/backup_tool/tools_op_restore_async_test.cpp index c7f7a7b9e6e3d66e676b36c9e284cf5c0a9a4a32..cc797c548c9475a7a4664552ec0d23784e5331e4 100644 --- a/tests/unittests/backup_tools/backup_tool/tools_op_restore_async_test.cpp +++ b/tests/unittests/backup_tools/backup_tool/tools_op_restore_async_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 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 @@ -293,6 +293,32 @@ HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_0400, testing::ext::Tes GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-end tools_op_restore_async_0400"; } +/** + * @tc.number: SUB_backup_tools_op_restore_async_0401 + * @tc.name: tools_op_restore_async_0401 + * @tc.desc: test func + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9JNFM + */ +HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_0401, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-begin tools_op_restore_async_0401"; + try { + auto ctx = make_shared(); + ctx->cnt_ = 1; + ErrCode err = -1; + BundleName name = "testBundle"; + OnBundleStarted(ctx, err, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-end tools_op_restore_async_0401"; +} + /** * @tc.number: SUB_backup_tools_op_restore_async_0500 * @tc.name: tools_op_restore_async_0500 @@ -318,6 +344,32 @@ HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_0500, testing::ext::Tes GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-end tools_op_restore_async_0500"; } +/** + * @tc.number: SUB_backup_tools_op_restore_async_0501 + * @tc.name: tools_op_restore_async_0501 + * @tc.desc: 测试OnBundleFinished方法 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9JNFM + */ +HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_0501, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-begin tools_op_restore_async_0501"; + try { + auto ctx = make_shared(); + ctx->cnt_ = 1; + ErrCode err = -1; + BundleName name = "testBundle"; + OnBundleFinished(ctx, err, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-end tools_op_restore_async_0501"; +} + /** * @tc.number: SUB_backup_tools_op_restore_async_0600 * @tc.name: tools_op_restore_async_0600 @@ -452,8 +504,9 @@ HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_1001, testing::ext::Tes GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-begin tools_op_restore_async_1001"; try { vector bundleNames; - bundleNames.push_back("bundle/name");\ + bundleNames.push_back("bundle/name"); shared_ptr restore = make_shared(); + restore->session_ = {}; RestoreApp(restore, bundleNames); } catch (BError &e) { EXPECT_EQ(e.GetCode(), BError(BError::Codes::TOOL_INVAL_ARG).GetCode()); @@ -479,8 +532,9 @@ HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_1002, testing::ext::Tes GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-begin tools_op_restore_async_1002"; try { vector bundleNames; - bundleNames.push_back("bundlename");\ + bundleNames.push_back("bundlename"); shared_ptr restore = make_shared(); + restore->session_ = {}; RestoreApp(restore, bundleNames); } catch (BError &e) { EXPECT_EQ(e.GetCode(), BError(BError::Codes::TOOL_INVAL_ARG).GetCode()); @@ -508,7 +562,7 @@ HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_1100, testing::ext::Tes string pathCapFile = "/data/user/0/test/files/bundleInfo.json"; vector bundleNames = {"bundlenames"}; string type = "false"; - int32_t ret =ChangeBundleInfo(pathCapFile, bundleNames, type); + int32_t ret = ChangeBundleInfo(pathCapFile, bundleNames, type); EXPECT_LT(ret, 0); } catch (...) { EXPECT_TRUE(false); @@ -533,7 +587,7 @@ HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_1101, testing::ext::Tes string pathCapFile = " "; vector bundleNames = {"bundlenames"}; string type = "false"; - int32_t ret =ChangeBundleInfo(pathCapFile, bundleNames, type); + int32_t ret = ChangeBundleInfo(pathCapFile, bundleNames, type); EXPECT_LT(ret, 0); } catch (...) { EXPECT_TRUE(false); @@ -558,7 +612,7 @@ HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_1102, testing::ext::Tes string pathCapFile = "/data/user/0/test/files/bundleInfo.json"; vector bundleNames = {}; string type = "true"; - int32_t ret =ChangeBundleInfo(pathCapFile, bundleNames, type); + int32_t ret = ChangeBundleInfo(pathCapFile, bundleNames, type); EXPECT_LT(ret, 0); } catch (...) { EXPECT_TRUE(false); @@ -768,7 +822,6 @@ HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_1401, testing::ext::Tes { GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-begin tools_op_restore_async_1401"; try { - map> mapArgToVal; int ret = Exec(mapArgToVal); EXPECT_EQ(ret, -EPERM); @@ -778,4 +831,97 @@ HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_1401, testing::ext::Tes } GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-end tools_op_restore_async_1401"; } + +/** + * @tc.number: SUB_backup_tools_op_restore_async_1500 + * @tc.name: tools_op_restore_async_1500 + * @tc.desc: test func + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9NOPD + */ +HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_1500, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-begin tools_op_restore_async_1500"; + try { + std::string path = "/data/backup/receive"; + std::vector pkgInfo; + ExtManageInfo info; + info.hashName = "hashName"; + info.fileName = "fileName"; + info.isBigFile = false; + info.isUserTar = false; + pkgInfo.push_back(info); + + auto result = ReadyExtManage(path, pkgInfo); + EXPECT_EQ(result.size(), 1); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-end tools_op_restore_async_1500"; +} + +/** + * @tc.number: SUB_backup_tools_op_restore_async_1501 + * @tc.name: tools_op_restore_async_1501 + * @tc.desc: test func + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9NOPD + */ +HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_1501, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-begin tools_op_restore_async_1501"; + try { + std::string path = "/data/backup/receive"; + std::vector pkgInfo; + ExtManageInfo info; + info.hashName = ""; + info.fileName = ""; + info.isBigFile = false; + info.isUserTar = false; + pkgInfo.push_back(info); + + auto result = ReadyExtManage(path, pkgInfo); + EXPECT_EQ(result.size(), 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-end tools_op_restore_async_1501"; +} + +/** + * @tc.number: SUB_backup_tools_op_restore_async_1502 + * @tc.name: tools_op_restore_async_1502 + * @tc.desc: test func + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9NOPD + */ +HWTEST_F(ToolsOpRestoreAsyncTest, tools_op_restore_async_1502, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-begin tools_op_restore_async_1502"; + try { + std::string path = "/data/backup/receive"; + std::vector pkgInfo; + ExtManageInfo info; + info.hashName = "hashName"; + info.fileName = "fileName"; + info.isBigFile = true; + info.isUserTar = true; + pkgInfo.push_back(info); + + auto result = ReadyExtManage(path, pkgInfo); + EXPECT_EQ(result.size(), 1); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreAsyncTest-end tools_op_restore_async_1502"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_tools/backup_tool/tools_op_restore_test.cpp b/tests/unittests/backup_tools/backup_tool/tools_op_restore_test.cpp index 3d7220db85a358fa0c4f93d12d617b5967018527..7f594449ebc3416ce4862b29916a89d4d0fa4210 100644 --- a/tests/unittests/backup_tools/backup_tool/tools_op_restore_test.cpp +++ b/tests/unittests/backup_tools/backup_tool/tools_op_restore_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-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 @@ -432,6 +432,129 @@ HWTEST_F(ToolsOpRestoreTest, tools_op_restore_OnBundleStarted_0601, testing::ext GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_OnBundleStarted_0601"; } +/** + * @tc.number: SUB_backup_tools_op_restore_0700 + * @tc.name: tools_op_restore_OnBundleFinished_0700 + * @tc.desc: test func + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9NOPD + */ +HWTEST_F(ToolsOpRestoreTest, tools_op_restore_OnBundleFinished_0700, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-begin tools_op_restore_OnBundleFinished_0700"; + try { + auto ctx = make_shared(); + ctx->cnt_ = 1; + ErrCode err = 0; + BundleName name = BUNDLE_NAME; + OnBundleFinished(ctx, err, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_OnBundleFinished_0700"; +} + +/** + * @tc.number: SUB_backup_tools_op_restore_0701 + * @tc.name: tools_op_restore_OnBundleFinished_0701 + * @tc.desc: test func + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9NOPD + */ +HWTEST_F(ToolsOpRestoreTest, tools_op_restore_OnBundleFinished_0701, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-begin tools_op_restore_OnBundleFinished_0701"; + try { + auto ctx = make_shared(); + ctx->cnt_ = 1; + ErrCode err = -1; + BundleName name = BUNDLE_NAME; + OnBundleFinished(ctx, err, name); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_OnBundleFinished_0701"; +} + +/** + * @tc.number: SUB_backup_tools_op_restore_0702 + * @tc.name: tools_op_restore_OnBundleFinished_0702 + * @tc.desc: test func + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9NOPD + */ +HWTEST_F(ToolsOpRestoreTest, tools_op_restore_OnBundleFinished_0702, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-begin tools_op_restore_OnBundleFinished_0702"; + try { + auto ctx = make_shared(); + ErrCode err = 0; + OnAllBundlesFinished(ctx, err); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_OnBundleFinished_0702"; +} + +/** + * @tc.number: SUB_backup_tools_op_restore_0703 + * @tc.name: tools_op_restore_OnBundleFinished_0703 + * @tc.desc: test func + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9NOPD + */ +HWTEST_F(ToolsOpRestoreTest, tools_op_restore_OnBundleFinished_0703, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-begin tools_op_restore_OnBundleFinished_0703"; + try { + auto ctx = make_shared(); + ErrCode err = -1; + OnAllBundlesFinished(ctx, err); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_OnBundleFinished_0703"; +} + +/** + * @tc.number: SUB_backup_tools_op_restore_0704 + * @tc.name: tools_op_restore_OnBundleFinished_0704 + * @tc.desc: test func + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9NOPD + */ +HWTEST_F(ToolsOpRestoreTest, tools_op_restore_OnBundleFinished_0704, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-begin tools_op_restore_OnBundleFinished_0704"; + try { + auto ctx = make_shared(); + OnBackupServiceDied(ctx); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_OnBundleFinished_0704"; +} + /** * @tc.number: SUB_backup_tools_op_restore_0800 * @tc.name: tools_op_restore_OnResultReport_0800 @@ -639,6 +762,31 @@ HWTEST_F(ToolsOpRestoreTest, tools_op_restore_InitRestoreSession_1100, testing:: GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_GInitRestoreSession_1100"; } +/** + * @tc.number: SUB_backup_tools_op_restore_1101 + * @tc.name: tools_op_restore_InitRestoreSession_1101 + * @tc.desc: 测试当ctx + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9NOPD + */ +HWTEST_F(ToolsOpRestoreTest, tools_op_restore_InitRestoreSession_1101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-begin tools_op_restore_InitRestoreSession_1101"; + try { + shared_ptr ctx = make_shared(); + InitRestoreSession(ctx); + } catch (BError &e) { + EXPECT_EQ(e.GetCode(), BError(BError::Codes::TOOL_INVAL_ARG).GetCode()); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_InitRestoreSession_1101"; +} + /** * @tc.number: SUB_backup_tools_op_restore_1200 * @tc.name: tools_op_restore_InitPathCapFile_1200 @@ -664,6 +812,56 @@ HWTEST_F(ToolsOpRestoreTest, tools_op_restore_InitPathCapFile_1200, testing::ext GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_InitPathCapFile_1200"; } +/** + * @tc.number: SUB_backup_tools_op_restore_1201 + * @tc.name: tools_op_restore_InitPathCapFile_1201 + * @tc.desc: test func + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9NOPD + */ +HWTEST_F(ToolsOpRestoreTest, tools_op_restore_InitPathCapFile_1201, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-begin tools_op_restore_InitPathCapFile_1201"; + try { + string pathCapFile = "/data/backup/tmp"; + vector bundleNames = {"com.example.app2backup/"}; + bool depMode = true; + int32_t ret = InitPathCapFile(pathCapFile, bundleNames, depMode); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_InitPathCapFile_1201"; +} + +/** + * @tc.number: SUB_backup_tools_op_restore_1202 + * @tc.name: tools_op_restore_InitPathCapFile_1202 + * @tc.desc: test func + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9NOPD + */ +HWTEST_F(ToolsOpRestoreTest, tools_op_restore_InitPathCapFile_1202, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-begin tools_op_restore_InitPathCapFile_1202"; + try { + string pathCapFile = "/data/backup/tmp"; + vector bundleNames = {"com.example.app2backup/"}; + bool depMode = false; + int32_t ret = InitPathCapFile(pathCapFile, bundleNames, depMode); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_InitPathCapFile_1202"; +} + /** * @tc.number: SUB_backup_tools_op_restore_1300 * @tc.name: tools_op_restore_Exec_1300 @@ -767,4 +965,29 @@ HWTEST_F(ToolsOpRestoreTest, tools_op_restore_Exec_1303, testing::ext::TestSize. } GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_Exec_1303"; } + +/** + * @tc.number: SUB_backup_tools_op_restore_1304 + * @tc.name: tools_op_restore_Exec_1304 + * @tc.desc: test func + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I9NOPD + */ +HWTEST_F(ToolsOpRestoreTest, tools_op_restore_Exec_1304, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-begin tools_op_restore_Exec_1304"; + try { + map> mapArgToVal; + mapArgToVal["pathCapFile"] = {"/data/backup/recived/com.example.app2backup/"}; + mapArgToVal["bundles"] = {"com.example.app2backup/"}; + int ret = Exec(mapArgToVal); + EXPECT_LT(ret, 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-an exception occurred by construction."; + } + GTEST_LOG_(INFO) << "ToolsOpRestoreTest-end tools_op_restore_Exec_1304"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_utils/BUILD.gn b/tests/unittests/backup_utils/BUILD.gn index 40476eb1bc07c723cb250aff488ce0299725b90a..47be52ea6dd1446c0188c4ae061912a00918e737 100644 --- a/tests/unittests/backup_utils/BUILD.gn +++ b/tests/unittests/backup_utils/BUILD.gn @@ -54,6 +54,8 @@ ohos_unittest("b_file_test") { "b_filesystem/b_file_test.cpp", ] + include_dirs = [ "${path_backup}/utils/src/b_filesystem" ] + deps = [ "${path_backup}/tests/utils:backup_test_utils", "${path_backup}/utils/:backup_utils", @@ -293,6 +295,7 @@ group("backup_test") { ":b_file_test", ":b_json_other_test", ":b_json_test", + ":b_jsonutil_test", ":b_process_test", ":b_tarball_cmdline_test", ":b_tarball_factory_test", diff --git a/tests/unittests/backup_utils/b_error/b_error_test.cpp b/tests/unittests/backup_utils/b_error/b_error_test.cpp index d48c401d7f3cfe0a1db5e3bb6ca29dcaecad66a0..027edb73998249ca89a499945825c4c25f8b55a1 100644 --- a/tests/unittests/backup_utils/b_error/b_error_test.cpp +++ b/tests/unittests/backup_utils/b_error/b_error_test.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-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 @@ -452,4 +452,58 @@ HWTEST_F(BErrorTest, b_error_int_0100, testing::ext::TestSize.Level0) EXPECT_EQ(result, 0); GTEST_LOG_(INFO) << "BErrorTest-end b_error_int_0100"; } + +/** + * @tc.number: SUB_backup_b_error_GetCodeByErrno_0100 + * @tc.name: b_error_GetCodeByErrno_0100 + * @tc.desc: Test function of int interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BErrorTest, b_error_GetCodeByErrno_0100, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BErrorTest-begin b_error_GetCodeByErrno_0100"; + int32_t errnoSys = 0; + int result = BError::GetCodeByErrno(errnoSys); + EXPECT_EQ(result, 0); + GTEST_LOG_(INFO) << "BErrorTest-end b_error_GetCodeByErrno_0100"; +} + +/** + * @tc.number: SUB_backup_b_error_GetCodeByErrno_0200 + * @tc.name: b_error_GetCodeByErrno_0200 + * @tc.desc: Test function of int interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BErrorTest, b_error_GetCodeByErrno_0200, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BErrorTest-begin b_error_GetCodeByErrno_0200"; + int32_t errnoSys = EPERM; + int result = BError::GetCodeByErrno(errnoSys); + EXPECT_EQ(result, BError::BackupErrorCode::E_IPCSS); + GTEST_LOG_(INFO) << "BErrorTest-end b_error_GetCodeByErrno_0200"; +} + +/** + * @tc.number: SUB_backup_b_error_GetCodeByErrno_0300 + * @tc.name: b_error_GetCodeByErrno_0300 + * @tc.desc: Test function of int interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BErrorTest, b_error_GetCodeByErrno_0300, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BErrorTest-begin b_error_GetCodeByErrno_0300"; + int32_t errnoSys = -EPERM; + int result = BError::GetCodeByErrno(errnoSys); + EXPECT_EQ(result, BError::BackupErrorCode::E_UKERR); + GTEST_LOG_(INFO) << "BErrorTest-end b_error_GetCodeByErrno_0300"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_utils/b_filesystem/b_dir_test.cpp b/tests/unittests/backup_utils/b_filesystem/b_dir_test.cpp index fc93f542ff066a40012f593fdd5117bbdf1e2f1e..531a634068daea86216edfda91281b66399674f2 100644 --- a/tests/unittests/backup_utils/b_filesystem/b_dir_test.cpp +++ b/tests/unittests/backup_utils/b_filesystem/b_dir_test.cpp @@ -24,6 +24,7 @@ #include #include "b_filesystem/b_dir.h" +#include "b_dir.cpp" #include "b_process/b_process.h" #include "test_manager.h" @@ -318,4 +319,28 @@ HWTEST_F(BDirTest, b_dir_GetDirs_0100, testing::ext::TestSize.Level1) GTEST_LOG_(INFO) << "BDirTest-end b_dir_GetDirs_0100"; } +/** + * @tc.number: SUB_backup_b_dir_GetFile_0100 + * @tc.name: b_dir_GetFile_0100 + * @tc.desc: Test function of GetFile interface for SUCCESS + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(BDirTest, b_dir_GetFile_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BDirTest-begin b_dir_GetFile_0100"; + try { + string path = "/"; + auto [errCode, subFiles, subSmallFiles] = GetFile(path); + string pathData = "/data"; + auto [errCode1, subFiles1, subSmallFiles1] = GetFile(pathData, PATH_MAX_LEN); + auto [errCode2, subFiles2, subSmallFiles2] = GetFile(pathData); + EXPECT_EQ(errCode, 0); + } catch (...) { + GTEST_LOG_(INFO) << "BDirTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BDirTest-end b_dir_GetFile_0100"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_utils/b_filesystem/b_file_hash_test.cpp b/tests/unittests/backup_utils/b_filesystem/b_file_hash_test.cpp index a0f8621a8dc4d1c4ec672f0cdd7c6376339f5b66..bedfa2e60bd566005d67345090e3cd916e1a411a 100644 --- a/tests/unittests/backup_utils/b_filesystem/b_file_hash_test.cpp +++ b/tests/unittests/backup_utils/b_filesystem/b_file_hash_test.cpp @@ -74,4 +74,26 @@ HWTEST_F(BFileHashTest, b_file_hash_HashWithSHA256_0100, testing::ext::TestSize. } GTEST_LOG_(INFO) << "BFileHashTest-end b_file_hash_HashWithSHA256_0100"; } + +/** + * @tc.number: SUB_backup_b_file_hash_HashWithSHA256_0101 + * @tc.name: b_file_hash_HashWithSHA256_0100 + * @tc.desc: Test function of HashWithSHA256 interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(BFileHashTest, b_file_hash_HashWithSHA256_0101, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BFileHashTest-begin b_file_hash_HashWithSHA256_0101"; + try { + std::string filePath = "/errPath"; + auto [res, fileHash] = BackupFileHash::HashWithSHA256(filePath); + EXPECT_NE(res, 0); + } catch (const exception &e) { + GTEST_LOG_(INFO) << "BFileHashTest-an exception occurred by HashWithSHA256."; + e.what(); + } + GTEST_LOG_(INFO) << "BFileHashTest-end b_file_hash_HashWithSHA256_0101"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_utils/b_json/b_json_entity_ext_manage_test.cpp b/tests/unittests/backup_utils/b_json/b_json_entity_ext_manage_test.cpp index a09c55ebcb4078fde2d0f056290d2126acc82c6c..239a274bd5d832f0ff427e16b675148c0f5a7598 100644 --- a/tests/unittests/backup_utils/b_json/b_json_entity_ext_manage_test.cpp +++ b/tests/unittests/backup_utils/b_json/b_json_entity_ext_manage_test.cpp @@ -526,6 +526,31 @@ HWTEST_F(BJsonEntityExtManageTest, b_json_entity_ext_manage_0803, testing::ext:: GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-end b_json_entity_ext_manage_0803"; } +/** + * @tc.number: SUB_backup_b_json_entity_ext_manage_0804 + * @tc.name: b_json_entity_ext_manage_0804 + * @tc.desc: 测试GetExtManageInfo + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonEntityExtManageTest, b_json_entity_ext_manage_0804, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-begin b_json_entity_ext_manage_0804"; + try { + string_view sv = R"([{"isBigFile":false}, {"fileName":"test"}])"; + BJsonCachedEntity cachedEntity(sv); + auto cache = cachedEntity.Structuralize(); + auto mp = cache.GetExtManageInfo(); + EXPECT_TRUE(mp.empty()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-end b_json_entity_ext_manage_0804"; +} + /** * @tc.number: SUB_backup_b_json_entity_ext_manage_0900 * @tc.name: b_json_entity_ext_manage_0900 @@ -674,4 +699,32 @@ HWTEST_F(BJsonEntityExtManageTest, b_json_entity_ext_manage_0903, testing::ext:: } GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-end b_json_entity_ext_manage_0903"; } + +/** + * @tc.number: SUB_backup_b_json_entity_ext_manage_0904 + * @tc.name: b_json_entity_ext_manage_0904 + * @tc.desc: 测试CheckOwnPackTar各种异常分支 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issuesI9JXNH + */ +HWTEST_F(BJsonEntityExtManageTest, b_json_entity_ext_manage_0904, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-begin b_json_entity_ext_manage_0904"; + try { + string fileName = "/home/user/test.tar"; + auto ret = CheckOwnPackTar(fileName); + EXPECT_FALSE(ret); + + fileName = string(BConstants::PATH_BUNDLE_BACKUP_HOME) + .append(BConstants::SA_BUNDLE_BACKUP_BACKUP).append("/part1.tar"); + ret = CheckOwnPackTar(fileName); + EXPECT_TRUE(ret); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonEntityExtManageTest-end b_json_entity_ext_manage_0904"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_utils/b_json/b_report_entity_test.cpp b/tests/unittests/backup_utils/b_json/b_report_entity_test.cpp index 3e51ac25818a0f48ff46284217bc782764ccb5bf..cbdba7332b544426885262d980bc04c16559f53b 100644 --- a/tests/unittests/backup_utils/b_json/b_report_entity_test.cpp +++ b/tests/unittests/backup_utils/b_json/b_report_entity_test.cpp @@ -227,4 +227,124 @@ HWTEST_F(BReportEntityTest, b_report_entity_DealLine_0100, testing::ext::TestSiz GTEST_LOG_(INFO) << "BReportEntityTest-end b_report_entity_DealLine_0100"; } +/** + * @tc.number: SUB_backup_b_report_entity_DealLine_0101 + * @tc.name: b_report_entity_DealLine_0101 + * @tc.desc: Test function of DealLine interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(BReportEntityTest, b_report_entity_DealLine_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BReportEntityTest-begin b_report_entity_DealLine_0101"; + try { + unordered_map keys; + int num = 1; + string line = ""; + unordered_map infos; + DealLine(keys, num, line, infos); + EXPECT_EQ(infos.size(), 0); + } catch (const exception &e) { + GTEST_LOG_(INFO) << "BReportEntityTest-an exception occurred by DealLine. " << e.what(); + EXPECT_TRUE(false); + } + GTEST_LOG_(INFO) << "BReportEntityTest-end b_report_entity_DealLine_0101"; +} + +/** + * @tc.number: SUB_backup_b_report_entity_StorageDealLine_0100 + * @tc.name: b_report_entity_StorageDealLine_0100 + * @tc.desc: Test function of DealLine interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(BReportEntityTest, b_report_entity_StorageDealLine_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BReportEntityTest-begin b_report_entity_StorageDealLine_0100"; + try { + unordered_map keys; + int num = 1; + string line = ""; + StorageDealLine(keys, num, line); + EXPECT_TRUE(true); + } catch (const exception &e) { + GTEST_LOG_(INFO) << "BReportEntityTest-an exception occurred by DealLine. " << e.what(); + EXPECT_TRUE(false); + } + GTEST_LOG_(INFO) << "BReportEntityTest-end b_report_entity_StorageDealLine_0100"; +} + +/** + * @tc.number: SUB_backup_b_report_entity_StorageDealLine_0101 + * @tc.name: b_report_entity_StorageDealLine_0101 + * @tc.desc: Test function of DealLine interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(BReportEntityTest, b_report_entity_StorageDealLine_0101, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BReportEntityTest-begin b_report_entity_StorageDealLine_0101"; + try { + unordered_map keys; + int num = 0; + string line = "test\r"; + StorageDealLine(keys, num, line); + EXPECT_TRUE(true); + } catch (const exception &e) { + GTEST_LOG_(INFO) << "BReportEntityTest-an exception occurred by DealLine. " << e.what(); + EXPECT_TRUE(false); + } + GTEST_LOG_(INFO) << "BReportEntityTest-end b_report_entity_StorageDealLine_0101"; +} + +/** + * @tc.number: SUB_backup_b_report_entity_StorageDealLine_0102 + * @tc.name: b_report_entity_StorageDealLine_0102 + * @tc.desc: Test function of DealLine interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(BReportEntityTest, b_report_entity_StorageDealLine_0102, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BReportEntityTest-begin b_report_entity_StorageDealLine_0102"; + try { + unordered_map keys; + int num = 1; + string line = "key1;key2;key3"; + StorageDealLine(keys, num, line); + EXPECT_TRUE(true); + } catch (const exception &e) { + GTEST_LOG_(INFO) << "BReportEntityTest-an exception occurred by DealLine. " << e.what(); + EXPECT_TRUE(false); + } + GTEST_LOG_(INFO) << "BReportEntityTest-end b_report_entity_StorageDealLine_0102"; +} + +/** + * @tc.number: SUB_backup_b_report_entity_StorageDealLine_0103 + * @tc.name: b_report_entity_StorageDealLine_0103 + * @tc.desc: Test function of DealLine interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(BReportEntityTest, b_report_entity_StorageDealLine_0103, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BReportEntityTest-begin b_report_entity_StorageDealLine_0103"; + try { + unordered_map keys; + int num = INFO_ALIGN_NUM; + string line = "key1;key2;key3"; + StorageDealLine(keys, num, line); + EXPECT_TRUE(true); + } catch (const exception &e) { + GTEST_LOG_(INFO) << "BReportEntityTest-an exception occurred by DealLine. " << e.what(); + EXPECT_TRUE(false); + } + GTEST_LOG_(INFO) << "BReportEntityTest-end b_report_entity_StorageDealLine_0103"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_utils/b_jsonutil/b_jsonutil_test.cpp b/tests/unittests/backup_utils/b_jsonutil/b_jsonutil_test.cpp index e21b944df14a0dca02301b77c6246491a6e061e1..f1536a8510faa178482c75c5239a4fae7131522b 100644 --- a/tests/unittests/backup_utils/b_jsonutil/b_jsonutil_test.cpp +++ b/tests/unittests/backup_utils/b_jsonutil/b_jsonutil_test.cpp @@ -30,6 +30,10 @@ namespace OHOS::FileManagement::Backup { using namespace std; +namespace { +constexpr uint32_t TEST_USER_ID = 100; +} // namespace + class BJsonUtilTest : public testing::Test { public: static void SetUpTestCase(void) {}; @@ -52,8 +56,7 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_ParseBundleNameIndexStr_0100, testing::ext::T GTEST_LOG_(INFO) << "BJsonUtilTest-begin b_dir_GetDirFiles_0100"; try { std::string bundleName = "com.hos.app01:1"; - std::string pattern = ":"; - BJsonUtil::BundleDetailInfo detailInfo = BJsonUtil::ParseBundleNameIndexStr(bundleName, pattern); + BJsonUtil::BundleDetailInfo detailInfo = BJsonUtil::ParseBundleNameIndexStr(bundleName); EXPECT_EQ("com.hos.app01", detailInfo.bundleName); } catch (...) { EXPECT_TRUE(false); @@ -62,6 +65,29 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_ParseBundleNameIndexStr_0100, testing::ext::T GTEST_LOG_(INFO) << "BDirTest-end b_dir_GetDirFiles_0100"; } +/** + * @tc.number: b_jsonutil_ParseBundleNameIndexStr_0200 + * @tc.name: b_jsonutil_ParseBundleNameIndexStr_0200 + * @tc.desc: Test function of ParseBundleNameIndexStr interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_ParseBundleNameIndexStr_0200, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin ParseBundleNameIndexStr_0200"; + try { + std::string bundleName = "com.hos.app01"; + BJsonUtil::BundleDetailInfo detailInfo = BJsonUtil::ParseBundleNameIndexStr(bundleName); + EXPECT_EQ("com.hos.app01", detailInfo.bundleName); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BDirTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BDirTest-end ParseBundleNameIndexStr_0200"; +} + /** * @tc.number: b_jsonutil_BuildBundleInfos_0100 * @tc.name: b_jsonutil_BuildBundleInfos_0100 @@ -77,63 +103,473 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0100, testing::ext::TestSize try { std::vector bundleNames; std::string bundleName = "com.hos.app01:1"; - std::string bundleName1 = "com.hos.app02"; bundleNames.push_back(bundleName); - bundleNames.push_back(bundleName1); - std::string pattern = ":"; - std::vector detailInfos; - std::string detail01 = "{ - "infos" : [ { - "details" : [ { - "detail" : [ { "source" : "com.ohos.app01", "target" : "com.hos.app01" } ], - "type" : "app_mapping_relation" } ], - "type" : "broadcast" } ] - }"; - detailInfos.push_back(detail01); - detailInfos.push_back(""); - int32_t userId = 100; - std::vector realBundleNames; - std::map> bundleNameDetailMap = - BJsonUtil::BuildBundleInfos(bundleNames, detailInfos, realBundleNames, userId); - std::string key = "com.hos.app01"; - EXPECT_EQ("com.hos.app01", bundleNameDetailMap[key].bundleName[0]); + std::vector bundleInfos; + std::string bundleInfo = "info1"; + std::string bundleInfo2 = "info2"; + bundleInfos.push_back(bundleInfo); + bundleInfos.push_back(bundleInfo2); + int32_t userId = TEST_USER_ID; + std::vector bundleNamesOnly; + std::map isClearDataFlags; + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + userId, isClearDataFlags); + EXPECT_TRUE(result.empty()); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; } - GTEST_LOG_(INFO) << "BJsonUtilTest-end b_dir_BuildBundleInfos_0100"; + GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildBundleInfos_0100"; } -/* * - * @tc.number: b_jsonutil_BuildBundleInfos_0101 - * @tc.name: b_jsonutil_BuildBundleInfos_0101 - * @tc.desc: Test function of BuildBundleInfos for enmpty. +/** + * @tc.number: b_jsonutil_BuildBundleInfos_0200 + * @tc.name: b_jsonutil_BuildBundleInfos_0200 + * @tc.desc: Test function of BuildBundleInfos interface for SUCCESS. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 0 * @tc.require: I6F3GV */ -HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0101, testing::ext::TestSize.Level0) +HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0200, testing::ext::TestSize.Level0) { - GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildBundleInfos_0101"; + GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildBundleInfos_0200"; try { std::vector bundleNames; - std::string bundleName = "com.hos.app01:1"; - std::string bundleName1 = "com.hos.app02"; + std::string bundleName = "bundle"; + bundleNames.push_back(bundleName); + std::vector bundleInfos; + std::string bundleInfo = "{\"infos\":\"infos\"}"; + bundleInfos.push_back(bundleInfo); + int32_t userId = TEST_USER_ID; + std::vector bundleNamesOnly; + std::map isClearDataFlags; + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + userId, isClearDataFlags); + EXPECT_FALSE(result.empty()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildBundleInfos_0200"; +} + +/** + * @tc.number: b_jsonutil_BuildBundleInfos_0300 + * @tc.name: b_jsonutil_BuildBundleInfos_0300 + * @tc.desc: Test function of BuildBundleInfos interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0300, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildBundleInfos_0300"; + try { + std::vector bundleNames; + std::string bundleName = "bundle1:"; + bundleNames.push_back(bundleName); + std::vector bundleInfos; + std::string bundleInfo = "info1"; + bundleInfos.push_back(bundleInfo); + int32_t userId = TEST_USER_ID; + std::vector bundleNamesOnly; + std::map isClearDataFlags; + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + userId, isClearDataFlags); + EXPECT_TRUE(result.empty()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildBundleInfos_0300"; +} + +/** + * @tc.number: b_jsonutil_BuildBundleInfos_0301 + * @tc.name: b_jsonutil_BuildBundleInfos_0301 + * @tc.desc: Test function of BuildBundleInfos interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0301, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildBundleInfos_0301"; + try { + std::vector bundleNames; + std::string bundleName = ":bundle1"; + bundleNames.push_back(bundleName); + std::vector bundleInfos; + std::string bundleInfo = "info1"; + bundleInfos.push_back(bundleInfo); + int32_t userId = TEST_USER_ID; + std::vector bundleNamesOnly; + std::map isClearDataFlags; + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + userId, isClearDataFlags); + EXPECT_TRUE(result.empty()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildBundleInfos_0301"; +} + +/** + * @tc.number: b_jsonutil_BuildBundleInfos_0400 + * @tc.name: b_jsonutil_BuildBundleInfos_0400 + * @tc.desc: Test function of BuildBundleInfos interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0400, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildBundleInfos_0400"; + try { + std::vector bundleNames; + std::string bundleName = "bundle1"; + bundleNames.push_back(bundleName); + std::vector bundleInfos; + std::string bundleInfo = { + "{\"infos\":[{\"type\":\"type1\",\"details\":\"details1\"}],\"clearBackupData\": \"false\"}" + }; + bundleInfos.push_back(bundleInfo); + int32_t userId = TEST_USER_ID; + std::vector bundleNamesOnly; + std::map isClearDataFlags; + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + userId, isClearDataFlags); + EXPECT_EQ(isClearDataFlags[bundleName], false); + EXPECT_FALSE(result.empty()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildBundleInfos_0400"; +} + +/** + * @tc.number: b_jsonutil_BuildBundleInfos_0500 + * @tc.name: b_jsonutil_BuildBundleInfos_0500 + * @tc.desc: Test function of BuildBundleInfos interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0500, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildBundleInfos_0500"; + try { + std::vector bundleNames; + std::string bundleName = "bundle"; + bundleNames.push_back(bundleName); + std::vector bundleInfos; + std::string bundleInfo = {"{\"infos\":[{\"type\":null}]}"}; + bundleInfos.push_back(bundleInfo); + int32_t userId = TEST_USER_ID; + std::vector bundleNamesOnly; + std::map isClearDataFlags; + + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + userId, isClearDataFlags); + EXPECT_EQ(isClearDataFlags[bundleName], true); + EXPECT_FALSE(result.empty()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildBundleInfos_0500"; +} + +/** + * @tc.number: b_jsonutil_BuildBundleInfos_0600 + * @tc.name: b_jsonutil_BuildBundleInfos_0600 + * @tc.desc: Test function of BuildBundleInfos interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0600, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildBundleInfos_0600"; + try { + std::vector bundleNames; + std::string bundleName = "bundle"; bundleNames.push_back(bundleName); - bundleNames.push_back(bundleName1); - std::string pattern = ":"; - std::vector detailInfos; - detailInfos.push_back(""); - int32_t userId = 100; - std::vector realBundleNames; - std::map> bundleNameDetailMap = - BJsonUtil::BuildBundleInfos(bundleNames, detailInfos, realBundleNames, userId); - EXPECT_EQ(0, bundleNameDetailMap.size()); + std::vector bundleInfos; + std::string bundleInfo = {"{\"infos\":[{\"type\":123}],\"clearBackupData\": \"true\"}"}; + bundleInfos.push_back(bundleInfo); + int32_t userId = TEST_USER_ID; + std::vector bundleNamesOnly; + std::map isClearDataFlags; + + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + userId, isClearDataFlags); + EXPECT_EQ(isClearDataFlags[bundleName], true); + EXPECT_FALSE(result.empty()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildBundleInfos_0600"; +} + +/** + * @tc.number: b_jsonutil_BuildBundleInfos_0700 + * @tc.name: b_jsonutil_BuildBundleInfos_0700 + * @tc.desc: Test function of BuildBundleInfos interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0700, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildBundleInfos_0700"; + try { + std::vector bundleNames; + std::string bundleName = "bundle"; + bundleNames.push_back(bundleName); + std::vector bundleInfos; + std::string bundleInfo = {"{\"infos\":[{\"type\":\"testType\",\"details\":null}]}"}; + bundleInfos.push_back(bundleInfo); + int32_t userId = TEST_USER_ID; + std::vector bundleNamesOnly; + std::map isClearDataFlags; + + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + userId, isClearDataFlags); + EXPECT_FALSE(result.empty()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildBundleInfos_0700"; +} + +/** + * @tc.number: b_jsonutil_BuildBundleInfos_0800 + * @tc.name: b_jsonutil_BuildBundleInfos_0800 + * @tc.desc: Test function of BuildBundleInfos interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0800, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildBundleInfos_0800"; + try { + std::vector bundleNames; + std::string bundleName = "bundle"; + bundleNames.push_back(bundleName); + std::vector bundleInfos; + std::string bundleInfo = {"{\"infos\":[{\"type\":\"testType\",\"details\":[]}]}"}; + bundleInfos.push_back(bundleInfo); + int32_t userId = TEST_USER_ID; + std::vector bundleNamesOnly; + std::map isClearDataFlags; + + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + userId, isClearDataFlags); + EXPECT_FALSE(result.empty()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildBundleInfos_0800"; +} + +/** + * @tc.number: b_jsonutil_BuildBundleInfos_0900 + * @tc.name: b_jsonutil_BuildBundleInfos_0900 + * @tc.desc: Test function of BuildBundleInfos interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0900, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildBundleInfos_0900"; + try { + std::vector bundleNames; + std::string bundleName = "bundle"; + bundleNames.push_back(bundleName); + std::vector bundleInfos; + std::string bundleInfo = {"{\"infos\":[{\"type\":\"testType\",\"details\":[\"detail\"]}]}"}; + bundleInfos.push_back(bundleInfo); + int32_t userId = TEST_USER_ID; + std::vector bundleNamesOnly; + std::map isClearDataFlags; + + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + userId, isClearDataFlags); + EXPECT_FALSE(result.empty()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildBundleInfos_0900"; +} + +/** + * @tc.number: b_jsonutil_BuildBundleInfos_1000 + * @tc.name: b_jsonutil_BuildBundleInfos_1000 + * @tc.desc: Test function of BuildBundleInfos interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_1000, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildBundleInfos_1000"; + try { + std::vector bundleNames; + std::string bundleName = "bundle"; + bundleNames.push_back(bundleName); + std::vector bundleInfos; + std::string bundleInfo = {"{\"infos\":[\"infos\"]}"}; + bundleInfos.push_back(bundleInfo); + int32_t userId = TEST_USER_ID; + std::vector bundleNamesOnly; + std::map isClearDataFlags; + + auto result = BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + userId, isClearDataFlags); + EXPECT_FALSE(result.empty()); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildBundleInfos_1000"; +} + +/** + * @tc.number: b_jsonutil_FindBundleInfoByName_0100 + * @tc.name: b_jsonutil_FindBundleInfoByName_0100 + * @tc.desc: Test function of FindBundleInfoByName interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_FindBundleInfoByName_0100, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin FindBundleInfoByName_0100"; + try { + std::map> bundleNameDetailsMap; + std::string bundleName = "bundle1"; + std::string jobType = "type"; + BJsonUtil::BundleDetailInfo bundleDetail; + + bool result = BJsonUtil::FindBundleInfoByName(bundleNameDetailsMap, bundleName, jobType, bundleDetail); + EXPECT_EQ(false, result); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end FindBundleInfoByName_0100"; +} + +/** + * @tc.number: b_jsonutil_FindBundleInfoByName_0200 + * @tc.name: b_jsonutil_FindBundleInfoByName_0200 + * @tc.desc: Test function of FindBundleInfoByName interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_FindBundleInfoByName_0200, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin FindBundleInfoByName_0200"; + try { + std::map> bundleNameDetailsMap; + std::string bundleName = "bundle1"; + std::string jobType = "type"; + BJsonUtil::BundleDetailInfo detailInfo; + detailInfo.bundleName = bundleName; + detailInfo.type = jobType; + bundleNameDetailsMap[bundleName] = {detailInfo}; + BJsonUtil::BundleDetailInfo bundleDetail; + + bool result = BJsonUtil::FindBundleInfoByName(bundleNameDetailsMap, bundleName, jobType, bundleDetail); + EXPECT_EQ(true, result); + EXPECT_EQ(bundleDetail.type, detailInfo.type); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end FindBundleInfoByName_0200"; +} + +/** + * @tc.number: b_jsonutil_FindBundleInfoByName_0300 + * @tc.name: b_jsonutil_FindBundleInfoByName_0300 + * @tc.desc: Test function of FindBundleInfoByName interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_FindBundleInfoByName_0300, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin FindBundleInfoByName_0300"; + try { + std::map> bundleNameDetailsMap; + std::string bundleName = "bundle1"; + std::string jobType = "type"; + std::string jobType1 = "type1"; + BJsonUtil::BundleDetailInfo detailInfo; + detailInfo.bundleName = bundleName; + detailInfo.type = jobType; + bundleNameDetailsMap[bundleName] = {detailInfo}; + BJsonUtil::BundleDetailInfo bundleDetail; + + bool result = BJsonUtil::FindBundleInfoByName(bundleNameDetailsMap, bundleName, jobType1, bundleDetail); + EXPECT_EQ(false, result); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BJsonUtilTest-end FindBundleInfoByName_0300"; +} + +/** + * @tc.number: b_jsonutil_BuildRestoreErrInfo_0100 + * @tc.name: b_jsonutil_BuildRestoreErrInfo_0100 + * @tc.desc: Test function of BuildRestoreErrInfo interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(BJsonUtilTest, b_jsonutil_BuildRestoreErrInfo_0100, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "BJsonUtilTest-begin BuildRestoreErrInfo_0100"; + try { + std::string jsonStr; + int errCode = 1; + std::string errMsg = "error"; + + bool result = BJsonUtil::BuildRestoreErrInfo(jsonStr, errCode, errMsg); + EXPECT_EQ(true, result); + EXPECT_NE(jsonStr.find("errorCode"), std::string::npos); + EXPECT_NE(jsonStr.find("errorInfo"), std::string::npos); + EXPECT_NE(jsonStr.find("type"), std::string::npos); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "BJsonUtilTest-an exception occurred."; } - GTEST_LOG_(INFO) << "BJsonUtilTest-end b_jsonutil_BuildBundleInfos_0101"; + GTEST_LOG_(INFO) << "BJsonUtilTest-end BuildRestoreErrInfo_0100"; } } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/utils/BUILD.gn b/utils/BUILD.gn index 632b98ae19d07e3f5b0b2cba10d0607a7e2cd9fd..151ab2480952d44f0d996e643939aa1ccf607bb8 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -83,12 +83,15 @@ ohos_shared_library("backup_utils") { public_configs = [ ":utils_public_config" ] external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", "cJSON:cjson", "c_utils:utils", "faultloggerd:libdfx_dumpcatcher", "hilog:libhilog", "hitrace:hitrace_meter", "init:libbegetutil", + "ipc:ipc_core", ] include_dirs = [ diff --git a/utils/include/b_error/b_error.h b/utils/include/b_error/b_error.h index 02bd0440ef0a0fee58fc295e28e33e799135a652..8e84877d29c8c26aacef04be39d22a769dea0490 100644 --- a/utils/include/b_error/b_error.h +++ b/utils/include/b_error/b_error.h @@ -70,8 +70,9 @@ public: SA_REFUSED_ACT = 0x3002, SA_BROKEN_ROOT_DIR = 0x3003, SA_FORBID_BACKUP_RESTORE = 0x3004, - SA_BOOT_TIMEOUT = 0x3005, + SA_BOOT_EXT_TIMEOUT = 0x3005, SA_BUNDLE_INFO_EMPTY = 0x3006, + SA_BOOT_EXT_FAIL = 0x3007, // 0x4000~0x4999 backup_SDK错误 SDK_INVAL_ARG = 0x4000, @@ -89,6 +90,7 @@ public: EXT_BACKUP_PACKET_ERROR = 0x5007, EXT_METHOD_NOT_EXIST = 0x5008, EXT_THROW_EXCEPTION = 0x5009, + EXT_BACKUP_UNPACKET_ERROR = 0x5010, // 0x6000~0x6999 sa_ext错误 SA_EXT_ERR_CALL = 0x6000, @@ -112,6 +114,8 @@ public: E_EMPTY = 13500005, E_PACKET = 13500006, E_EXCEPTION = 13500007, + E_UNPACKET = 13500008, + E_BEF = 13500009, }; public: @@ -227,8 +231,9 @@ private: {Codes::SA_REFUSED_ACT, "SA refuse to act"}, {Codes::SA_BROKEN_ROOT_DIR, "SA failed to operate on the given root dir"}, {Codes::SA_FORBID_BACKUP_RESTORE, "SA forbid backup or restore"}, - {Codes::SA_BOOT_TIMEOUT, "SA boot application extension time out"}, + {Codes::SA_BOOT_EXT_TIMEOUT, "SA boot application extension time out"}, {Codes::SA_BUNDLE_INFO_EMPTY, "SA the bundle info for backup/restore is empty"}, + {Codes::SA_BOOT_EXT_FAIL, "SA failed to boot application extension"}, {Codes::SDK_INVAL_ARG, "SDK received invalid arguments"}, {Codes::SDK_BROKEN_IPC, "SDK failed to do IPC"}, {Codes::SDK_MIXED_SCENARIO, "SDK involed backup/restore when doing the contrary"}, @@ -241,6 +246,7 @@ private: {Codes::EXT_FORBID_BACKUP_RESTORE, "forbid backup or restore"}, {Codes::EXT_BACKUP_PACKET_ERROR, "Backup packet error"}, {Codes::EXT_THROW_EXCEPTION, "Extension throw exception"}, + {Codes::EXT_BACKUP_UNPACKET_ERROR, "Backup unpacket error"}, }; static inline const std::map errCodeTable_ { @@ -256,8 +262,9 @@ private: {static_cast(Codes::SA_REFUSED_ACT), BackupErrorCode::E_PERM}, {static_cast(Codes::SA_BROKEN_ROOT_DIR), BackupErrorCode::E_UKERR}, {static_cast(Codes::SA_FORBID_BACKUP_RESTORE), BackupErrorCode::E_FORBID}, - {static_cast(Codes::SA_BOOT_TIMEOUT), BackupErrorCode::E_BTO}, + {static_cast(Codes::SA_BOOT_EXT_TIMEOUT), BackupErrorCode::E_BTO}, {static_cast(Codes::SA_BUNDLE_INFO_EMPTY), BackupErrorCode::E_EMPTY}, + {static_cast(Codes::SA_BOOT_EXT_FAIL), BackupErrorCode::E_BEF}, {static_cast(Codes::SDK_INVAL_ARG), BackupErrorCode::E_INVAL}, {static_cast(Codes::SDK_BROKEN_IPC), BackupErrorCode::E_IPCSS}, {static_cast(Codes::SDK_MIXED_SCENARIO), BackupErrorCode::E_INVAL}, @@ -270,6 +277,7 @@ private: {static_cast(Codes::EXT_FORBID_BACKUP_RESTORE), BackupErrorCode::E_FORBID}, {static_cast(Codes::EXT_BACKUP_PACKET_ERROR), BackupErrorCode::E_PACKET}, {static_cast(Codes::EXT_THROW_EXCEPTION), BackupErrorCode::E_EXCEPTION}, + {static_cast(Codes::EXT_BACKUP_UNPACKET_ERROR), BackupErrorCode::E_UNPACKET}, {BackupErrorCode::E_IPCSS, BackupErrorCode::E_IPCSS}, {BackupErrorCode::E_INVAL, BackupErrorCode::E_INVAL}, {BackupErrorCode::E_NOTEXIST, BackupErrorCode::E_NOTEXIST}, @@ -285,10 +293,12 @@ private: {BackupErrorCode::E_EMPTY, BackupErrorCode::E_EMPTY}, {BackupErrorCode::E_PACKET, BackupErrorCode::E_PACKET}, {BackupErrorCode::E_EXCEPTION, BackupErrorCode::E_EXCEPTION}, + {BackupErrorCode::E_UNPACKET, BackupErrorCode::E_UNPACKET}, + {BackupErrorCode::E_BEF, BackupErrorCode::E_BEF}, }; static inline const std::map sysErrnoCodeTable_ { - {EPERM, BackupErrorCode::E_IPCSS}, + {EPERM, BackupErrorCode::E_PERM}, {EIO, BackupErrorCode::E_IO}, {EBADF, BackupErrorCode::E_IO}, {EACCES, BackupErrorCode::E_IO}, diff --git a/utils/include/b_filesystem/b_dir.h b/utils/include/b_filesystem/b_dir.h index 753529cb63e2eb48567c061412314a7ceb966072..e1e728d2947304cda7e4f980e4a7acfd591244c3 100644 --- a/utils/include/b_filesystem/b_dir.h +++ b/utils/include/b_filesystem/b_dir.h @@ -46,7 +46,7 @@ public: * @param excludes 需要排除的文件及目录集合 * @return 错误码、大文件名集合 */ - static std::tuple, std::vector> GetBigFiles( + static std::tuple, std::map> GetBigFiles( const std::vector &includes, const std::vector &excludes); /** diff --git a/utils/include/b_json/b_json_entity_caps.h b/utils/include/b_json/b_json_entity_caps.h index 548beef14028f335b4138673c18544a286212624..e641077e010be6bec3657ce1e2f5891d498bfdc7 100644 --- a/utils/include/b_json/b_json_entity_caps.h +++ b/utils/include/b_json/b_json_entity_caps.h @@ -24,6 +24,7 @@ class BJsonEntityCaps : public BJsonEntity { public: struct BundleInfo { std::string name; + int appIndex; int64_t versionCode; std::string versionName; int64_t spaceOccupied; @@ -74,6 +75,7 @@ public: for (const auto &item : bundleInfos) { Json::Value arrObj; arrObj["name"] = item.name; + arrObj["appIndex"] = item.appIndex; arrObj["versionCode"] = item.versionCode; arrObj["versionName"] = item.versionName; arrObj["spaceOccupied"] = item.spaceOccupied; @@ -146,7 +148,7 @@ public: return obj_["extraInfo"]; } - bool CheckBundlePropertiesIsValid(const Json::Value &bundleInfo) + bool CheckBundlePropertiesValid(const Json::Value &bundleInfo) { if (!bundleInfo) { HILOGE("Failed Check bundleInfo"); @@ -187,7 +189,7 @@ public: } std::vector bundleInfos; for (const auto &item : obj_["bundleInfos"]) { - if (!CheckBundlePropertiesIsValid(item)) { + if (!CheckBundlePropertiesValid(item)) { return {}; } string restoreDeps(""); @@ -210,7 +212,11 @@ public: if (item.isMember("fullBackupOnly") && item["fullBackupOnly"].isBool()) { fullBackupOnly = item["fullBackupOnly"].asBool(); } - bundleInfos.emplace_back(BundleInfo {item["name"].asString(), item["versionCode"].asInt64(), + int appIndex = 0; + if (item.isMember("appIndex") && item["appIndex"].isInt()) { + appIndex = item["appIndex"].asInt(); + } + bundleInfos.emplace_back(BundleInfo {item["name"].asString(), appIndex, item["versionCode"].asInt64(), item["versionName"].asString(), item["spaceOccupied"].asInt64(), increSpaceOccupied, item["allToBackup"].asBool(), fullBackupOnly, diff --git a/utils/include/b_jsonutil/b_jsonutil.h b/utils/include/b_jsonutil/b_jsonutil.h index 9efa19376a7aefef8919af267bb726b03d044de9..e3e729ca2278e5efae42bec2eacc138ba082df03 100644 --- a/utils/include/b_jsonutil/b_jsonutil.h +++ b/utils/include/b_jsonutil/b_jsonutil.h @@ -34,11 +34,10 @@ public: * @brief 带有拼接字符的bundleName按照拼接字符进行分割 * * @param bundleNameStr bundleName拼接index的字符串 - * @param patternInfo 拼接字符串 * * @return 分割好的结果赋值给结构体 */ - static BundleDetailInfo ParseBundleNameIndexStr (const std::string &bundleNameStr, const std::string &patternInfo); + static BundleDetailInfo ParseBundleNameIndexStr (const std::string &bundleNameStr); /** * @brief 将传进来的bundleNames的集合进行按照拼接字符分割处理 @@ -48,26 +47,27 @@ public: * @param patternInfo 拼接的字符 * @param realBundleNames 分割后真正的bundleNames * @param userId userId + * @param isClearDataFlags 框架是否清理标志集合 * * @return 包名和解析结果的对应关系集合 * */ static std::map> BuildBundleInfos( const std::vector &bundleNames, const std::vector &details, - std::vector &realBundleNames, int32_t userId); + std::vector &realBundleNames, int32_t userId, + std::map &isClearDataFlags); /** * @brief 解析单个bundle对应的json串 * - * @param bundleDetailInfo json串 - * @param bundleDetail 结构体对象 - * @param bundleNameOnly bundle名称 - * @param bundleIndex bundle对应的索引 - * @param userId userId + * @param bundleInfo json串 + * @param bundleDetails 结构体对象 + * @param bundleDetailInfo bundle信息 + * @param isClearData 框架是否清理标志 * */ static void ParseBundleInfoJson(const std::string &bundleInfo, std::vector &bundleDetails, - std::string &bundleNameOnly, int bundleIndex, int32_t userId); + BJsonUtil::BundleDetailInfo bundleDetailInfo, bool &isClearData); /** * @brief 根据业务类型和bundleName确定唯一的bundleInfo @@ -94,6 +94,16 @@ public: * */ static bool BuildRestoreErrInfo(std::string &jsonStr, int errCode, std::string errMsg); + + /** + * @brief 拼接包名和分身对应的索引 + * + * @param bundleName 包名 + * @param bundleIndex 索引 + * + * @return 拼接结果 + */ + static std::string BuildBundleNameIndexInfo(const std::string &bundleName, int bundleIndex); }; } // namespace OHOS::FileManagement::Backup diff --git a/utils/include/b_resources/b_constants.h b/utils/include/b_resources/b_constants.h index 512526b5caba6b5f2a9c5910abd550148247f969..7d85e5f907475e13c556b03a6878db74ed8ff9fe 100644 --- a/utils/include/b_resources/b_constants.h +++ b/utils/include/b_resources/b_constants.h @@ -30,6 +30,7 @@ static inline const char *EXTENSION_VERSION_CODE_PARA = "versionCode"; static inline const char *EXTENSION_VERSION_NAME_PARA = "versionName"; static inline const char *EXTENSION_RESTORE_EXT_INFO_PARA = "restoreExtInfo"; static inline const char *EXTENSION_BACKUP_EXT_INFO_PARA = "backupExtInfo"; +static inline const char *EXTENSION_APP_CLONE_INDEX_PARA = "ohos.extra.param.key.appCloneIndex"; enum class ExtensionAction { INVALID = 0, diff --git a/utils/include/b_sa/b_sa_utils.h b/utils/include/b_sa/b_sa_utils.h index 1548fed1e68e7450da4138c4eb273a70e8e1eb21..86d1b8aa995db8ee53eb0b40000ac358607531d1 100644 --- a/utils/include/b_sa/b_sa_utils.h +++ b/utils/include/b_sa/b_sa_utils.h @@ -21,6 +21,9 @@ namespace OHOS::FileManagement::Backup { class SAUtils { public: static bool IsSABundleName(std::string bundleName); + static bool CheckBackupPermission(); + static bool CheckPermission(const std::string &permission); + static bool IsSystemApp(); }; } // namespace OHOS::FileManagement::Backup::BEncryption #endif // OHOS_FILEMGMT_BACKUP_B_SA_H \ No newline at end of file diff --git a/utils/src/b_error/b_error.cpp b/utils/src/b_error/b_error.cpp index d99d3e62e83b2a882b9cf10ca0a3de5a7374cb64..5d13b4ec6b8800db1043bcf26851e467e388c88c 100644 --- a/utils/src/b_error/b_error.cpp +++ b/utils/src/b_error/b_error.cpp @@ -52,6 +52,7 @@ string BError::WrapMessageWithExtraInfos(const char *fileName, (void)HILOG_IMPL(LOG_CORE, LOG_DEBUG, LOG_DOMAIN, LOG_TAG, "%{public}s", res.c_str()); return res; } + int BError::GetCode() const { int code = static_cast(GetRawCode()); diff --git a/utils/src/b_filesystem/b_dir.cpp b/utils/src/b_filesystem/b_dir.cpp index f8c70da1be67c17dba8c26707d7512478710d751..d99581d28ad66551737e0a08273f893ba28703ef 100644 --- a/utils/src/b_filesystem/b_dir.cpp +++ b/utils/src/b_filesystem/b_dir.cpp @@ -40,6 +40,7 @@ static bool IsEmptyDirectory(const string &path) { DIR *dir = opendir(path.c_str()); if (dir == nullptr) { + HILOGE("Opendir failed, errno:%{public}d", errno); return false; } bool isEmpty = true; @@ -54,10 +55,10 @@ static bool IsEmptyDirectory(const string &path) return isEmpty; } -static tuple, vector> GetFile(const string &path, off_t size = -1) +static tuple, map> GetFile(const string &path, off_t size = -1) { map files; - vector smallFiles; + map smallFiles; struct stat sta = {}; if (stat(path.data(), &sta) == -1) { return {BError(errno).GetCode(), files, smallFiles}; @@ -66,7 +67,7 @@ static tuple, vector> GetFile(const st return {BError(BError::Codes::OK).GetCode(), files, smallFiles}; } if (sta.st_size <= size) { - smallFiles.emplace_back(path); + smallFiles.insert(make_pair(path, sta.st_size)); } else { files.try_emplace(path, sta); } @@ -84,19 +85,19 @@ static uint32_t CheckOverLongPath(const string &path) return len; } -static tuple, vector> GetDirFilesDetail(const string &path, - bool recursion, - off_t size = -1) +static tuple, map> GetDirFilesDetail(const string &path, + bool recursion, + off_t size = -1) { map files; - vector smallFiles; + map smallFiles; if (IsEmptyDirectory(path)) { string newPath = path; if (path.at(path.size()-1) != '/') { newPath += '/'; } - smallFiles.emplace_back(newPath); + smallFiles.insert(make_pair(newPath, 0)); return {ERR_OK, files, smallFiles}; } @@ -110,32 +111,33 @@ static tuple, vector> GetDirFilesDetai // current dir OR parent dir if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0)) { continue; - } else if (ptr->d_type == DT_DIR) { - if (!recursion) { - continue; - } - auto [errCode, subFiles, subSmallFiles] = - GetDirFilesDetail(IncludeTrailingPathDelimiter(path) + string(ptr->d_name), recursion, size); - if (errCode != 0) { - return {errCode, files, smallFiles}; - } - files.merge(subFiles); - smallFiles.insert(smallFiles.end(), subSmallFiles.begin(), subSmallFiles.end()); - } else if (ptr->d_type == DT_LNK) { - continue; - } else { + } else if (ptr->d_type == DT_REG) { struct stat sta = {}; string fileName = IncludeTrailingPathDelimiter(path) + string(ptr->d_name); if (CheckOverLongPath(fileName) >= PATH_MAX_LEN || stat(fileName.data(), &sta) == -1) { continue; } if (sta.st_size <= size) { - smallFiles.emplace_back(fileName); + smallFiles.insert(make_pair(fileName, sta.st_size)); continue; } files.try_emplace(fileName, sta); + } else if (ptr->d_type != DT_DIR) { + HILOGE("Not support file type"); + continue; + } + // DT_DIR type + if (!recursion) { + continue; } + auto [errCode, subFiles, subSmallFiles] = + GetDirFilesDetail(IncludeTrailingPathDelimiter(path) + string(ptr->d_name), recursion, size); + if (errCode != 0) { + return {errCode, files, smallFiles}; + } + files.merge(subFiles); + smallFiles.insert(subSmallFiles.begin(), subSmallFiles.end()); } return {ERR_OK, files, smallFiles}; } @@ -197,20 +199,20 @@ static set ExpandPathWildcard(const vector &vec, bool onlyPath) return filteredPath; } -tuple, vector> BDir::GetBigFiles(const vector &includes, - const vector &excludes) +tuple, map> BDir::GetBigFiles(const vector &includes, + const vector &excludes) { set inc = ExpandPathWildcard(includes, false); map incFiles; - vector incSmallFiles; + map incSmallFiles; for (const auto &item : inc) { auto [errCode, files, smallFiles] = GetDirFilesDetail(item, true, BConstants::BIG_FILE_BOUNDARY); if (errCode == 0) { int32_t num = static_cast(files.size()); incFiles.merge(move(files)); HILOGI("big files: %{public}d; small files: %{public}d", num, static_cast(smallFiles.size())); - incSmallFiles.insert(incSmallFiles.end(), smallFiles.begin(), smallFiles.end()); + incSmallFiles.insert(smallFiles.begin(), smallFiles.end()); } } @@ -233,10 +235,10 @@ tuple, vector> BDir::GetBigFiles(const return false; }; - vector resSmallFiles; + map resSmallFiles; for (const auto &item : incSmallFiles) { - if (!isMatch(excludes, item)) { - resSmallFiles.emplace_back(item); + if (!isMatch(excludes, item.first)) { + resSmallFiles.insert(make_pair(item.first, item.second)); } } diff --git a/utils/src/b_filesystem/b_file.cpp b/utils/src/b_filesystem/b_file.cpp index f5828df41e84daca1131cc0b3cf2c4b9487a225a..0971256732a8aab8abfb855db754fc20fe2974ba 100644 --- a/utils/src/b_filesystem/b_file.cpp +++ b/utils/src/b_filesystem/b_file.cpp @@ -186,10 +186,19 @@ bool BFile::MoveFile(const string &from, const string &to) throw BError(errno); } newPath.append("/").append(basename(name.get())); - if (rename(oldPath.c_str(), newPath.c_str())) { - HILOGE("failed to rename path, oldPath:%{public}s ,newPath: %{public}s", - GetAnonyPath(oldPath).c_str(), GetAnonyPath(newPath).c_str()); - throw BError(errno); + if (rename(oldPath.c_str(), newPath.c_str()) != 0) { + HILOGI("rename err,try copy errno: %{public}d", errno); + UniqueFd fdFrom(open(oldPath.data(), O_RDONLY)); + if (fdFrom == -1) { // -1: fd error code + HILOGE("failed to open the file %{public}s", GetAnonyPath(from).c_str()); + throw BError(errno); + } + UniqueFd fdTo(open(newPath.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)); + if (fdTo == -1) { // -1: fd error code + HILOGE("failed to open the file %{public}s", GetAnonyPath(to).c_str()); + throw BError(errno); + } + SendFile(fdTo, fdFrom); } return true; } catch (const BError &e) { diff --git a/utils/src/b_json/b_report_entity.cpp b/utils/src/b_json/b_report_entity.cpp index 7acdd932a631921c8f1eafb71272caae7d6c5b5b..fb5d342c1838aa648f3d5a8af73e7ffcdc84cf3a 100644 --- a/utils/src/b_json/b_report_entity.cpp +++ b/utils/src/b_json/b_report_entity.cpp @@ -257,7 +257,8 @@ void BReportEntity::CheckAndUpdateIfReportLineEncoded(std::string &path) } unordered_map infos = GetReportInfos(); - if (infos.size() == 1) { + constexpr int BIG_FILE_REPORT_INFO_NUM = 1; + if (infos.size() == BIG_FILE_REPORT_INFO_NUM) { auto info = infos.begin(); path = info->first; } else { diff --git a/utils/src/b_jsonutil/b_jsonutil.cpp b/utils/src/b_jsonutil/b_jsonutil.cpp index 578be2fd88434d25ac0cc544aed426a17ade112f..b50042c1ccd0d0d2a56851cf32d9810e008bb5b2 100644 --- a/utils/src/b_jsonutil/b_jsonutil.cpp +++ b/utils/src/b_jsonutil/b_jsonutil.cpp @@ -28,11 +28,10 @@ namespace { const static std::string BUNDLE_INDEX_SPLICE = ":"; } -BJsonUtil::BundleDetailInfo BJsonUtil::ParseBundleNameIndexStr(const std::string &bundleNameStr, - const std::string &patternInfo) +BJsonUtil::BundleDetailInfo BJsonUtil::ParseBundleNameIndexStr(const std::string &bundleNameStr) { HILOGI("Start parse bundle name and index"); - size_t hasPos = bundleNameStr.find(patternInfo); + size_t hasPos = bundleNameStr.find(BUNDLE_INDEX_SPLICE); BundleDetailInfo bundleDetailInfo; if (hasPos == std::string::npos) { bundleDetailInfo.bundleName = bundleNameStr; @@ -50,7 +49,8 @@ BJsonUtil::BundleDetailInfo BJsonUtil::ParseBundleNameIndexStr(const std::string std::map> BJsonUtil::BuildBundleInfos( const std::vector &bundleNames, const std::vector &bundleInfos, - std::vector &bundleNamesOnly, int32_t userId) + std::vector &bundleNamesOnly, int32_t userId, + std::map &isClearDataFlags) { std::map> bundleNameDetailMap; if (bundleNames.size() != bundleInfos.size()) { @@ -74,28 +74,42 @@ std::map> BJsonUtil::Build bundleNamesOnly.emplace_back(bundleName); } else { std::string bundleNameSplit = bundleName.substr(0, pos); - std::string indexSplit = bundleName.substr(pos, bundleName.size() - 1); + std::string indexSplit = bundleName.substr(pos + 1); int index = std::stoi(indexSplit); bundleNameOnly = bundleNameSplit; bundleIndex = index; bundleNamesOnly.emplace_back(bundleNameSplit); } std::string bundleInfo = bundleInfos[i]; - ParseBundleInfoJson(bundleInfo, bundleDetailInfos, bundleNameOnly, bundleIndex, userId); - bundleNameDetailMap[bundleNameOnly] = bundleDetailInfos; + bool isClearData = true; + BJsonUtil::BundleDetailInfo bundleDetailInfo; + bundleDetailInfo.bundleName = bundleNameOnly; + bundleDetailInfo.bundleIndex = bundleIndex; + bundleDetailInfo.userId = userId; + ParseBundleInfoJson(bundleInfo, bundleDetailInfos, bundleDetailInfo, isClearData); + isClearDataFlags[bundleName] = isClearData; + bundleNameDetailMap[bundleName] = bundleDetailInfos; } HILOGI("End BuildBundleInfos"); return bundleNameDetailMap; } void BJsonUtil::ParseBundleInfoJson(const std::string &bundleInfo, std::vector &bundleDetails, - std::string &bundleNameOnly, int bundleIndex, int32_t userId) + BJsonUtil::BundleDetailInfo bundleDetailInfo, bool &isClearData) { cJSON *root = cJSON_Parse(bundleInfo.c_str()); if (root == nullptr) { HILOGE("Parse json error,root is null"); return; } + cJSON *clearBackupData = cJSON_GetObjectItem(root, "clearBackupData"); + if (clearBackupData == nullptr || !cJSON_IsString(clearBackupData) || (clearBackupData->valuestring == nullptr)) { + HILOGE("Parse json error."); + } else { + std::string value = clearBackupData->valuestring; + isClearData = value.compare("false") != 0; + HILOGI("bundleName:%{public}s clear data falg:%{public}d", bundleDetailInfo.bundleName.c_str(), isClearData); + } cJSON *infos = cJSON_GetObjectItem(root, "infos"); if (infos == nullptr || !cJSON_IsArray(infos) || cJSON_GetArraySize(infos) == 0) { HILOGE("Parse json error, infos is not array"); @@ -104,10 +118,6 @@ void BJsonUtil::ParseBundleInfoJson(const std::string &bundleInfo, std::vector GetConfigParameterValue(const string &key, uint32_t len) { int handle = static_cast(FindParameter(key.c_str())); - HILOGI("start get config param value."); if (handle == -1) { HILOGI("Fail to find parameter."); return {false, ""}; @@ -50,7 +49,6 @@ static tuple GetConfigParameterValue(const string &key, uint32_t l HILOGI("Fail to get parameter value."); return {false, ""}; } - HILOGI("end get config param value."); return {true, buffer.get()}; } catch (const bad_alloc &e) { HILOGE("Fail to get parameter value: %{public}s.", e.what()); diff --git a/utils/src/b_sa/b_sa_utils.cpp b/utils/src/b_sa/b_sa_utils.cpp index 05d090e81c1edb26c4ab53827ecf582ef9ebdc71..399cb10269a26f1a124ea9d4957ea154737e1b20 100644 --- a/utils/src/b_sa/b_sa_utils.cpp +++ b/utils/src/b_sa/b_sa_utils.cpp @@ -14,9 +14,17 @@ */ #include "b_sa/b_sa_utils.h" +#include "access_token.h" +#include "accesstoken_kit.h" +#include "ipc_skeleton.h" +#include "tokenid_kit.h" namespace OHOS::FileManagement::Backup { +namespace { + const std::string BACKUP_PERMISSION = "ohos.permission.BACKUP"; +} + bool SAUtils::IsSABundleName(std::string bundleName) { if (bundleName.empty()) { @@ -29,4 +37,24 @@ bool SAUtils::IsSABundleName(std::string bundleName) } return true; } + +bool SAUtils::CheckBackupPermission() +{ + Security::AccessToken::AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + return Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, BACKUP_PERMISSION) == + Security::AccessToken::PermissionState::PERMISSION_GRANTED; +} + +bool SAUtils::CheckPermission(const std::string &permission) +{ + Security::AccessToken::AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + return Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, permission) == + Security::AccessToken::PermissionState::PERMISSION_GRANTED; +} + +bool SAUtils::IsSystemApp() +{ + uint64_t fullTokenId = OHOS::IPCSkeleton::GetCallingFullTokenID(); + return Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId); +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file