Merge branch 'master' of gitee.com:openharmony/filemanagement_app_file_service into master

Signed-off-by: yaoruozi <15969709967@163.com>
This commit is contained in:
yaoruozi 2024-08-16 07:27:13 +00:00 committed by yaoruozi1@huawei.com
commit e6a322feb8
116 changed files with 6777 additions and 1349 deletions

View File

@ -34,6 +34,7 @@ ohos_shared_library("backup_extension_ability_native") {
"src/ext_backup_loader.cpp",
"src/ext_extension.cpp",
"src/ext_extension_stub.cpp",
"src/sub_ext_extension.cpp",
"src/tar_file.cpp",
"src/untar_file.cpp",
]

View File

@ -175,6 +175,8 @@ public:
*/
bool RestoreDataReady();
void SetClearDataFlag(bool isClearData);
/**
* @brief Invoke the extended function of the APP
*/
@ -200,6 +202,7 @@ private:
BConstants::ExtensionAction extAction_ {BConstants::ExtensionAction::INVALID};
ErrCode GetParament(const AAFwk::Want &want);
static CreatorFunc creator_;
bool isClearData_ {true};
};
} // namespace OHOS::FileManagement::Backup

View File

@ -73,6 +73,13 @@ struct CallbackInfoEx {
}
};
struct OnProcessCallBackInfo {
std::function<void(ErrCode, const std::string)> onProcessCallback;
OnProcessCallBackInfo(std::function<void(ErrCode, const std::string)> param) : onProcessCallback(param)
{
}
};
class ExtBackupJs : public ExtBackup {
public:
/**
@ -161,6 +168,7 @@ private:
std::shared_ptr<CallbackInfoBackup> callbackInfoBackup_;
std::shared_ptr<CallbackInfoEx> callbackInfoEx_;
std::shared_ptr<CallbackInfo> callbackInfo_;
std::shared_ptr<OnProcessCallBackInfo> onProcessCallback_;
std::condition_variable callJsCon_;
std::mutex callJsMutex_;
std::atomic<bool> callExtDefaultFunc_ {false}; // extension default method, onBackup or onRestore

View File

@ -34,6 +34,7 @@
#include "thread_pool.h"
#include "timer.h"
#include "unique_fd.h"
#include "untar_file.h"
namespace OHOS::FileManagement::Backup {
using CompareFilesResult = tuple<map<string, struct ReportFileInfo>,
@ -44,17 +45,15 @@ 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<UniqueFd, UniqueFd> GetIncrementalBackupFileHandle() override;
ErrCode GetBackupInfo(std::string &result) override;
ErrCode GetBundleProcessInfo();
ErrCode UpdateFdSendRate(std::string &bundleName, int32_t sendRate) override;
void AsyncTaskRestoreForUpgrade(void);
void ExtClear(void);
void AsyncTaskIncrementalRestoreForUpgrade(void);
@ -88,7 +87,7 @@ private:
*
* @param fileName name of the file that to be untar
*/
int DoRestore(const string &fileName);
int DoRestore(const string &fileName, const off_t fileSize);
/**
* @brief incremental restore
@ -115,12 +114,13 @@ private:
ErrCode errCode = 0);
/**
* @brief extension backup restore is done
* @brief extension process Info
*
* @param restoreRetInfo app restore reportInfo
* @param restoreRetInfo app processInfo
* @param scenario backup or restore
* @param errCode errCode
*/
void ReportAppProcessInfo(const std::string restoreRetInfo, BackupRestoreScenario scenario,
ErrCode errCode = 0);
void ReportAppProcessInfo(const std::string processInfo, BackupRestoreScenario scenario);
/**
* @brief Executing Backup Tasks Asynchronously
@ -165,11 +165,14 @@ private:
void AsyncTaskOnIncrementalBackup();
ErrCode IncrementalBigFileReady(const TarMap &pkgInfo, const vector<struct ReportFileInfo> &bigInfos,
sptr<IService> proxy);
ErrCode BigFileReady(sptr<IService> proxy);
ErrCode BigFileReady(const TarMap &bigFileInfo, sptr<IService> 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<struct ReportFileInfo> &infos, TarMap &tar, sptr<IService> proxy);
void DoPacket(const map<string, size_t> &srcFiles, TarMap &tar, sptr<IService> proxy);
void CheckTmpDirFileInfos(bool isSpecialVersion = false);
std::map<std::string, off_t> GetIdxFileInfos(bool isSpecialVersion = false);
tuple<bool, vector<string>> CheckRestoreFileInfos();
/**
* @brief extension incremental backup restore is done
*
@ -182,7 +185,14 @@ private:
*
* @param errCode
*/
std::function<void(ErrCode, const std::string)> RestoreResultCallbackEx(wptr<BackupExtExtension> obj);
std::function<void(ErrCode, const std::string)> FullRestoreCallbackEx(wptr<BackupExtExtension> obj);
/**
* @brief get callback for execute onRestore
*
* @param errCode
*/
std::function<void(ErrCode, const std::string)> FullRestoreCallback(wptr<BackupExtExtension> obj);
/**
* @brief get callbackEx for execute onRestore with string param
@ -191,6 +201,13 @@ private:
*/
std::function<void(ErrCode, const std::string)> IncRestoreResultCallbackEx(wptr<BackupExtExtension> obj);
/**
* @brief get callback for execute onRestore with string param
*
* @param errCode
*/
std::function<void(ErrCode, const std::string)> IncRestoreResultCallback(wptr<BackupExtExtension> obj);
/**
* @brief get callbackEx for execute onRestore
*
@ -203,7 +220,40 @@ private:
*/
std::function<void(ErrCode, std::string)> AppDoneCallbackEx(wptr<BackupExtExtension> obj);
std::function<void(ErrCode, const std::string)> HandleBackupEx(wptr<BackupExtExtension> obj);
std::function<void(ErrCode, const std::string)> HandleTaskBackupEx(wptr<BackupExtExtension> obj);
std::function<void(ErrCode, const std::string)> HandleFullBackupCallbackEx(wptr<BackupExtExtension> obj);
std::function<void(ErrCode, const std::string)> HandleFullBackupCallback(wptr<BackupExtExtension> obj);
void HandleSpecialVersionRestore();
void DeleteBackupIncrementalTars();
void DeleteBackupTars();
void SetClearDataFlag(bool isClearData);
std::vector<ExtManageInfo> GetExtManageInfo();
ErrCode RestoreFilesForSpecialCloneCloud();
void RestoreBigFilesForSpecialCloneCloud(const ExtManageInfo &item);
ErrCode RestoreTarForSpecialCloneCloud(const ExtManageInfo &item);
void RestoreBigFiles(bool appendTargetPath);
void FillEndFileInfos(const std::string &path, const unordered_map<string, struct ReportFileInfo> &result);
void RestoreBigFileAfter(const string &filePath, const struct stat &sta);
void DealIncreUnPacketResult(const off_t tarFileSize, const std::string &tarFileName,
const std::tuple<int, EndFileInfo, ErrFileInfo> &result);
std::function<void(ErrCode, const std::string)> ExecOnProcessCallback(wptr<BackupExtExtension> obj,
BackupRestoreScenario scenario);
// std::function<void(ErrCode, const std::string)> ExecOnProcessTimeoutCallback(wptr<BackupExtExtension> obj);
bool CreateExecOnProcessTask(BackupRestoreScenario scenario);
bool ShutDownExecOnProcessTask();
bool ExecOnProcessTimeoutTask(wptr<BackupExtExtension> obj);
bool ShutDownOnProcessTimeoutTask();
private:
std::shared_mutex lock_;
std::shared_ptr<ExtBackup> extension_;
@ -217,7 +267,41 @@ private:
std::mutex waitTimeLock_;
std::string bundleName_;
int32_t sendRate_ = BConstants::DEFAULT_FD_SEND_RATE;
Utils::Timer extTime_ {"queryOnProcessTimer"};
bool isClearData_ {true};
bool isDebug_ {false};
std::map<std::string, off_t> endFileInfos_;
std::map<std::string, std::vector<ErrCode>> errFileInfos_;
bool isRpValid_ {false};
Utils::Timer execOnProcessTaskTimer_ {"execOnProcessTaskTimer_"};
uint32_t execOnProcessTaskTimerId_;
Utils::Timer execOnProcessTimeoutTimer_ {"execOnProcessTimeoutTimer_"};
uint32_t execOnProcessTimeoutTimerId_;
int execOnProcessTimeoutTimes_;
bool isSameClock_ {false};
bool appExecFinished_ {false};
};
} // namespace OHOS::FileManagement::Backup

View File

@ -42,7 +42,6 @@ private:
ErrCode CmdIncrementalOnBackup(MessageParcel &data, MessageParcel &reply);
ErrCode CmdGetIncrementalBackupFileHandle(MessageParcel &data, MessageParcel &reply);
ErrCode CmdGetBackupInfo(MessageParcel &data, MessageParcel &reply);
ErrCode CmdGetProcessInfo(MessageParcel &data, MessageParcel &reply);
ErrCode CmdUpdateFdSendRate(MessageParcel &data, MessageParcel &reply);
private:

View File

@ -28,13 +28,22 @@ struct FileStatInfo {
off_t mtime {0};
std::string longName {};
};
using ErrFileInfo = std::map<std::string, std::vector<int>>;
using EndFileInfo = std::map<std::string, off_t>;
const int FIRST_PARAM = 0;
const int SECOND_PARAM = 1;
const int THIRD_PARAM = 2;
class UntarFile {
public:
typedef enum { ERR_FORMAT = -1 } ErrorCode;
static UntarFile &GetInstance();
int UnPacket(const std::string &tarFile, const std::string &rootPath);
int IncrementalUnPacket(const std::string &tarFile, const std::string &rootPath,
const std::unordered_map<std::string, struct ReportFileInfo> &includes);
std::tuple<int, EndFileInfo, ErrFileInfo> UnPacket(
const std::string &tarFile, const std::string &rootPath);
std::tuple<int, EndFileInfo, ErrFileInfo> IncrementalUnPacket(
const std::string &tarFile, const std::string &rootPath,
const std::unordered_map<std::string, struct ReportFileInfo> &includes);
private:
UntarFile() = default;
@ -47,14 +56,14 @@ private:
*
* @param rootpath
*/
int ParseTarFile(const std::string &rootPath);
std::tuple<int, EndFileInfo, ErrFileInfo> ParseTarFile(const std::string &rootPath);
/**
* @brief parse incremental tar file
*
* @param rootpath
*/
int ParseIncrementalTarFile(const std::string &rootPath);
std::tuple<int, EndFileInfo, ErrFileInfo> ParseIncrementalTarFile(const std::string &rootPath);
/**
* @brief verfy check sum
@ -84,7 +93,7 @@ private:
* @param path
* @param mode
*/
void CreateDir(std::string &path, mode_t mode);
ErrFileInfo CreateDir(std::string &path, mode_t mode);
/**
* @brief creat a file
@ -101,7 +110,7 @@ private:
* @param info
* @param typeFlag
*/
void ParseRegularFile(FileStatInfo &info, char typeFlag);
ErrFileInfo ParseRegularFile(FileStatInfo &info, char typeFlag);
/**
* @brief handle tar buffer
@ -110,7 +119,7 @@ private:
* @param name
* @param info
*/
void HandleTarBuffer(const std::string &buff, const std::string &name, FileStatInfo &info);
off_t HandleTarBuffer(const std::string &buff, const std::string &name, FileStatInfo &info);
/**
* @brief parse file by typeFlag
@ -118,7 +127,7 @@ private:
* @param typeFlag
* @param info
*/
void ParseFileByTypeFlag(char typeFlag, FileStatInfo &info);
std::tuple<int, bool, ErrFileInfo> ParseFileByTypeFlag(char typeFlag, FileStatInfo &info);
/**
* @brief parse incremental file by typeFlag
@ -126,7 +135,52 @@ private:
* @param typeFlag
* @param info
*/
int ParseIncrementalFileByTypeFlag(char typeFlag, FileStatInfo &info);
std::tuple<int, bool, ErrFileInfo> ParseIncrementalFileByTypeFlag(char typeFlag, FileStatInfo &info);
/**
* @brief Check tar and fill tar size
*/
int CheckAndFillTarSize();
/**
* @brief Read long name and recode errinfo
*
* @param info file state info
*/
std::tuple<int, ErrFileInfo> ReadLongName(FileStatInfo &info);
/**
* @brief deal parse tar file result
*
* @param result parse tar file result info
* @param fileSize size of the file in tar
* @param fileName file state info
* @param fileInfos out param, record file info
* @param errInfos out param, record err file info
*/
int DealParseTarFileResult(const std::tuple<int, bool, ErrFileInfo> &result,
const off_t fileSize, const std::string &fileName, EndFileInfo &fileInfos, ErrFileInfo &errInfos);
/**
* @brief deal incremental parse tar file result
*
* @param result parse tar file result info
* @param fileSize size of the file in tar
* @param fileName file state info
* @param fileInfos out param, record file info
* @param errInfos out param, record err file info
*/
int DealIncreParseTarFileResult(const std::tuple<int, bool, ErrFileInfo> &result,
const off_t fileSize, const std::string &fileName, EndFileInfo &fileInfos, ErrFileInfo &errInfos);
/**
* @brief check if tar block valid
*
* @param buff check buff info
* @param header check header info
* @param ret out param, the err info
*/
bool CheckIfTarBlockValid(char *buff, size_t buffLen, TarHeader *header, int &ret);
private:
std::string rootPath_ {};

View File

@ -189,12 +189,6 @@ sptr<IRemoteObject> ExtBackup::OnConnect(const AAFwk::Want &want)
auto remoteObject =
sptr<BackupExtExtension>(new BackupExtExtension(std::static_pointer_cast<ExtBackup>(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<BackupExtExtension>(
new BackupExtExtension(std::static_pointer_cast<ExtBackup>(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<void(ErrCode, std::string)> callback)
{
HILOGI("BackupExtensionAbility(base) OnBackup.");

View File

@ -844,10 +844,9 @@ ErrCode ExtBackupJs::OnProcess(std::function<void(ErrCode, const std::string)> c
HILOGI("BackupExtensionAbility(JS) OnProcess begin.");
BExcepUltils::BAssert(jsObj_, BError::Codes::EXT_BROKEN_FRAMEWORK,
"The app does not provide the OnProcess interface.");
callbackInfoBackup_ = std::make_shared<CallbackInfoBackup>(callback);
auto retParser = [jsRuntime {&jsRuntime_}, callBackInfo {callbackInfoBackup_}](napi_env env,
onProcessCallback_ = std::make_shared<OnProcessCallBackInfo>(callback);
auto retParser = [jsRuntime {&jsRuntime_}, callBackInfo {onProcessCallback_}](napi_env env,
napi_value result) -> bool {
if (!CheckPromise(env, result)) {
size_t strLen = 0;
napi_status status = napi_get_value_string_utf8(env, result, nullptr, -1, &strLen);
if (status != napi_ok) {
@ -856,13 +855,9 @@ ErrCode ExtBackupJs::OnProcess(std::function<void(ErrCode, const std::string)> c
size_t bufLen = strLen + 1;
unique_ptr<char[]> str = make_unique<char[]>(bufLen);
status = napi_get_value_string_utf8(env, result, str.get(), bufLen, &strLen);
callBackInfo->callbackParam(BError(BError::Codes::OK), str.get());
callBackInfo->onProcessCallback(BError(BError::Codes::OK), str.get());
return true;
}
HILOGI("BackupExtensionAbulity(JS) OnProcess ok.");
return CallPromiseEx(*jsRuntime, result, callBackInfo.get());
};
auto errCode = CallJsMethod("onProcess", jsRuntime_, jsObj_.get(), {}, retParser);
if (errCode != ERR_OK) {
HILOGE("CallJsMethod error, code:%{public}d.", errCode);

File diff suppressed because it is too large Load Diff

View File

@ -47,8 +47,6 @@ ExtExtensionStub::ExtExtensionStub()
&ExtExtensionStub::CmdGetIncrementalBackupFileHandle;
opToInterfaceMap_[static_cast<uint32_t>(IExtensionInterfaceCode::CMD_GET_BACKUP_INFO)] =
&ExtExtensionStub::CmdGetBackupInfo;
opToInterfaceMap_[static_cast<uint32_t>(IExtensionInterfaceCode::CMD_GET_PROCESS_INFO)] =
&ExtExtensionStub::CmdGetProcessInfo;
opToInterfaceMap_[static_cast<uint32_t>(IExtensionInterfaceCode::CMD_INCREMENTAL_ON_BACKUP)] =
&ExtExtensionStub::CmdIncrementalOnBackup;
opToInterfaceMap_[static_cast<uint32_t>(IExtensionInterfaceCode::CMD_UPDATE_FD_SENDRATE)] =
@ -108,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;
@ -135,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;
@ -189,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;
@ -241,18 +245,4 @@ ErrCode ExtExtensionStub::CmdUpdateFdSendRate(MessageParcel &data, MessageParcel
}
return BError(BError::Codes::OK);
}
ErrCode ExtExtensionStub::CmdGetProcessInfo(MessageParcel &data, MessageParcel &reply)
{
HILOGI("CmdGetProcessInfo Begin");
std::string result;
int ret = GetBackupInfo(result);
if (!reply.WriteInt32(ret)) {
return BError(BError::Codes::EXT_BROKEN_IPC, "Failed to send out the ret").GetCode();
}
if (!reply.WriteString(result)) {
return BError(BError::Codes::EXT_BROKEN_IPC, "Failed to send out the result").GetCode();
}
return BError(BError::Codes::OK);
}
} // namespace OHOS::FileManagement::Backup

View File

@ -0,0 +1,651 @@
/*
* 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 "ext_extension.h"
#include <algorithm>
#include <chrono>
#include <fstream>
#include <iomanip>
#include <map>
#include <regex>
#include <string>
#include <thread>
#include <tuple>
#include <unordered_map>
#include <vector>
#include <directory_ex.h>
#include <sys/stat.h>
#include <unistd.h>
#include <directory_ex.h>
#include <unique_fd.h>
#include "accesstoken_kit.h"
#include "bundle_mgr_client.h"
#include "errors.h"
#include "ipc_skeleton.h"
#include "b_error/b_error.h"
#include "b_error/b_excep_utils.h"
#include "b_filesystem/b_dir.h"
#include "b_filesystem/b_file.h"
#include "b_filesystem/b_file_hash.h"
#include "b_json/b_json_cached_entity.h"
#include "b_jsonutil/b_jsonutil.h"
#include "b_ohos/startup/backup_para.h"
#include "b_tarball/b_tarball_factory.h"
#include "filemgmt_libhilog.h"
#include "hitrace_meter.h"
#include "i_service.h"
#include "sandbox_helper.h"
#include "service_proxy.h"
#include "tar_file.h"
#include "b_anony/b_anony.h"
namespace OHOS::FileManagement::Backup {
const uint32_t MAX_FD_GROUP_USE_TIME = 1000; // 每组打开最大时间1000ms
void BackupExtExtension::WaitToSendFd(std::chrono::system_clock::time_point &startTime, int &fdSendNum)
{
HILOGD("WaitToSendFd Begin");
std::unique_lock<std::mutex> lock(startSendMutex_);
startSendFdRateCon_.wait(lock, [this] { return sendRate_ > 0; });
if (fdSendNum >= sendRate_) {
HILOGI("current time fd num is max rate, bundle name:%{public}s, rate:%{public}d", bundleName_.c_str(),
sendRate_);
auto curTime = std::chrono::system_clock::now();
auto useTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(curTime - startTime).count();
if (useTimeMs < MAX_FD_GROUP_USE_TIME) {
int32_t sleepTime = MAX_FD_GROUP_USE_TIME - useTimeMs;
HILOGI("will wait time:%{public}d ms", sleepTime);
std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime));
} else {
HILOGW("current fd send num exceeds one second");
}
fdSendNum = 0;
startTime = std::chrono::system_clock::now();
}
HILOGD("WaitToSendFd End");
}
void BackupExtExtension::RefreshTimeInfo(std::chrono::system_clock::time_point &startTime, int &fdSendNum)
{
auto currentTime = std::chrono::system_clock::now();
auto useTime = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - startTime).count();
if (useTime >= MAX_FD_GROUP_USE_TIME) {
HILOGI("RefreshTimeInfo Begin, fdSendNum is:%{public}d", fdSendNum);
startTime = std::chrono::system_clock::now();
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();
}
}
std::map<std::string, off_t> BackupExtExtension::GetIdxFileInfos(bool isSpecialVersion)
{
string restoreDir = isSpecialVersion ? "" :
string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE);
auto extManageInfo = GetExtManageInfo();
std::map<std::string, off_t> idxFileInfos;
for (size_t i = 0; i < extManageInfo.size(); ++i) {
std::string realPath = restoreDir + extManageInfo[i].hashName;
idxFileInfos[realPath] = extManageInfo[i].sta.st_size;
}
return idxFileInfos;
}
void BackupExtExtension::CheckTmpDirFileInfos(bool isSpecialVersion)
{
ErrFileInfo errFiles;
auto idxFileInfos = GetIdxFileInfos(isSpecialVersion);
struct stat attr;
for (auto it : idxFileInfos) {
if (it.first.size() >= PATH_MAX || stat(it.first.data(), &attr) == -1) {
HILOGE("(Debug) Failed to get stat of %{public}s, errno = %{public}d",
GetAnonyPath(it.first).c_str(), errno);
errFiles[it.first].push_back(errno);
} else if (it.second != attr.st_size) {
HILOGE("(Debug) RecFile:%{public}s size err, recSize: %{public}" PRId64 ", idxSize: %{public}" PRId64 "",
GetAnonyPath(it.first).c_str(), attr.st_size, it.second);
errFiles[it.first] = std::vector<int>();
}
}
HILOGE("(Debug) Temp file check result: Total file: %{public}zu, err file: %{public}zu",
idxFileInfos.size(), errFiles.size());
if (!errFiles.empty()) {
HILOGE("(Debug) The received file and idx is not same");
} else {
HILOGI("(Debug) The received file and idx is same");
}
}
tuple<bool, vector<string>> BackupExtExtension::CheckRestoreFileInfos()
{
vector<string> errFiles;
struct stat curFileStat {};
for (const auto& it : endFileInfos_) {
if (lstat(it.first.c_str(), &curFileStat) != 0) {
HILOGE("(Debug) Failed to lstat, err = %{public}d", errno);
errFiles.emplace_back(it.first);
errFileInfos_[it.first].push_back(errno);
} else if (curFileStat.st_size != it.second) {
HILOGE("(Debug) File size check error, file: %{public}s", GetAnonyPath(it.first).c_str());
errFiles.emplace_back(it.first);
errFileInfos_[it.first].push_back(errno);
}
}
for (const auto& it : errFileInfos_) {
for (const auto &codeIt : it.second) {
HILOGE("(Debug) errfileInfos file = %{public}s -> %{public}d", GetAnonyPath(it.first).c_str(), codeIt);
}
}
HILOGE("(Debug) End file check result Total file: %{public}zu, err file: %{public}zu",
endFileInfos_.size(), errFileInfos_.size());
if (errFiles.size()) {
return {false, errFiles};
}
return {true, errFiles};
}
std::function<void(ErrCode, const std::string)> BackupExtExtension::HandleFullBackupCallbackEx(
wptr<BackupExtExtension> obj)
{
HILOGI("Begin get HandleFullBackupCallbackEx");
return [obj](ErrCode errCode, const std::string backupExRetInfo) {
HILOGI("begin call backup");
auto extensionPtr = obj.promote();
if (extensionPtr == nullptr) {
HILOGE("Ext extension handle have been released");
return;
}
if (extensionPtr->extension_ == nullptr) {
HILOGE("Extension handle have been released");
return;
}
extensionPtr->extension_->InvokeAppExtMethod(errCode, backupExRetInfo);
if (backupExRetInfo.size()) {
HILOGI("Will notify backup result report");
extensionPtr->appExecFinished_ = true;
extensionPtr->ShutDownExecOnProcessTask();
extensionPtr->AsyncTaskBackup(extensionPtr->extension_->GetUsrConfig());
extensionPtr->AppResultReport(backupExRetInfo, BackupRestoreScenario::FULL_BACKUP);
}
};
}
std::function<void(ErrCode, const std::string)> BackupExtExtension::HandleFullBackupCallback(
wptr<BackupExtExtension> obj)
{
HILOGI("Begin get HandleFullBackupCallbackEx");
return [obj](ErrCode errCode, std::string errMsg) {
HILOGI("begin call backup");
auto extensionPtr = obj.promote();
if (extensionPtr == nullptr) {
HILOGE("Ext extension handle have been released");
return;
}
extensionPtr->appExecFinished_ = true;
extensionPtr->ShutDownExecOnProcessTask();
if (extensionPtr->extension_ == nullptr) {
HILOGE("Extension handle have been released");
return;
}
extensionPtr->AsyncTaskBackup(extensionPtr->extension_->GetUsrConfig());
};
}
std::function<void(ErrCode, std::string)> BackupExtExtension::FullRestoreCallbackEx(wptr<BackupExtExtension> obj)
{
HILOGI("Begin get callbackEx");
return [obj](ErrCode errCode, const std::string restoreRetInfo) {
auto extensionPtr = obj.promote();
if (extensionPtr == nullptr) {
HILOGE("Ext extension handle have been released");
return;
}
if (extensionPtr->extension_ == nullptr) {
HILOGE("Extension handle have been released");
return;
}
extensionPtr->extension_->InvokeAppExtMethod(errCode, restoreRetInfo);
if (errCode == ERR_OK) {
if (restoreRetInfo.size()) {
HILOGI("Will notify restore result report");
extensionPtr->AppResultReport(restoreRetInfo, BackupRestoreScenario::FULL_RESTORE);
}
return;
}
if (restoreRetInfo.empty()) {
extensionPtr->AppDone(errCode);
extensionPtr->DoClear();
} else {
std::string errInfo;
BJsonUtil::BuildRestoreErrInfo(errInfo, errCode, restoreRetInfo);
extensionPtr->AppResultReport(errInfo, BackupRestoreScenario::FULL_RESTORE, errCode);
extensionPtr->DoClear();
}
};
}
std::function<void(ErrCode, std::string)> BackupExtExtension::FullRestoreCallback(wptr<BackupExtExtension> obj)
{
return [obj](ErrCode errCode, std::string errMsg) {
auto extensionPtr = obj.promote();
if (extensionPtr == nullptr) {
HILOGE("Ext extension handle have been released");
return;
}
extensionPtr->appExecFinished_ = true;
extensionPtr->ShutDownExecOnProcessTask();
HILOGI("Current bundle will execute app done");
if (errMsg.empty()) {
extensionPtr->AppDone(errCode);
} else {
std::string errInfo;
BJsonUtil::BuildRestoreErrInfo(errInfo, errCode, errMsg);
extensionPtr->AppResultReport(errInfo, BackupRestoreScenario::FULL_RESTORE, errCode);
}
extensionPtr->DoClear();
};
}
std::function<void(ErrCode, std::string)> BackupExtExtension::IncRestoreResultCallback(wptr<BackupExtExtension> obj)
{
HILOGI("Begin get callback for onRestore");
return [obj](ErrCode errCode, std::string errMsg) {
auto extensionPtr = obj.promote();
if (extensionPtr == nullptr) {
HILOGE("Ext extension handle have been released");
return;
}
extensionPtr->appExecFinished_ = true;
extensionPtr->ShutDownExecOnProcessTask();
HILOGI("Current bundle will execute app done");
if (errMsg.empty()) {
extensionPtr->AppIncrementalDone(errCode);
} else {
std::string errInfo;
BJsonUtil::BuildRestoreErrInfo(errInfo, errCode, errMsg);
extensionPtr->AppResultReport(errInfo, BackupRestoreScenario::INCREMENTAL_RESTORE, errCode);
}
extensionPtr->DoClear();
};
}
void BackupExtExtension::ReportAppProcessInfo(const std::string processInfo, BackupRestoreScenario scenario)
{
auto proxy = ServiceProxy::GetInstance();
if (proxy == nullptr) {
HILOGE("Report app process error, proxy is empty");
return;
}
auto ret = proxy->ReportAppProcessInfo(processInfo, scenario);
if (ret != ERR_OK) {
HILOGE("Report app process error, ipc failed, ret:%{public}d", ret);
return;
}
}
std::function<void(ErrCode, const std::string)> BackupExtExtension::ExecOnProcessCallback(wptr<BackupExtExtension> obj,
BackupRestoreScenario scenario)
{
return [obj, scenario](ErrCode errCode, const std::string processInfo) {
auto extPtr = obj.promote();
if (extPtr == nullptr) {
HILOGE("Execute onProcess callback error, extPtr is empty");
return;
}
extPtr->ShutDownOnProcessTimeoutTask();
if (extPtr->isSameClock_ && extPtr->execOnProcessTimeoutTimes_ > 0) {
HILOGE("Current time call onProcess no result, timeOut count:%{public}d",
extPtr->execOnProcessTimeoutTimes_);
return;
}
extPtr->execOnProcessTimeoutTimes_ = 0; // 正常场景重置超时次数
if (processInfo.size()) {
extPtr->ReportAppProcessInfo(processInfo, scenario);
} else {
extPtr->ShutDownExecOnProcessTask(); // 认为没实现onProcess,停掉定时器
return;
}
};
}
// std::function<void(ErrCode, const std::string)> BackupExtExtension::ExecOnProcessTimeoutCallback(
// wptr<BackupExtExtension> obj)
// {
// }
bool BackupExtExtension::CreateExecOnProcessTask(BackupRestoreScenario scenario)
{
auto taskCallBack = [obj{ wptr<BackupExtExtension>(this) }, scenario]() {
HILOGI("1111");
auto extPtr = obj.promote();
if (extPtr == nullptr) {
HILOGE("CreateExecOnProcessTask error, extPtr is empty");
return;
}
extPtr->isSameClock_ = true;
auto onProcessCallback = extPtr->ExecOnProcessCallback(obj, scenario);
if (!extPtr->appExecFinished_) { // app没有结束就继续执行
extPtr->ExecOnProcessTimeoutTask(obj);
ErrCode ret = extPtr->extension_->OnProcess(onProcessCallback);
if (ret != ERR_OK) {
HILOGE("Execute js method onProcess error, ret:%{public}d", ret);
return;
}
}
extPtr->isSameClock_ = false;
};
execOnProcessTaskTimer_.Setup();
uint32_t onProcessTimerId = execOnProcessTaskTimer_.Register(taskCallBack,
BConstants::CALL_APP_ON_PROCESS_TIME_INTERVAL, false);
execOnProcessTaskTimerId_ = onProcessTimerId;
return true;
}
bool BackupExtExtension::ShutDownExecOnProcessTask()
{
HILOGI("Start Shutdown onProcess task timer");
execOnProcessTaskTimer_.Shutdown();
execOnProcessTaskTimer_.Unregister(execOnProcessTaskTimerId_);
HILOGI("End Shutdown onProcess task timer, execOnProcessTaskTimerId: %{public}d", execOnProcessTaskTimerId_);
return true;
}
bool BackupExtExtension::ExecOnProcessTimeoutTask(wptr<BackupExtExtension> obj)
{
auto timeoutCallback = [obj]() {
auto extPtr = obj.promote();
if (extPtr == nullptr) {
HILOGE("CreateExecOnProcessTask error, extPtr is empty");
return;
}
if (extPtr->execOnProcessTimeoutTimes_ >= BConstants::APP_ON_PROCESS_TIMEOUT_MAX_COUNT) {
HILOGE("Current App timeout more than three times, Will Report");
extPtr->execOnProcessTimeoutTimes_ = 0; // 已经满足三次超时条件
extPtr->ShutDownOnProcessTimeoutTask();
extPtr->ShutDownExecOnProcessTask();
extPtr->AppDone(BError(BError::Codes::EXT_ABILITY_DIED));
} else {
extPtr->execOnProcessTimeoutTimes_++;
}
};
execOnProcessTimeoutTimer_.Setup();
uint32_t timeoutTimerId = execOnProcessTimeoutTimer_.Register(timeoutCallback,
BConstants::APP_ON_PROCESS_MAX_TIMEOUT, true);
execOnProcessTimeoutTimerId_ = timeoutTimerId;
return true;
}
bool BackupExtExtension::ShutDownOnProcessTimeoutTask()
{
HILOGI("Start Shutdown onProcess Timeout timer");
execOnProcessTimeoutTimer_.Shutdown();
execOnProcessTimeoutTimer_.Unregister(execOnProcessTimeoutTimerId_);
HILOGI("End Shutdown onProcess Timeout timer, timeoutTimerId: %{public}d", execOnProcessTimeoutTimerId_);
return true;
}
} // namespace OHOS::FileManagement::Backup

View File

@ -196,23 +196,23 @@ bool TarFile::I2OcsConvert(const struct stat &st, TarHeader &hdr, string &fileNa
if (S_ISREG(st.st_mode)) {
hdr.typeFlag = REGTYPE;
off_t hdrSize = st.st_size;
if (sizeof(off_t) <= OFF_T_SIZE || st.st_size <= static_cast<off_t>(MAX_FILE_SIZE)) {
size = I2Ocs(sizeof(hdr.size), hdrSize);
ret = memcpy_s(hdr.size, sizeof(hdr.size), size.c_str(), min(sizeof(hdr.size) - 1, size.length()));
if (ret != EOK) {
HILOGE("Failed to call memcpy_s, err = %{public}d", ret);
return false;
}
} else {
HILOGE("Invalid tar header size");
return false;
}
} else if (S_ISDIR(st.st_mode)) {
hdr.typeFlag = DIRTYPE;
} else {
return true;
}
off_t hdrSize = st.st_size;
if (sizeof(off_t) <= OFF_T_SIZE || st.st_size <= static_cast<off_t>(MAX_FILE_SIZE)) {
size = I2Ocs(sizeof(hdr.size), hdrSize);
ret = memcpy_s(hdr.size, sizeof(hdr.size), size.c_str(), min(sizeof(hdr.size) - 1, size.length()));
if (ret != EOK) {
HILOGE("Failed to call memcpy_s, err = %{public}d", ret);
return false;
}
} else {
HILOGE("Invalid tar header size");
return false;
}
if (S_ISDIR(st.st_mode) && fileName.back() != '/') {
fileName.append("/");

View File

@ -77,23 +77,34 @@ static void RTrimNull(std::string &s)
s.erase(iter.base(), s.end());
}
static int ReadLongName(FileStatInfo &info, FILE *tarFilePtr_, off_t tarFileSize_)
std::tuple<int, ErrFileInfo> UntarFile::ReadLongName(FileStatInfo &info)
{
size_t nameLen = static_cast<size_t>(tarFileSize_);
int ret = 0;
if (nameLen <= PATH_MAX_LEN) {
string tempName("");
tempName.resize(nameLen);
size_t read = fread(&(tempName[0]), sizeof(char), nameLen, tarFilePtr_);
if (read < nameLen) {
HILOGE("Failed to fread longName of %{private}s", info.fullPath.c_str());
return -1;
ret = -1;
}
info.longName = tempName;
} else {
HILOGE("longName of %{private}s exceed PATH_MAX_LEN", info.fullPath.c_str());
ret = -1;
}
return 0;
ErrFileInfo errFileInfo;
if (ret != 0) {
errFileInfo[info.fullPath].push_back(ret);
return {-1, errFileInfo};
}
if (fseeko(tarFilePtr_, pos_ + tarFileBlockCnt_ * BLOCK_SIZE, SEEK_SET) != 0) {
HILOGE("Failed to fseeko of %{private}s, err = %{public}d", info.fullPath.c_str(), errno);
errFileInfo[info.fullPath].push_back(errno);
return {-1, errFileInfo};
}
return {0, errFileInfo};
}
UntarFile &UntarFile::GetInstance()
@ -102,45 +113,48 @@ UntarFile &UntarFile::GetInstance()
return instance;
}
int UntarFile::UnPacket(const string &tarFile, const string &rootPath)
std::tuple<int, EndFileInfo, ErrFileInfo> UntarFile::UnPacket(
const std::string &tarFile, const std::string &rootPath)
{
tarFilePtr_ = fopen(tarFile.c_str(), "rb");
if (tarFilePtr_ == nullptr) {
HILOGE("Failed to open tar file %{public}s, err = %{public}d", tarFile.c_str(), errno);
return errno;
return {errno, {}, {}};
}
if (ParseTarFile(rootPath) != 0) {
auto [ret, fileInfos, errInfos] = ParseTarFile(rootPath);
if (ret != 0) {
HILOGE("Failed to parse tar file");
}
fclose(tarFilePtr_);
tarFilePtr_ = nullptr;
return 0;
return {ret, fileInfos, errInfos};
}
int UntarFile::IncrementalUnPacket(const string &tarFile, const string &rootPath,
const unordered_map<string, struct ReportFileInfo> &includes)
std::tuple<int, EndFileInfo, ErrFileInfo> UntarFile::IncrementalUnPacket(
const string &tarFile, const string &rootPath, const unordered_map<string, struct ReportFileInfo> &includes)
{
includes_ = includes;
tarFilePtr_ = fopen(tarFile.c_str(), "rb");
if (tarFilePtr_ == nullptr) {
HILOGE("Failed to open tar file %{public}s, err = %{public}d", tarFile.c_str(), errno);
return errno;
return {errno, {}, {}};
}
if (ParseIncrementalTarFile(rootPath) != 0) {
auto [ret, fileInfos, errFileInfos] = ParseIncrementalTarFile(rootPath);
if (ret != 0) {
HILOGE("Failed to parse tar file");
}
fclose(tarFilePtr_);
tarFilePtr_ = nullptr;
return 0;
return {ret, fileInfos, errFileInfos};
}
void UntarFile::HandleTarBuffer(const string &buff, const string &name, FileStatInfo &info)
off_t UntarFile::HandleTarBuffer(const string &buff, const string &name, FileStatInfo &info)
{
info.mode = static_cast<mode_t>(ParseOctalStr(&buff[0] + TMODE_BASE, TMODE_LEN));
info.uid = static_cast<uid_t>(ParseOctalStr(&buff[0] + TUID_BASE, TUID_LEN));
@ -158,194 +172,244 @@ void UntarFile::HandleTarBuffer(const string &buff, const string &name, FileStat
}
if (realName.length() > 0 && realName[0] == '/') {
info.fullPath = realName.substr(1, realName.length() - 1);
return;
return tarFileSize_;
}
info.fullPath = realName;
return tarFileSize_;
}
int UntarFile::ParseTarFile(const string &rootPath)
int UntarFile::CheckAndFillTarSize()
{
// re-parse tar header
rootPath_ = rootPath;
char buff[BLOCK_SIZE] = {0};
FileStatInfo info {};
// tarFileSize
int ret = fseeko(tarFilePtr_, 0L, SEEK_END);
if (ret != 0) {
HILOGE("Failed to fseeko tarFileSize SEEK_SET, err = %{public}d", errno);
return ret;
}
tarFileSize_ = ftello(tarFilePtr_);
// reback file to begin
ret = fseeko(tarFilePtr_, 0L, SEEK_SET);
if (ret != 0) {
HILOGE("Failed to fseeko reback SEEK_SET, err = %{public}d", errno);
return ret;
}
while (1) {
readCnt_ = fread(buff, 1, BLOCK_SIZE, tarFilePtr_);
if (readCnt_ < BLOCK_SIZE) {
HILOGE("Parsing tar file completed, read data count is less then block size.");
return 0;
}
TarHeader *header = reinterpret_cast<TarHeader *>(buff);
// two empty continuous block indicate end of file
if (IsEmptyBlock(buff) && header->typeFlag != GNUTYPE_LONGNAME) {
char tailBuff[BLOCK_SIZE] = {0};
size_t tailRead = fread(tailBuff, 1, BLOCK_SIZE, tarFilePtr_);
if (tailRead == BLOCK_SIZE && IsEmptyBlock(tailBuff)) {
HILOGE("Parsing tar file completed, tailBuff is empty.");
return 0;
}
}
// check header
if (!IsValidTarBlock(*header)) {
// when split unpack, ftell size is over than file really size [0,READ_BUFF_SIZE]
if (ftello(tarFilePtr_) > (tarFileSize_ + READ_BUFF_SIZE) || !IsEmptyBlock(buff)) {
HILOGE("Invalid tar file format");
ret = ERR_FORMAT;
}
HILOGE("invalid tar block header");
return ret;
}
HandleTarBuffer(string(buff, BLOCK_SIZE), header->name, info);
ParseFileByTypeFlag(header->typeFlag, info);
}
return ret;
}
int UntarFile::ParseIncrementalTarFile(const string &rootPath)
int UntarFile::DealParseTarFileResult(const std::tuple<int, bool, ErrFileInfo> &result,
const off_t fileSize, const std::string &fileName, EndFileInfo &fileInfos, ErrFileInfo &errInfos)
{
auto [ret, isFilter, subErrInfos] = result;
if (ret != 0) {
HILOGE("Failed to parse incremental file by type flag");
return ret;
}
if (!isFilter) {
fileInfos[fileName] = fileSize;
}
if (!errInfos.empty()) {
errInfos.merge(subErrInfos);
}
return 0;
}
bool UntarFile::CheckIfTarBlockValid(char *buff, size_t buffLen, TarHeader *header, int &ret)
{
// two empty continuous block indicate end of file
if (buff == nullptr || buffLen != BLOCK_SIZE || header == nullptr) {
return false;
}
if (IsEmptyBlock(buff) && header->typeFlag != GNUTYPE_LONGNAME) {
char tailBuff[BLOCK_SIZE] = {0};
size_t tailRead = fread(tailBuff, 1, BLOCK_SIZE, tarFilePtr_);
if (tailRead == BLOCK_SIZE && IsEmptyBlock(tailBuff)) {
HILOGE("Parsing tar file completed, tailBuff is empty.");
ret = 0;
}
return false;
}
// check header
if (!IsValidTarBlock(*header)) {
// when split unpack, ftell size is over than file really size [0,READ_BUFF_SIZE]
if (ftello(tarFilePtr_) > (tarFileSize_ + READ_BUFF_SIZE) || !IsEmptyBlock(buff)) {
HILOGE("Invalid tar file format");
ret = ERR_FORMAT;
}
HILOGE("invalid tar block header");
return false;
}
return true;
}
std::tuple<int, EndFileInfo, ErrFileInfo> UntarFile::ParseTarFile(const string &rootPath)
{
// re-parse tar header
rootPath_ = rootPath;
char buff[BLOCK_SIZE] = {0};
FileStatInfo info {};
int ret = 0;
if ((ret = CheckAndFillTarSize()) != 0) {
return {ret, {}, {}};
}
EndFileInfo fileInfos;
ErrFileInfo errInfos;
while (1) {
readCnt_ = fread(buff, 1, BLOCK_SIZE, tarFilePtr_);
if (readCnt_ < BLOCK_SIZE) {
HILOGE("Parsing tar file completed, read data count is less then block size.");
return {0, fileInfos, errInfos};
}
TarHeader *header = reinterpret_cast<TarHeader *>(buff);
bool isValid = CheckIfTarBlockValid(buff, sizeof(buff), header, ret);
if (!isValid) {
return {ret, fileInfos, errInfos};
}
off_t fileSize = HandleTarBuffer(string(buff, BLOCK_SIZE), header->name, info);
auto result = ParseFileByTypeFlag(header->typeFlag, info);
if ((ret = DealParseTarFileResult(result, fileSize, info.fullPath, fileInfos, errInfos)) != 0) {
return {ret, fileInfos, errInfos};
}
}
// tarFileSize
int ret = fseeko(tarFilePtr_, 0L, SEEK_END);
return {ret, fileInfos, errInfos};
}
int UntarFile::DealIncreParseTarFileResult(const std::tuple<int, bool, ErrFileInfo> &result,
const off_t fileSize, const std::string &fileName, EndFileInfo &fileInfos, ErrFileInfo &errInfos)
{
auto [ret, isFilter, subErrInfo] = result;
if (ret != 0) {
HILOGE("Failed to fseeko tarFile SEEK_END, err = %{public}d", errno);
HILOGE("Failed to parse incremental file by type flag");
return ret;
}
tarFileSize_ = ftello(tarFilePtr_);
// reback file to begin
if ((ret = fseeko(tarFilePtr_, 0L, SEEK_SET)) != 0) {
HILOGE("Failed to fseeko tarFile SEEK_SET, err = %{public}d", errno);
return ret;
if (!isFilter) {
fileInfos[fileName] = fileSize;
if (!subErrInfo.empty()) {
errInfos.merge(subErrInfo);
}
}
return 0;
}
std::tuple<int, EndFileInfo, ErrFileInfo> UntarFile::ParseIncrementalTarFile(const string &rootPath)
{
// re-parse tar header
rootPath_ = rootPath;
char buff[BLOCK_SIZE] = {0};
FileStatInfo info {};
int ret = 0;
if ((ret = CheckAndFillTarSize()) != 0) {
return {ret, {}, {}};
}
EndFileInfo fileInfos;
ErrFileInfo errFileInfo;
do {
readCnt_ = fread(buff, 1, BLOCK_SIZE, tarFilePtr_);
if (readCnt_ < BLOCK_SIZE) {
HILOGE("Parsing tar file completed, read data count is less then block size.");
return 0;
return {0, fileInfos, errFileInfo};
}
TarHeader *header = reinterpret_cast<TarHeader *>(buff);
// two empty continuous block indicate end of file
if (IsEmptyBlock(buff) && header->typeFlag != GNUTYPE_LONGNAME) {
char tailBuff[BLOCK_SIZE] = {0};
size_t tailRead = fread(tailBuff, 1, BLOCK_SIZE, tarFilePtr_);
if (tailRead == BLOCK_SIZE && IsEmptyBlock(tailBuff)) {
HILOGE("Parsing tar file completed, tailBuff is empty.");
return 0;
}
bool isValid = CheckIfTarBlockValid(buff, sizeof(buff), header, ret);
if (!isValid) {
return {ret, fileInfos, errFileInfo};
}
// check header
if (!IsValidTarBlock(*header)) {
// when split unpack, ftell size is over than file really size [0,READ_BUFF_SIZE]
if (ftello(tarFilePtr_) > (tarFileSize_ + READ_BUFF_SIZE) || !IsEmptyBlock(buff)) {
HILOGE("Invalid tar file format");
ret = ERR_FORMAT;
}
return ret;
}
HandleTarBuffer(string(buff, BLOCK_SIZE), header->name, info);
if ((ret = ParseIncrementalFileByTypeFlag(header->typeFlag, info)) != 0) {
HILOGE("Failed to parse incremental file by type flag");
return ret;
off_t fileSize = HandleTarBuffer(string(buff, BLOCK_SIZE), header->name, info);
auto result = ParseIncrementalFileByTypeFlag(header->typeFlag, info);
ret = DealIncreParseTarFileResult(result, fileSize, info.fullPath, fileInfos, errFileInfo);
if (ret != 0) {
return {ret, fileInfos, errFileInfo};
}
} while (readCnt_ >= BLOCK_SIZE);
return ret;
return {ret, fileInfos, errFileInfo};
}
void UntarFile::ParseFileByTypeFlag(char typeFlag, FileStatInfo &info)
tuple<int, bool, ErrFileInfo> UntarFile::ParseFileByTypeFlag(char typeFlag, FileStatInfo &info)
{
HILOGD("untar file: %{public}s, rootPath: %{public}s", GetAnonyPath(info.fullPath).c_str(), rootPath_.c_str());
bool isFilter = true;
ErrFileInfo errFileInfo;
switch (typeFlag) {
case REGTYPE:
case AREGTYPE:
info.fullPath = GenRealPath(rootPath_, info.fullPath);
ParseRegularFile(info, typeFlag);
errFileInfo = ParseRegularFile(info, typeFlag);
isFilter = false;
break;
case SYMTYPE:
break;
case DIRTYPE:
info.fullPath = GenRealPath(rootPath_, info.fullPath);
CreateDir(info.fullPath, info.mode);
errFileInfo = CreateDir(info.fullPath, info.mode);
isFilter = false;
break;
case GNUTYPE_LONGNAME: {
ReadLongName(info, tarFilePtr_, tarFileSize_);
fseeko(tarFilePtr_, pos_ + tarFileBlockCnt_ * BLOCK_SIZE, SEEK_SET);
break;
}
default: {
fseeko(tarFilePtr_, tarFileBlockCnt_ * BLOCK_SIZE, SEEK_CUR);
break;
}
}
}
int UntarFile::ParseIncrementalFileByTypeFlag(char typeFlag, FileStatInfo &info)
{
HILOGD("untar file: %{public}s, rootPath: %{public}s", GetAnonyPath(info.fullPath).c_str(), rootPath_.c_str());
string tmpFullPath = info.fullPath;
RTrimNull(tmpFullPath);
switch (typeFlag) {
case REGTYPE:
case AREGTYPE:
if (!includes_.empty() && includes_.find(tmpFullPath) == includes_.end()) { // not in includes
if (fseeko(tarFilePtr_, pos_ + tarFileBlockCnt_ * BLOCK_SIZE, SEEK_SET) != 0) {
HILOGE("Failed to fseeko of %{private}s, err = %{public}d", info.fullPath.c_str(), errno);
return -1;
}
break;
}
info.fullPath = GenRealPath(rootPath_, info.fullPath);
ParseRegularFile(info, typeFlag);
break;
case SYMTYPE:
break;
case DIRTYPE:
info.fullPath = GenRealPath(rootPath_, info.fullPath);
CreateDir(info.fullPath, info.mode);
break;
case GNUTYPE_LONGNAME: {
int ret = ReadLongName(info, tarFilePtr_, tarFileSize_);
if (ret != 0) {
return ret;
}
if (fseeko(tarFilePtr_, pos_ + tarFileBlockCnt_ * BLOCK_SIZE, SEEK_SET) != 0) {
HILOGE("Failed to fseeko of %{private}s, err = %{public}d", info.fullPath.c_str(), errno);
return -1;
}
auto result = ReadLongName(info);
errFileInfo = std::get<SECOND_PARAM>(result);
return {std::get<FIRST_PARAM>(result), isFilter, errFileInfo};
break;
}
default: {
if (fseeko(tarFilePtr_, tarFileBlockCnt_ * BLOCK_SIZE, SEEK_CUR) != 0) {
HILOGE("Failed to fseeko of %{private}s, err = %{public}d", info.fullPath.c_str(), errno);
return -1;
return {-1, true, errFileInfo};
}
break;
}
}
return {0, isFilter, errFileInfo};
}
std::tuple<int, bool, ErrFileInfo> UntarFile::ParseIncrementalFileByTypeFlag(char typeFlag, FileStatInfo &info)
{
HILOGD("untar file: %{public}s, rootPath: %{public}s", GetAnonyPath(info.fullPath).c_str(), rootPath_.c_str());
string tmpFullPath = info.fullPath;
bool isFilter = true;
ErrFileInfo errFileInfo;
RTrimNull(tmpFullPath);
switch (typeFlag) {
case REGTYPE:
case AREGTYPE: {
if (!includes_.empty() && includes_.find(tmpFullPath) == includes_.end()) { // not in includes
if (fseeko(tarFilePtr_, pos_ + tarFileBlockCnt_ * BLOCK_SIZE, SEEK_SET) != 0) {
HILOGE("Failed to fseeko of %{private}s, err = %{public}d", info.fullPath.c_str(), errno);
return {-1, true, {}};
}
break;
}
info.fullPath = GenRealPath(rootPath_, info.fullPath);
errFileInfo = ParseRegularFile(info, typeFlag);
isFilter = false;
break;
}
case SYMTYPE:
break;
case DIRTYPE:
info.fullPath = GenRealPath(rootPath_, info.fullPath);
errFileInfo = CreateDir(info.fullPath, info.mode);
isFilter = false;
break;
case GNUTYPE_LONGNAME: {
auto result = ReadLongName(info);
return {std::get<FIRST_PARAM>(result), isFilter, std::get<SECOND_PARAM>(result)};
break;
}
default: {
if (fseeko(tarFilePtr_, tarFileBlockCnt_ * BLOCK_SIZE, SEEK_CUR) != 0) {
HILOGE("Failed to fseeko of %{private}s, err = %{public}d", info.fullPath.c_str(), errno);
return {-1, true, {}};
}
break;
}
}
return 0;
return {0, isFilter, errFileInfo};
}
void UntarFile::ParseRegularFile(FileStatInfo &info, char typeFlag)
ErrFileInfo UntarFile::ParseRegularFile(FileStatInfo &info, char typeFlag)
{
ErrFileInfo errFileInfo;
FILE *destFile = CreateFile(info.fullPath, info.mode, typeFlag);
if (destFile != nullptr) {
string destStr("");
@ -361,27 +425,32 @@ void UntarFile::ParseRegularFile(FileStatInfo &info, char typeFlag)
remainSize -= readBuffSize;
}
fclose(destFile);
chmod(info.fullPath.data(), info.mode);
if (chmod(info.fullPath.data(), info.mode) != 0) {
HILOGE("Failed to chmod of %{public}s, err = %{public}d", GetAnonyPath(info.fullPath).c_str(), errno);
errFileInfo[info.fullPath].push_back(errno);
}
struct utimbuf times;
struct stat attr;
if (stat(info.fullPath.c_str(), &attr) != 0) {
HILOGE("Failed to get stat of %{public}s, err = %{public}d",
GetAnonyPath(info.fullPath).c_str(), errno);
errFileInfo[info.fullPath].push_back(errno);
HILOGE("Failed to get stat of %{public}s, err = %{public}d", GetAnonyPath(info.fullPath).c_str(), errno);
times.actime = info.mtime;
} else {
times.actime = attr.st_atime;
}
times.modtime = info.mtime;
if (info.mtime != 0 && utime(info.fullPath.c_str(), &times) != 0) {
HILOGE("Failed to set mtime of %{public}s, err = %{public}d",
GetAnonyPath(info.fullPath).c_str(), errno);
errFileInfo[info.fullPath].push_back(errno);
HILOGE("Failed to set mtime of %{public}s, err = %{public}d", GetAnonyPath(info.fullPath).c_str(), errno);
}
// anyway, go to correct
fseeko(tarFilePtr_, pos_ + tarFileBlockCnt_ * BLOCK_SIZE, SEEK_SET);
} else {
HILOGE("Failed to create file %{public}s, err = %{public}d", GetAnonyPath(info.fullPath).c_str(), errno);
errFileInfo[info.fullPath].push_back(errno);
fseeko(tarFilePtr_, tarFileBlockCnt_ * BLOCK_SIZE, SEEK_CUR);
}
return errFileInfo;
}
bool UntarFile::VerifyChecksum(TarHeader &header)
@ -430,10 +499,11 @@ string UntarFile::GenRealPath(const string &rootPath, const string &realName)
return realPath;
}
void UntarFile::CreateDir(string &path, mode_t mode)
ErrFileInfo UntarFile::CreateDir(string &path, mode_t mode)
{
ErrFileInfo errFileInfo;
if (path.empty()) {
return;
return errFileInfo;
}
size_t len = path.length();
if (path[len - 1] == '/') {
@ -443,8 +513,10 @@ void UntarFile::CreateDir(string &path, mode_t mode)
HILOGW("directory does not exist, path:%{public}s, err = %{public}d", path.c_str(), errno);
if (!ForceCreateDirectoryWithMode(path, mode)) {
HILOGE("Failed to force create directory %{public}s, err = %{public}d", path.c_str(), errno);
errFileInfo[path].push_back(errno);
}
}
return errFileInfo;
}
FILE *UntarFile::CreateFile(string &filePath, mode_t mode, char fileType)

View File

@ -72,7 +72,7 @@ void ServiceReverse::IncrementalBackupOnAllBundlesFinished(int32_t errCode)
void ServiceReverse::IncrementalBackupOnProcessInfo(std::string bundleName, std::string processInfo)
{
HILOGI("errCode = %{public}d", errCode);
HILOGI("bundleName = %{public}s", bundleName.c_str());
if (scenario_ != Scenario::BACKUP || !callbacksIncrementalBackup_.onProcess) {
HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_);
return;
@ -137,7 +137,7 @@ void ServiceReverse::IncrementalRestoreOnResultReport(std::string result, std::s
void ServiceReverse::IncrementalRestoreOnProcessInfo(std::string bundleName, std::string processInfo)
{
HILOGI("begin incremental restore on result report, bundleName:%{public}s", bundleName.c_str());
HILOGI("begin incremental report processInfo, bundleName:%{public}s", bundleName.c_str());
if (scenario_ != Scenario::RESTORE || !callbacksIncrementalRestore_.onProcess) {
HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_);
return;

View File

@ -597,14 +597,14 @@ ErrCode ServiceProxy::ReportAppProcessInfo(const std::string processInfo, const
if (!data.WriteString(processInfo)) {
return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send bundleName").GetCode();
}
if (!data.WriteInt32(static_cast<int32_t>(scenario))) {
if (!data.WriteInt32(static_cast<int32_t>(sennario))) {
return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the scenario").GetCode();
}
MessageParcel reply;
MessageOption option;
option.SetWaitTime(BConstants::IPC_MAX_WAIT_TIME);
int32_t ret = Remote()-> SendRequest(static_cast<uint32_t>(
IServiceInterfaceCode::SERVICE_CMD_NOTIFY_BUNDLE_PROCESS_INFO), data, reply, option);
IServiceInterfaceCode::SERVICE_CMD_REPORT_APP_PROCESS_INFO), data, reply, option);
if (ret != NO_ERROR) {
string str = "Failed to send out the request because of " + to_string(ret);
return BError(BError::Codes::SDK_INVAL_ARG, str.data()).GetCode();

View File

@ -71,7 +71,7 @@ void ServiceReverse::BackupOnAllBundlesFinished(int32_t errCode)
void ServiceReverse::BackupOnProcessInfo(std::string bundleName, std::string processInfo)
{
HILOGI("errCode = %{public}d", errCode);
HILOGI("bundleName = %{public}s", bundleName.c_str());
if (scenario_ != Scenario::BACKUP || !callbacksBackup_.onProcess) {
HILOGI("Error scenario or callback is nullptr");
return;
@ -137,7 +137,7 @@ void ServiceReverse::RestoreOnResultReport(string result, std::string bundleName
void ServiceReverse::RestoreOnProcessInfo(std::string bundleName, std::string processInfo)
{
HILOGI("errCode = %{public}d", errCode);
HILOGI("bundleName = %{public}s", bundleName.c_str());
if (scenario_ != Scenario::RESTORE || !callbacksRestore_.onProcess) {
HILOGI("Error scenario or callback is nullptr");
return;

View File

@ -76,7 +76,7 @@ ServiceReverseStub::ServiceReverseStub()
&ServiceReverseStub::CmdBackupOnBundleFinished;
opToInterfaceMap_[static_cast<uint32_t>(IServiceReverseInterfaceCode::SERVICER_BACKUP_ON_TASK_FINISHED)] =
&ServiceReverseStub::CmdBackupOnAllBundlesFinished;
opToInterfaceMap_[static_cast<uint32_t>(IServiceReverseInterfaceCode::SERVICER_RESTORE_ON_PROCESS_INFO)] =
opToInterfaceMap_[static_cast<uint32_t>(IServiceReverseInterfaceCode::SERVICER_BACKUP_ON_PROCESS_INFO)] =
&ServiceReverseStub::CmdBackupOnProcessInfo;
opToInterfaceMap_[static_cast<uint32_t>(IServiceReverseInterfaceCode::SERVICER_RESTORE_ON_FILE_READY)] =
@ -89,7 +89,7 @@ ServiceReverseStub::ServiceReverseStub()
&ServiceReverseStub::CmdRestoreOnBundleFinished;
opToInterfaceMap_[static_cast<uint32_t>(IServiceReverseInterfaceCode::SERVICER_RESTORE_ON_TASK_FINISHED)] =
&ServiceReverseStub::CmdRestoreOnAllBundlesFinished;
opToInterfaceMap_[static_cast<uint32_t>(IServiceReverseInterfaceCode::SERVICER_BACKUP_ON_PROCESS_INFO)] =
opToInterfaceMap_[static_cast<uint32_t>(IServiceReverseInterfaceCode::SERVICER_RESTORE_ON_PROCESS_INFO)] =
&ServiceReverseStub::CmdRestoreOnProcessInfo;
opToInterfaceMap_[static_cast<uint32_t>(IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_BACKUP_ON_FILE_READY)] =

View File

@ -35,6 +35,7 @@ public:
std::function<void(ErrCode)> onAllBundlesFinished; // 当整个恢复流程结束或意外中止时执行的回调函数
std::function<void(const std::string, const std::string)> onResultReport; // 某个应用恢复流程中自定义错误信息的上报的回调函数
std::function<void()> onBackupServiceDied; // 当备份服务意外死亡时执行的回调函数
std::function<void(const std::string, const std::string)> onProcess; // 某个应用上报执行进度的的回调函数
};
public:

View File

@ -30,16 +30,15 @@ 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<UniqueFd, UniqueFd> GetIncrementalBackupFileHandle() = 0;
virtual ErrCode GetBackupInfo(std::string &result) = 0;
virtual ErrCode GetBackupInfo(std::string &processInfo) = 0;
virtual ErrCode UpdateFdSendRate(std::string &bundleName, int32_t sendRate) = 0;
};
} // namespace OHOS::FileManagement::Backup

View File

@ -31,7 +31,6 @@ enum class IExtensionInterfaceCode {
CMD_GET_BACKUP_INFO,
CMD_INCREMENTAL_ON_BACKUP,
CMD_UPDATE_FD_SENDRATE,
CMD_GET_PROCESS_INFO,
};
} // namespace OHOS::FileManagement::Backup

View File

@ -47,7 +47,7 @@ enum class IServiceInterfaceCode {
SERVICE_CMD_UPDATE_TIMER,
SERVICE_CMD_UPDATE_SENDRATE,
SERVICE_CMD_GET_APP_LOCAL_LIST_AND_DO_INCREMENTAL_BACKUP,
SERVICE_CMD_REPORT_BUNDLE_PROCESS_INFO,
SERVICE_CMD_REPORT_APP_PROCESS_INFO,
};
} // namespace OHOS::FileManagement::Backup

View File

@ -64,7 +64,7 @@ public:
ErrCode errCode = 0) = 0;
virtual void IncrementalRestoreOnBundleFinished(int32_t errCode, std::string bundleName) = 0;
virtual void IncrementalRestoreOnAllBundlesFinished(int32_t errCode) = 0;
virtual void IncrementalRestoreOnProcessInfo(const std::string &bundleName, const std::string &processInfo) = 0;
virtual void IncrementalRestoreOnProcessInfo(const std::string bundleName, const std::string processInfo) = 0;
DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.FileManagement.Backup.IServiceReverse")
};

View File

@ -59,7 +59,7 @@ string FileUri::GetName()
return "";
}
if (posLast == sandboxPath.size()) {
if (posLast == (sandboxPath.size() - 1)) {
return "";
}

View File

@ -53,7 +53,7 @@ public:
LibN::NAsyncWorkCallback onAllBundlesEnd;
LibN::NAsyncWorkCallback onBackupServiceDied;
BackupRestoreCallback onResultReport;
LibN::NAsyncWorkCallback onProcess;
BackupRestoreCallback onProcess;
};
} // namespace OHOS::FileManagement::Backup
#endif // INTERFACES_KITS_JS_SRC_MOD_BACKUP_PROPERTIES_GENERAL_CALLBACKS_H

View File

@ -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;

View File

@ -269,7 +269,7 @@ static void OnProcess(weak_ptr<GeneralCallbacks> pCallbacks, const BundleName na
napi_create_string_utf8(env, bundleName.c_str(), bundleName.size(), &napi_bName);
argv.push_back(napi_bName);
napi_value napi_process = nullptr;
napi_create_string_utf8(env, process.c_str(), process.size(), &napi_res);
napi_create_string_utf8(env, process.c_str(), process.size(), &napi_process);
argv.push_back(napi_process);
return true;
};
@ -279,6 +279,16 @@ static void OnProcess(weak_ptr<GeneralCallbacks> pCallbacks, const BundleName na
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.");
@ -355,6 +365,16 @@ static bool VerifyParamSuccess(NFuncArg &funcArg, std::vector<std::string> &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<std::string> bundleNames;
std::vector<std::string> bundleInfos;
NFuncArg funcArg(env, cbinfo);
@ -398,6 +418,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.");

View File

@ -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"
@ -275,7 +276,7 @@ static void OnProcess(weak_ptr<GeneralCallbacks> pCallbacks, const BundleName na
napi_create_string_utf8(env, bundleName.c_str(), bundleName.size(), &napi_bName);
argv.push_back(napi_bName);
napi_value napi_process = nullptr;
napi_create_string_utf8(env, process.c_str(), process.size(), &napi_res);
napi_create_string_utf8(env, process.c_str(), process.size(), &napi_process);
argv.push_back(napi_process);
return true;
};
@ -285,6 +286,16 @@ static void OnProcess(weak_ptr<GeneralCallbacks> pCallbacks, const BundleName na
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");
@ -420,6 +431,16 @@ static bool VerifyParamSuccess(NFuncArg &funcArg, std::vector<BIncrementalData>
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<BIncrementalData> backupBundles;
std::vector<std::string> bundleInfos;
NFuncArg funcArg(env, cbinfo);
@ -460,6 +481,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.");

View File

@ -281,7 +281,7 @@ static void OnProcess(weak_ptr<GeneralCallbacks> pCallbacks, const BundleName na
napi_create_string_utf8(env, bundleName.c_str(), bundleName.size(), &napi_bName);
argv.push_back(napi_bName);
napi_value napi_process = nullptr;
napi_create_string_utf8(env, process.c_str(), process.size(), &napi_res);
napi_create_string_utf8(env, process.c_str(), process.size(), &napi_process);
argv.push_back(napi_process);
return true;
};
@ -399,6 +399,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;
@ -434,23 +444,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<std::string> &bundleNames, const std::vector<std::string> &bundleInfos)
{
HILOGI("called SessionRestore::AppendBundles begin");
int32_t fdRestore = BConstants::INVALID_FD_NUM;
std::vector<std::string> bundleNames;
std::vector<std::string> bundleInfos;
NFuncArg funcArg(env, cbinfo);
if (!VerifyAppendBundlesParam(funcArg, fdRestore, bundleNames, bundleInfos, env)) {
return nullptr;
}
auto restoreEntity = NClass::GetEntityOf<RestoreEntity>(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());
}
@ -469,10 +472,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<std::string> bundleNames;
std::vector<std::string> 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_;
@ -486,24 +517,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<RestoreEntity>(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());
}
@ -514,17 +537,42 @@ napi_value SessionRestoreNExporter::PublishFile(napi_env env, napi_callback_info
if (SAUtils::IsSABundleName(fileName)) {
HILOGI("SA %{public}s pushlish file", bundleName.c_str());
if (fcntl(std::atoi(fileName.c_str()), F_GETFD) == -1) {
HILOGE("PublishFile fd is invalid.");
return NError(BError(BError::Codes::SDK_INVAL_ARG, "PublishFile fd is invalid.").GetCode());
}
HILOGE("PublishFile fd is invalid.");
return NError(BError(BError::Codes::SDK_INVAL_ARG, "PublishFile fd is invalid.").GetCode());
}
return NError(entity->sessionSheet->PublishSAFile(fileInfo, UniqueFd(std::atoi(fileName.c_str()))));
}
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());
@ -536,9 +584,42 @@ napi_value SessionRestoreNExporter::PublishFile(napi_env env, napi_callback_info
}
}
static NContextCBExec GetFileHandleCBExec(napi_env env, NFuncArg &funcArg, std::unique_ptr<char[]> bundleName,
std::unique_ptr<char[]> fileName)
{
auto restoreEntity = NClass::GetEntityOf<RestoreEntity>(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.");
@ -560,29 +641,14 @@ napi_value SessionRestoreNExporter::GetFileHandle(napi_env env, napi_callback_in
return nullptr;
}
auto restoreEntity = NClass::GetEntityOf<RestoreEntity>(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());
@ -597,6 +663,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.");
@ -623,7 +699,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());

View File

@ -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<int(const std::vector<OHOS::AppFileService::UriPolicyInfo> &uriPolicies,
std::deque<struct OHOS::AppFileService::PolicyErrorResult> &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<OHOS::AppFileService::UriPolicyInfo> 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<OHOS::AppFileService::UriPolicyInfo> uriPolicies;
if (!ConvertPolicyInfo(policies, policyNum, uriPolicies)) {
return E_PARAMS;

View File

@ -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",

View File

@ -63,6 +63,10 @@ public:
static std::vector<BJsonEntityCaps::BundleInfo> GetBundleInfosForSA();
static void GetBundleInfoForSA(std::string bundleName, std::vector<BJsonEntityCaps::BundleInfo> &bundleInfos);
private:
static bool GetCurBundleExtenionInfo(AppExecFwk::BundleInfo &installedBundle, const std::string &bundleName,
std::vector<AppExecFwk::ExtensionAbilityInfo> &extensionInfos, sptr<AppExecFwk::IBundleMgr> bms,
int32_t userId);
};
} // namespace OHOS::FileManagement::Backup
#endif // OHOS_FILEMGMT_BACKUP_BUNDLE_MGR_ADAPTER_H

View File

@ -77,7 +77,7 @@ public:
ErrCode GetBackupInfo(BundleName &bundleName, std::string &result) override;
ErrCode UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &result) override;
ErrCode UpdateSendRate(std::string &bundleName, int32_t sendRate, bool &result) override;
ErrCode ReportBundleProcessInfo(const std::string processInfo, const BackupRestoreScenario sennario) override;
ErrCode ReportAppProcessInfo(const std::string processInfo, const BackupRestoreScenario sennario) override;
ErrCode SAResultReport(const std::string bundleName, const std::string resultInfo,
const ErrCode errCode, const BackupRestoreScenario sennario);
@ -319,12 +319,13 @@ private:
* @param restoreBundleInfos
* @param restoreBundleNames
* @param bundleNameDetailMap bundle和detail的对应关系
* @param isClearDataFlags
* @param restoreType
*/
void SetCurrentSessProperties(std::vector<BJsonEntityCaps::BundleInfo> &restoreBundleInfos,
std::vector<std::string> &restoreBundleNames,
std::map<std::string, std::vector<BJsonUtil::BundleDetailInfo>> &bundleNameDetailMap,
RestoreTypeEnum restoreType);
std::map<std::string, bool> &isClearDataFlags, RestoreTypeEnum restoreType);
/**
* @brief set session info

View File

@ -62,7 +62,7 @@ private:
int32_t CmdGetBackupInfo(MessageParcel &data, MessageParcel &reply);
int32_t CmdUpdateTimer(MessageParcel &data, MessageParcel &reply);
int32_t CmdUpdateSendRate(MessageParcel &data, MessageParcel &reply);
int32_t CmdReportBundleProcessInfo(MessageParcel &data, MessageParcel &reply);
int32_t CmdReportAppProcessInfo(MessageParcel &data, MessageParcel &reply);
void ServiceStubSupplement();
void ServiceStubSuppAppendBundles();

View File

@ -76,7 +76,7 @@ public:
* @param callConnected
*/
void SetCallback(std::function<void(const std::string &&)> callConnected);
/**
* @brief Set the CallDied object
*
@ -91,8 +91,9 @@ public:
public:
SvcBackupConnection(std::function<void(const std::string &&)> callDied,
std::function<void(const std::string &&)> callConnected)
: callDied_(callDied), callConnected_(callConnected)
std::function<void(const std::string &&)> callConnected,
std::string bundleNameIndexInfo)
: callDied_(callDied), callConnected_(callConnected), bundleNameIndexInfo_(bundleNameIndexInfo)
{
}
~SvcBackupConnection() override {};
@ -108,6 +109,7 @@ private:
std::function<void(const std::string &&)> callDied_;
std::function<void(const std::string &&)> callConnected_;
std::string bundleNameIndexInfo_;
};
} // namespace OHOS::FileManagement::Backup

View File

@ -25,13 +25,13 @@ class SvcExtensionProxy : public IRemoteProxy<IExtension> {
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<UniqueFd, UniqueFd> GetIncrementalBackupFileHandle() override;
ErrCode GetBackupInfo(std::string &result) override;
ErrCode UpdateFdSendRate(std::string &bundleName, int32_t sendRate) override;

View File

@ -66,6 +66,7 @@ struct BackupExtInfo {
int32_t backupPriority;
std::string extInfo;
int32_t appendNum {1};
bool isClearData {true};
};
class Service;
@ -478,6 +479,9 @@ public:
Impl GetImpl();
int GetSessionCnt();
void SetClearDataFlag(const std::string &bundleName, bool isClearData);
bool GetClearDataFlag(const std::string &bundleName);
private:
/**
* @brief backup extension ability

View File

@ -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<string> 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<int64_t> 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<BJsonEntityCaps::BundleInfo> 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<AppExecFwk::ExtensionAbilityInfo> 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<string> &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<BJsonEntityCaps::BundleInfo> 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<AppExecFwk::ExtensionAbilityInfo> 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<BJsonEntityCaps::BundleInfo> 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<BJsonEntityCaps::BundleInfo> 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<BJsonEntityCaps::BundleInfo> 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<BJ
HILOGE("SA %{public}d is not surport backup.", saId);
return;
}
bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {bundleName, 0, "", 0, 0, true, false, "", "", "", ""});
bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {bundleName, 0, 0, "", 0, 0, true, false, "", "", "", ""});
HILOGI("SA %{public}s GetBundleInfo end.", bundleName.c_str());
}
bool BundleMgrAdapter::GetCurBundleExtenionInfo(AppExecFwk::BundleInfo &installedBundle,
const std::string &bundleName, std::vector<AppExecFwk::ExtensionAbilityInfo> &extensionInfos,
sptr<AppExecFwk::IBundleMgr> bms, int32_t userId)
{
BJsonUtil::BundleDetailInfo bundleDetailInfo = BJsonUtil::ParseBundleNameIndexStr(bundleName);
int32_t flags = static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE) |
static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY) |
static_cast<int32_t>(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<AppExecFwk::HapModuleInfo> 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

View File

@ -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 */
@ -202,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());
@ -217,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;
}
}
@ -285,16 +301,27 @@ ErrCode Service::InitBackupSession(sptr<IServiceReverse> 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)
@ -338,6 +365,7 @@ static vector<BJsonEntityCaps::BundleInfo> 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,
@ -355,6 +383,7 @@ static vector<BJsonEntityCaps::BundleInfo> GetRestoreBundleNames(UniqueFd fd,
continue;
}
BJsonEntityCaps::BundleInfo info = {.name = (*it).name,
.appIndex = (*it).appIndex,
.versionCode = (*it).versionCode,
.versionName = (*it).versionName,
.spaceOccupied = (*it).spaceOccupied,
@ -372,7 +401,8 @@ static void HandleExceptionOnAppendBundles(sptr<SvcSessionManager> session,
const vector<BundleName> &appendBundleNames, const vector<BundleName> &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; });
@ -396,9 +426,10 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, const vector<BundleNam
}
VerifyCaller(IServiceReverse::Scenario::RESTORE);
std::vector<std::string> bundleNamesOnly;
std::map<std::string, bool> isClearDataFlags;
std::map<std::string, std::vector<BJsonUtil::BundleDetailInfo>> 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()) {
@ -407,7 +438,8 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, const vector<BundleNam
return BError(BError::Codes::OK);
}
session_->AppendBundles(restoreBundleNames);
SetCurrentSessProperties(restoreInfos, restoreBundleNames, bundleNameDetailMap, restoreType);
SetCurrentSessProperties(restoreInfos, restoreBundleNames, bundleNameDetailMap,
isClearDataFlags, restoreType);
OnStartSched();
session_->DecreaseSessionCnt();
HILOGI("End");
@ -492,42 +524,52 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd,
void Service::SetCurrentSessProperties(std::vector<BJsonEntityCaps::BundleInfo> &restoreBundleInfos,
std::vector<std::string> &restoreBundleNames,
std::map<std::string, std::vector<BJsonUtil::BundleDetailInfo>> &bundleNameDetailMap, RestoreTypeEnum restoreType)
std::map<std::string, std::vector<BJsonUtil::BundleDetailInfo>> &bundleNameDetailMap,
std::map<std::string, bool> &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<NotifyWorkService>::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");
@ -579,22 +621,26 @@ ErrCode Service::AppendBundlesDetailsBackupSession(const vector<BundleName> &bun
session_->IncreaseSessionCnt(); // BundleMgrAdapter::GetBundleInfos可能耗时
VerifyCaller(IServiceReverse::Scenario::BACKUP);
std::vector<std::string> bundleNamesOnly;
std::map<std::string, bool> isClearDataFlags;
std::map<std::string, std::vector<BJsonUtil::BundleDetailInfo>> 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);
}
@ -623,10 +669,15 @@ ErrCode Service::AppendBundlesDetailsBackupSession(const vector<BundleName> &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)
@ -822,21 +873,23 @@ void Service::NotifyCloneBundleFinish(std::string bundleName)
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 */
HILOGD("BackupExtName: %{public}s, bundleName: %{public}s", backupExtName.data(), bundleName.data());
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(bundleName, backupExtName);
want.SetElementName(bundleDetail.bundleName, backupExtName);
want.SetParam(BConstants::EXTENSION_ACTION_PARA, static_cast<int>(action));
want.SetParam(BConstants::EXTENSION_VERSION_CODE_PARA, static_cast<long>(versionCode));
want.SetParam(BConstants::EXTENSION_RESTORE_TYPE_PARA, static_cast<int>(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)
@ -868,7 +921,11 @@ ErrCode Service::LaunchBackupExtension(const BundleName &bundleName)
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) {
@ -1030,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);
@ -1041,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) {
@ -1469,8 +1526,8 @@ ErrCode Service::GetBackupInfoCmdHandle(BundleName &bundleName, std::string &res
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);
HILOGE("ConnectBackupExtAbility faild, bundleName:%{public}s, ret:%{public}d", bundleName.c_str(), ret);
return BError(BError::Codes::SA_BOOT_EXT_FAIL);
}
std::unique_lock<std::mutex> lock(getBackupInfoMutx_);
getBackupInfoCondition_.wait_for(lock, std::chrono::seconds(CONNECT_WAIT_TIME_S));
@ -1709,7 +1766,7 @@ void Service::NotifyCallerCurAppDone(ErrCode errCode, const std::string &callerN
}
}
ErrCode Service::ReportBundleProcessInfo(const std::string processInfo, BackupRestoreScenario sennario)
ErrCode Service::ReportAppProcessInfo(const std::string processInfo, BackupRestoreScenario sennario)
{
HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
try {
@ -1729,9 +1786,6 @@ ErrCode Service::ReportBundleProcessInfo(const std::string processInfo, BackupRe
} catch (const exception &e) {
HILOGI("Catched an unexpected low-level exception %{public}s", e.what());
return EPERM;
} catch (...) {
HILOGI("Unexpected exception");
return EPERM;
}
}
} // namespace OHOS::FileManagement::Backup

View File

@ -293,22 +293,26 @@ ErrCode Service::AppendBundlesIncrementalBackupSession(const std::vector<BIncrem
bundleNames.emplace_back(bundle.bundleName);
}
std::vector<std::string> bundleNamesOnly;
std::map<std::string, bool> isClearDataFlags;
std::map<std::string, std::vector<BJsonUtil::BundleDetailInfo>> 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) {

View File

@ -121,6 +121,24 @@ void ServiceReverseProxy::IncrementalBackupOnAllBundlesFinished(int32_t errCode)
}
}
void ServiceReverseProxy::IncrementalBackupOnProcessInfo(std::string bundleName, std::string processInfo)
{
BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr");
MessageParcel data;
if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteString(bundleName) || !data.WriteString(processInfo)) {
throw BError(BError::Codes::SA_BROKEN_IPC);
}
MessageParcel reply;
MessageOption option;
if (int err = Remote()->SendRequest(
static_cast<uint32_t>(IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_BACKUP_ON_PROCESS_INFO),
data, reply, option);
err != ERR_OK) {
throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err));
}
}
void ServiceReverseProxy::IncrementalRestoreOnBundleStarted(int32_t errCode, string bundleName)
{
BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr");
@ -217,4 +235,22 @@ void ServiceReverseProxy::IncrementalRestoreOnFileReady(string bundleName, strin
throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err));
}
}
void ServiceReverseProxy::IncrementalRestoreOnProcessInfo(std::string bundleName, std::string processInfo)
{
BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr");
MessageParcel data;
if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteString(bundleName) || !data.WriteString(processInfo)) {
throw BError(BError::Codes::SA_BROKEN_IPC);
}
MessageParcel reply;
MessageOption option;
if (int err = Remote()->SendRequest(
static_cast<uint32_t>(IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_PROCESS_INFO),
data, reply, option);
err != ERR_OK) {
throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err));
}
}
} // namespace OHOS::FileManagement::Backup

View File

@ -113,6 +113,23 @@ void ServiceReverseProxy::BackupOnAllBundlesFinished(int32_t errCode)
}
}
void ServiceReverseProxy::BackupOnProcessInfo(std::string bundleName, std::string processInfo)
{
BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr");
MessageParcel data;
if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteString(bundleName) || !data.WriteString(processInfo)) {
throw BError(BError::Codes::SA_BROKEN_IPC);
}
MessageParcel reply;
MessageOption option;
if (int err = Remote()->SendRequest(
static_cast<uint32_t>(IServiceReverseInterfaceCode::SERVICER_BACKUP_ON_PROCESS_INFO), data, reply, option);
err != ERR_OK) {
throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err));
}
}
void ServiceReverseProxy::RestoreOnBundleStarted(int32_t errCode, string bundleName)
{
BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr");
@ -209,4 +226,21 @@ void ServiceReverseProxy::RestoreOnResultReport(string result, std::string bundl
throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err));
}
}
void ServiceReverseProxy::RestoreOnProcessInfo(std::string bundleName, std::string processInfo)
{
BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr");
MessageParcel data;
if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteString(bundleName) || !data.WriteString(processInfo)) {
throw BError(BError::Codes::SA_BROKEN_IPC);
}
MessageParcel reply;
MessageOption option;
if (int err = Remote()->SendRequest(
static_cast<uint32_t>(IServiceReverseInterfaceCode::SERVICER_RESTORE_ON_PROCESS_INFO), data, reply, option);
err != ERR_OK) {
throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err));
}
}
} // namespace OHOS::FileManagement::Backup

View File

@ -44,8 +44,8 @@ void ServiceStub::ServiceStubSupplement()
IServiceInterfaceCode::SERVICE_CMD_GET_APP_LOCAL_LIST_AND_DO_INCREMENTAL_BACKUP)] =
&ServiceStub::CmdGetAppLocalListAndDoIncrementalBackup;
opToInterfaceMap_[static_cast<uint32_t>(
IServiceInterfaceCode::SERVICE_CMD_REPORT_BUNDLE_PROCESS_INFO)] =
&ServiceStub::CmdReportBundleProcessInfo;
IServiceInterfaceCode::SERVICE_CMD_REPORT_APP_PROCESS_INFO)] =
&ServiceStub::CmdReportAppProcessInfo;
}
void ServiceStub::ServiceStubSuppAppendBundles()
@ -625,17 +625,18 @@ int32_t ServiceStub::CmdGetIncrementalFileHandle(MessageParcel &data, MessagePar
return GetIncrementalFileHandle(bundleName, fileName);
}
int32_t ServiceStub::CmdReportBundleProcessInfo(MessageParcel &data, MessageParcel &reply)
int32_t ServiceStub::CmdReportAppProcessInfo(MessageParcel &data, MessageParcel &reply)
{
string processInfo;
if (!data.ReadString(processInfo)) {
return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive bundleName").GetCode();
}
BackupRestoreScenario secenrioInfo = static_cast<BackupRestoreScenario>(scenario);
if (!data.ReadInt32(errCode)) {
int32_t scenario;
if (!data.ReadInt32(scenario)) {
return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive errCode");
}
return ReportBundleProcessInfo(processInfo, secenrioInfo);
BackupRestoreScenario secenrioInfo = static_cast<BackupRestoreScenario>(scenario);
return ReportAppProcessInfo(processInfo, secenrioInfo);
}
template <typename T>

View File

@ -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");
}

View File

@ -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;

View File

@ -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;

View File

@ -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,11 +29,12 @@ vector<string> SvcRestoreDepsManager::GetRestoreBundleNames(const vector<BJsonEn
BuildDepsMap(bundleInfos); // 构建依赖Map
for (auto &bundleInfo : bundleInfos) {
restoreBundleNames.emplace_back(bundleInfo.name);
std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(bundleInfo.name, bundleInfo.appIndex);
restoreBundleNames.emplace_back(bundleNameIndexInfo);
string restoreDeps = bundleInfo.restoreDeps;
if (!restoreDeps.empty()) {
HILOGI("RestoreDeps is not empty, bundleName=%{public}s", bundleInfo.name.c_str());
if (IsAllDepsRestored(bundleInfo.name)) {
HILOGI("RestoreDeps is not empty, bundleName=%{public}s", bundleNameIndexInfo.c_str());
if (IsAllDepsRestored(bundleNameIndexInfo)) {
HILOGI("RestoreDeps is all restored, bundleName=%{public}s", bundleInfo.name.c_str());
}
}
@ -77,7 +79,8 @@ bool SvcRestoreDepsManager::IsAllDepsRestored(const string &bundle)
void SvcRestoreDepsManager::BuildDepsMap(const vector<BJsonEntityCaps::BundleInfo> &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);
@ -92,7 +95,7 @@ void SvcRestoreDepsManager::BuildDepsMap(const vector<BJsonEntityCaps::BundleInf
}
}
depsMap_.insert(make_pair(bundleInfo.name, depsList));
depsMap_.insert(make_pair(bundleNameIndexInfo, depsList));
}
}

View File

@ -281,7 +281,7 @@ sptr<SvcBackupConnection> SvcSessionManager::GetBackupAbilityExt(const string &b
revPtrStrong->ExtConnectDone(move(bundleName));
};
return sptr<SvcBackupConnection>(new SvcBackupConnection(callDied, callConnected));
return sptr<SvcBackupConnection>(new SvcBackupConnection(callDied, callConnected, bundleName));
}
std::shared_ptr<SABackupConnection> SvcSessionManager::GetBackupSAExt(const std::string &bundleName)
@ -847,6 +847,26 @@ void SvcSessionManager::SetMemParaCurSize(int32_t size)
memoryParaCurSize_ = size;
}
void SvcSessionManager::SetClearDataFlag(const std::string &bundleName, bool isClearData)
{
unique_lock<shared_mutex> 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<shared_mutex> 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;

View File

@ -83,7 +83,7 @@ void SchedScheduler::ExecutingQueueTasks(const string &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);

View File

@ -42,6 +42,7 @@ ohos_fuzztest("BackupExtFuzzTest") {
"${path_backup}/frameworks/native/backup_ext/src/ext_backup_loader.cpp",
"${path_backup}/frameworks/native/backup_ext/src/ext_extension.cpp",
"${path_backup}/frameworks/native/backup_ext/src/ext_extension_stub.cpp",
"${path_backup}/frameworks/native/backup_ext/src/sub_ext_extension.cpp",
"${path_backup}/frameworks/native/backup_ext/src/tar_file.cpp",
"${path_backup}/frameworks/native/backup_ext/src/untar_file.cpp",
"backupext_fuzzer.cpp",

View File

@ -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",
]
}

View File

@ -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 <cstdlib>
#include <cstring>
#include <gtest/gtest.h>
#include <string>
#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

View File

@ -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",
]

View File

@ -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 <cassert>
#include <fcntl.h>
#include <gtest/gtest.h>
#include <singleton.h>
#include <string>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/types.h>
#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<FilePermissionMock> filePermMoc_ = nullptr;
};
void NDKFileSharePermissionSupTest::SetUpTestCase()
{
GrantNativePermission();
filePermMoc_ = make_shared<FilePermissionMock>();
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<PolicyErrorResult> 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<PolicyErrorResult> 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<bool> 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<bool> 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

View File

@ -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"

View File

@ -30,7 +30,7 @@
#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"
@ -70,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);
@ -115,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";
}
@ -145,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(FileShare_PolicyErrorCode::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";
@ -224,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(FileShare_PolicyErrorCode::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";
@ -259,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";
}
@ -296,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(FileShare_PolicyErrorCode::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";
@ -371,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,
@ -385,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(FileShare_PolicyErrorCode::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";
@ -420,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";
}
@ -457,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(FileShare_PolicyErrorCode::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";
@ -532,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,
@ -546,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(FileShare_PolicyErrorCode::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";
@ -581,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";
}
@ -626,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(FileShare_PolicyErrorCode::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";
@ -701,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,
@ -722,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(FileShare_PolicyErrorCode::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";
@ -758,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);
@ -804,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);
@ -884,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,
@ -900,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<OHOS::AppFileService::UriPolicyInfo> 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<OHOS::AppFileService::UriPolicyInfo> 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<OHOS::AppFileService::UriPolicyInfo> 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<OHOS::AppFileService::UriPolicyInfo> 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<OHOS::AppFileService::PolicyErrorResult> 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<OHOS::AppFileService::PolicyErrorResult> 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<OHOS::AppFileService::PolicyErrorResult> 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<OHOS::AppFileService::PolicyErrorResult> 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<bool> 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<bool> 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<bool> 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<int32_t>(E_NO_ERROR)), E_NO_ERROR);
EXPECT_EQ(ErrorCodeConversion(static_cast<int32_t>(E_PERMISSION)), E_PERMISSION);
EXPECT_EQ(ErrorCodeConversion(static_cast<int32_t>(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

View File

@ -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";
}

View File

@ -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",
]
}

View File

@ -24,6 +24,7 @@
#include <unordered_map>
#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<string> 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<string> 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<string> uriList = {"file://docs/storage/Users/currentUser/./Document/1.txt"};
const string networkId = "100";
const string deviceId = "001";
vector<string> 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";
}
}

View File

@ -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

View File

@ -187,6 +187,11 @@ ErrCode ServiceProxy::UpdateSendRate(std::string &bundleName, int32_t sendRate,
return BError(BError::Codes::OK);
}
ErrCode ServiceProxy::ReportAppProcessInfo(const std::string processInfo, const BackupRestoreScenario sennario)
{
return BError(BError::Codes::OK);
}
sptr<IService> ServiceProxy::GetInstance()
{
if (!GetMockGetInstance()) {

View File

@ -32,7 +32,8 @@ vector<BJsonEntityCaps::BundleInfo> BundleMgrAdapter::GetBundleInfos(const vecto
{
vector<BJsonEntityCaps::BundleInfo> 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<BJsonEntityCaps::BundleInfo> BundleMgrAdapter::GetBundleInfosForIncrement
{
vector<BJsonEntityCaps::BundleInfo> 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<BJsonEntityCaps::BundleInfo> BundleMgrAdapter::GetBundleInfosForIncrement
{
vector<BJsonEntityCaps::BundleInfo> 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;
}

View File

@ -226,6 +226,11 @@ ErrCode Service::UpdateSendRate(std::string &bundleName, int32_t sendRate, bool
return BError(BError::Codes::OK);
}
ErrCode Service::ReportAppProcessInfo(const std::string processInfo, const BackupRestoreScenario sennario)
{
return BError(BError::Codes::OK);
}
void Service::OnSABackup(const std::string &bundleName,
const int &fd,
const std::string &result,

View File

@ -30,6 +30,8 @@ void ServiceReverseProxy::BackupOnBundleFinished(int32_t errCode, string bundleN
void ServiceReverseProxy::BackupOnAllBundlesFinished(int32_t errCode) {}
void ServiceReverseProxy::BackupOnProcessInfo(std::string bundleName, std::string processInfo) {}
void ServiceReverseProxy::RestoreOnBundleStarted(int32_t errCode, string bundleName) {}
void ServiceReverseProxy::RestoreOnBundleFinished(int32_t errCode, string bundleName) {}
@ -40,6 +42,8 @@ void ServiceReverseProxy::RestoreOnFileReady(string bundleName, string fileName,
void ServiceReverseProxy::RestoreOnResultReport(string result, string bundleName, ErrCode errCode) {}
void ServiceReverseProxy::RestoreOnProcessInfo(std::string bundleName, std::string processInfo) {}
void ServiceReverseProxy::IncrementalBackupOnFileReady(string bundleName, string fileName, int fd, int manifestFd,
int32_t errCode) {}
@ -51,6 +55,8 @@ void ServiceReverseProxy::IncrementalBackupOnBundleFinished(int32_t errCode, str
void ServiceReverseProxy::IncrementalBackupOnAllBundlesFinished(int32_t errCode) {}
void ServiceReverseProxy::IncrementalBackupOnProcessInfo(std::string bundleName, std::string processInfo) {}
void ServiceReverseProxy::IncrementalRestoreOnBundleStarted(int32_t errCode, string bundleName) {}
void ServiceReverseProxy::IncrementalRestoreOnBundleFinished(int32_t errCode, string bundleName) {}
@ -61,4 +67,6 @@ void ServiceReverseProxy::IncrementalRestoreOnFileReady(string bundleName, strin
int32_t errCode) {}
void ServiceReverseProxy::IncrementalRestoreOnResultReport(string result, string bundleName, ErrCode errCode) {}
void ServiceReverseProxy::IncrementalRestoreOnProcessInfo(std::string bundleName, std::string processInfo) {}
} // namespace OHOS::FileManagement::Backup

View File

@ -81,6 +81,8 @@ void ServiceStub::ServiceStubSupplement()
&ServiceStub::CmdUpdateTimer;
opToInterfaceMap_[static_cast<uint32_t>(IServiceInterfaceCode::SERVICE_CMD_UPDATE_SENDRATE)] =
&ServiceStub::CmdUpdateSendRate;
opToInterfaceMap_[static_cast<uint32_t>(IServiceInterfaceCode::SERVICE_CMD_REPORT_APP_PROCESS_INFO)] =
&ServiceStub::CmdReportAppProcessInfo;
}
int32_t ServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
@ -311,4 +313,9 @@ int32_t ServiceStub::CmdGetIncrementalFileHandle(MessageParcel &data, MessagePar
{
return BError(BError::Codes::OK);
}
int32_t ServiceStub::CmdReportAppProcessInfo(MessageParcel &data, MessageParcel &reply)
{
return BError(BError::Codes::OK);
}
} // namespace OHOS::FileManagement::Backup

View File

@ -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;
}

View File

@ -104,7 +104,8 @@ wptr<SvcBackupConnection> SvcSessionManager::GetExtConnection(const BundleName &
if (!it->second.backUpConnection) {
auto callDied = [](const string &&bundleName) {};
auto callConnected = [](const string &&bundleName) {};
it->second.backUpConnection = sptr<SvcBackupConnection>(new SvcBackupConnection(callDied, callConnected));
it->second.backUpConnection = sptr<SvcBackupConnection>(new SvcBackupConnection(callDied, callConnected,
bundleName));
sptr<BackupExtExtensionMock> mock = sptr(new BackupExtExtensionMock());
it->second.backUpConnection->OnAbilityConnectDone({}, mock->AsObject(), 0);
}
@ -114,7 +115,7 @@ wptr<SvcBackupConnection> SvcSessionManager::GetExtConnection(const BundleName &
sptr<SvcBackupConnection> SvcSessionManager::GetBackupAbilityExt(const string &bundleName)
{
GTEST_LOG_(INFO) << "GetBackupAbilityExt";
return sptr<SvcBackupConnection>(new SvcBackupConnection(nullptr, nullptr));
return sptr<SvcBackupConnection>(new SvcBackupConnection(nullptr, nullptr, bundleName));
}
void SvcSessionManager::DumpInfo(const int fd, const std::vector<std::u16string> &args)
@ -398,6 +399,13 @@ 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)

View File

@ -280,6 +280,16 @@ 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);

View File

@ -79,6 +79,8 @@ public:
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;
@ -140,6 +142,8 @@ public:
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 &));

View File

@ -309,4 +309,70 @@ HWTEST_F(BSessionBackupTest, SUB_backup_b_session_backup_0700, testing::ext::Tes
}
GTEST_LOG_(INFO) << "BSessionBackupTest-end SUB_backup_b_session_backup_0700";
}
/**
* @tc.number: SUB_backup_b_session_backup_0800
* @tc.name: SUB_backup_b_session_backup_0800
* @tc.desc: AppendBundles接口
* @tc.size: MEDIUM
* @tc.type: FUNC
* @tc.level Level 1
* @tc.require: I6F3GV
*/
HWTEST_F(BSessionBackupTest, SUB_backup_b_session_backup_0800, testing::ext::TestSize.Level1)
{
GTEST_LOG_(INFO) << "BSessionBackupTest-AppendBundles SUB_backup_b_session_backup_0800";
try {
if (backupPtr_ == nullptr) {
GTEST_LOG_(INFO) << "SUB_backup_b_session_backup_0800 backupPtr_ == nullptr";
return;
}
vector<BundleName> bundleNames;
vector<std::string> detailInfos;
GTEST_LOG_(INFO) << "GetInstance is true";
SetMockGetInstance(true);
auto ret = backupPtr_->AppendBundles(bundleNames, detailInfos);
EXPECT_EQ(ret, ErrCode(BError::Codes::OK));
GTEST_LOG_(INFO) << "GetInstance is false";
SetMockGetInstance(false);
ret = backupPtr_->AppendBundles(bundleNames, detailInfos);
EXPECT_NE(ret, ErrCode(BError::Codes::OK));
} catch (...) {
EXPECT_TRUE(false);
GTEST_LOG_(INFO) << "BSessionBackupTest-an exception occurred by AppendBundles.";
}
GTEST_LOG_(INFO) << "BSessionBackupTest-end SUB_backup_b_session_backup_0800";
}
/**
* @tc.number: SUB_backup_b_session_backup_0900
* @tc.name: SUB_backup_b_session_backup_0900
* @tc.desc: AppendBundles接口
* @tc.size: MEDIUM
* @tc.type: FUNC
* @tc.level Level 1
* @tc.require: I6F3GV
*/
HWTEST_F(BSessionBackupTest, SUB_backup_b_session_backup_0900, testing::ext::TestSize.Level1)
{
GTEST_LOG_(INFO) << "BSessionBackupTest-Release SUB_backup_b_session_backup_0900";
try {
if (backupPtr_ == nullptr) {
GTEST_LOG_(INFO) << "SUB_backup_b_session_backup_0900 backupPtr_ == nullptr";
return;
}
GTEST_LOG_(INFO) << "GetInstance is true";
SetMockGetInstance(true);
auto ret = backupPtr_->Release();
EXPECT_EQ(ret, ErrCode(BError::Codes::OK));
GTEST_LOG_(INFO) << "GetInstance is false";
SetMockGetInstance(false);
ret = backupPtr_->Release();
EXPECT_NE(ret, ErrCode(BError::Codes::OK));
} catch (...) {
EXPECT_TRUE(false);
GTEST_LOG_(INFO) << "BSessionBackupTest-an exception occurred by Release.";
}
GTEST_LOG_(INFO) << "BSessionBackupTest-end SUB_backup_b_session_backup_0900";
}
} // namespace OHOS::FileManagement::Backup

View File

@ -236,6 +236,9 @@ HWTEST_F(BSessionRestoreAsyncTest, SUB_backup_b_session_restore_async_0500, test
EXPECT_EQ(ret, ErrCode(BError::Codes::OK));
ret = restorePtr_->AppendBundles(UniqueFd(-1), bundleNames);
EXPECT_EQ(ret, ErrCode(BError::Codes::OK));
SetMockGetInstance(false);
ret = restorePtr_->AppendBundles(UniqueFd(-1), bundleNames);
EXPECT_NE(ret, ErrCode(BError::Codes::OK));
restorePtr_ = nullptr;
} catch (...) {
EXPECT_TRUE(false);
@ -269,6 +272,9 @@ HWTEST_F(BSessionRestoreAsyncTest, SUB_backup_b_session_restore_async_0501, test
EXPECT_EQ(ret, ErrCode(BError::Codes::OK));
ret = restorePtr_->AppendBundles(UniqueFd(-1), bundleNames, detailInfos);
EXPECT_EQ(ret, ErrCode(BError::Codes::OK));
SetMockGetInstance(false);
ret = restorePtr_->AppendBundles(UniqueFd(-1), bundleNames, detailInfos);
EXPECT_NE(ret, ErrCode(BError::Codes::OK));
restorePtr_ = nullptr;
} catch (...) {
EXPECT_TRUE(false);
@ -300,10 +306,43 @@ HWTEST_F(BSessionRestoreAsyncTest, SUB_backup_b_session_restore_async_0600, test
GTEST_LOG_(INFO) << "GetInstance is true but not equal to parameter";
SetMockGetInstance(true);
restorePtr_->RegisterBackupServiceDied(nullptr);
Init();
SetMockGetInstance(true);
restorePtr_->RegisterBackupServiceDied(callbacks_.onBackupServiceDied);
} catch (...) {
EXPECT_TRUE(false);
GTEST_LOG_(INFO) << "BSessionRestoreAsyncTest-an exception occurred by RegisterBackupServiceDied.";
}
GTEST_LOG_(INFO) << "BSessionRestoreAsyncTest-end SUB_backup_b_session_restore_async_0600";
}
/**
* @tc.number: SUB_backup_b_session_restore_async_0700
* @tc.name: SUB_backup_b_session_restore_async_0700
* @tc.desc: Release接口
* @tc.size: MEDIUM
* @tc.type: FUNC
* @tc.level Level 1
* @tc.require: I7L7A6
*/
HWTEST_F(BSessionRestoreAsyncTest, SUB_backup_b_session_restore_async_0700, testing::ext::TestSize.Level1)
{
GTEST_LOG_(INFO) << "BSessionRestoreAsyncTest-begin SUB_backup_b_session_restore_async_0700";
try {
if (restorePtr_ == nullptr) {
GTEST_LOG_(INFO) << "SUB_backup_b_session_restore_async_0700 restorePtr_ == nullptr";
return;
}
SetMockGetInstance(false);
ErrCode ret = restorePtr_->Release();
EXPECT_NE(ret, ErrCode(BError::Codes::OK));
SetMockGetInstance(true);
ret = restorePtr_->Release();
EXPECT_EQ(ret, ErrCode(BError::Codes::OK));
} catch (...) {
EXPECT_TRUE(false);
GTEST_LOG_(INFO) << "BSessionRestoreAsyncTest-an exception occurred by ~BSessionRestoreAsync.";
}
GTEST_LOG_(INFO) << "BSessionRestoreAsyncTest-end SUB_backup_b_session_restore_async_0700";
}
} // namespace OHOS::FileManagement::Backup

View File

@ -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);
};

View File

@ -203,6 +203,11 @@ public:
{
return BError(BError::Codes::OK);
}
ErrCode ReportAppProcessInfo(const std::string processInfo, const BackupRestoreScenario sennario)
{
return BError(BError::Codes::OK);
}
};
} // namespace OHOS::FileManagement::Backup
#endif // MOCK_I_SERVICE_MOCK_H

View File

@ -41,12 +41,14 @@ public:
void BackupOnResultReport(std::string result, std::string bundleName) override {};
void BackupOnBundleFinished(int32_t errCode, std::string bundleName) override {}
void BackupOnAllBundlesFinished(int32_t errCode) override {}
void BackupOnProcessInfo(std::string bundleName, std::string processInfo) override {}
void RestoreOnBundleStarted(int32_t errCode, std::string bundleName) override {}
void RestoreOnBundleFinished(int32_t errCode, std::string bundleName) override {}
void RestoreOnAllBundlesFinished(int32_t errCode) override {}
void RestoreOnFileReady(std::string bundleName, std::string fileName, int fd, int32_t errCode) override {}
void RestoreOnResultReport(std::string result, std::string bundleName, ErrCode errCode) override {}
void RestoreOnProcessInfo(std::string bundleName, std::string processInfo) override {}
void IncrementalBackupOnFileReady(std::string bundleName, std::string fileName, int fd, int manifestFd,
int32_t errCode) override {}
@ -54,6 +56,7 @@ public:
void IncrementalBackupOnResultReport(std::string result, std::string bundleName) override {}
void IncrementalBackupOnBundleFinished(int32_t errCode, std::string bundleName) override {}
void IncrementalBackupOnAllBundlesFinished(int32_t errCode) override {}
void IncrementalBackupOnProcessInfo(std::string bundleName, std::string processInfo) override {}
void IncrementalRestoreOnBundleStarted(int32_t errCode, std::string bundleName) override {}
void IncrementalRestoreOnBundleFinished(int32_t errCode, std::string bundleName) override {}
@ -61,6 +64,7 @@ public:
void IncrementalRestoreOnFileReady(std::string bundleName, std::string fileName, int fd, int manifestFd,
int32_t errCode) override {}
void IncrementalRestoreOnResultReport(std::string result, std::string bundleName, ErrCode errCode) override {};
void IncrementalRestoreOnProcessInfo(std::string bundleName, std::string processInfo) override {}
};
} // namespace OHOS::FileManagement::Backup
#endif // MOCK_SERVICE_REVERSE_MOCK_H

View File

@ -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<std::string> bundleNames;
std::vector<std::string> 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
@ -604,6 +666,43 @@ HWTEST_F(ServiceProxyTest, SUB_Service_proxy_PublishIncrementalFile_0100, testin
GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_PublishIncrementalFile_0100";
}
/**
* @tc.number: SUB_Service_proxy_PublishSAIncrementalFile_0100
* @tc.name: SUB_Service_proxy_PublishSAIncrementalFile_0100
* @tc.desc: PublishSAIncrementalFile
* @tc.size: MEDIUM
* @tc.type: FUNC
* @tc.level Level 1
* @tc.require: I90ZV5
*/
HWTEST_F(ServiceProxyTest, SUB_Service_proxy_PublishSAIncrementalFile_0100, testing::ext::TestSize.Level1)
{
GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_PublishSAIncrementalFile_0100";
if (proxy_ == nullptr) {
GTEST_LOG_(INFO) << "SUB_Service_proxy_PublishSAIncrementalFile_0100 proxy_ == nullptr";
return;
}
EXPECT_CALL(*mock_, SendRequest(_, _, _, _))
.Times(2)
.WillOnce(Invoke(mock_.GetRefPtr(), &IServiceMock::InvokeSendRequest))
.WillOnce(Return(EPERM));
string bundleName = "com.example.app2backup";
string fileName = "";
BFileInfo fileInfo(bundleName, fileName, -1);
TestManager tm("AppIncrementalFileReady_GetFd_0100");
std::string filePath = tm.GetRootDirCurTest().append(FILE_NAME);
UniqueFd fd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR));
ErrCode ret = proxy_->PublishSAIncrementalFile(fileInfo, move(fd));
EXPECT_EQ(ret, BError(BError::Codes::OK));
TestManager tmErr("AppIncrementalFileReady_GetFd_0200");
UniqueFd fdErr(open(tmErr.GetRootDirCurTest().append(FILE_NAME).data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR));
ret = proxy_->PublishSAIncrementalFile(fileInfo, move(fdErr));
EXPECT_NE(ret, BError(BError::Codes::OK));
GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_PublishSAIncrementalFile_0100";
}
/**
* @tc.number: SUB_Service_proxy_AppIncrementalFileReady_0100
* @tc.name: SUB_Service_proxy_AppIncrementalFileReady_0100

View File

@ -45,23 +45,27 @@ public:
MOCK_METHOD2(BackupOnResultReport, void(string result, std::string bundleName));
MOCK_METHOD2(BackupOnBundleFinished, void(int32_t errCode, string bundleName));
MOCK_METHOD1(BackupOnAllBundlesFinished, void(int32_t errCode));
MOCK_METHOD2(BackupOnProcessInfo, void(std::string bundleName, std::string processInfo));
MOCK_METHOD2(RestoreOnBundleStarted, void(int32_t errCode, std::string bundleName));
MOCK_METHOD2(RestoreOnBundleFinished, void(int32_t errCode, string bundleName));
MOCK_METHOD1(RestoreOnAllBundlesFinished, void(int32_t errCode));
MOCK_METHOD4(RestoreOnFileReady, void(string bundleName, string fileName, int fd, int32_t errCode));
MOCK_METHOD3(RestoreOnResultReport, void(string result, string bundleName, ErrCode errCode));
MOCK_METHOD2(RestoreOnProcessInfo, void(std::string bundleName, std::string processInfo));
MOCK_METHOD5(IncrementalBackupOnFileReady,
void(string bundleName, string fileName, int fd, int manifestFd, int32_t errCode));
MOCK_METHOD2(IncrementalBackupOnBundleStarted, void(int32_t errCode, string bundleName));
MOCK_METHOD2(IncrementalBackupOnResultReport, void(string result, std::string bundleName));
MOCK_METHOD2(IncrementalBackupOnBundleFinished, void(int32_t errCode, string bundleName));
MOCK_METHOD1(IncrementalBackupOnAllBundlesFinished, void(int32_t errCode));
MOCK_METHOD2(IncrementalBackupOnProcessInfo, void(std::string bundleName, std::string processInfo));
MOCK_METHOD2(IncrementalRestoreOnBundleStarted, void(int32_t errCode, std::string bundleName));
MOCK_METHOD2(IncrementalRestoreOnBundleFinished, void(int32_t errCode, string bundleName));
MOCK_METHOD1(IncrementalRestoreOnAllBundlesFinished, void(int32_t errCode));
MOCK_METHOD5(IncrementalRestoreOnFileReady,
void(string bundleName, string fileName, int fd, int manifestFd, int32_t errCode));
MOCK_METHOD3(IncrementalRestoreOnResultReport, void(string result, string bundleName, ErrCode errCode));
MOCK_METHOD2(IncrementalRestoreOnProcessInfo, void(std::string bundleName, std::string processInfo));
};
class ServiceReverseStubTest : public testing::Test {

View File

@ -139,6 +139,7 @@ ohos_unittest("tar_file_test") {
"${path_backup}/frameworks/native/backup_ext/src/ext_backup_loader.cpp",
"${path_backup}/frameworks/native/backup_ext/src/ext_extension.cpp",
"${path_backup}/frameworks/native/backup_ext/src/ext_extension_stub.cpp",
"${path_backup}/frameworks/native/backup_ext/src/sub_ext_extension.cpp",
"${path_backup}/frameworks/native/backup_ext/src/tar_file.cpp",
"${path_backup}/frameworks/native/backup_ext/src/untar_file.cpp",
"tar_file_test.cpp",
@ -211,6 +212,7 @@ ohos_unittest("untar_file_test") {
"${path_backup}/frameworks/native/backup_ext/src/ext_backup_loader.cpp",
"${path_backup}/frameworks/native/backup_ext/src/ext_extension.cpp",
"${path_backup}/frameworks/native/backup_ext/src/ext_extension_stub.cpp",
"${path_backup}/frameworks/native/backup_ext/src/sub_ext_extension.cpp",
"${path_backup}/frameworks/native/backup_ext/src/tar_file.cpp",
"${path_backup}/frameworks/native/backup_ext/src/untar_file.cpp",
"untar_file_test.cpp",

View File

@ -1282,4 +1282,153 @@ HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_CallJSRestoreEx_0200, testing::ext::
}
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<CallbackInfo>([](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<CallJsParam *>(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<ARG_INDEX_FIRST>(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<CallJsParam *>(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<CallbackInfo>([](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<ARG_INDEX_SECOND>(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<CallJsParam *>(work->data);
param->retParser(nullptr, reinterpret_cast<napi_value>(&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<NativeReferenceMock>();
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<CallJsParam *>(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<CallJsParam *>(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<ARG_INDEX_SECOND>(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<CallJsParam *>(work->data);
param->retParser(nullptr, reinterpret_cast<napi_value>(&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

View File

@ -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<UniqueFd, UniqueFd>), 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));

View File

@ -27,6 +27,7 @@
#include "b_error/b_error.h"
#include "b_error/b_excep_utils.h"
#include "ext_extension.cpp"
#include "sub_ext_extension.cpp"
namespace OHOS::FileManagement::Backup {
using namespace std;
@ -153,8 +154,10 @@ HWTEST_F(ExtExtensionTest, Ext_Extension_Test_0300, testing::ext::TestSize.Level
try {
string tarFile = " ";
vector<ExtManageInfo> extManageInfo;
bool ret = IsUserTar(tarFile, extManageInfo);
off_t tarFileSize = 0;
bool ret = IsUserTar(tarFile, extManageInfo, tarFileSize);
EXPECT_FALSE(ret);
EXPECT_TRUE(tarFileSize == 0);
} catch (...) {
EXPECT_TRUE(false);
GTEST_LOG_(INFO) << "ExtExtensionTest-an exception occurred by construction.";
@ -177,8 +180,10 @@ HWTEST_F(ExtExtensionTest, Ext_Extension_Test_0301, testing::ext::TestSize.Level
try {
string tarFile = TAR_FILE;
vector<ExtManageInfo> extManageInfo;
bool ret = IsUserTar(tarFile, extManageInfo);
off_t tarFileSize = 0;
bool ret = IsUserTar(tarFile, extManageInfo, tarFileSize);
EXPECT_FALSE(ret);
EXPECT_TRUE(tarFileSize == 0);
} catch (...) {
EXPECT_TRUE(false);
GTEST_LOG_(INFO) << "ExtExtensionTest-an exception occurred by construction.";
@ -204,9 +209,12 @@ HWTEST_F(ExtExtensionTest, Ext_Extension_Test_0302, testing::ext::TestSize.Level
ExtManageInfo info;
info.hashName = TAR_FILE;
info.isUserTar = true;
info.sta.st_size = 1; // 1: test number;
extManageInfo.push_back(info);
bool ret = IsUserTar(tarFile, extManageInfo);
off_t tarFileSize = 0;
bool ret = IsUserTar(tarFile, extManageInfo, tarFileSize);
EXPECT_TRUE(ret);
EXPECT_TRUE(tarFileSize == 1);
} catch (...) {
EXPECT_TRUE(false);
GTEST_LOG_(INFO) << "ExtExtensionTest-an exception occurred by construction.";

View File

@ -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.";

View File

@ -108,7 +108,7 @@ HWTEST_F(UntarFileTest, SUB_Untar_File_UnPacket_0100, testing::ext::TestSize.Lev
try {
string tarFile("");
string rootPath("");
int ret = UntarFile::GetInstance().UnPacket(tarFile, rootPath);
auto [ret, fileInfos, errFileInfos] = UntarFile::GetInstance().UnPacket(tarFile, rootPath);
EXPECT_EQ(ret, ENOENT);
ClearCache();
} catch (...) {
@ -151,7 +151,7 @@ HWTEST_F(UntarFileTest, SUB_Untar_File_UnPacket_0200, testing::ext::TestSize.Lev
GTEST_LOG_(INFO) << " execute tar failure, errno :" << errno;
throw BError(errno);
}
int ret = UntarFile::GetInstance().UnPacket(tarFile, rootPath);
auto [ret, fileInfos, errFileInfos] = UntarFile::GetInstance().UnPacket(tarFile, rootPath);
EXPECT_EQ(ret, 0);
ClearCache();
} catch (...) {
@ -186,7 +186,7 @@ HWTEST_F(UntarFileTest, SUB_Untar_File_UnPacket_0300, testing::ext::TestSize.Lev
SaveStringToFile(aFile, "hello");
string rootPath(root);
int ret = UntarFile::GetInstance().UnPacket(aFile, rootPath);
auto [ret, fileInfos, errFileInfos] = UntarFile::GetInstance().UnPacket(aFile, rootPath);
EXPECT_EQ(ret, 0);
ClearCache();
} catch (...) {
@ -225,7 +225,7 @@ HWTEST_F(UntarFileTest, SUB_Untar_File_UnPacket_0400, testing::ext::TestSize.Lev
}
string rootPath(root);
int ret = UntarFile::GetInstance().UnPacket(tarFile, rootPath);
auto [ret, fileInfos, errFileInfos] = UntarFile::GetInstance().UnPacket(tarFile, rootPath);
EXPECT_EQ(ret, 0);
ClearCache();
} catch (...) {
@ -276,7 +276,7 @@ HWTEST_F(UntarFileTest, SUB_Untar_File_UnPacket_0500, testing::ext::TestSize.Lev
TarFile::GetInstance().Packet(smallFiles, "test", root, tarMap);
string rootPath(root);
int ret = UntarFile::GetInstance().UnPacket(tarFile, rootPath);
auto [ret, fileInfos, errFileInfos] = UntarFile::GetInstance().UnPacket(tarFile, rootPath);
EXPECT_EQ(ret, 0);
ClearCache();
} catch (...) {
@ -328,7 +328,8 @@ HWTEST_F(UntarFileTest, SUB_Untar_File_IncrementalUnPacket_0100, testing::ext::T
string tarFile = root + "/test.0.tar";
string rootPath(root);
unordered_map<string, struct ReportFileInfo> cloudFiles;
int ret = UntarFile::GetInstance().IncrementalUnPacket(tarFile, rootPath, cloudFiles);
auto [ret, fileInfos, errFileInfos] =
UntarFile::GetInstance().IncrementalUnPacket(tarFile, rootPath, cloudFiles);
EXPECT_EQ(ret, 0);
ClearCache();
} catch (...) {
@ -358,7 +359,8 @@ HWTEST_F(UntarFileTest, SUB_Untar_File_IncrementalUnPacket_0200, testing::ext::T
string tarFile = root + "/empty.0.tar";
string rootPath(root);
unordered_map<string, struct ReportFileInfo> cloudFiles;
int ret = UntarFile::GetInstance().IncrementalUnPacket(tarFile, rootPath, cloudFiles);
auto [ret, fileInfos, errFileInfos] =
UntarFile::GetInstance().IncrementalUnPacket(tarFile, rootPath, cloudFiles);
EXPECT_EQ(ret, 2); // 错误码2表示找不到文件或路径
ClearCache();
} catch (...) {
@ -404,7 +406,8 @@ HWTEST_F(UntarFileTest, SUB_Untar_File_IncrementalUnPacket_0300, testing::ext::T
FILE *currentTarFile = fopen(tarFile.c_str(), "wb+");
fwrite("\0", sizeof(uint8_t), 1, currentTarFile);
fclose(currentTarFile);
int ret = UntarFile::GetInstance().IncrementalUnPacket(tarFile, rootPath, cloudFiles);
auto [ret, fileInfos, errFileInfos] =
UntarFile::GetInstance().IncrementalUnPacket(tarFile, rootPath, cloudFiles);
EXPECT_EQ(ret, 0);
ClearCache();
} catch (...) {
@ -461,7 +464,8 @@ HWTEST_F(UntarFileTest, SUB_Untar_File_IncrementalUnPacket_0400, testing::ext::T
fseeko(currentTarFile, 1L, SEEK_SET);
fwrite("\0", sizeof(uint8_t), 1, currentTarFile);
fclose(currentTarFile);
int ret = UntarFile::GetInstance().IncrementalUnPacket(tarFile, rootPath, cloudFiles);
auto [ret, fileInfos, errFileInfos] =
UntarFile::GetInstance().IncrementalUnPacket(tarFile, rootPath, cloudFiles);
EXPECT_EQ(ret, 0);
ClearCache();
} catch (...) {

View File

@ -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",

View File

@ -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<SchedScheduler> 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

View File

@ -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

View File

@ -81,6 +81,7 @@ public:
MOCK_METHOD2(GetBackupInfo, ErrCode(string &bundleName, string &result));
MOCK_METHOD3(UpdateTimer, ErrCode(BundleName &bundleName, uint32_t timeOut, bool &result));
MOCK_METHOD3(UpdateSendRate, ErrCode(std::string &bundleName, int32_t sendRate, bool &result));
MOCK_METHOD2(ReportAppProcessInfo, ErrCode(const std::string processInfo, BackupRestoreScenario sennario));
};
class ServiceStubTest : public testing::Test {
@ -1331,4 +1332,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

View File

@ -20,6 +20,7 @@
#include <sys/types.h>
#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<BackupRestoreScenario>(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,638 @@ 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_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<Service> reversePtr(new Service(saID));
sptr<SvcSessionManager> 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<Service> reversePtr(new Service(saID));
sptr<SvcSessionManager> session(new SvcSessionManager(reversePtr));
vector<BundleName> appendBundleNames {"123456"};
vector<BundleName> 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<BJsonEntityCaps::BundleInfo> restoreBundleInfos {aInfo};
std::vector<std::string> 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<BJsonEntityCaps::BundleInfo> restoreBundleInfos {aInfo};
std::vector<std::string> 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<BJsonEntityCaps::BundleInfo> restoreBundleInfos {aInfo};
std::vector<std::string> 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<BundleName> 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<SABackupConnection>(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

View File

@ -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>();
IfaceCastMock::cast = castMock;
}

View File

@ -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);
@ -287,6 +291,66 @@ HWTEST_F(SvcExtensionProxyTest, SUB_Ext_Extension_proxy_GetBackupInfo_0100, test
GTEST_LOG_(INFO) << "SvcExtensionProxyTest-end SUB_Ext_Extension_proxy_GetBackupInfo_0100";
}
/**
* @tc.number: SUB_Ext_Extension_proxy_UpdateFdSendRate_0100
* @tc.name: SUB_Ext_Extension_proxy_UpdateFdSendRate_0100
* @tc.desc: HandleRestore
* @tc.size: MEDIUM
* @tc.type: FUNC
* @tc.level Level 1
* @tc.require: I6F3GV
*/
HWTEST_F(SvcExtensionProxyTest, SUB_Service_GetBackupInfoCmdHandle_0100, testing::ext::TestSize.Level1)
{
GTEST_LOG_(INFO) << "SvcExtensionProxyTest-begin SUB_Ext_Extension_proxy_UpdateFdSendRate_0100";
try {
std::string bundleName = "bundleName";
int32_t sendRate = 0;
EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true));
EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(false));
EXPECT_TRUE(proxy_ != nullptr);
ErrCode ret = proxy_->UpdateFdSendRate(bundleName, sendRate);
EXPECT_EQ(EPERM, ret);
EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true));
EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true));
EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(false));
EXPECT_TRUE(proxy_ != nullptr);
ret = proxy_->UpdateFdSendRate(bundleName, sendRate);
EXPECT_EQ(EPERM, ret);
EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true));
EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true));
EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true));
EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(EPERM));
EXPECT_TRUE(proxy_ != nullptr);
ret = proxy_->UpdateFdSendRate(bundleName, sendRate);
EXPECT_EQ(EPERM, ret);
EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true));
EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true));
EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true));
EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(NO_ERROR));
EXPECT_CALL(*messageParcelMock_, ReadInt32(_)).WillOnce(Return(false));
EXPECT_TRUE(proxy_ != nullptr);
ret = proxy_->UpdateFdSendRate(bundleName, sendRate);
EXPECT_EQ(BError(BError::Codes::OK), ret);
EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true));
EXPECT_CALL(*messageParcelMock_, WriteString(_)).WillOnce(Return(true));
EXPECT_CALL(*messageParcelMock_, WriteInt32(_)).WillOnce(Return(true));
EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(NO_ERROR));
EXPECT_CALL(*messageParcelMock_, ReadInt32(_)).WillOnce(Return(true));
EXPECT_TRUE(proxy_ != nullptr);
ret = proxy_->UpdateFdSendRate(bundleName, sendRate);
EXPECT_EQ(BError(BError::Codes::OK), ret);
} catch (...) {
EXPECT_TRUE(false);
GTEST_LOG_(INFO) << "SvcExtensionProxyTest-an exception occurred by UpdateFdSendRate.";
}
GTEST_LOG_(INFO) << "SvcExtensionProxyTest-end SUB_Ext_Extension_proxy_UpdateFdSendRate_0100";
}
/**
* @tc.number: SUB_Ext_Extension_proxy_GetIncrementalFileHandle_0100
* @tc.name: SUB_Ext_Extension_proxy_GetIncrementalFileHandle_0100
@ -398,6 +462,51 @@ HWTEST_F(SvcExtensionProxyTest, SUB_Ext_Extension_proxy_HandleIncrementalBackup_
GTEST_LOG_(INFO) << "SvcExtensionProxyTest-end SUB_Ext_Extension_proxy_HandleIncrementalBackup_0100";
}
/**
* @tc.number: SUB_Ext_Extension_proxy_IncrementalOnBackup_0100
* @tc.name: SUB_Ext_Extension_proxy_IncrementalOnBackup_0100
* @tc.desc: IncrementalOnBackup
* @tc.size: MEDIUM
* @tc.type: FUNC
* @tc.level Level 1
* @tc.require: I6F3GV
*/
HWTEST_F(SvcExtensionProxyTest, SUB_Ext_Extension_proxy_IncrementalOnBackup_0100, testing::ext::TestSize.Level1)
{
GTEST_LOG_(INFO) << "SvcExtensionProxyTest-begin SUB_Ext_Extension_proxy_IncrementalOnBackup_0100";
try {
EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(false));
EXPECT_CALL(*messageParcelMock_, WriteBool(_)).WillOnce(Return(true));
EXPECT_TRUE(proxy_ != nullptr);
ErrCode ret = proxy_->IncrementalOnBackup(true);
EXPECT_NE(ret, ErrCode(BError::Codes::OK));
EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true));
EXPECT_CALL(*messageParcelMock_, WriteBool(_)).WillOnce(Return(false));
EXPECT_TRUE(proxy_ != nullptr);
ret = proxy_->IncrementalOnBackup(true);
EXPECT_NE(ret, ErrCode(BError::Codes::OK));
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);
ret = proxy_->IncrementalOnBackup(true);
EXPECT_EQ(ret, ErrCode(EPERM));
EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true));
EXPECT_CALL(*messageParcelMock_, WriteBool(_)).WillOnce(Return(true));
EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(NO_ERROR));
EXPECT_TRUE(proxy_ != nullptr);
ret = proxy_->IncrementalOnBackup(true);
EXPECT_EQ(ret, ErrCode(BError::Codes::OK));
} catch (...) {
EXPECT_TRUE(false);
GTEST_LOG_(INFO) << "SvcExtensionProxyTest-an exception occurred by IncrementalOnBackup.";
}
GTEST_LOG_(INFO) << "SvcExtensionProxyTest-end SUB_Ext_Extension_proxy_IncrementalOnBackup_0100";
}
/**
* @tc.number: SUB_Ext_Extension_proxy_GetIncrementalBackupFileHandle_0100
* @tc.name: SUB_Ext_Extension_proxy_GetIncrementalBackupFileHandle_0100

View File

@ -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";
}

View File

@ -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

View File

@ -646,4 +646,34 @@ HWTEST_F(IncrementalSessionTest, SUB_b_incremental_session_test_1900, testing::e
GTEST_LOG_(INFO) << "IncrementalSessionTest-end SUB_b_incremental_session_test_1900";
}
/**
* @tc.number: SUB_b_incremental_session_test_2000
* @tc.name: SUB_b_incremental_session_test_2000
* @tc.desc: PublishSAFile
* @tc.size: MEDIUM
* @tc.type: FUNC
* @tc.level Level 1
* @tc.require: issuesI9KPRL
*/
HWTEST_F(IncrementalSessionTest, SUB_b_incremental_session_test_2000, testing::ext::TestSize.Level1)
{
GTEST_LOG_(INFO) << "IncrementalSessionTest-begin SUB_b_incremental_session_test_2000";
try {
ServiceProxy::serviceProxy_ = nullptr;
BFileInfo fileInfo;
UniqueFd fd;
EXPECT_TRUE(restoreSession != nullptr);
auto err = restoreSession->PublishSAFile(fileInfo, move(fd));
EXPECT_EQ(err, BError(BError::Codes::SDK_BROKEN_IPC).GetCode());
EXPECT_CALL(*proxy, PublishIncrementalFile(_)).WillOnce(Return(0));
ServiceProxy::serviceProxy_ = proxy;
err = restoreSession->PublishSAFile(fileInfo, move(fd));
EXPECT_EQ(err, BError(BError::Codes::OK).GetCode());
} catch (...) {
EXPECT_TRUE(true);
GTEST_LOG_(INFO) << "IncrementalSessionTest-an exception occurred by RemoveExtConn.";
}
GTEST_LOG_(INFO) << "IncrementalSessionTest-end SUB_b_incremental_session_test_2000";
}
} // namespace OHOS::FileManagement::Backup

View File

@ -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",

View File

@ -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<SessionBckup>();
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<SessionBckup>();
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<SessionBckup>();
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<SessionBckup>();
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<SessionBckup>();
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<SessionBckup>();
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<SessionBckup>();
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<SessionBckup>();
string pathCapFile = "";
vector<string> bundleNames;
bundleNames.push_back("bundle1");
bundleNames.push_back("bundle2");
vector<string> 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<SessionBckup>();
string pathCapFile = "/data/backup";
vector<string> bundleNames;
bundleNames.push_back("bundle1");
bundleNames.push_back("bundle2");
vector<string> 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<string> bundleNames;
bundleNames.push_back("bundle1");
bundleNames.push_back("bundle2");
vector<string> 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<string, vector<string>> 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<string, vector<string>> 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<string, vector<string>> 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<string, vector<string>> 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

View File

@ -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<SessionRestore>();
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<SessionRestore>();
vector<BundleName> bundleNames;
bundleNames.push_back("bundle1");
bundleNames.push_back("bundle2");
vector<string> 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<SessionRestore>();
vector<BundleName> bundleNames;
bundleNames.push_back("bundle1");
bundleNames.push_back("bundle2");
vector<string> 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<SessionRestore>();
vector<BundleName> bundleNames;
bundleNames.push_back("bundle1");
bundleNames.push_back("bundle2");
vector<string> 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<SessionRestore>();
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<SessionRestore>();
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<SessionRestore>();
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<SessionRestore>();
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<SessionRestore>();
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<SessionRestore>();
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<SessionRestore>();
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<SessionRestore> 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<SessionRestore> restore = make_shared<SessionRestore>();
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<SessionRestore> restore = make_shared<SessionRestore>();
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<SessionRestore>();
vector<BundleName> bundleNames;
bundleNames.push_back("bundle1");
bundleNames.push_back("bundle2");
vector<string> 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<string> bundleNames = {"com.example.app2backup/"};
bool depMode = true;
vector<string> 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<string> bundleNames = {"com.example.app2backup/"};
bool depMode = true;
vector<string> 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<string> bundleNames = {"com.example.app2backup/"};
bool depMode = false;
vector<string> 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<string, vector<string>> 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<string, vector<string>> 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<string, vector<string>> 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<string, vector<string>> 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<string, vector<string>> 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<string, vector<string>> 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

View File

@ -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",

View File

@ -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_PERM);
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

View File

@ -24,6 +24,7 @@
#include <gtest/gtest.h>
#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

View File

@ -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

View File

@ -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<BJsonEntityExtManage> 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

View File

@ -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<string, int> keys;
int num = 1;
string line = "";
unordered_map<string, struct ReportFileInfo> 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<string, int> 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<string, int> 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<string, int> 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<string, int> 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

Some files were not shown because too many files have changed in this diff Show More