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

Signed-off-by: 李勃 <libo429@huawei.com>
This commit is contained in:
李勃 2024-08-13 14:21:31 +00:00 committed by Gitee
commit 7e6b0f97b5
21 changed files with 2004 additions and 148 deletions

View File

@ -155,10 +155,11 @@ 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);
/**
* @brief extension incremental backup restore is done

View File

@ -141,14 +141,14 @@ static UniqueFd GetFileHandleForSpecialCloneCloud(const string &fileName)
size_t filePathPrefix = filePath.find_last_of(BConstants::FILE_SEPARATOR_CHAR);
if (filePathPrefix == string::npos) {
HILOGE("GetFileHandleForSpecialCloneCloud: Invalid fileName");
throw BError(BError::Codes::EXT_INVAL_ARG, fileName);
return UniqueFd(-1);
}
string path = filePath.substr(0, filePathPrefix);
if (access(path.c_str(), F_OK) != 0) {
bool created = ForceCreateDirectory(path.data());
if (!created) {
string str = string("Failed to create restore folder.");
throw BError(BError::Codes::EXT_INVAL_ARG, str);
HILOGE("Failed to create restore folder.");
return UniqueFd(-1);
}
}
UniqueFd fd(open(fileName.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR));
@ -214,43 +214,47 @@ static string GetReportFileName(const string &fileName)
static ErrCode GetIncreFileHandleForSpecialVersion(const string &fileName)
{
HILOGI("extension:GetIncreFileHandleForSpecialVersion, filename:%{public}s", fileName.c_str());
ErrCode errCode = ERR_OK;
UniqueFd fd = GetFileHandleForSpecialCloneCloud(fileName);
if (fd < 0) {
HILOGE("Failed to open file = %{private}s, err = %{public}d", fileName.c_str(), errno);
throw BError(BError::Codes::EXT_INVAL_ARG, string("open tar file failed"));
errCode = errno;
}
string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE);
if (mkdir(path.data(), S_IRWXU) && errno != EEXIST) {
string str = string("Failed to create restore folder. ").append(std::generic_category().message(errno));
throw BError(BError::Codes::EXT_INVAL_ARG, str);
HILOGE("Failed to create restore folder : %{private}s, err = %{public}d", path.c_str(), errno);
errCode = errno;
}
string reportName = path + BConstants::BLANK_REPORT_NAME;
UniqueFd reportFd(open(reportName.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR));
if (reportFd < 0) {
HILOGE("Failed to open report file = %{private}s, err = %{public}d", reportName.c_str(), errno);
throw BError(BError::Codes::EXT_INVAL_ARG, string("open report file failed"));
errCode = errno;
}
auto proxy = ServiceProxy::GetInstance();
if (proxy == nullptr) {
throw BError(BError::Codes::EXT_BROKEN_BACKUP_SA, std::generic_category().message(errno));
HILOGE("Failed to get file handle for special version clone");
return BError(BError::Codes::EXT_BROKEN_BACKUP_SA).GetCode();
}
auto ret = proxy->AppIncrementalFileReady(fileName, move(fd), move(reportFd), ERR_OK);
auto ret = proxy->AppIncrementalFileReady(fileName, move(fd), move(reportFd), errCode);
if (ret != ERR_OK) {
HILOGE("Failed to AppIncrementalFileReady %{public}d", ret);
}
return ERR_OK;
}
static string GetIncrementalFileHandlePath()
static string GetIncrementalFileHandlePath(const string &fileName)
{
string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE);
if (mkdir(path.data(), S_IRWXU) && errno != EEXIST) {
string str = string("Failed to create restore folder. ").append(std::generic_category().message(errno));
throw BError(BError::Codes::EXT_INVAL_ARG, str);
}
return path;
string tarName = path + fileName;
return tarName;
}
ErrCode BackupExtExtension::GetIncrementalFileHandle(const string &fileName)
@ -262,19 +266,18 @@ ErrCode BackupExtExtension::GetIncrementalFileHandle(const string &fileName)
extension_->GetExtensionAction());
throw BError(BError::Codes::EXT_INVAL_ARG, "Action is invalid");
}
HILOGI("extension: Start GetIncrementalFileHandle");
VerifyCaller();
if (extension_->SpecialVersionForCloneAndCloud()) {
return GetIncreFileHandleForSpecialVersion(fileName);
}
HILOGI("extension: single to single fileName:%{public}s", GetAnonyPath(fileName).c_str());
string path = GetIncrementalFileHandlePath();
string tarName = path + fileName;
if (access(tarName.c_str(), F_OK) == 0) {
throw BError(BError::Codes::EXT_INVAL_ARG, string("The file already exists"));
}
HILOGI("extension: GetIncrementalFileHandle single to single Name:%{public}s", GetAnonyPath(fileName).c_str());
string tarName = GetIncrementalFileHandlePath(fileName);
int32_t errCode = ERR_OK;
if (access(tarName.c_str(), F_OK) == 0) {
HILOGE("The file already exists, tarname = %{private}s, err =%{public}d", tarName.c_str(), errno);
errCode = errno;
}
UniqueFd fd(open(tarName.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR));
if (fd < 0) {
HILOGE("Failed to open tar file = %{private}s, err = %{public}d", tarName.c_str(), errno);
@ -283,7 +286,8 @@ ErrCode BackupExtExtension::GetIncrementalFileHandle(const string &fileName)
// 对应的简报文件
string reportName = GetReportFileName(tarName);
if (access(reportName.c_str(), F_OK) == 0) {
throw BError(BError::Codes::EXT_INVAL_ARG, string("The report file already exists"));
HILOGE("The report file already exists, Name = %{private}s, err =%{public}d", reportName.c_str(), errno);
errCode = errno;
}
UniqueFd reportFd(open(reportName.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR));
if (reportFd < 0) {
@ -303,24 +307,29 @@ ErrCode BackupExtExtension::GetIncrementalFileHandle(const string &fileName)
} catch (...) {
HILOGE("Failed to get incremental file handle");
DoClear();
return BError(BError::Codes::EXT_INVAL_ARG).GetCode();
return BError(BError::Codes::EXT_BROKEN_IPC).GetCode();
}
}
ErrCode BackupExtExtension::HandleClear()
{
HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
HILOGI("begin clear");
if (extension_ == nullptr) {
HILOGE("Failed to handle clear, extension is nullptr");
return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode();
try {
HILOGI("begin clear");
if (extension_ == nullptr) {
HILOGE("Failed to handle clear, extension is nullptr");
return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode();
}
if (extension_->GetExtensionAction() == BConstants::ExtensionAction::INVALID) {
return BError(BError::Codes::EXT_INVAL_ARG, "Action is invalid").GetCode();
}
VerifyCaller();
DoClear();
return ERR_OK;
} catch (...) {
HILOGE("Failed to handle clear");
return BError(BError::Codes::EXT_BROKEN_IPC).GetCode();
}
if (extension_->GetExtensionAction() == BConstants::ExtensionAction::INVALID) {
return BError(BError::Codes::EXT_INVAL_ARG, "Action is invalid").GetCode();
}
VerifyCaller();
DoClear();
return ERR_OK;
}
static ErrCode IndexFileReady(const TarMap &pkgInfo, sptr<IService> proxy)
@ -352,36 +361,26 @@ static ErrCode IndexFileReady(const TarMap &pkgInfo, sptr<IService> proxy)
return ret;
}
ErrCode BackupExtExtension::BigFileReady(sptr<IService> proxy)
ErrCode BackupExtExtension::BigFileReady(const TarMap &bigFileInfo, sptr<IService> proxy)
{
HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
UniqueFd fd(open(INDEX_FILE_BACKUP.data(), O_RDONLY));
if (fd < 0) {
HILOGE("Failed to open index json file = %{private}s, err = %{public}d", INDEX_FILE_BACKUP.c_str(), errno);
return BError::GetCodeByErrno(errno);
}
BJsonCachedEntity<BJsonEntityExtManage> cachedEntity(move(fd));
auto cache = cachedEntity.Structuralize();
auto pkgInfo = cache.GetExtManageInfo();
HILOGI("BigFileReady Begin: pkgInfo file size is: %{public}zu", pkgInfo.size());
HILOGI("BigFileReady Begin: bigFileInfo file size is: %{public}zu", bigFileInfo.size());
ErrCode ret {ERR_OK};
auto startTime = std::chrono::system_clock::now();
int fdNum = 0;
for (auto &item : pkgInfo) {
if (item.hashName.empty() || item.fileName.empty()) {
continue;
}
for (auto &item : bigFileInfo) {
WaitToSendFd(startTime, fdNum);
int32_t errCode = ERR_OK;
UniqueFd fd(open(item.fileName.data(), O_RDONLY));
string fllePath = std::get<0>(item.second);
UniqueFd fd(open(fllePath.data(), O_RDONLY));
if (fd < 0) {
HILOGE("open file failed, file name is %{public}s, err = %{public}d", item.fileName.c_str(), errno);
HILOGE("open file failed, file name is %{public}s, err = %{public}d", fllePath.c_str(), errno);
errCode = errno;
}
ret = proxy->AppFileReady(item.hashName, std::move(fd), errCode);
ret = proxy->AppFileReady(item.first, std::move(fd), errCode);
if (SUCCEEDED(ret)) {
HILOGI("The application is packaged successfully, package name is %{public}s", item.hashName.c_str());
HILOGI("The application is packaged successfully, package name is %{public}s", item.first.c_str());
} else {
HILOGW("Current file execute app file ready interface failed, ret is:%{public}d", ret);
}
@ -483,7 +482,7 @@ ErrCode BackupExtExtension::HandleBackup(bool isClearData)
.GetCode();
}
AsyncTaskOnBackup();
return 0;
return ERR_OK;
}
static bool IsUserTar(const string &tarFile, const std::vector<ExtManageInfo> &extManageInfo)
@ -502,7 +501,7 @@ static bool IsUserTar(const string &tarFile, const std::vector<ExtManageInfo> &e
return false;
}
static pair<TarMap, vector<string>> GetFileInfos(const vector<string> &includes, const vector<string> &excludes)
static pair<TarMap, map<string, size_t>> GetFileInfos(const vector<string> &includes, const vector<string> &excludes)
{
HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
auto [errCode, files, smallFiles] = BDir::GetBigFiles(includes, excludes);
@ -538,6 +537,76 @@ static pair<TarMap, vector<string>> GetFileInfos(const vector<string> &includes,
return {bigFiles, smallFiles};
}
/**
* tar包回传
*/
static ErrCode TarFileReady(const TarMap &tarFileInfo, sptr<IService> proxy)
{
if (tarFileInfo.empty()) {
HILOGI("TarFileReady: No tar file found");
return ERR_OK;
}
string tarName = tarFileInfo.begin()->first;
string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_BACKUP);
string tarPath = path + tarName;
int32_t errCode = ERR_OK;
UniqueFd fd(open(tarPath.data(), O_RDONLY));
if (fd < 0) {
HILOGE("TarFileReady open file failed, file name is %{public}s, err = %{public}d", tarName.c_str(), errno);
errCode = errno;
}
int ret = proxy->AppFileReady(tarName, std::move(fd), errCode);
if (SUCCEEDED(ret)) {
HILOGI("TarFileReady: AppFileReady success for %{public}s", tarName.c_str());
// 删除文件
RemoveFile(tarName);
} else {
HILOGE("TarFileReady AppFileReady fail to be invoked for %{public}s: ret = %{public}d", tarName.c_str(), ret);
}
return ret;
}
void BackupExtExtension::DoPacket(const map<string, size_t> &srcFiles, TarMap &tar, sptr<IService> proxy)
{
HILOGI("DoPacket begin, infos count: %{public}zu", srcFiles.size());
string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_BACKUP);
int64_t totalSize = 0;
uint32_t fileCount = 0;
vector<string> packFiles;
TarFile::GetInstance().SetPacketMode(true); // 设置下打包模式
auto startTime = std::chrono::system_clock::now();
int fdNum = 0;
for (auto small : srcFiles) {
totalSize += small.second;
fileCount += 1;
packFiles.emplace_back(small.first);
if (totalSize >= DEFAULT_SLICE_SIZE || fileCount >= MAX_FILE_COUNT) {
TarMap tarMap {};
TarFile::GetInstance().Packet(packFiles, "part", path, tarMap);
tar.insert(tarMap.begin(), tarMap.end());
// 执行tar包回传功能
WaitToSendFd(startTime, fdNum);
TarFileReady(tarMap, proxy);
totalSize = 0;
fileCount = 0;
packFiles.clear();
fdNum += FILE_AND_MANIFEST_FD_COUNT;
RefreshTimeInfo(startTime, fdNum);
}
}
if (fileCount > 0) {
// 打包回传
TarMap tarMap {};
TarFile::GetInstance().Packet(packFiles, "part", path, tarMap);
TarFileReady(tarMap, proxy);
fdNum = 1;
WaitToSendFd(startTime, fdNum);
tar.insert(tarMap.begin(), tarMap.end());
packFiles.clear();
RefreshTimeInfo(startTime, fdNum);
}
}
int BackupExtExtension::DoBackup(const BJsonEntityExtensionConfig &usrConfig)
{
HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
@ -558,6 +627,11 @@ int BackupExtExtension::DoBackup(const BJsonEntityExtensionConfig &usrConfig)
vector<string> includes = usrConfig.GetIncludes();
vector<string> excludes = usrConfig.GetExcludes();
auto proxy = ServiceProxy::GetInstance();
if (proxy == nullptr) {
throw BError(BError::Codes::EXT_BROKEN_BACKUP_SA, std::generic_category().message(errno));
}
// 大文件处理
HILOGI("Start packet bigfiles and small files");
auto [bigFileInfo, smallFiles] = GetFileInfos(includes, excludes);
@ -568,21 +642,22 @@ int BackupExtExtension::DoBackup(const BJsonEntityExtensionConfig &usrConfig)
}
}
// 回传大文件
HILOGI("Will notify BigFileReady");
auto res = BigFileReady(bigFileInfo, proxy);
HILOGI("Start packet Tar files");
// 分片打包
// 分片打包 回传tar包
TarMap tarMap {};
TarFile::GetInstance().Packet(smallFiles, "part", path, tarMap);
DoPacket(smallFiles, tarMap, proxy);
bigFileInfo.insert(tarMap.begin(), tarMap.end());
auto proxy = ServiceProxy::GetInstance();
if (proxy == nullptr) {
throw BError(BError::Codes::EXT_BROKEN_BACKUP_SA, std::generic_category().message(errno));
}
HILOGI("Do backup, DoPacket end");
HILOGI("Will notify IndexFileReady");
if (auto ret = IndexFileReady(bigFileInfo, proxy); ret) {
return ret;
}
HILOGI("Will notify BigFileReady");
auto res = BigFileReady(proxy);
HILOGI("HandleBackup finish, ret = %{public}d", res);
return res;
}
@ -1317,30 +1392,34 @@ void BackupExtExtension::AsyncTaskOnBackup()
ErrCode BackupExtExtension::HandleRestore(bool isClearData)
{
HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
VerifyCaller();
SetClearDataFlag(isClearData);
if (extension_ == nullptr) {
HILOGE("Failed to handle restore, extension is nullptr");
throw BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr");
}
if (extension_->GetExtensionAction() != BConstants::ExtensionAction::RESTORE) {
HILOGE("Failed to get file handle, because action is %{public}d invalid", extension_->GetExtensionAction());
throw BError(BError::Codes::EXT_INVAL_ARG, "Action is invalid");
}
// read backup_config is allow to backup or restore
if (!extension_->AllowToBackupRestore()) {
HILOGE("Application does not allow backup or restore");
return BError(BError::Codes::EXT_FORBID_BACKUP_RESTORE, "Application does not allow backup or restore")
.GetCode();
}
try {
VerifyCaller();
SetClearDataFlag(isClearData);
if (extension_ == nullptr) {
HILOGE("Failed to handle restore, extension is nullptr");
return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode();
}
if (extension_->GetExtensionAction() != BConstants::ExtensionAction::RESTORE) {
HILOGE("Failed to get file handle, because action is %{public}d invalid", extension_->GetExtensionAction());
return BError(BError::Codes::EXT_INVAL_ARG, "Action is invalid").GetCode();
}
// read backup_config is allow to backup or restore
if (!extension_->AllowToBackupRestore()) {
HILOGE("Application does not allow backup or restore");
return BError(BError::Codes::EXT_FORBID_BACKUP_RESTORE, "Application does not allow backup or restore")
.GetCode();
}
// async do restore.
if (extension_->WasFromSpecialVersion() && extension_->RestoreDataReady()) {
HILOGI("Restore directly when upgrading.");
AsyncTaskRestoreForUpgrade();
// async do restore.
if (extension_->WasFromSpecialVersion() && extension_->RestoreDataReady()) {
HILOGI("Restore directly when upgrading.");
AsyncTaskRestoreForUpgrade();
}
return ERR_OK;
} catch (...) {
HILOGE("Failed to handle restore");
return BError(BError::Codes::EXT_BROKEN_IPC).GetCode();
}
return 0;
}
static bool CheckTar(const string &fileName)
@ -1422,22 +1501,27 @@ void BackupExtExtension::CompareFiles(UniqueFd incrementalFd,
ErrCode BackupExtExtension::HandleIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd)
{
HILOGI("Start HandleIncrementalBackup");
HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
if (extension_ == nullptr) {
HILOGE("Failed to handle incremental backup, extension is nullptr");
return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode();
try {
HILOGI("Start HandleIncrementalBackup");
if (extension_ == nullptr) {
HILOGE("Failed to handle incremental backup, extension is nullptr");
return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode();
}
string usrConfig = extension_->GetUsrConfig();
BJsonCachedEntity<BJsonEntityExtensionConfig> cachedEntity(usrConfig);
auto cache = cachedEntity.Structuralize();
if (!cache.GetAllowToBackupRestore()) {
HILOGE("Application does not allow backup or restore");
return BError(BError::Codes::EXT_FORBID_BACKUP_RESTORE, "Application does not allow backup or restore")
.GetCode();
}
AsyncTaskDoIncrementalBackup(move(incrementalFd), move(manifestFd));
return ERR_OK;
} catch (...) {
HILOGE("Failed to handle incremental backup");
return BError(BError::Codes::EXT_INVAL_ARG).GetCode();
}
string usrConfig = extension_->GetUsrConfig();
BJsonCachedEntity<BJsonEntityExtensionConfig> cachedEntity(usrConfig);
auto cache = cachedEntity.Structuralize();
if (!cache.GetAllowToBackupRestore()) {
HILOGE("Application does not allow backup or restore");
return BError(BError::Codes::EXT_FORBID_BACKUP_RESTORE, "Application does not allow backup or restore")
.GetCode();
}
AsyncTaskDoIncrementalBackup(move(incrementalFd), move(manifestFd));
return 0;
}
ErrCode BackupExtExtension::IncrementalOnBackup(bool isClearData)
@ -1457,7 +1541,7 @@ ErrCode BackupExtExtension::IncrementalOnBackup(bool isClearData)
.GetCode();
}
AsyncTaskOnIncrementalBackup();
return 0;
return ERR_OK;
}
tuple<UniqueFd, UniqueFd> BackupExtExtension::GetIncrementalBackupFileHandle()
@ -1870,15 +1954,20 @@ ErrCode BackupExtExtension::GetBackupInfo(std::string &result)
ErrCode BackupExtExtension::UpdateFdSendRate(std::string &bundleName, int32_t sendRate)
{
std::lock_guard<std::mutex> lock(updateSendRateLock_);
HILOGI("Update SendRate, bundleName:%{public}s, sendRate:%{public}d", bundleName.c_str(), sendRate);
VerifyCaller();
bundleName_ = bundleName;
sendRate_ = sendRate;
if (sendRate > 0) {
startSendFdRateCon_.notify_one();
try {
std::lock_guard<std::mutex> lock(updateSendRateLock_);
HILOGI("Update SendRate, bundleName:%{public}s, sendRate:%{public}d", bundleName.c_str(), sendRate);
VerifyCaller();
bundleName_ = bundleName;
sendRate_ = sendRate;
if (sendRate > 0) {
startSendFdRateCon_.notify_one();
}
return ERR_OK;
} catch (...) {
HILOGE("Failed to UpdateFdSendRate");
return BError(BError::Codes::EXT_BROKEN_IPC).GetCode();
}
return ERR_OK;
}
std::function<void(ErrCode, std::string)> BackupExtExtension::RestoreResultCallbackEx(wptr<BackupExtExtension> obj)

View File

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

View File

@ -287,16 +287,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)
@ -644,10 +655,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)

View File

@ -16,7 +16,9 @@ import("//build/test.gni")
group("unittest") {
testonly = true
deps = [
"file_share_nopermission_sup_test:file_share_no_permission_ndk_sup_test",
"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

@ -0,0 +1,55 @@
# Copyright (c) 2024 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/test.gni")
import("//foundation/filemanagement/app_file_service/app_file_service.gni")
ohos_unittest("file_share_no_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/parameter_mock/include",
"//third_party/googletest/include",
]
sources = [
"${app_file_service_path}/interfaces/kits/ndk/fileshare/src/oh_file_share.cpp",
"${app_file_service_path}/tests/mock/parameter_mock/src/parameter_mock.cpp",
"file_share_nopermission_sup_test.cpp",
]
external_deps = [
"ability_base:zuri",
"access_token:libaccesstoken_sdk",
"c_utils:utils",
"file_api:filemgmt_libn",
"hilog:libhilog",
"init:libbegetutil",
"ipc:ipc_core",
]
deps = [
"${app_file_service_path}/interfaces/innerkits/native:fileshare_native",
"//third_party/googletest:gmock_main",
"//third_party/googletest:gtest_main",
]
}

View File

@ -0,0 +1,218 @@
/*
* 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 <memory>
#include <string>
#include "securec.h"
#include "common_func.h"
#include "error_code.h"
#include "oh_file_share.h"
#include "parameter_mock.h"
using namespace testing::ext;
using namespace testing;
using namespace OHOS::AppFileService;
using namespace std;
namespace OHOS::AppFileService::ModuleFileShareNoPermission {
class NDKFileShareNoPermissionSupTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp() {};
void TearDown() {};
static inline shared_ptr<ParamMoc> paramMoc_ = nullptr;
};
void NDKFileShareNoPermissionSupTest::SetUpTestCase()
{
paramMoc_ = make_shared<ParamMoc>();
ParamMoc::paramMoc = paramMoc_;
}
void NDKFileShareNoPermissionSupTest::TearDownTestCase()
{
ParamMoc::paramMoc = nullptr;
paramMoc_ = nullptr;
}
/**
* @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(NDKFileShareNoPermissionSupTest, 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 = 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(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) {
memcpy_s(value, sizeof("false"), "true", sizeof("true"));
})), Return(1)));
FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum);
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(NDKFileShareNoPermissionSupTest, 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 = 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(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) {
memcpy_s(value, sizeof("false"), "true", sizeof("true"));
})), Return(1)));
FileManagement_ErrCode ret = OH_FileShare_RevokePermission(policies, policiesNum, &result, &resultNum);
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(NDKFileShareNoPermissionSupTest, 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 = 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(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) {
memcpy_s(value, sizeof("false"), "true", sizeof("true"));
})), Return(1)));
FileManagement_ErrCode ret = OH_FileShare_ActivatePermission(policies, policiesNum, &result, &resultNum);
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(NDKFileShareNoPermissionSupTest, 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 = 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(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) {
memcpy_s(value, sizeof("false"), "true", sizeof("true"));
})), Return(1)));
FileManagement_ErrCode ret = OH_FileShare_DeactivatePermission(policies, policiesNum, &result, &resultNum);
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(NDKFileShareNoPermissionSupTest, 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 = 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(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) {
memcpy_s(value, sizeof("false"), "true", sizeof("true"));
})), Return(1)));
FileManagement_ErrCode ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum);
EXPECT_EQ(ret, E_PERMISSION);
if (result != nullptr) {
free(result);
}
GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test end";
}
} // namespace OHOS::AppFileService::ModuleFileShareNoPermission

View File

@ -0,0 +1,61 @@
# 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.
import("//build/test.gni")
import("//foundation/filemanagement/app_file_service/app_file_service.gni")
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",
]
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",
"${app_file_service_path}/tests/mock/parameter_mock/src/parameter_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",
"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",
"//third_party/googletest:gmock_main",
"//third_party/googletest:gtest_main",
]
}

View File

@ -0,0 +1,448 @@
/*
* 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"
#include "parameter_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<ParamMoc> paramMoc_ = nullptr;
static inline shared_ptr<FilePermissionMock> filePermMoc_ = nullptr;
};
void NDKFileSharePermissionSupTest::SetUpTestCase()
{
GrantNativePermission();
paramMoc_ = make_shared<ParamMoc>();
ParamMoc::paramMoc = paramMoc_;
filePermMoc_ = make_shared<FilePermissionMock>();
FilePermissionMock::filePermissionMock = filePermMoc_;
}
void NDKFileSharePermissionSupTest::TearDownTestCase()
{
ParamMoc::paramMoc = nullptr;
paramMoc_ = nullptr;
FilePermissionMock::filePermissionMock = nullptr;
filePermMoc_ = nullptr;
}
/**
* @tc.name: OH_FileShare_PersistPermission_test_001
* @tc.desc: Test function of OH_FileShare_PersistPermission() interface for SUCCESS.
* @tc.size: MEDIUM
* @tc.type: FUNC
* @tc.level Level 1
* @tc.require:
*/
HWTEST_F(NDKFileSharePermissionSupTest, OH_FileShare_PersistPermission_test_001, TestSize.Level1)
{
GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_001 start";
char policyUriChar[] = "file://com.example.filesharea/data/storage/el2/base/PersistPermission.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(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(Return(-1));
FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum);
EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT);
OH_FileShare_ReleasePolicyErrorResult(result, resultNum);
EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(Return(1));
ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum);
EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT);
OH_FileShare_ReleasePolicyErrorResult(result, resultNum);
GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_001 end";
}
/**
* @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;
EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) {
memcpy_s(value, sizeof("false"), "true", sizeof("true"));
})), Return(1)));
FileManagement_ErrCode ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum);
EXPECT_EQ(ret, E_PARAMS);
OH_FileShare_ReleasePolicyErrorResult(result, resultNum);
policies[0].uri = policyUriChar;
EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) {
memcpy_s(value, sizeof("false"), "true", sizeof("true"));
})), Return(1)));
ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum);
EXPECT_EQ(ret, E_PARAMS);
OH_FileShare_ReleasePolicyErrorResult(result, resultNum);
policies[0].length = sizeof(policyUriChar);
EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) {
memcpy_s(value, sizeof("false"), "true", sizeof("true"));
})), Return(1)));
ret = OH_FileShare_PersistPermission(policies, policiesNum, &result, &resultNum);
EXPECT_EQ(ret, E_PARAMS);
OH_FileShare_ReleasePolicyErrorResult(result, resultNum);
GTEST_LOG_(INFO) << "OH_FileShare_PersistPermission_test_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(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) {
memcpy_s(value, sizeof("false"), "true", sizeof("true"));
})), Return(1)));
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(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) {
memcpy_s(value, sizeof("false"), "true", sizeof("true"));
})), Return(1)));
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(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) {
memcpy_s(value, sizeof("false"), "true", sizeof("true"));
})), Return(1)));
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(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) {
memcpy_s(value, sizeof("false"), "true", sizeof("true"));
})), Return(1)));
EXPECT_CALL(*filePermMoc_, PersistPermission(_, _))
.WillOnce(DoAll(SetArgReferee<1>(errorResults), Return(E_DEVICE_NOT_SUPPORT)));
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(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) {
memcpy_s(value, sizeof("false"), "true", sizeof("true"));
})), Return(1)));
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_001
* @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_001, TestSize.Level1)
{
GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test_001 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(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(Return(-1));
FileManagement_ErrCode ret = OH_FileShare_CheckPersistentPermission(policies, policiesNum, &result, &resultNum);
EXPECT_EQ(ret, E_DEVICE_NOT_SUPPORT);
if (result != nullptr) {
free(result);
}
GTEST_LOG_(INFO) << "OH_FileShare_CheckPersistentPermission_test_001 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;
EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) {
memcpy_s(value, sizeof("false"), "true", sizeof("true"));
})), Return(1)));
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(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) {
memcpy_s(value, sizeof("false"), "true", sizeof("true"));
})), Return(1)));
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(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) {
memcpy_s(value, sizeof("false"), "true", sizeof("true"));
})), Return(1)));
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(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) {
memcpy_s(value, sizeof("false"), "true", sizeof("true"));
})), Return(1)));
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;
//char value[] = "false";
std::vector<bool> errorResults;
errorResults.push_back(false);
EXPECT_CALL(*paramMoc_, GetParameter(_, _, _, _)).WillOnce(DoAll(WithArgs<2>(Invoke([](char *value) {
memcpy_s(value, sizeof("false"), "true", sizeof("true"));
})), Return(1)));
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"
@ -916,4 +916,283 @@ HWTEST_F(NDKFileSharePermissionTest, OH_FileShare_CheckPersistentPermission_test
}
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

@ -396,6 +396,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 +570,74 @@ 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);
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";
}
}

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

@ -143,6 +143,7 @@ ohos_unittest("backup_service_test") {
blocklist = "${path_backup}/cfi_blocklist.txt"
}
defines = [ "private=public" ]
use_exceptions = true
}

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

@ -441,6 +441,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
@ -945,4 +982,29 @@ HWTEST_F(ServiceTest, SUB_Service_UpdateTimer_0100, testing::ext::TestSize.Level
}
GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_UpdateTimer_0100";
}
/**
* @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";
}
} // namespace OHOS::FileManagement::Backup

View File

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

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

@ -46,7 +46,7 @@ public:
* @param excludes
* @return
*/
static std::tuple<ErrCode, std::map<std::string, struct stat>, std::vector<std::string>> GetBigFiles(
static std::tuple<ErrCode, std::map<std::string, struct stat>, std::map<std::string, size_t>> GetBigFiles(
const std::vector<std::string> &includes, const std::vector<std::string> &excludes);
/**

View File

@ -55,10 +55,10 @@ static bool IsEmptyDirectory(const string &path)
return isEmpty;
}
static tuple<ErrCode, map<string, struct stat>, vector<string>> GetFile(const string &path, off_t size = -1)
static tuple<ErrCode, map<string, struct stat>, map<string, size_t>> GetFile(const string &path, off_t size = -1)
{
map<string, struct stat> files;
vector<string> smallFiles;
map<string, size_t> smallFiles;
struct stat sta = {};
if (stat(path.data(), &sta) == -1) {
return {BError(errno).GetCode(), files, smallFiles};
@ -67,7 +67,7 @@ static tuple<ErrCode, map<string, struct stat>, vector<string>> GetFile(const st
return {BError(BError::Codes::OK).GetCode(), files, smallFiles};
}
if (sta.st_size <= size) {
smallFiles.emplace_back(path);
smallFiles.insert(make_pair(path, sta.st_size));
} else {
files.try_emplace(path, sta);
}
@ -85,19 +85,19 @@ static uint32_t CheckOverLongPath(const string &path)
return len;
}
static tuple<ErrCode, map<string, struct stat>, vector<string>> GetDirFilesDetail(const string &path,
bool recursion,
off_t size = -1)
static tuple<ErrCode, map<string, struct stat>, map<string, size_t>> GetDirFilesDetail(const string &path,
bool recursion,
off_t size = -1)
{
map<string, struct stat> files;
vector<string> smallFiles;
map<string, size_t> smallFiles;
if (IsEmptyDirectory(path)) {
string newPath = path;
if (path.at(path.size()-1) != '/') {
newPath += '/';
}
smallFiles.emplace_back(newPath);
smallFiles.insert(make_pair(newPath, 0));
return {ERR_OK, files, smallFiles};
}
@ -111,32 +111,33 @@ static tuple<ErrCode, map<string, struct stat>, vector<string>> GetDirFilesDetai
// current dir OR parent dir
if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0)) {
continue;
} else if (ptr->d_type == DT_DIR) {
if (!recursion) {
continue;
}
auto [errCode, subFiles, subSmallFiles] =
GetDirFilesDetail(IncludeTrailingPathDelimiter(path) + string(ptr->d_name), recursion, size);
if (errCode != 0) {
return {errCode, files, smallFiles};
}
files.merge(subFiles);
smallFiles.insert(smallFiles.end(), subSmallFiles.begin(), subSmallFiles.end());
} else if (ptr->d_type == DT_LNK) {
continue;
} else {
} else if (ptr->d_type == DT_REG) {
struct stat sta = {};
string fileName = IncludeTrailingPathDelimiter(path) + string(ptr->d_name);
if (CheckOverLongPath(fileName) >= PATH_MAX_LEN || stat(fileName.data(), &sta) == -1) {
continue;
}
if (sta.st_size <= size) {
smallFiles.emplace_back(fileName);
smallFiles.insert(make_pair(fileName, sta.st_size));
continue;
}
files.try_emplace(fileName, sta);
} else if (ptr->d_type != DT_DIR) {
HILOGE("Not support file type");
continue;
}
// DT_DIR type
if (!recursion) {
continue;
}
auto [errCode, subFiles, subSmallFiles] =
GetDirFilesDetail(IncludeTrailingPathDelimiter(path) + string(ptr->d_name), recursion, size);
if (errCode != 0) {
return {errCode, files, smallFiles};
}
files.merge(subFiles);
smallFiles.insert(subSmallFiles.begin(), subSmallFiles.end());
}
return {ERR_OK, files, smallFiles};
}
@ -198,20 +199,20 @@ static set<string> ExpandPathWildcard(const vector<string> &vec, bool onlyPath)
return filteredPath;
}
tuple<ErrCode, map<string, struct stat>, vector<string>> BDir::GetBigFiles(const vector<string> &includes,
const vector<string> &excludes)
tuple<ErrCode, map<string, struct stat>, map<string, size_t>> BDir::GetBigFiles(const vector<string> &includes,
const vector<string> &excludes)
{
set<string> inc = ExpandPathWildcard(includes, false);
map<string, struct stat> incFiles;
vector<string> incSmallFiles;
map<string, size_t> incSmallFiles;
for (const auto &item : inc) {
auto [errCode, files, smallFiles] = GetDirFilesDetail(item, true, BConstants::BIG_FILE_BOUNDARY);
if (errCode == 0) {
int32_t num = static_cast<int32_t>(files.size());
incFiles.merge(move(files));
HILOGI("big files: %{public}d; small files: %{public}d", num, static_cast<int32_t>(smallFiles.size()));
incSmallFiles.insert(incSmallFiles.end(), smallFiles.begin(), smallFiles.end());
incSmallFiles.insert(smallFiles.begin(), smallFiles.end());
}
}
@ -234,10 +235,10 @@ tuple<ErrCode, map<string, struct stat>, vector<string>> BDir::GetBigFiles(const
return false;
};
vector<string> resSmallFiles;
map<string, size_t> resSmallFiles;
for (const auto &item : incSmallFiles) {
if (!isMatch(excludes, item)) {
resSmallFiles.emplace_back(item);
if (!isMatch(excludes, item.first)) {
resSmallFiles.insert(make_pair(item.first, item.second));
}
}