From 07242f0fd870240584929c84490c16c87d6e8ee8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9C=E5=B0=8F=E6=9E=97?= Date: Fri, 16 May 2025 17:32:12 +0800 Subject: [PATCH 01/19] =?UTF-8?q?copy=E6=8E=A5=E5=8F=A3bug=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Change-Id: I4958b6b4ea03d236d089391c2c755b5391f0d485 Signed-off-by: 姜小林 --- interfaces/kits/js/BUILD.gn | 6 +- .../js/src/mod_fs/ani/ets/@ohos.file.fs.ets | 15 +- .../class_tasksignal/ani/task_signal_ani.cpp | 81 ++----- .../class_tasksignal/ani/task_signal_ani.h | 8 +- .../ani/task_signal_listener_ani.cpp | 63 +++++ .../task_signal_listener_ani.h} | 41 ++-- .../ani/task_signal_wrapper.cpp | 71 ++++++ .../ani/task_signal_wrapper.h | 37 +++ .../class_tasksignal/fs_task_signal.cpp | 79 +++++++ .../mod_fs/class_tasksignal/fs_task_signal.h | 50 ++++ .../js/src/mod_fs/properties/ani/copy_ani.cpp | 159 ++++++------- .../js/src/mod_fs/properties/copy_core.cpp | 222 ++++++++---------- .../kits/js/src/mod_fs/properties/copy_core.h | 126 +++++----- .../ani/progress_listener_ani.cpp | 93 ++++++++ .../copy_listener/ani/progress_listener_ani.h | 39 +++ .../copy_listener/i_progress_listener.h} | 27 ++- .../copy_listener/trans_listener_core.cpp | 56 +++-- .../copy_listener/trans_listener_core.h | 28 +-- 18 files changed, 782 insertions(+), 419 deletions(-) create mode 100644 interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_listener_ani.cpp rename interfaces/kits/js/src/mod_fs/class_tasksignal/{task_signal_entity_core.h => ani/task_signal_listener_ani.h} (47%) create mode 100644 interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_wrapper.cpp create mode 100644 interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_wrapper.h create mode 100644 interfaces/kits/js/src/mod_fs/class_tasksignal/fs_task_signal.cpp create mode 100644 interfaces/kits/js/src/mod_fs/class_tasksignal/fs_task_signal.h create mode 100644 interfaces/kits/js/src/mod_fs/properties/copy_listener/ani/progress_listener_ani.cpp create mode 100644 interfaces/kits/js/src/mod_fs/properties/copy_listener/ani/progress_listener_ani.h rename interfaces/kits/js/src/mod_fs/{class_tasksignal/task_signal_entity_core.cpp => properties/copy_listener/i_progress_listener.h} (50%) diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index 3c4ddabd9..125de4eed 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -681,6 +681,7 @@ ohos_shared_library("ani_file_fs") { "src/mod_fs/properties", "src/mod_fs/properties/ani", "src/mod_fs/properties/copy_listener", + "src/mod_fs/properties/copy_listener/ani", ] sources = [ "src/common/ani_helper/ani_signature.cpp", @@ -709,7 +710,9 @@ ohos_shared_library("ani_file_fs") { "src/mod_fs/class_stream/fs_stream.cpp", "src/mod_fs/class_stream/stream_instantiator.cpp", "src/mod_fs/class_tasksignal/ani/task_signal_ani.cpp", - "src/mod_fs/class_tasksignal/task_signal_entity_core.cpp", + "src/mod_fs/class_tasksignal/ani/task_signal_listener_ani.cpp", + "src/mod_fs/class_tasksignal/ani/task_signal_wrapper.cpp", + "src/mod_fs/class_tasksignal/fs_task_signal.cpp", "src/mod_fs/class_watcher/ani/fs_watcher_ani.cpp", "src/mod_fs/class_watcher/ani/fs_watcher_wrapper.cpp", "src/mod_fs/class_watcher/ani/watch_event_listener.cpp", @@ -755,6 +758,7 @@ ohos_shared_library("ani_file_fs") { "src/mod_fs/properties/copy_core.cpp", "src/mod_fs/properties/copy_dir_core.cpp", "src/mod_fs/properties/copy_file_core.cpp", + "src/mod_fs/properties/copy_listener/ani/progress_listener_ani.cpp", "src/mod_fs/properties/copy_listener/trans_listener_core.cpp", "src/mod_fs/properties/create_randomaccessfile_core.cpp", "src/mod_fs/properties/create_stream_core.cpp", diff --git a/interfaces/kits/js/src/mod_fs/ani/ets/@ohos.file.fs.ets b/interfaces/kits/js/src/mod_fs/ani/ets/@ohos.file.fs.ets index 03f56f6b0..1ebce3e37 100644 --- a/interfaces/kits/js/src/mod_fs/ani/ets/@ohos.file.fs.ets +++ b/interfaces/kits/js/src/mod_fs/ani/ets/@ohos.file.fs.ets @@ -1263,20 +1263,29 @@ export type ProgressListener = (progress: Progress) => void; export class TaskSignal { private nativeTaskSignal: long = 0; + private native onCancelNative(): void; - private onCancelResolve: (path: string) => void = (path: string): void => {}; + + private onCancelResolve: (path: string) => void; private onCancelCallback(path: string): void { if (this.onCancelResolve) { this.onCancelResolve(path); } } + native cancel(): void; + onCancel(): Promise { - return new Promise((resolve: (path: string) => void, reject: (e: BusinessError) => void): void => { + return new Promise((resolve: (result: string) => void, reject: (e: BusinessError) => void): void => { this.onCancelResolve = resolve; - this.onCancelNative(); + try { + this.onCancelNative(); + } catch (e: BusinessError) { + reject(e); + } }); } + } export interface CopyOptions { diff --git a/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_ani.cpp b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_ani.cpp index f22a814f9..2b1229a69 100644 --- a/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_ani.cpp @@ -19,7 +19,8 @@ #include "copy_core.h" #include "error_handler.h" #include "filemgmt_libhilog.h" -#include "task_signal_entity_core.h" +#include "fs_task_signal.h" +#include "task_signal_wrapper.h" #include "type_converter.h" namespace OHOS { @@ -29,84 +30,40 @@ namespace ANI { using namespace std; using namespace OHOS::FileManagement::ModuleFileIO; -static TaskSignalEntityCore *Unwrap(ani_env *env, ani_object object) -{ - ani_long entity; - auto ret = env->Object_GetFieldByName_Long(object, "nativeTaskSignal", &entity); - if (ret != ANI_OK) { - HILOGE("Unwrap taskSignalEntityCore err: %{private}d", ret); - return nullptr; - } - return reinterpret_cast(entity); -} - void TaskSignalAni::Cancel(ani_env *env, [[maybe_unused]] ani_object object) { - auto entity = Unwrap(env, object); - if (entity == nullptr) { + FsTaskSignal *copySignal = TaskSignalWrapper::Unwrap(env, object); + if (copySignal == nullptr) { + HILOGE("Cannot unwrap copySignal!"); ErrorHandler::Throw(env, EINVAL); return; } - if (entity->taskSignal_ == nullptr) { - HILOGE("Failed to get watcherEntity when stop."); - ErrorHandler::Throw(env, EINVAL); - return; - } - - auto ret = entity->taskSignal_->Cancel(); - if (ret != NO_ERROR) { - HILOGE("Failed to cancel the task."); - ErrorHandler::Throw(env, CANCEL_ERR); + auto ret = copySignal->Cancel(); + if (!ret.IsSuccess()) { + HILOGE("Cannot Cancel!"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); return; } } void TaskSignalAni::OnCancel(ani_env *env, [[maybe_unused]] ani_object object) { - auto entity = Unwrap(env, object); - if (entity == nullptr) { + FsTaskSignal *copySignal = TaskSignalWrapper::Unwrap(env, object); + if (copySignal == nullptr) { + HILOGE("Cannot unwrap copySignal!"); ErrorHandler::Throw(env, EINVAL); return; } - if (entity->taskSignal_ == nullptr) { - HILOGE("Failed to get watcherEntity when stop."); - ErrorHandler::Throw(env, EINVAL); - return; - } - - ani_ref globalObj; - auto status = env->GlobalReference_Create(object, &globalObj); - if (status != ANI_OK) { - HILOGE("GlobalReference_Create, err: %{private}d", status); + auto ret = copySignal->OnCancel(); + if (!ret.IsSuccess()) { + HILOGE("Cannot Cancel!"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); return; } - ani_vm *vm = nullptr; - env->GetVM(&vm); - auto cb = [vm, &globalObj](string filePath) -> void { - auto env = AniHelper::GetThreadEnv(vm); - if (env == nullptr) { - HILOGE("failed to GetThreadEnv"); - return; - } - - // std::vector vec; - auto [succPath, path] = TypeConverter::ToAniString(env, filePath); - if (!succPath) { - HILOGE("ToAniString failed"); - return; - } - - auto ret = env->Object_CallMethodByName_Void(static_cast(globalObj), - "onCancelCallback", nullptr, path); - if (ret != ANI_OK) { - HILOGE("Call onCancelCallback failed, err: %{private}d", ret); - return; - } - }; - auto callbackContext = std::make_shared(cb); - entity->callbackContextCore_ = callbackContext; - entity->taskSignal_->SetTaskSignalListener(entity); } + } // namespace ANI } // namespace ModuleFileIO } // namespace FileManagement diff --git a/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_ani.h b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_ani.h index 6db3301ce..d27e52538 100644 --- a/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_ani.h +++ b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_ani.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef FILEMANAGEMENT_FILE_API_TASK_SIGNAL_ANI_H -#define FILEMANAGEMENT_FILE_API_TASK_SIGNAL_ANI_H +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_TASKSIGNAL_ANI_TASK_SIGNAL_ANI_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_TASKSIGNAL_ANI_TASK_SIGNAL_ANI_H #include @@ -22,13 +22,15 @@ namespace OHOS { namespace FileManagement { namespace ModuleFileIO { namespace ANI { + class TaskSignalAni final { public: static void Cancel(ani_env *env, [[maybe_unused]] ani_object object); static void OnCancel(ani_env *env, [[maybe_unused]] ani_object object); }; + } // namespace ANI } // namespace ModuleFileIO } // namespace FileManagement } // namespace OHOS -#endif // FILEMANAGEMENT_FILE_API_TASK_SIGNAL_ANI_H \ No newline at end of file +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_TASKSIGNAL_ANI_TASK_SIGNAL_ANI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_listener_ani.cpp b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_listener_ani.cpp new file mode 100644 index 000000000..a80010e95 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_listener_ani.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "task_signal_listener_ani.h" + +#include +#include "ani_helper.h" +#include "ani_signature.h" +#include "file_utils.h" +#include "filemgmt_libhilog.h" +#include "type_converter.h" + +namespace OHOS::FileManagement::ModuleFileIO::ANI { +using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; + +void TaskSignalListenerAni::OnCancel() +{ + auto filepath = taskSignal->filePath_; + auto task = [this, filepath]() { SendCancelEvent(filepath); }; + AniHelper::SendEventToMainThread(task); +} + +void TaskSignalListenerAni::SendCancelEvent(const string &filepath) const +{ + if (vm == nullptr) { + HILOGE("Cannot send cancel event because the vm is null."); + return; + } + if (signalObj == nullptr) { + HILOGE("Cannot send cancel event because the signalObj is null."); + return; + } + ani_env *env = AniHelper::GetThreadEnv(vm); + if (env == nullptr) { + HILOGE("Cannot send cancel event because the env is null."); + return; + } + auto [succ, aniPath] = TypeConverter::ToAniString(env, filepath); + if (!succ) { + HILOGE("Cannot convert filepath to ani string!"); + return; + } + auto ret = env->Object_CallMethodByName_Void(signalObj, "onCancelCallback", nullptr, aniPath); + if (ret != ANI_OK) { + HILOGE("Call onCancelCallback failed, err: %{private}d", ret); + return; + } +} + +} // namespace OHOS::FileManagement::ModuleFileIO::ANI diff --git a/interfaces/kits/js/src/mod_fs/class_tasksignal/task_signal_entity_core.h b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_listener_ani.h similarity index 47% rename from interfaces/kits/js/src/mod_fs/class_tasksignal/task_signal_entity_core.h rename to interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_listener_ani.h index c301442c7..a11be571b 100644 --- a/interfaces/kits/js/src/mod_fs/class_tasksignal/task_signal_entity_core.h +++ b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_listener_ani.h @@ -13,34 +13,35 @@ * limitations under the License. */ -#ifndef FILEMANAGEMENT_FILE_API_TASK_SIGNAL_ENTITY_CORE_H -#define FILEMANAGEMENT_FILE_API_TASK_SIGNAL_ENTITY_CORE_H +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_TASKSIGNAL_ANI_TASK_SIGNAL_LISTENER_ANI_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_TASKSIGNAL_ANI_TASK_SIGNAL_LISTENER_ANI_H -#include "task_signal.h" +#include #include "task_signal_listener.h" +#include "task_signal.h" -namespace OHOS::FileManagement::ModuleFileIO { +namespace OHOS::FileManagement::ModuleFileIO::ANI { using namespace DistributedFS::ModuleTaskSignal; -typedef std::function TaskSignalCb; -class CallbackContextCore { +class TaskSignalListenerAni : public TaskSignalListener { public: - explicit CallbackContextCore(TaskSignalCb cb) : cb(cb) {} - ~CallbackContextCore() = default; - - TaskSignalCb cb; - std::string filePath_; -}; + TaskSignalListenerAni(ani_vm *vm, const ani_object &signalObj, std::shared_ptr taskSignal) + : vm(vm), signalObj(signalObj), taskSignal(taskSignal) {} + void OnCancel() override; -class TaskSignalEntityCore : public TaskSignalListener { public: - TaskSignalEntityCore() = default; - ~TaskSignalEntityCore() override; - void OnCancel() override; + TaskSignalListenerAni() = default; + ~TaskSignalListenerAni() = default; - std::shared_ptr taskSignal_ = nullptr; - std::shared_ptr callbackContextCore_ = nullptr; +private: + void SendCancelEvent(const std::string &filepath) const; + +private: + ani_vm *vm; + ani_object signalObj; + std::shared_ptr taskSignal; }; -} // namespace OHOS::FileManagement::ModuleFileIO -#endif // FILEMANAGEMENT_FILE_API_TASK_SIGNAL_ENTITY_CORE_H \ No newline at end of file +} // namespace OHOS::FileManagement::ModuleFileIO::ANI + +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_TASKSIGNAL_ANI_TASK_SIGNAL_LISTENER_ANI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_wrapper.cpp b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_wrapper.cpp new file mode 100644 index 000000000..79be64231 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_wrapper.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "task_signal_wrapper.h" + +#include "ani_signature.h" +#include "error_handler.h" +#include "filemgmt_libhilog.h" +#include "fs_task_signal.h" +#include "type_converter.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { +using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; + +FsTaskSignal *TaskSignalWrapper::Unwrap(ani_env *env, ani_object object) +{ + ani_long nativePtr; + auto status = env->Object_GetFieldByName_Long(object, "nativeTaskSignal", &nativePtr); + if (status != ANI_OK) { + HILOGE("Unwrap taskSignal obj failed! status: %{public}d", status); + return nullptr; + } + uintptr_t ptrValue = static_cast(nativePtr); + FsTaskSignal *copySignal = reinterpret_cast(ptrValue); + return copySignal; +} + +bool TaskSignalWrapper::Wrap(ani_env *env, ani_object object, const FsTaskSignal *signal) +{ + if (object == nullptr) { + HILOGE("TaskSignal obj is null!"); + return false; + } + + if (signal == nullptr) { + HILOGE("FsTaskSignal pointer is null!"); + return false; + } + + ani_long ptr = static_cast(reinterpret_cast(signal)); + + auto status = env->Object_SetFieldByName_Long(object, "nativeTaskSignal", ptr); + if (status != ANI_OK) { + HILOGE("Wrap taskSignal obj failed! status: %{public}d", status); + return false; + } + + return true; +} + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_wrapper.h b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_wrapper.h new file mode 100644 index 000000000..2cfd04e4d --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_wrapper.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_TASKSIGNAL_ANI_TASK_SIGNAL_WRAPPER_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_TASKSIGNAL_ANI_TASK_SIGNAL_WRAPPER_H + +#include +#include "fs_task_signal.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +class TaskSignalWrapper final { +public: + static FsTaskSignal *Unwrap(ani_env *env, ani_object object); + static bool Wrap(ani_env *env, ani_object object, const FsTaskSignal *signal); +}; + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_TASKSIGNAL_ANI_TASK_SIGNAL_WRAPPER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_tasksignal/fs_task_signal.cpp b/interfaces/kits/js/src/mod_fs/class_tasksignal/fs_task_signal.cpp new file mode 100644 index 000000000..d9b4b6ffe --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_tasksignal/fs_task_signal.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "fs_task_signal.h" + +#include "file_utils.h" +#include "filemgmt_libhilog.h" +#include "fs_utils.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; + +FsResult> FsTaskSignal::Constructor( + shared_ptr taskSignal, shared_ptr signalListener) +{ + if (!taskSignal) { + HILOGE("Invalid taskSignal"); + return FsResult>::Error(EINVAL); + } + if (!signalListener) { + HILOGE("Invalid signalListener"); + return FsResult>::Error(EINVAL); + } + auto copySignal = CreateSharedPtr(); + if (copySignal == nullptr) { + HILOGE("Failed to request heap memory."); + return FsResult>::Error(ENOMEM); + } + copySignal->taskSignal_ = move(taskSignal); + copySignal->signalListener_ = move(signalListener); + return FsResult>::Success(copySignal); +} + +FsResult FsTaskSignal::Cancel() +{ + if (taskSignal_ == nullptr) { + HILOGE("Failed to get taskSignal"); + return FsResult::Error(EINVAL); + } + auto ret = taskSignal_->Cancel(); + if (ret != ERRNO_NOERR) { + HILOGE("Failed to cancel the task."); + return FsResult::Error(CANCEL_ERR); + } + return FsResult::Success(); +} + +FsResult FsTaskSignal::OnCancel() +{ + if (taskSignal_ == nullptr) { + HILOGE("Failed to get taskSignal"); + return FsResult::Error(EINVAL); + } + taskSignal_->SetTaskSignalListener(signalListener_.get()); + return FsResult::Success(); +} + +shared_ptr FsTaskSignal::GetTaskSignal() const +{ + return taskSignal_; +} + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_tasksignal/fs_task_signal.h b/interfaces/kits/js/src/mod_fs/class_tasksignal/fs_task_signal.h new file mode 100644 index 000000000..33161108c --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_tasksignal/fs_task_signal.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_TASKSIGNAL_FS_TASK_SIGNAL_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_TASKSIGNAL_FS_TASK_SIGNAL_H + +#include "filemgmt_libfs.h" +#include "task_signal.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; +using namespace DistributedFS::ModuleTaskSignal; + +class FsTaskSignal { +public: + static FsResult> Constructor( + shared_ptr taskSignal, shared_ptr signalListener); + FsResult Cancel(); + FsResult OnCancel(); + shared_ptr GetTaskSignal() const; + +public: + FsTaskSignal() = default; + ~FsTaskSignal() = default; + FsTaskSignal(const FsTaskSignal &other) = delete; + FsTaskSignal &operator=(const FsTaskSignal &other) = delete; + +private: + shared_ptr taskSignal_ = nullptr; + shared_ptr signalListener_ = nullptr; +}; + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_TASKSIGNAL_FS_TASK_SIGNAL_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/copy_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/copy_ani.cpp index e086c5ee1..7e84bce8f 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/copy_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/ani/copy_ani.cpp @@ -21,6 +21,10 @@ #include "error_handler.h" #include "file_utils.h" #include "filemgmt_libhilog.h" +#include "fs_task_signal.h" +#include "progress_listener_ani.h" +#include "task_signal_listener_ani.h" +#include "task_signal_wrapper.h" #include "type_converter.h" namespace OHOS { @@ -31,112 +35,100 @@ using namespace std; using namespace OHOS::FileManagement::ModuleFileIO; using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; -static void SetProgressListenerCb(ani_env *env, ani_ref &callback, CopyOptions &opts) +static bool ParseListenerFromOptionArg(ani_env *env, const ani_object &options, CopyOptions &opts) { + ani_ref prog; + if (ANI_OK != env->Object_GetPropertyByName_Ref(options, "progressListener", &prog)) { + HILOGE("Illegal options.progressListener type"); + return false; + } + + ani_boolean isUndefined = true; + env->Reference_IsUndefined(prog, &isUndefined); + if (isUndefined) { + return true; + } + + ani_ref cbRef; + if (ANI_OK != env->GlobalReference_Create(prog, &cbRef)) { + HILOGE("Illegal options.progressListener type"); + return false; + } + ani_vm *vm = nullptr; env->GetVM(&vm); + auto listener = CreateSharedPtr(vm, cbRef); + if (listener == nullptr) { + HILOGE("Failed to request heap memory."); + return false; + } - opts.listenerCb = [vm, &callback](uint64_t progressSize, uint64_t totalSize) -> void { - ani_status ret; - ani_object progress = {}; - auto classDesc = FS::ProgressInner::classDesc.c_str(); - ani_class cls; - - auto env = AniHelper::GetThreadEnv(vm); - if (env == nullptr) { - HILOGE("failed to GetThreadEnv"); - return; - } - - if (progressSize > MAX_VALUE || totalSize > MAX_VALUE) { - HILOGE("progressSize or totalSize exceed MAX_VALUE: %{private}" PRIu64 " %{private}" PRIu64, progressSize, - totalSize); - } - - if ((ret = env->FindClass(classDesc, &cls)) != ANI_OK) { - HILOGE("Not found %{private}s, err: %{private}d", classDesc, ret); - return; - } - - auto ctorDesc = FS::ProgressInner::ctorDesc.c_str(); - auto ctorSig = FS::ProgressInner::ctorSig.c_str(); - ani_method ctor; - if ((ret = env->Class_FindMethod(cls, ctorDesc, ctorSig, &ctor)) != ANI_OK) { - HILOGE("Not found ctor, err: %{private}d", ret); - return; - } - - if ((ret = env->Object_New(cls, ctor, &progress, ani_double(static_cast(progressSize)), - ani_double(static_cast(totalSize)))) != ANI_OK) { - HILOGE("New ProgressInner Fail, err: %{private}d", ret); - return; - } - - std::vector vec; - vec.push_back(progress); - ani_ref result; - ret = env->FunctionalObject_Call(static_cast(callback), vec.size(), vec.data(), &result); - if (ret != ANI_OK) { - HILOGE("FunctionalObject_Call, err: %{private}d", ret); - return; - } - }; + opts.progressListener = move(listener); + return true; } -static bool SetTaskSignal(ani_env *env, ani_ref ©Signal, CopyOptions &opts) +static bool ParseCopySignalFromOptionArg(ani_env *env, const ani_object &options, CopyOptions &opts) { - ani_status ret; - auto taskSignalEntityCore = CreateSharedPtr(); - if (taskSignalEntityCore == nullptr) { + ani_ref prog; + if (ANI_OK != env->Object_GetPropertyByName_Ref(options, "copySignal", &prog)) { + HILOGE("Illegal options.CopySignal type"); + return false; + } + + ani_boolean isUndefined = true; + env->Reference_IsUndefined(prog, &isUndefined); + if (isUndefined) { + return true; + } + + auto taskSignal = CreateSharedPtr(); + if (taskSignal == nullptr) { HILOGE("Failed to request heap memory."); return false; } - ret = env->Object_SetFieldByName_Long(static_cast(copySignal), "nativeTaskSignal", - reinterpret_cast(taskSignalEntityCore.get())); - if (ret != ANI_OK) { - HILOGE("Object set nativeTaskSignal err: %{private}d", ret); + auto signalObj = static_cast(prog); + ani_vm *vm = nullptr; + env->GetVM(&vm); + auto listener = CreateSharedPtr(vm, signalObj, taskSignal); + if (listener == nullptr) { + HILOGE("Failed to request heap memory."); return false; } - taskSignalEntityCore->taskSignal_ = std::make_shared(); - opts.taskSignalEntityCore = move(taskSignalEntityCore); + auto result = FsTaskSignal::Constructor(taskSignal, listener); + if (!result.IsSuccess()) { + return false; + } + auto copySignal = result.GetData().value(); + auto succ = TaskSignalWrapper::Wrap(env, signalObj, copySignal.get()); + if (!succ) { + return false; + } + + opts.copySignal = move(copySignal); return true; } -static tuple> ParseOptions(ani_env *env, ani_ref &cb, ani_object &options) +static tuple> ParseOptions(ani_env *env, ani_object &options) { ani_boolean isUndefined; - ani_status ret; env->Reference_IsUndefined(options, &isUndefined); if (isUndefined) { return { true, nullopt }; } CopyOptions opts; - ani_ref prog; - if ((ret = env->Object_GetPropertyByName_Ref(options, "progressListener", &prog)) != ANI_OK) { - HILOGE("Object_GetPropertyByName_Ref progressListener, err: %{private}d", ret); + auto succ = ParseListenerFromOptionArg(env, options, opts); + if (!succ) { return { false, nullopt }; } - env->Reference_IsUndefined(prog, &isUndefined); - if (!isUndefined) { - env->GlobalReference_Create(prog, &cb); - SetProgressListenerCb(env, cb, opts); - } - ani_ref signal; - if ((ret = env->Object_GetPropertyByName_Ref(options, "copySignal", &signal)) != ANI_OK) { - HILOGE("Object_GetPropertyByName_Ref copySignal, err: %{private}d", ret); + succ = ParseCopySignalFromOptionArg(env, options, opts); + if (!succ) { return { false, nullopt }; } - env->Reference_IsUndefined(signal, &isUndefined); - if (!isUndefined) { - if (!SetTaskSignal(env, signal, opts)) { - return { false, nullopt }; - } - } return { true, make_optional(move(opts)) }; } @@ -146,24 +138,15 @@ void CopyAni::CopySync( { auto [succSrc, src] = TypeConverter::ToUTF8String(env, srcUri); auto [succDest, dest] = TypeConverter::ToUTF8String(env, destUri); - if (!succSrc || !succDest) { - HILOGE("The first/second argument requires filepath"); - ErrorHandler::Throw(env, EINVAL); - return; - } + auto [succOpts, opts] = ParseOptions(env, options); - ani_ref cb; - auto [succOpts, opts] = ParseOptions(env, cb, options); - if (!succOpts) { - HILOGE("Failed to parse opts"); - ErrorHandler::Throw(env, EINVAL); + if (!succSrc || !succDest || !succOpts) { + HILOGE("The first/second/third argument requires uri/uri/napi_function"); + ErrorHandler::Throw(env, E_PARAMS); return; } auto ret = CopyCore::DoCopy(src, dest, opts); - if (opts.has_value() && opts->listenerCb != nullptr) { - env->GlobalReference_Delete(cb); - } if (!ret.IsSuccess()) { HILOGE("DoCopy failed!"); const FsError &err = ret.GetError(); diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_core.cpp b/interfaces/kits/js/src/mod_fs/properties/copy_core.cpp index f3d4613d7..45403ca6d 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy_core.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copy_core.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2024 Huawei Device Co., Ltd. + * Copyright (c) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -60,25 +60,9 @@ constexpr int BUF_SIZE = 1024; constexpr size_t MAX_SIZE = 1024 * 1024 * 4; constexpr std::chrono::milliseconds NOTIFY_PROGRESS_DELAY(300); std::recursive_mutex CopyCore::mutex_; -std::map> CopyCore::jsCbMap_; +std::map> CopyCore::callbackMap_; -static string GetModeFromFlags(unsigned int flags) -{ - const string readMode = "r"; - const string writeMode = "w"; - const string appendMode = "a"; - const string truncMode = "t"; - string mode = readMode; - mode += (((flags & O_RDWR) == O_RDWR) ? writeMode : ""); - mode = (((flags & O_WRONLY) == O_WRONLY) ? writeMode : mode); - if (mode != readMode) { - mode += ((flags & O_TRUNC) ? truncMode : ""); - mode += ((flags & O_APPEND) ? appendMode : ""); - } - return mode; -} - -static int OpenSrcFile(const string &srcPth, std::shared_ptr infos, int32_t &srcFd) +static int OpenSrcFile(const string &srcPth, std::shared_ptr infos, int32_t &srcFd) { Uri uri(infos->srcUri); if (uri.GetAuthority() == MEDIA) { @@ -93,7 +77,7 @@ static int OpenSrcFile(const string &srcPth, std::shared_ptr info HILOGE("Failed to connect to datashare"); return E_PERMISSION; } - srcFd = dataShareHelper->OpenFile(uri, GetModeFromFlags(O_RDONLY)); + srcFd = dataShareHelper->OpenFile(uri, FsUtils::GetModeFromFlags(O_RDONLY)); if (srcFd < 0) { HILOGE("Open media uri by data share fail. ret = %{public}d", srcFd); return EPERM; @@ -108,18 +92,17 @@ static int OpenSrcFile(const string &srcPth, std::shared_ptr info return ERRNO_NOERR; } -static int SendFileCore(std::unique_ptr srcFdg, - std::unique_ptr destFdg, - std::shared_ptr infos) +static int SendFileCore(std::unique_ptr srcFdg, std::unique_ptr destFdg, + std::shared_ptr infos) { - std::unique_ptr sendFileReq = { - new (nothrow) uv_fs_t, FsUtils::FsReqCleanup }; + std::unique_ptr sendFileReq = { new (nothrow) uv_fs_t, + FsUtils::FsReqCleanup }; if (sendFileReq == nullptr) { HILOGE("Failed to request heap memory."); return ENOMEM; } int64_t offset = 0; - struct stat srcStat{}; + struct stat srcStat {}; if (fstat(srcFdg->GetFD(), &srcStat) < 0) { HILOGE("Failed to get stat of file by fd: %{public}d ,errno = %{public}d", srcFdg->GetFD(), errno); return errno; @@ -127,15 +110,13 @@ static int SendFileCore(std::unique_ptr srcFdg, int32_t ret = 0; int64_t size = static_cast(srcStat.st_size); while (size >= 0) { - ret = uv_fs_sendfile(nullptr, sendFileReq.get(), destFdg->GetFD(), srcFdg->GetFD(), - offset, MAX_SIZE, nullptr); + ret = uv_fs_sendfile(nullptr, sendFileReq.get(), destFdg->GetFD(), srcFdg->GetFD(), offset, MAX_SIZE, nullptr); if (ret < 0) { HILOGE("Failed to sendfile by errno : %{public}d", errno); return errno; } if (infos != nullptr && infos->taskSignal != nullptr) { if (infos->taskSignal->CheckCancelIfNeed(infos->srcPath)) { - HILOGE("===Copy Task Canceled Success"); return ECANCELED; } } @@ -159,10 +140,7 @@ bool CopyCore::IsValidUri(const std::string &uri) bool CopyCore::ValidOperand(std::string uriStr) { - if (IsValidUri(uriStr)) { - return true; - } - return false; + return IsValidUri(uriStr); } bool CopyCore::IsRemoteUri(const std::string &uri) @@ -228,7 +206,7 @@ int CopyCore::CheckOrCreatePath(const std::string &destPath) return ERRNO_NOERR; } -int CopyCore::CopyFile(const string &src, const string &dest, std::shared_ptr infos) +int CopyCore::CopyFile(const string &src, const string &dest, std::shared_ptr infos) { HILOGD("src = %{public}s, dest = %{public}s", GetAnonyString(src).c_str(), GetAnonyString(dest).c_str()); int32_t srcFd = -1; @@ -264,7 +242,7 @@ int CopyCore::MakeDir(const string &path) return ERRNO_NOERR; } -int CopyCore::CopySubDir(const string &srcPath, const string &destPath, std::shared_ptr infos) +int CopyCore::CopySubDir(const string &srcPath, const string &destPath, std::shared_ptr infos) { std::error_code errCode; if (!filesystem::exists(destPath, errCode) && errCode.value() == ERRNO_NOERR) { @@ -286,14 +264,14 @@ int CopyCore::CopySubDir(const string &srcPath, const string &destPath, std::sha } { std::lock_guard lock(CopyCore::mutex_); - auto iter = CopyCore::jsCbMap_.find(*infos); + auto iter = CopyCore::callbackMap_.find(*infos); auto receiveInfo = CreateSharedPtr(); if (receiveInfo == nullptr) { HILOGE("Failed to request heap memory."); return ENOMEM; } receiveInfo->path = destPath; - if (iter == CopyCore::jsCbMap_.end() || iter->second == nullptr) { + if (iter == CopyCore::callbackMap_.end() || iter->second == nullptr) { HILOGE("Failed to find infos, srcPath = %{public}s, destPath = %{public}s", GetAnonyString(infos->srcPath).c_str(), GetAnonyString(infos->destPath).c_str()); return UNKNOWN_ERR; @@ -329,11 +307,11 @@ static void Deleter(struct NameList *arg) arg = nullptr; } -std::string CopyCore::GetRealPath(const std::string& path) +std::string CopyCore::GetRealPath(const std::string &path) { fs::path tempPath(path); - fs::path realPath{}; - for (const auto& component : tempPath) { + fs::path realPath {}; + for (const auto &component : tempPath) { if (component == ".") { continue; } else if (component == "..") { @@ -345,7 +323,7 @@ std::string CopyCore::GetRealPath(const std::string& path) return realPath.string(); } -uint64_t CopyCore::GetDirSize(std::shared_ptr infos, std::string path) +uint64_t CopyCore::GetDirSize(std::shared_ptr infos, std::string path) { unique_ptr pNameList = { new (nothrow) struct NameList, Deleter }; if (pNameList == nullptr) { @@ -374,7 +352,7 @@ uint64_t CopyCore::GetDirSize(std::shared_ptr infos, std::string return size; } -int CopyCore::RecurCopyDir(const string &srcPath, const string &destPath, std::shared_ptr infos) +int CopyCore::RecurCopyDir(const string &srcPath, const string &destPath, std::shared_ptr infos) { unique_ptr pNameList = { new (nothrow) struct NameList, Deleter }; if (pNameList == nullptr) { @@ -404,7 +382,7 @@ int CopyCore::RecurCopyDir(const string &srcPath, const string &destPath, std::s return ERRNO_NOERR; } -int CopyCore::CopyDirFunc(const string &src, const string &dest, std::shared_ptr infos) +int CopyCore::CopyDirFunc(const string &src, const string &dest, std::shared_ptr infos) { HILOGD("CopyDirFunc in, src = %{public}s, dest = %{public}s", GetAnonyString(src).c_str(), GetAnonyString(dest).c_str()); @@ -421,7 +399,7 @@ int CopyCore::CopyDirFunc(const string &src, const string &dest, std::shared_ptr return CopySubDir(src, destStr, infos); } -int CopyCore::ExecLocal(std::shared_ptr infos, std::shared_ptr callback) +int CopyCore::ExecLocal(std::shared_ptr infos, std::shared_ptr callback) { if (infos->isFile) { if (infos->srcPath == infos->destPath) { @@ -446,8 +424,7 @@ int CopyCore::ExecLocal(std::shared_ptr infos, std::shared_ptr infos, - std::shared_ptr callback) +int CopyCore::SubscribeLocalListener(std::shared_ptr infos, std::shared_ptr callback) { infos->notifyFd = inotify_init(); if (infos->notifyFd < 0) { @@ -465,7 +442,7 @@ int CopyCore::SubscribeLocalListener(std::shared_ptr infos, if (newWd < 0) { auto errCode = errno; HILOGE("Failed to add watch, errno = %{public}d, notifyFd: %{public}d, destPath: %{public}s", errno, - infos->notifyFd, infos->destPath.c_str()); + infos->notifyFd, infos->destPath.c_str()); CloseNotifyFdLocked(infos, callback); return errCode; } @@ -489,66 +466,73 @@ int CopyCore::SubscribeLocalListener(std::shared_ptr infos, return err; } -std::shared_ptr CopyCore::RegisterListener(const std::shared_ptr &infos) +std::shared_ptr CopyCore::RegisterListener(const std::shared_ptr &infos) { - auto callback = CreateSharedPtr(infos->listenerCb); + auto callback = CreateSharedPtr(infos->listener); if (callback == nullptr) { HILOGE("Failed to request heap memory."); return nullptr; } std::lock_guard lock(mutex_); - auto iter = jsCbMap_.find(*infos); - if (iter != jsCbMap_.end()) { + auto iter = callbackMap_.find(*infos); + if (iter != callbackMap_.end()) { HILOGE("CopyCore::RegisterListener, already registered."); return nullptr; } - jsCbMap_.insert({ *infos, callback }); + callbackMap_.insert({ *infos, callback }); return callback; } -void CopyCore::UnregisterListener(std::shared_ptr fileInfos) +void CopyCore::UnregisterListener(std::shared_ptr fileInfos) { if (fileInfos == nullptr) { HILOGE("fileInfos is nullptr"); return; } std::lock_guard lock(mutex_); - auto iter = jsCbMap_.find(*fileInfos); - if (iter == jsCbMap_.end()) { + auto iter = callbackMap_.find(*fileInfos); + if (iter == callbackMap_.end()) { HILOGI("It is not be registered."); return; } - jsCbMap_.erase(*fileInfos); + callbackMap_.erase(*fileInfos); } -void CopyCore::ReceiveComplete(std::shared_ptr entry) +void CopyCore::ReceiveComplete(std::shared_ptr entry) { if (entry == nullptr) { HILOGE("entry pointer is nullptr."); return; } + if (entry->callback == nullptr) { + HILOGE("entry callback pointer is nullptr."); + return; + } auto processedSize = entry->progressSize; if (processedSize < entry->callback->maxProgressSize) { - HILOGE("enter ReceiveComplete2"); return; } entry->callback->maxProgressSize = processedSize; - - entry->callback->listenerCb(processedSize, entry->totalSize); + auto listener = entry->callback->listener; + if (listener == nullptr) { + HILOGE("listener pointer is nullptr."); + return; + } + listener->InvokeListener(processedSize, entry->totalSize); } -UvEntryCore *CopyCore::GetUVEntry(std::shared_ptr infos) +FsUvEntry *CopyCore::GetUVEntry(std::shared_ptr infos) { - UvEntryCore *entry = nullptr; + FsUvEntry *entry = nullptr; { std::lock_guard lock(mutex_); - auto iter = jsCbMap_.find(*infos); - if (iter == jsCbMap_.end()) { + auto iter = callbackMap_.find(*infos); + if (iter == callbackMap_.end()) { HILOGE("Failed to find callback"); return nullptr; } auto callback = iter->second; - entry = new (std::nothrow) UvEntryCore(iter->second, infos); + entry = new (std::nothrow) FsUvEntry(iter->second, infos); if (entry == nullptr) { HILOGE("entry ptr is nullptr."); return nullptr; @@ -559,9 +543,9 @@ UvEntryCore *CopyCore::GetUVEntry(std::shared_ptr infos) return entry; } -void CopyCore::OnFileReceive(std::shared_ptr infos) +void CopyCore::OnFileReceive(std::shared_ptr infos) { - std::shared_ptr entry(GetUVEntry(infos)); + std::shared_ptr entry(GetUVEntry(infos)); if (entry == nullptr) { HILOGE("failed to get uv entry"); return; @@ -569,25 +553,22 @@ void CopyCore::OnFileReceive(std::shared_ptr infos) ReceiveComplete(entry); } -std::shared_ptr CopyCore::GetReceivedInfo(int wd, std::shared_ptr callback) +std::shared_ptr CopyCore::GetReceivedInfo(int wd, std::shared_ptr callback) { - auto it = find_if(callback->wds.begin(), callback->wds.end(), [wd](const auto& item) { - return item.first == wd; - }); + auto it = find_if(callback->wds.begin(), callback->wds.end(), [wd](const auto &item) { return item.first == wd; }); if (it != callback->wds.end()) { return it->second; } return nullptr; } -bool CopyCore::CheckFileValid(const std::string &filePath, std::shared_ptr infos) +bool CopyCore::CheckFileValid(const std::string &filePath, std::shared_ptr infos) { return infos->filePaths.count(filePath) != 0; } -int CopyCore::UpdateProgressSize(const std::string &filePath, - std::shared_ptr receivedInfo, - std::shared_ptr callback) +int CopyCore::UpdateProgressSize( + const std::string &filePath, std::shared_ptr receivedInfo, std::shared_ptr callback) { auto [err, fileSize] = GetFileSize(filePath); if (err != ERRNO_NOERR) { @@ -608,18 +589,18 @@ int CopyCore::UpdateProgressSize(const std::string &filePath, return ERRNO_NOERR; } -std::shared_ptr CopyCore::GetRegisteredListener(std::shared_ptr infos) +std::shared_ptr CopyCore::GetRegisteredListener(std::shared_ptr infos) { std::lock_guard lock(mutex_); - auto iter = jsCbMap_.find(*infos); - if (iter == jsCbMap_.end()) { + auto iter = callbackMap_.find(*infos); + if (iter == callbackMap_.end()) { HILOGE("It is not registered."); return nullptr; } return iter->second; } -void CopyCore::CloseNotifyFd(std::shared_ptr infos, std::shared_ptr callback) +void CopyCore::CloseNotifyFd(std::shared_ptr infos, std::shared_ptr callback) { callback->closed = false; infos->eventFd = -1; @@ -631,7 +612,7 @@ void CopyCore::CloseNotifyFd(std::shared_ptr infos, std::shared_p } } -void CopyCore::CloseNotifyFdLocked(std::shared_ptr infos, std::shared_ptr callback) +void CopyCore::CloseNotifyFdLocked(std::shared_ptr infos, std::shared_ptr callback) { { lock_guard lock(callback->readMutex); @@ -645,7 +626,7 @@ void CopyCore::CloseNotifyFdLocked(std::shared_ptr infos, std::sh } tuple CopyCore::HandleProgress( - inotify_event *event, std::shared_ptr infos, std::shared_ptr callback) + inotify_event *event, std::shared_ptr infos, std::shared_ptr callback) { if (callback == nullptr) { return { true, EINVAL, false }; @@ -674,14 +655,15 @@ tuple CopyCore::HandleProgress( return { true, callback->errorCode, true }; } -void CopyCore::ReadNotifyEvent(std::shared_ptr infos) +void CopyCore::ReadNotifyEvent(std::shared_ptr infos) { char buf[BUF_SIZE] = { 0 }; struct inotify_event *event = nullptr; int len = 0; int64_t index = 0; auto callback = GetRegisteredListener(infos); - while (infos->run && ((len = read(infos->notifyFd, &buf, sizeof(buf))) < 0) && (errno == EINTR)) {} + while (infos->run && ((len = read(infos->notifyFd, &buf, sizeof(buf))) < 0) && (errno == EINTR)) { + } while (infos->run && index < len) { event = reinterpret_cast(buf + index); auto [needContinue, errCode, needSend] = HandleProgress(event, infos, callback); @@ -706,7 +688,7 @@ void CopyCore::ReadNotifyEvent(std::shared_ptr infos) } } -void CopyCore::ReadNotifyEventLocked(std::shared_ptr infos, std::shared_ptr callback) +void CopyCore::ReadNotifyEventLocked(std::shared_ptr infos, std::shared_ptr callback) { { std::lock_guard lock(callback->readMutex); @@ -728,7 +710,7 @@ void CopyCore::ReadNotifyEventLocked(std::shared_ptr infos, std:: } } -void CopyCore::GetNotifyEvent(std::shared_ptr infos) +void CopyCore::GetNotifyEvent(std::shared_ptr infos) { auto callback = GetRegisteredListener(infos); if (callback == nullptr) { @@ -760,17 +742,16 @@ void CopyCore::GetNotifyEvent(std::shared_ptr infos) } { std::unique_lock lock(callback->cvLock); - callback->cv.wait_for(lock, std::chrono::microseconds(SLEEP_TIME), [callback]() -> bool { - return callback->notifyFd == -1; - }); + callback->cv.wait_for( + lock, std::chrono::microseconds(SLEEP_TIME), [callback]() -> bool { return callback->notifyFd == -1; }); } } } -tuple> CopyCore::CreateFileInfos( - const std::string &srcUri, const std::string &destUri, std::optional options) +tuple> CopyCore::CreateFileInfos( + const std::string &srcUri, const std::string &destUri, const std::optional &options) { - auto infos = CreateSharedPtr(); + auto infos = CreateSharedPtr(); if (infos == nullptr) { HILOGE("Failed to request heap memory."); return { ENOMEM, nullptr }; @@ -785,29 +766,29 @@ tuple> CopyCore::CreateFileInfos( infos->destPath = GetRealPath(infos->destPath); infos->isFile = IsMediaUri(infos->srcUri) || IsFile(infos->srcPath); infos->notifyTime = std::chrono::steady_clock::now() + NOTIFY_PROGRESS_DELAY; - if (options != std::nullopt) { - if (options.value().listenerCb) { + if (options.has_value()) { + auto listener = options.value().progressListener; + if (listener) { infos->hasListener = true; - infos->listenerCb = options.value().listenerCb; + infos->listener = listener; } - if (options.value().taskSignalEntityCore != nullptr) { - infos->taskSignal = options.value().taskSignalEntityCore->taskSignal_; + auto copySignal = options.value().copySignal; + if (copySignal) { + infos->taskSignal = copySignal->GetTaskSignal(); } } return { ERRNO_NOERR, infos }; } -void CopyCore::StartNotify(std::shared_ptr infos, std::shared_ptr callback) +void CopyCore::StartNotify(std::shared_ptr infos, std::shared_ptr callback) { if (infos->hasListener && callback != nullptr) { - callback->notifyHandler = std::thread([infos] { - GetNotifyEvent(infos); - }); + callback->notifyHandler = std::thread([infos] { GetNotifyEvent(infos); }); } } -int CopyCore::ExecCopy(std::shared_ptr infos) +int CopyCore::ExecCopy(std::shared_ptr infos) { if (infos->isFile && IsFile(infos->destPath)) { // copyFile @@ -826,25 +807,18 @@ int CopyCore::ExecCopy(std::shared_ptr infos) return EINVAL; } -int CopyCore::ValidParam(const string& src, const string& dest, - std::optional options, - std::shared_ptr &fileInfos) +bool CopyCore::ValidParams(const string &src, const string &dest) { auto succSrc = ValidOperand(src); auto succDest = ValidOperand(dest); if (!succSrc || !succDest) { HILOGE("The first/second argument requires uri/uri"); - return E_PARAMS; - } - auto [errCode, infos] = CreateFileInfos(src, dest, options); - if (errCode != ERRNO_NOERR) { - return errCode; + return false; } - fileInfos = infos; - return ERRNO_NOERR; + return true; } -void CopyCore::WaitNotifyFinished(std::shared_ptr callback) +void CopyCore::WaitNotifyFinished(std::shared_ptr callback) { if (callback != nullptr) { if (callback->notifyHandler.joinable()) { @@ -853,7 +827,7 @@ void CopyCore::WaitNotifyFinished(std::shared_ptr callback) } } -void CopyCore::CopyComplete(std::shared_ptr infos, std::shared_ptr callback) +void CopyCore::CopyComplete(std::shared_ptr infos, std::shared_ptr callback) { if (callback != nullptr && infos->hasListener) { callback->progressSize = callback->totalSize; @@ -861,12 +835,16 @@ void CopyCore::CopyComplete(std::shared_ptr infos, std::shared_pt } } -FsResult CopyCore::DoCopy(const string& src, const string& dest, std::optional &options) +FsResult CopyCore::DoCopy(const string &src, const string &dest, std::optional &options) { - std::shared_ptr infos = nullptr; - auto result = ValidParam(src, dest, options, infos); - if (result != ERRNO_NOERR) { - return FsResult::Error(result); + auto isValid = ValidParams(src, dest); + if (!isValid) { + return FsResult::Error(E_PARAMS); + } + + auto [errCode, infos] = CreateFileInfos(src, dest, options); + if (errCode != ERRNO_NOERR) { + return FsResult::Error(errCode); } auto callback = RegisterListener(infos); @@ -878,23 +856,25 @@ FsResult CopyCore::DoCopy(const string& src, const string& dest, std::opti if (infos->taskSignal != nullptr) { infos->taskSignal->MarkRemoteTask(); } - auto ret = TransListenerCore::CopyFileFromSoftBus(infos->srcUri, infos->destUri, - infos, std::move(callback)); + auto ret = TransListenerCore::CopyFileFromSoftBus(infos->srcUri, infos->destUri, infos, std::move(callback)); + UnregisterListener(infos); if (ret != ERRNO_NOERR) { return FsResult::Error(ret); } else { return FsResult::Success(); } } - result = CopyCore::ExecLocal(infos, callback); + auto result = CopyCore::ExecLocal(infos, callback); CloseNotifyFdLocked(infos, callback); infos->run = false; WaitNotifyFinished(callback); if (result != ERRNO_NOERR) { infos->exceptionCode = result; + UnregisterListener(infos); return FsResult::Error(infos->exceptionCode); } CopyComplete(infos, callback); + UnregisterListener(infos); if (infos->exceptionCode != ERRNO_NOERR) { return FsResult::Error(infos->exceptionCode); } else { diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_core.h b/interfaces/kits/js/src/mod_fs/properties/copy_core.h index 58aa4f999..387792260 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy_core.h +++ b/interfaces/kits/js/src/mod_fs/properties/copy_core.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,20 +13,20 @@ * limitations under the License. */ -#ifndef FILEMANAGEMENT_FILE_API_COPY_CORE_H -#define FILEMANAGEMENT_FILE_API_COPY_CORE_H +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_CORE_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_CORE_H #include #include #include -#include #include +#include #include "bundle_mgr_client_impl.h" #include "filemgmt_libfs.h" #include "filemgmt_libhilog.h" -#include "task_signal.h" -#include "task_signal_entity_core.h" +#include "fs_task_signal.h" +#include "i_progress_listener.h" namespace OHOS { namespace FileManagement { @@ -34,12 +34,10 @@ namespace ModuleFileIO { using namespace std; using namespace OHOS::AppExecFwk; using namespace DistributedFS::ModuleTaskSignal; -const uint64_t MAX_VALUE = 0x7FFFFFFFFFFFFFFF; -typedef std::function ProgressListenerCb; struct CopyOptions { - ProgressListenerCb listenerCb; - std::shared_ptr taskSignalEntityCore; + std::shared_ptr progressListener; + std::shared_ptr copySignal; }; struct ReceiveInfo { @@ -47,8 +45,8 @@ struct ReceiveInfo { std::map fileList; // filename, proceededSize }; -struct CallbackObjectCore { - ProgressListenerCb listenerCb; +struct FsCallbackObject { + std::shared_ptr listener = nullptr; int32_t notifyFd = -1; int32_t eventFd = -1; std::vector>> wds; @@ -62,7 +60,7 @@ struct CallbackObjectCore { std::mutex cvLock; bool reading = false; bool closed = false; - explicit CallbackObjectCore(ProgressListenerCb cb) : listenerCb(cb) {} + explicit FsCallbackObject(std::shared_ptr listener) : listener(listener) {} void CloseFd() { @@ -80,13 +78,13 @@ struct CallbackObjectCore { notifyFd = -1; } - ~CallbackObjectCore() + ~FsCallbackObject() { CloseFd(); } }; -struct FileInfosCore { +struct FsFileInfos { std::string srcUri; std::string destUri; std::string srcPath; @@ -97,15 +95,15 @@ struct FileInfosCore { int32_t eventFd = -1; bool run = true; bool hasListener = false; - ProgressListenerCb listenerCb; + std::shared_ptr listener = nullptr; std::shared_ptr taskSignal = nullptr; std::set filePaths; - int exceptionCode = ERRNO_NOERR; // notify copy thread or listener thread has exceptions. - bool operator==(const FileInfosCore &infos) const + int exceptionCode = ERRNO_NOERR; // notify copy thread or listener thread has exceptions. + bool operator==(const FsFileInfos &infos) const { return (srcUri == infos.srcUri && destUri == infos.destUri); } - bool operator<(const FileInfosCore &infos) const + bool operator<(const FsFileInfos &infos) const { if (srcUri == infos.srcUri) { return destUri < infos.destUri; @@ -114,73 +112,65 @@ struct FileInfosCore { } }; -struct UvEntryCore { - std::shared_ptr callback; - std::shared_ptr fileInfos; +struct FsUvEntry { + std::shared_ptr callback; + std::shared_ptr fileInfos; uint64_t progressSize = 0; uint64_t totalSize = 0; - UvEntryCore(const std::shared_ptr &cb, std::shared_ptr fileInfos) + FsUvEntry(const std::shared_ptr &cb, std::shared_ptr fileInfos) : callback(cb), fileInfos(fileInfos) { } - explicit UvEntryCore(const std::shared_ptr &cb) : callback(cb) {} + explicit FsUvEntry(const std::shared_ptr &cb) : callback(cb) {} }; class CopyCore final { public: - static std::map> jsCbMap_; - static void UnregisterListener(std::shared_ptr fileInfos); - static std::recursive_mutex mutex_; - static FsResult DoCopy(const string& src, const string& dest, std::optional &options); + static FsResult DoCopy(const string &src, const string &dest, std::optional &options); private: - // operator of napi + // operator of params static bool ValidOperand(std::string uriStr); static int CheckOrCreatePath(const std::string &destPath); - static int ValidParam(const string& src, const string& dest, std::optional options, - std::shared_ptr &fileInfos); + static bool ValidParams(const string &src, const string &dest); // operator of local listener - static int ExecLocal(std::shared_ptr infos, std::shared_ptr callback); - static void CopyComplete(std::shared_ptr infos, std::shared_ptr callback); - static void WaitNotifyFinished(std::shared_ptr callback); - static void ReadNotifyEvent(std::shared_ptr infos); - static void ReadNotifyEventLocked(std::shared_ptr infos, - std::shared_ptr callback); - static int SubscribeLocalListener(std::shared_ptr infos, - std::shared_ptr callback); - static std::shared_ptr RegisterListener( - const std::shared_ptr &infos); - static void OnFileReceive(std::shared_ptr infos); - static void GetNotifyEvent(std::shared_ptr infos); - static void StartNotify(std::shared_ptr infos, std::shared_ptr callback); - static UvEntryCore *GetUVEntry(std::shared_ptr infos); - static void ReceiveComplete(std::shared_ptr entry); - static std::shared_ptr GetRegisteredListener(std::shared_ptr infos); - static void CloseNotifyFd(std::shared_ptr infos, std::shared_ptr callback); - static void CloseNotifyFdLocked(std::shared_ptr infos, - std::shared_ptr callback); + static std::shared_ptr RegisterListener(const std::shared_ptr &infos); + static std::shared_ptr GetRegisteredListener(std::shared_ptr infos); + static void UnregisterListener(std::shared_ptr fileInfos); + static int ExecLocal(std::shared_ptr infos, std::shared_ptr callback); + static void CopyComplete(std::shared_ptr infos, std::shared_ptr callback); + static void WaitNotifyFinished(std::shared_ptr callback); + static void ReadNotifyEvent(std::shared_ptr infos); + static void ReadNotifyEventLocked(std::shared_ptr infos, std::shared_ptr callback); + static int SubscribeLocalListener(std::shared_ptr infos, std::shared_ptr callback); + static void OnFileReceive(std::shared_ptr infos); + static void GetNotifyEvent(std::shared_ptr infos); + static void StartNotify(std::shared_ptr infos, std::shared_ptr callback); + static FsUvEntry *GetUVEntry(std::shared_ptr infos); + static void ReceiveComplete(std::shared_ptr entry); + static void CloseNotifyFd(std::shared_ptr infos, std::shared_ptr callback); + static void CloseNotifyFdLocked(std::shared_ptr infos, std::shared_ptr callback); // operator of file - static int RecurCopyDir(const string &srcPath, const string &destPath, std::shared_ptr infos); + static int RecurCopyDir(const string &srcPath, const string &destPath, std::shared_ptr infos); static tuple GetFileSize(const std::string &path); - static uint64_t GetDirSize(std::shared_ptr infos, std::string path); - static int CopyFile(const string &src, const string &dest, std::shared_ptr infos); + static uint64_t GetDirSize(std::shared_ptr infos, std::string path); + static int CopyFile(const string &src, const string &dest, std::shared_ptr infos); static int MakeDir(const string &path); - static int CopySubDir(const string &srcPath, const string &destPath, std::shared_ptr infos); - static int CopyDirFunc(const string &src, const string &dest, std::shared_ptr infos); - static tuple> CreateFileInfos( - const std::string &srcUri, const std::string &destUri, std::optional options); - static int ExecCopy(std::shared_ptr infos); + static int CopySubDir(const string &srcPath, const string &destPath, std::shared_ptr infos); + static int CopyDirFunc(const string &src, const string &dest, std::shared_ptr infos); + static tuple> CreateFileInfos( + const std::string &srcUri, const std::string &destUri, const std::optional &options); + static int ExecCopy(std::shared_ptr infos); // operator of file size - static int UpdateProgressSize(const std::string &filePath, - std::shared_ptr receivedInfo, - std::shared_ptr callback); + static int UpdateProgressSize(const std::string &filePath, std::shared_ptr receivedInfo, + std::shared_ptr callback); static tuple HandleProgress( - inotify_event *event, std::shared_ptr infos, std::shared_ptr callback); - static std::shared_ptr GetReceivedInfo(int wd, std::shared_ptr callback); - static bool CheckFileValid(const std::string &filePath, std::shared_ptr infos); + inotify_event *event, std::shared_ptr infos, std::shared_ptr callback); + static std::shared_ptr GetReceivedInfo(int wd, std::shared_ptr callback); + static bool CheckFileValid(const std::string &filePath, std::shared_ptr infos); // operator of uri or path static bool IsValidUri(const std::string &uri); @@ -189,10 +179,14 @@ private: static bool IsFile(const std::string &path); static bool IsMediaUri(const std::string &uriPath); static std::string ConvertUriToPath(const std::string &uri); - static std::string GetRealPath(const std::string& path); + static std::string GetRealPath(const std::string &path); + +private: + static std::recursive_mutex mutex_; + static std::map> callbackMap_; }; } // namespace ModuleFileIO } // namespace FileManagement } // namespace OHOS -#endif // FILEMANAGEMENT_FILE_API_COPY_CORE_H \ No newline at end of file +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_CORE_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_listener/ani/progress_listener_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/copy_listener/ani/progress_listener_ani.cpp new file mode 100644 index 000000000..58be19337 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/copy_listener/ani/progress_listener_ani.cpp @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "progress_listener_ani.h" + +#include +#include "ani_helper.h" +#include "ani_signature.h" +#include "file_utils.h" +#include "filemgmt_libhilog.h" +#include "type_converter.h" + +namespace OHOS::FileManagement::ModuleFileIO::ANI { +using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; + +void ProgressListenerAni::InvokeListener(uint64_t progressSize, uint64_t totalSize) const +{ + auto task = [this, progressSize, totalSize]() { SendCopyProgress(progressSize, totalSize); }; + AniHelper::SendEventToMainThread(task); +} + +static ani_object WrapCopyProgress(ani_env *env, uint64_t progressSize, uint64_t totalSize) +{ + auto classDesc = FS::ProgressInner::classDesc.c_str(); + ani_class cls; + if (ANI_OK != env->FindClass(classDesc, &cls)) { + HILOGE("Cannot find class %{private}s", classDesc); + return nullptr; + } + auto ctorDesc = FS::ProgressInner::ctorDesc.c_str(); + auto ctorSig = FS::ProgressInner::ctorSig.c_str(); + ani_method ctor; + if (ANI_OK != env->Class_FindMethod(cls, ctorDesc, ctorSig, &ctor)) { + HILOGE("Cannot find constructor method for class %{private}s", classDesc); + return nullptr; + } + + const ani_double aniProgressSize = static_cast(progressSize <= MAX_VALUE ? progressSize : 0); + const ani_double aniTotalSize = static_cast(totalSize <= MAX_VALUE ? totalSize : 0); + + ani_object obj; + if (ANI_OK != env->Object_New(cls, ctor, &obj, aniProgressSize, aniTotalSize)) { + HILOGE("Create %{private}s object failed!", classDesc); + return nullptr; + } + return obj; +} + +void ProgressListenerAni::SendCopyProgress(uint64_t progressSize, uint64_t totalSize) const +{ + if (vm == nullptr) { + HILOGE("Cannot send copy progress because the vm is null."); + return; + } + if (listener == nullptr) { + HILOGE("Cannot send copy progress because the listener is null."); + return; + } + ani_env *env = AniHelper::GetThreadEnv(vm); + if (env == nullptr) { + HILOGE("Cannot send copy progress because the env is null."); + return; + } + auto evtObj = WrapCopyProgress(env, progressSize, totalSize); + if (evtObj == nullptr) { + HILOGE("Create copy progress obj failed!"); + return; + } + vector args = { static_cast(evtObj) }; + auto argc = args.size(); + ani_ref result; + auto cbObj = static_cast(listener); + auto status = env->FunctionalObject_Call(cbObj, argc, args.data(), &result); + if (status != ANI_OK) { + HILOGE("Failed to call FunctionalObject_Call, status: %{public}d", static_cast(status)); + return; + } +} + +} // namespace OHOS::FileManagement::ModuleFileIO::ANI diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_listener/ani/progress_listener_ani.h b/interfaces/kits/js/src/mod_fs/properties/copy_listener/ani/progress_listener_ani.h new file mode 100644 index 000000000..07894982a --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/copy_listener/ani/progress_listener_ani.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_LISTENER_ANI_PROGRESS_LISTENER_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_LISTENER_ANI_PROGRESS_LISTENER_H + +#include +#include +#include "i_progress_listener.h" + +namespace OHOS::FileManagement::ModuleFileIO::ANI { + +class ProgressListenerAni final : public IProgressListener { +public: + ProgressListenerAni(ani_vm *vm, const ani_ref &listener) : vm(vm), listener(listener) {} + void InvokeListener(uint64_t progressSize, uint64_t totalSize) const override; + +private: + void SendCopyProgress(uint64_t progressSize, uint64_t totalSize) const; + +private: + ani_vm *vm; + ani_ref listener; +}; + +} // namespace OHOS::FileManagement::ModuleFileIO::ANI +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_LISTENER_ANI_PROGRESS_LISTENER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_tasksignal/task_signal_entity_core.cpp b/interfaces/kits/js/src/mod_fs/properties/copy_listener/i_progress_listener.h similarity index 50% rename from interfaces/kits/js/src/mod_fs/class_tasksignal/task_signal_entity_core.cpp rename to interfaces/kits/js/src/mod_fs/properties/copy_listener/i_progress_listener.h index 85dd60f91..f51f4f421 100644 --- a/interfaces/kits/js/src/mod_fs/class_tasksignal/task_signal_entity_core.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copy_listener/i_progress_listener.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,18 +13,19 @@ * limitations under the License. */ -#include "task_signal_entity_core.h" -#include "filemgmt_libhilog.h" +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_LISTENER_I_PROGRESS_LISTENER_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_LISTENER_I_PROGRESS_LISTENER_H + +#include namespace OHOS::FileManagement::ModuleFileIO { -TaskSignalEntityCore::~TaskSignalEntityCore() {} +const uint64_t MAX_VALUE = 0x7FFFFFFFFFFFFFFF; + +class IProgressListener { +public: + virtual ~IProgressListener() = default; + virtual void InvokeListener(uint64_t progressSize, uint64_t totalSize) const = 0; +}; -void TaskSignalEntityCore::OnCancel() -{ - if (!callbackContextCore_) { - return; - } - - callbackContextCore_->cb(taskSignal_->filePath_); -} -} // namespace OHOS::FileManagement::ModuleFileIO \ No newline at end of file +} // namespace OHOS::FileManagement::ModuleFileIO +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_LISTENER_I_PROGRESS_LISTENER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener_core.cpp b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener_core.cpp index 431a4f9e1..0b8d32b78 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener_core.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener_core.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,10 +19,10 @@ #include #include +#include "dfs_event_dfx.h" #include "ipc_skeleton.h" #include "sandbox_helper.h" #include "uri.h" -#include "dfs_event_dfx.h" #include "utils_log.h" namespace OHOS { @@ -70,22 +70,20 @@ int TransListenerCore::HandleCopyFailure(CopyEvent ©Event, const Storage::Di auto it = softbusErr2ErrCodeTable.find(copyEvent.errorCode); if (it == softbusErr2ErrCodeTable.end()) { RADAR_REPORT(RadarReporter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, - RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, - RadarReporter::SEND_FILE_ERROR, RadarReporter::CONCURRENT_ID, currentId, - RadarReporter::PACKAGE_NAME, to_string(copyEvent.errorCode)); + RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, RadarReporter::SEND_FILE_ERROR, + RadarReporter::CONCURRENT_ID, currentId, RadarReporter::PACKAGE_NAME, to_string(copyEvent.errorCode)); return EIO; } if (copyEvent.errorCode != DFS_CANCEL_SUCCESS) { HILOGE("HandleCopyFailure failed, copyEvent.errorCode = %{public}d.", copyEvent.errorCode); RADAR_REPORT(RadarReporter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, - RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, - RadarReporter::SEND_FILE_ERROR, RadarReporter::CONCURRENT_ID, currentId, - RadarReporter::PACKAGE_NAME, to_string(copyEvent.errorCode)); + RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, RadarReporter::SEND_FILE_ERROR, + RadarReporter::CONCURRENT_ID, currentId, RadarReporter::PACKAGE_NAME, to_string(copyEvent.errorCode)); } return it->second; } -int TransListenerCore::WaitForCopyResult(TransListenerCore* transListener) +int TransListenerCore::WaitForCopyResult(TransListenerCore *transListener) { if (transListener == nullptr) { HILOGE("transListener is nullptr"); @@ -93,14 +91,13 @@ int TransListenerCore::WaitForCopyResult(TransListenerCore* transListener) } std::unique_lock lock(transListener->cvMutex_); transListener->cv_.wait(lock, [&transListener]() { - return transListener->copyEvent_.copyResult == SUCCESS || - transListener->copyEvent_.copyResult == FAILED; + return transListener->copyEvent_.copyResult == SUCCESS || transListener->copyEvent_.copyResult == FAILED; }); return transListener->copyEvent_.copyResult; } int TransListenerCore::CopyFileFromSoftBus(const std::string &srcUri, const std::string &destUri, - std::shared_ptr fileInfos, std::shared_ptr callback) + std::shared_ptr fileInfos, std::shared_ptr callback) { HILOGI("CopyFileFromSoftBus begin."); std::string currentId = "CopyFile_" + std::to_string(getpid()) + "_" + std::to_string(getSequenceId_); @@ -115,7 +112,7 @@ int TransListenerCore::CopyFileFromSoftBus(const std::string &srcUri, const std: } transListener->callback_ = std::move(callback); - Storage::DistributedFile::HmdfsInfo info{}; + Storage::DistributedFile::HmdfsInfo info {}; Uri uri(destUri); info.authority = uri.GetAuthority(); info.sandboxPath = SandboxHelper::Decode(uri.GetPath()); @@ -151,14 +148,11 @@ int TransListenerCore::CopyFileFromSoftBus(const std::string &srcUri, const std: return ERRNO_NOERR; } -int32_t TransListenerCore::PrepareCopySession(const std::string &srcUri, - const std::string &destUri, - TransListenerCore* transListener, - Storage::DistributedFile::HmdfsInfo &info, - std::string &disSandboxPath) +int32_t TransListenerCore::PrepareCopySession(const std::string &srcUri, const std::string &destUri, + TransListenerCore *transListener, Storage::DistributedFile::HmdfsInfo &info, std::string &disSandboxPath) { std::string tmpDir; - if (info.authority != FILE_MANAGER_AUTHORITY && info.authority != MEDIA_AUTHORITY) { + if (info.authority != FILE_MANAGER_AUTHORITY && info.authority != MEDIA_AUTHORITY) { tmpDir = CreateDfsCopyPath(); disSandboxPath = DISTRIBUTED_PATH + tmpDir; std::error_code errCode; @@ -181,8 +175,8 @@ int32_t TransListenerCore::PrepareCopySession(const std::string &srcUri, info.copyPath = tmpDir; auto networkId = GetNetworkIdFromUri(srcUri); HILOGI("dfs PrepareSession begin."); - auto ret = Storage::DistributedFile::DistributedFileDaemonManager::GetInstance().PrepareSession(srcUri, destUri, - networkId, transListener, info); + auto ret = Storage::DistributedFile::DistributedFileDaemonManager::GetInstance().PrepareSession( + srcUri, destUri, networkId, transListener, info); if (ret != ERRNO_NOERR) { HILOGE("PrepareSession failed, ret = %{public}d.", ret); if (info.authority != FILE_MANAGER_AUTHORITY && info.authority != MEDIA_AUTHORITY) { @@ -218,8 +212,8 @@ int32_t TransListenerCore::CopyToSandBox(const std::string &srcUri, const std::s RmDir(disSandboxPath); return EIO; } - std::filesystem::copy(disSandboxPath + fileName, sandboxPath, std::filesystem::copy_options::update_existing, - errCode); + std::filesystem::copy( + disSandboxPath + fileName, sandboxPath, std::filesystem::copy_options::update_existing, errCode); if (errCode.value() != 0) { HILOGE("Copy file failed: errCode: %{public}d", errCode.value()); RADAR_REPORT(RadarReporter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, @@ -250,14 +244,24 @@ std::string TransListenerCore::GetNetworkIdFromUri(const std::string &uri) return uri.substr(uri.find(NETWORK_PARA) + NETWORK_PARA.size(), uri.size()); } -void TransListenerCore::CallbackComplete(std::shared_ptr entry) +void TransListenerCore::CallbackComplete(std::shared_ptr entry) { if (entry == nullptr) { HILOGE("entry pointer is nullptr."); return; } - entry->callback->listenerCb(entry->progressSize, entry->totalSize); + if (entry->callback == nullptr) { + HILOGE("entry callback pointer is nullptr."); + return; + } + + auto listener = entry->callback->listener; + if (listener == nullptr) { + HILOGE("listener pointer is nullptr."); + return; + } + listener->InvokeListener(entry->progressSize, entry->totalSize); } int32_t TransListenerCore::OnFileReceive(uint64_t totalBytes, uint64_t processedBytes) @@ -268,7 +272,7 @@ int32_t TransListenerCore::OnFileReceive(uint64_t totalBytes, uint64_t processed return ENOMEM; } - std::shared_ptr entry = std::make_shared(callback_); + std::shared_ptr entry = std::make_shared(callback_); if (entry == nullptr) { HILOGE("entry ptr is nullptr"); return ENOMEM; diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener_core.h b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener_core.h index d5b8f9585..c797454de 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener_core.h +++ b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener_core.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef FILEMANAGEMENT_FILE_API_TRANS_LISTENER_CORE_H -#define FILEMANAGEMENT_FILE_API_TRANS_LISTENER_CORE_H +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_LISTENER_TRANS_LISTENER_CORE_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_LISTENER_TRANS_LISTENER_CORE_H #include @@ -40,35 +40,31 @@ public: int32_t OnFileReceive(uint64_t totalBytes, uint64_t processedBytes) override; int32_t OnFinished(const std::string &sessionName) override; int32_t OnFailed(const std::string &sessionName, int32_t errorCode) override; - static int CopyFileFromSoftBus(const std::string &srcUri, - const std::string &destUri, - std::shared_ptr fileInfos, - std::shared_ptr callback); + static int CopyFileFromSoftBus(const std::string &srcUri, const std::string &destUri, + std::shared_ptr fileInfos, std::shared_ptr callback); + private: static std::string GetNetworkIdFromUri(const std::string &uri); - static void CallbackComplete(std::shared_ptr entry); + static void CallbackComplete(std::shared_ptr entry); static void RmDir(const std::string &path); static std::string CreateDfsCopyPath(); static std::string GetFileName(const std::string &path); static int32_t CopyToSandBox(const std::string &srcUri, const std::string &disSandboxPath, const std::string &sandboxPath, const std::string ¤tId); - static int32_t PrepareCopySession(const std::string &srcUri, - const std::string &destUri, - TransListenerCore* transListener, - Storage::DistributedFile::HmdfsInfo &info, - std::string &disSandboxPath); + static int32_t PrepareCopySession(const std::string &srcUri, const std::string &destUri, + TransListenerCore *transListener, Storage::DistributedFile::HmdfsInfo &info, std::string &disSandboxPath); static int HandleCopyFailure(CopyEvent ©Event, const Storage::DistributedFile::HmdfsInfo &info, const std::string &disSandboxPath, const std::string ¤tId); - static int WaitForCopyResult(TransListenerCore* transListener); + static int WaitForCopyResult(TransListenerCore *transListener); static std::atomic getSequenceId_; std::mutex cvMutex_; std::condition_variable cv_; CopyEvent copyEvent_; std::mutex callbackMutex_; - std::shared_ptr callback_; + std::shared_ptr callback_; }; } // namespace ModuleFileIO } // namespace FileManagement } // namespace OHOS -#endif // FILEMANAGEMENT_FILE_API_TRANS_LISTENER_CORE_H \ No newline at end of file +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_LISTENER_TRANS_LISTENER_CORE_H \ No newline at end of file -- Gitee From 52636652655255a1df8390f7ad3670b8f95384f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9C=E5=B0=8F=E6=9E=97?= Date: Fri, 13 Jun 2025 09:49:18 +0800 Subject: [PATCH 02/19] =?UTF-8?q?=E6=A0=B9=E6=8D=AE=E6=A3=80=E8=A7=86?= =?UTF-8?q?=E6=84=8F=E8=A7=81=E8=BF=9B=E8=A1=8C=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Change-Id: I1727413a28b67a39be892c644136f960df59590f Signed-off-by: 姜小林 --- .../kits/js/src/mod_fs/ani/ets/@ohos.file.fs.ets | 4 +++- .../ani/task_signal_listener_ani.cpp | 2 +- .../kits/js/src/mod_fs/properties/ani/copy_ani.cpp | 14 ++++++++++++-- 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/interfaces/kits/js/src/mod_fs/ani/ets/@ohos.file.fs.ets b/interfaces/kits/js/src/mod_fs/ani/ets/@ohos.file.fs.ets index 1ebce3e37..610c1094f 100644 --- a/interfaces/kits/js/src/mod_fs/ani/ets/@ohos.file.fs.ets +++ b/interfaces/kits/js/src/mod_fs/ani/ets/@ohos.file.fs.ets @@ -1266,7 +1266,7 @@ export class TaskSignal { private native onCancelNative(): void; - private onCancelResolve: (path: string) => void; + private onCancelResolve: (path: string) => void = (path: string): void => {}; private onCancelCallback(path: string): void { if (this.onCancelResolve) { this.onCancelResolve(path); @@ -1282,6 +1282,8 @@ export class TaskSignal { this.onCancelNative(); } catch (e: BusinessError) { reject(e); + } catch (e: Error) { + reject(e as BusinessError); } }); } diff --git a/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_listener_ani.cpp b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_listener_ani.cpp index a80010e95..8f533889c 100644 --- a/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_listener_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_listener_ani.cpp @@ -55,7 +55,7 @@ void TaskSignalListenerAni::SendCancelEvent(const string &filepath) const } auto ret = env->Object_CallMethodByName_Void(signalObj, "onCancelCallback", nullptr, aniPath); if (ret != ANI_OK) { - HILOGE("Call onCancelCallback failed, err: %{private}d", ret); + HILOGE("Call onCancelCallback failed, err: %{public}d", ret); return; } } diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/copy_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/copy_ani.cpp index 7e84bce8f..541cd7f6c 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/copy_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/ani/copy_ani.cpp @@ -140,8 +140,18 @@ void CopyAni::CopySync( auto [succDest, dest] = TypeConverter::ToUTF8String(env, destUri); auto [succOpts, opts] = ParseOptions(env, options); - if (!succSrc || !succDest || !succOpts) { - HILOGE("The first/second/third argument requires uri/uri/napi_function"); + if (!succSrc) { + HILOGE("The first argument requires uri"); + ErrorHandler::Throw(env, E_PARAMS); + return; + } + if (!succDest) { + HILOGE("The second argument requires uri"); + ErrorHandler::Throw(env, E_PARAMS); + return; + } + if (!succOpts) { + HILOGE("The third argument requires listener function"); ErrorHandler::Throw(env, E_PARAMS); return; } -- Gitee From bca792d7aacbfae4239bfa3452673db24cdf101c Mon Sep 17 00:00:00 2001 From: tianp Date: Mon, 16 Jun 2025 11:15:14 +0800 Subject: [PATCH 03/19] copyTDD Signed-off-by: tianp Change-Id: Ifaa8867aad18493f90a01787a1adff1252b7082f --- interfaces/test/unittest/js/BUILD.gn | 2 + .../js/mod_fs/properties/copy_core_test.cpp | 143 ++++++++++++++++++ 2 files changed, 145 insertions(+) create mode 100644 interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp diff --git a/interfaces/test/unittest/js/BUILD.gn b/interfaces/test/unittest/js/BUILD.gn index a22cb0a2b..0d4039ac2 100644 --- a/interfaces/test/unittest/js/BUILD.gn +++ b/interfaces/test/unittest/js/BUILD.gn @@ -31,10 +31,12 @@ ohos_unittest("ani_file_fs_test") { "${file_api_path}/interfaces/kits/js/src/mod_fs/class_stream", "${file_api_path}/interfaces/kits/js/src/mod_fs/class_tasksignal", "${file_api_path}/interfaces/kits/js/src/mod_fs/properties", + "${file_api_path}/interfaces/kits/js/src/mod_fs/properties/copy_listener", ] sources = [ "mod_fs/properties/close_core_test.cpp", + "mod_fs/properties/copy_core_test.cpp", "mod_fs/properties/create_stream_core_test.cpp", "mod_fs/properties/fdopen_stream_core_test.cpp", "mod_fs/properties/listfile_core_test.cpp", diff --git a/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp new file mode 100644 index 000000000..0260100e9 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp @@ -0,0 +1,143 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "copy_core.h" + +#include +#include + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class CopyCoreTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void CopyCoreTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + int32_t fd = open("/data/test/src.txt", O_CREAT | O_RDWR, 0644); + close(fd); +} + +void CopyCoreTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; + rmdir("/data/test/CopyCoreTest.txt"); +} + +void CopyCoreTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void CopyCoreTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: CopyCoreTest_ValidParams_001 + * @tc.desc: Test function of CopyCore::ValidParams interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_ValidParams_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_ValidParams_001"; + + string src = "invalid://data/test/src.txt"; + string dest = "file://data/test/dest.txt"; + + auto res = CopyCore::ValidParams(src, dest); + EXPECT_EQ(res, false); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_ValidParams_001"; +} + +/** + * @tc.name: CopyCoreTest_ValidParams_002 + * @tc.desc: Test function of CopyCore::ValidParams interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_ValidParams_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_ValidParams_002"; + + string src = "file://data/test/src.txt"; + string dest = "invalid://data/test/dest.txt"; + + auto res = CopyCore::ValidParams(src, dest); + EXPECT_EQ(res, false); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_ValidParams_002"; +} + +/** + * @tc.name: CopyCoreTest_ValidParams_003 + * @tc.desc: Test function of CopyCore::ValidParams interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_ValidParams_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_ValidParams_003"; + + string src = "file://data/test/src.txt"; + string dest = "file://data/test/dest.txt"; + + auto res = CopyCore::ValidParams(src, dest); + + EXPECT_EQ(res, true); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_ValidParams_003"; +} + +/** + * @tc.name: CopyCoreTest_CreateFileInfos_001 + * @tc.desc: Test function of CopyCore::CreateFileInfos interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_CreateFileInfos_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_CreateFileInfos_001"; + + string src = "file://data/test/src.txt"; + string dest = "file://data/test/dest.txt"; + optional options = std::make_optional(); + options->listener = std::make_shared(); + options-> + + + auto res = CopyCore::CreateFileInfos(src, dest, options); + + EXPECT_EQ(res, true); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_CreateFileInfos_001"; +} + +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file -- Gitee From c5861ab560af515dfcb5829a2bb180f1f86235d1 Mon Sep 17 00:00:00 2001 From: yangbiao59 Date: Tue, 17 Jun 2025 08:09:33 +0000 Subject: [PATCH 04/19] !1 add fs_task_signal_test.cpp * add tdd --- interfaces/test/unittest/js/BUILD.gn | 1 + .../class_tasksignal/fs_task_signal_test.cpp | 203 ++++++++++++++++++ .../js/mod_fs/properties/copy_core_test.cpp | 48 ++--- 3 files changed, 228 insertions(+), 24 deletions(-) create mode 100644 interfaces/test/unittest/js/mod_fs/class_tasksignal/fs_task_signal_test.cpp diff --git a/interfaces/test/unittest/js/BUILD.gn b/interfaces/test/unittest/js/BUILD.gn index 0d4039ac2..799c10eb3 100644 --- a/interfaces/test/unittest/js/BUILD.gn +++ b/interfaces/test/unittest/js/BUILD.gn @@ -42,6 +42,7 @@ ohos_unittest("ani_file_fs_test") { "mod_fs/properties/listfile_core_test.cpp", "mod_fs/properties/read_text_core_test.cpp", "mod_fs/class_stream/fs_stream_test.cpp", + "mod_fs/class_tasksignal/fs_task_signal_test.cpp", ] deps = [ diff --git a/interfaces/test/unittest/js/mod_fs/class_tasksignal/fs_task_signal_test.cpp b/interfaces/test/unittest/js/mod_fs/class_tasksignal/fs_task_signal_test.cpp new file mode 100644 index 000000000..7a429951b --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/class_tasksignal/fs_task_signal_test.cpp @@ -0,0 +1,203 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "fs_task_signal.h" + +#include + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class Assistant : public TaskSignalListener { +public: + void OnCancel() {} +}; + +class FsTaskSignalTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void FsTaskSignalTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; +} + +void FsTaskSignalTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void FsTaskSignalTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void FsTaskSignalTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: FsTaskSignalTest_Constructor_001 + * @tc.desc: Test function of FsTaskSignal::Constructor interface for False. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsTaskSignalTest, FsTaskSignalTest_Constructor_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NClassTest-begin FsTaskSignalTest_Constructor_001"; + + FsTaskSignal fsTaskSignal; + shared_ptr taskSignal = nullptr; + shared_ptr signalListener = nullptr; + + auto res = fsTaskSignal.Constructor(taskSignal, signalListener); + + EXPECT_EQ(taskSignal, nullptr); + EXPECT_EQ(res.IsSuccess(), false); + GTEST_LOG_(INFO) << "NClassTest-end FsTaskSignalTest_Constructor_001"; +} + +/** + * @tc.name: FsTaskSignalTest_Constructor_002 + * @tc.desc: Test function of FsTaskSignal::Constructor interface for False. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsTaskSignalTest, FsTaskSignalTest_Constructor_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NClassTest-begin FsTaskSignalTest_Constructor_002"; + + FsTaskSignal fsTaskSignal; + shared_ptr taskSignal = std::make_shared(); + shared_ptr signalListener = nullptr; + + auto res = fsTaskSignal.Constructor(taskSignal, signalListener); + + EXPECT_NE(taskSignal, nullptr); + EXPECT_EQ(res.IsSuccess(), false); + GTEST_LOG_(INFO) << "NClassTest-end FsTaskSignalTest_Constructor_002"; +} + +/** + * @tc.name: FsTaskSignalTest_Constructor_003 + * @tc.desc: Test function of FsTaskSignal::Constructor interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsTaskSignalTest, FsTaskSignalTest_Constructor_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NClassTest-begin FsTaskSignalTest_Constructor_003"; + + FsTaskSignal fsTaskSignal; + shared_ptr taskSignal = std::make_shared(); + shared_ptr signalListener = std::make_shared(); + + auto res = fsTaskSignal.Constructor(taskSignal, signalListener); + + EXPECT_NE(signalListener, nullptr); + EXPECT_EQ(res.IsSuccess(), true); + GTEST_LOG_(INFO) << "NClassTest-end FsTaskSignalTest_Constructor_003"; +} + +/** + * @tc.name: FsTaskSignalTest_Cancel_001 + * @tc.desc: Test function of FsTaskSignal::Cancel interface for false. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsTaskSignalTest, FsTaskSignalTest_Cancel_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NClassTest-begin FsTaskSignalTest_Cancel_001"; + + FsTaskSignal fsTaskSignal; + + auto res = fsTaskSignal.Cancel(); + + EXPECT_EQ(fsTaskSignal.taskSignal_, nullptr); + GTEST_LOG_(INFO) << "NClassTest-end FsTaskSignalTest_Cancel_001"; +} + +/** + * @tc.name: FsTaskSignalTest_Cancel_002 + * @tc.desc: Test function of FsTaskSignal::Cancel interface for false. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsTaskSignalTest, FsTaskSignalTest_Cancel_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NClassTest-begin FsTaskSignalTest_Cancel_002"; + + FsTaskSignal fsTaskSignal; + fsTaskSignal.taskSignal_ = std::make_shared(); + + auto res = fsTaskSignal.Cancel(); + + EXPECT_NE(fsTaskSignal.taskSignal_, nullptr); + GTEST_LOG_(INFO) << "NClassTest-end FsTaskSignalTest_Cancel_002"; +} + +/** + * @tc.name: FsTaskSignalTest_OnCancel_001 + * @tc.desc: Test function of FsTaskSignal::OnCancel interface for false. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsTaskSignalTest, FsTaskSignalTest_OnCancel_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NClassTest-begin FsTaskSignalTest_OnCancel_001"; + + FsTaskSignal fsTaskSignal; + + auto res = fsTaskSignal.OnCancel(); + + EXPECT_EQ(fsTaskSignal.taskSignal_, nullptr); + GTEST_LOG_(INFO) << "NClassTest-end FsTaskSignalTest_OnCancel_001"; +} + +/** + * @tc.name: FsTaskSignalTest_OnCancel_002 + * @tc.desc: Test function of FsTaskSignal::OnCancel interface for false. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(FsTaskSignalTest, FsTaskSignalTest_OnCancel_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "NClassTest-begin FsTaskSignalTest_OnCancel_002"; + + FsTaskSignal fsTaskSignal; + fsTaskSignal.taskSignal_ = std::make_shared(); + + auto res = fsTaskSignal.OnCancel(); + + EXPECT_NE(fsTaskSignal.taskSignal_, nullptr); + GTEST_LOG_(INFO) << "NClassTest-end FsTaskSignalTest_OnCancel_002"; +} + +} // OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp index 0260100e9..7d20dac9e 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp @@ -115,29 +115,29 @@ HWTEST_F(CopyCoreTest, CopyCoreTest_ValidParams_003, testing::ext::TestSize.Leve GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_ValidParams_003"; } -/** - * @tc.name: CopyCoreTest_CreateFileInfos_001 - * @tc.desc: Test function of CopyCore::CreateFileInfos interface for FALSE. - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - */ -HWTEST_F(CopyCoreTest, CopyCoreTest_CreateFileInfos_001, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_CreateFileInfos_001"; - - string src = "file://data/test/src.txt"; - string dest = "file://data/test/dest.txt"; - optional options = std::make_optional(); - options->listener = std::make_shared(); - options-> - - - auto res = CopyCore::CreateFileInfos(src, dest, options); - - EXPECT_EQ(res, true); - - GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_CreateFileInfos_001"; -} +// /** +// * @tc.name: CopyCoreTest_CreateFileInfos_001 +// * @tc.desc: Test function of CopyCore::CreateFileInfos interface for FALSE. +// * @tc.size: MEDIUM +// * @tc.type: FUNC +// * @tc.level Level 1 +// */ +// HWTEST_F(CopyCoreTest, CopyCoreTest_CreateFileInfos_001, testing::ext::TestSize.Level1) +// { +// GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_CreateFileInfos_001"; + +// string src = "file://data/test/src.txt"; +// string dest = "file://data/test/dest.txt"; +// optional options = std::make_optional(); +// options->listener = std::make_shared(); +// options-> + + +// auto res = CopyCore::CreateFileInfos(src, dest, options); + +// EXPECT_EQ(res, true); + +// GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_CreateFileInfos_001"; +// } } // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file -- Gitee From d55de428a50aabf7bd226ba9d1ba3b8292f6fe1d Mon Sep 17 00:00:00 2001 From: tianp Date: Tue, 17 Jun 2025 16:41:36 +0800 Subject: [PATCH 05/19] =?UTF-8?q?copyTDD=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: tianp Change-Id: I1aef1625484f6c1c18a1d8b8202c03872e13457d --- .../js/mod_fs/properties/copy_core_test.cpp | 541 +++++++++++++++++- 1 file changed, 512 insertions(+), 29 deletions(-) diff --git a/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp index 7d20dac9e..088817b9c 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp @@ -16,6 +16,7 @@ #include "copy_core.h" #include +#include #include namespace OHOS::FileManagement::ModuleFileIO::Test { @@ -29,19 +30,39 @@ public: static void TearDownTestCase(void); void SetUp(); void TearDown(); + + static const string testDir; + static const string srcDir; + static const string destDir; + static const string srcFile; + static const string destFile; }; +const string CopyCoreTest::testDir = "/data/test"; +const string CopyCoreTest::srcDir = testDir + "/src"; +const string CopyCoreTest::destDir = testDir + "/dest"; +const string CopyCoreTest::srcFile = srcDir + "/src.txt"; +const string CopyCoreTest::destFile = destDir + "/dest.txt"; + void CopyCoreTest::SetUpTestCase(void) { GTEST_LOG_(INFO) << "SetUpTestCase"; - int32_t fd = open("/data/test/src.txt", O_CREAT | O_RDWR, 0644); - close(fd); + mkdir(testDir.c_str(), 0755); + mkdir(srcDir.c_str(), 0755); + mkdir(destDir.c_str(), 0755); + int32_t fd = open(srcFile.c_str(), O_CREAT | O_RDWR, 0644); + if (fd >= 0) { + close(fd); + } } void CopyCoreTest::TearDownTestCase(void) { GTEST_LOG_(INFO) << "TearDownTestCase"; - rmdir("/data/test/CopyCoreTest.txt"); + remove(srcFile.c_str()); + rmdir(srcDir.c_str()); + rmdir(destDir.c_str()); + rmdir(testDir.c_str()); } void CopyCoreTest::SetUp(void) @@ -52,6 +73,275 @@ void CopyCoreTest::SetUp(void) void CopyCoreTest::TearDown(void) { GTEST_LOG_(INFO) << "TearDown"; + remove(destFile.c_str()); +} + +/** + * @tc.name: CopyCoreTest_IsValidUri_001 + * @tc.desc: Test function of CopyCore::IsValidUri interface for TRUE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_IsValidUri_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_IsValidUri_001"; + + string validUri = "file://data/test/file.txt"; + auto res = CopyCore::IsValidUri(validUri); + EXPECT_EQ(res, true); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_IsValidUri_001"; +} + +/** + * @tc.name: CopyCoreTest_IsValidUri_002 + * @tc.desc: Test function of CopyCore::IsValidUri interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_IsValidUri_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_IsValidUri_002"; + + string invalidUri = "invalid://data/test/file.txt"; + auto res = CopyCore::IsValidUri(invalidUri); + EXPECT_EQ(res, false); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_IsValidUri_002"; +} + +/** + * @tc.name: CopyCoreTest_IsRemoteUri_001 + * @tc.desc: Test function of CopyCore::IsRemoteUri interface for TRUE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_IsRemoteUri_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_IsRemoteUri_001"; + + string remoteUri = "file://data/test/file.txt?networkid=123"; + auto res = CopyCore::IsRemoteUri(remoteUri); + EXPECT_EQ(res, true); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_IsRemoteUri_001"; +} + +/** + * @tc.name: CopyCoreTest_IsRemoteUri_002 + * @tc.desc: Test function of CopyCore::IsRemoteUri interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_IsRemoteUri_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_IsRemoteUri_002"; + + string localUri = "file://data/test/file.txt"; + auto res = CopyCore::IsRemoteUri(localUri); + EXPECT_EQ(res, false); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_IsRemoteUri_002"; +} + +/** + * @tc.name: CopyCoreTest_IsDirectory_001 + * @tc.desc: Test function of CopyCore::IsDirectory interface for TRUE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_IsDirectory_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_IsDirectory_001"; + + auto res = CopyCore::IsDirectory(srcDir); + EXPECT_EQ(res, true); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_IsDirectory_001"; +} + +/** + * @tc.name: CopyCoreTest_IsDirectory_002 + * @tc.desc: Test function of CopyCore::IsDirectory interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_IsDirectory_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_IsDirectory_002"; + + auto res = CopyCore::IsDirectory(srcFile); + EXPECT_EQ(res, false); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_IsDirectory_002"; +} + +/** + * @tc.name: CopyCoreTest_IsFile_001 + * @tc.desc: Test function of CopyCore::IsFile interface for TRUE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_IsFile_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_IsFile_001"; + + auto res = CopyCore::IsFile(srcFile); + EXPECT_EQ(res, true); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_IsFile_001"; +} + +/** + * @tc.name: CopyCoreTest_IsFile_002 + * @tc.desc: Test function of CopyCore::IsFile interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_IsFile_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_IsFile_002"; + + auto res = CopyCore::IsFile(srcDir); + EXPECT_EQ(res, false); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_IsFile_002"; +} + +/** + * @tc.name: CopyCoreTest_GetFileSize_001 + * @tc.desc: Test function of CopyCore::GetFileSize interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_GetFileSize_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_GetFileSize_001"; + + auto [err, size] = CopyCore::GetFileSize(srcFile); + EXPECT_EQ(err, ERRNO_NOERR); + EXPECT_GE(size, 0); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_GetFileSize_001"; +} + +/** + * @tc.name: CopyCoreTest_GetFileSize_002 + * @tc.desc: Test function of CopyCore::GetFileSize interface for failure. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_GetFileSize_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_GetFileSize_002"; + + string nonExistentFile = "/data/test/non_existent.txt"; + auto [err, size] = CopyCore::GetFileSize(nonExistentFile); + EXPECT_NE(err, ERRNO_NOERR); + EXPECT_EQ(size, 0); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_GetFileSize_002"; +} + +/** + * @tc.name: CopyCoreTest_CheckOrCreatePath_001 + * @tc.desc: Test function of CopyCore::CheckOrCreatePath interface for existing file. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_CheckOrCreatePath_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_CheckOrCreatePath_001"; + + auto res = CopyCore::CheckOrCreatePath(srcFile); + EXPECT_EQ(res, ERRNO_NOERR); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_CheckOrCreatePath_001"; +} + +/** + * @tc.name: CopyCoreTest_CheckOrCreatePath_002 + * @tc.desc: Test function of CopyCore::CheckOrCreatePath interface for creating new file. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_CheckOrCreatePath_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_CheckOrCreatePath_002"; + + string newFile = destDir + "/new_file.txt"; + auto res = CopyCore::CheckOrCreatePath(newFile); + EXPECT_EQ(res, ERRNO_NOERR); + EXPECT_TRUE(CopyCore::IsFile(newFile)); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_CheckOrCreatePath_002"; +} + +/** + * @tc.name: CopyCoreTest_MakeDir_001 + * @tc.desc: Test function of CopyCore::MakeDir interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_MakeDir_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_MakeDir_001"; + + string newDir = destDir + "/new_dir"; + auto res = CopyCore::MakeDir(newDir); + EXPECT_EQ(res, ERRNO_NOERR); + EXPECT_TRUE(CopyCore::IsDirectory(newDir)); + + rmdir(newDir.c_str()); + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_MakeDir_001"; +} + +/** + * @tc.name: CopyCoreTest_MakeDir_002 + * @tc.desc: Test function of CopyCore::MakeDir interface for existing directory. + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 2 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_MakeDir_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_MakeDir_002"; + + auto res = CopyCore::MakeDir(srcDir); + EXPECT_EQ(res, ERRNO_NOERR); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_MakeDir_002"; +} + +/** + * @tc.name: CopyCoreTest_MakeDir_003 + * @tc.desc: Test function of CopyCore::MakeDir interface for invalid path. + * @tc.size: SMALL + * @tc.type: FUNC + * @tc.level Level 2 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_MakeDir_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_MakeDir_003"; + + string invalidPath = "/invalid/path/dir"; + auto res = CopyCore::MakeDir(invalidPath); + EXPECT_NE(res, ERRNO_NOERR); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_MakeDir_003"; } /** @@ -65,10 +355,9 @@ HWTEST_F(CopyCoreTest, CopyCoreTest_ValidParams_001, testing::ext::TestSize.Leve { GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_ValidParams_001"; - string src = "invalid://data/test/src.txt"; - string dest = "file://data/test/dest.txt"; + string srcFile = "invalid://data/test/src.txt"; - auto res = CopyCore::ValidParams(src, dest); + auto res = CopyCore::ValidParams(srcFile, destFile); EXPECT_EQ(res, false); GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_ValidParams_001"; @@ -85,10 +374,9 @@ HWTEST_F(CopyCoreTest, CopyCoreTest_ValidParams_002, testing::ext::TestSize.Leve { GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_ValidParams_002"; - string src = "file://data/test/src.txt"; - string dest = "invalid://data/test/dest.txt"; + string destFile = "invalid://data/test/dest.txt"; - auto res = CopyCore::ValidParams(src, dest); + auto res = CopyCore::ValidParams(srcFile, destFile); EXPECT_EQ(res, false); GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_ValidParams_002"; @@ -109,35 +397,230 @@ HWTEST_F(CopyCoreTest, CopyCoreTest_ValidParams_003, testing::ext::TestSize.Leve string dest = "file://data/test/dest.txt"; auto res = CopyCore::ValidParams(src, dest); - EXPECT_EQ(res, true); GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_ValidParams_003"; } -// /** -// * @tc.name: CopyCoreTest_CreateFileInfos_001 -// * @tc.desc: Test function of CopyCore::CreateFileInfos interface for FALSE. -// * @tc.size: MEDIUM -// * @tc.type: FUNC -// * @tc.level Level 1 -// */ -// HWTEST_F(CopyCoreTest, CopyCoreTest_CreateFileInfos_001, testing::ext::TestSize.Level1) -// { -// GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_CreateFileInfos_001"; +/** + * @tc.name: CopyCoreTest_CreateFileInfos_001 + * @tc.desc: Test function of CopyCore::CreateFileInfos interface for TRUE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_CreateFileInfos_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_CreateFileInfos_001"; + + optional options = std::make_optional(); -// string src = "file://data/test/src.txt"; -// string dest = "file://data/test/dest.txt"; -// optional options = std::make_optional(); -// options->listener = std::make_shared(); -// options-> + auto [errCode, infos] = CopyCore::CreateFileInfos(srcFile, destFile, options); + EXPECT_EQ(errCode, ERRNO_NOERR); + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_CreateFileInfos_001"; +} + +/** + * @tc.name: CopyCoreTest_CopySubDir_001 + * @tc.desc: Test function of CopyCore::CopySubDir interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_CopySubDir_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_CopySubDir_001"; -// auto res = CopyCore::CreateFileInfos(src, dest, options); + string subDir = srcDir + "/sub_dir"; + mkdir(subDir.c_str(), 0755); + string subFile = subDir + "/sub_file.txt"; + int fd = open(subFile.c_str(), O_CREAT | O_RDWR, 0644); + if (fd >= 0) { + close(fd); + } -// EXPECT_EQ(res, true); + string destSubDir = destDir + "/sub_dir"; + auto infos = make_shared(); + auto res = CopyCore::CopySubDir(subDir, destSubDir, infos); + string destSubFile = destSubDir + "/sub_file.txt"; + EXPECT_EQ(res, ERRNO_NOERR); + EXPECT_TRUE(CopyCore::IsDirectory(destSubDir)); + EXPECT_TRUE(CopyCore::IsFile(destSubFile)); -// GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_CreateFileInfos_001"; -// } + remove(subFile.c_str()); + rmdir(subDir.c_str()); + remove(destSubFile.c_str()); + rmdir(destSubDir.c_str()); + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_CopySubDir_001"; +} + +/** + * @tc.name: CopyCoreTest_RecurCopyDir_001 + * @tc.desc: Test function of CopyCore::RecurCopyDir interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_RecurCopyDir_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_RecurCopyDir_001"; + + string subDir = srcDir + "/sub_dir"; + mkdir(subDir.c_str(), 0755); + string subFile = subDir + "/sub_file.txt"; + int fd = open(subFile.c_str(), O_CREAT | O_RDWR, 0644); + if (fd >= 0) { + close(fd); + } + + string destSubDir = destDir + "/sub_dir"; + auto infos = make_shared(); + auto res = CopyCore::RecurCopyDir(srcDir, destDir, infos); + string destSubFile = destSubDir + "/sub_file.txt"; + EXPECT_EQ(res, ERRNO_NOERR); + EXPECT_TRUE(CopyCore::IsDirectory(destSubDir)); + EXPECT_TRUE(CopyCore::IsFile(destSubDir + "/sub_file.txt")); + + remove(subFile.c_str()); + rmdir(subDir.c_str()); + remove(destSubFile.c_str()); + rmdir(destSubDir.c_str()); + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_RecurCopyDir_001"; +} + +/** + * @tc.name: CopyCoreTest_CopyDirFunc_001 + * @tc.desc: Test function of CopyCore::CopyDirFunc interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_CopyDirFunc_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_CopyDirFunc_001"; + + string subDir = srcDir + "/sub_dir"; + mkdir(subDir.c_str(), 0755); + string subFile = subDir + "/sub_file.txt"; + int fd = open(subFile.c_str(), O_CREAT | O_RDWR, 0644); + if (fd >= 0) { + close(fd); + } + + string destSubDir = destDir + "/src/sub_dir"; + string destSubFile = destSubDir + "/sub_file.txt"; + string destSrcDir = destDir + "/src"; + auto infos = make_shared(); + auto res = CopyCore::CopyDirFunc(srcDir, destDir, infos); + EXPECT_EQ(res, ERRNO_NOERR); + EXPECT_EQ(CopyCore::IsDirectory(destSubDir), false); + EXPECT_EQ(CopyCore::IsFile(destSubDir + "/sub_file.txt"), false); + + remove(subFile.c_str()); + rmdir(subDir.c_str()); + remove(destSubFile.c_str()); + rmdir(destSubDir.c_str()); + rmdir(destSrcDir.c_str()); + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_CopyDirFunc_001"; +} + +/** + * @tc.name: CopyCoreTest_ExecLocal_001 + * @tc.desc: Test function of CopyCore::ExecLocal interface for file copy success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_ExecLocal_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_ExecLocal_001"; + + auto infos = make_shared(); + infos->isFile = true; + infos->srcPath = srcFile; + infos->destPath = destFile; + + auto callback = make_shared(nullptr); + auto res = CopyCore::ExecLocal(infos, callback); + EXPECT_EQ(res, ERRNO_NOERR); + EXPECT_TRUE(CopyCore::IsFile(destFile)); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_ExecLocal_001"; +} + +/** + * @tc.name: CopyCoreTest_RegisterListener_001 + * @tc.desc: Test function of CopyCore::RegisterListener interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_RegisterListener_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_RegisterListener_001"; + + auto infos = make_shared(); + auto callback = CopyCore::RegisterListener(infos); + EXPECT_NE(callback, nullptr); + + { + std::lock_guard lock(CopyCore::mutex_); + auto iter = CopyCore::callbackMap_.find(*infos); + EXPECT_NE(iter, CopyCore::callbackMap_.end()); + } + + CopyCore::UnregisterListener(infos); + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_RegisterListener_001"; +} + +/** + * @tc.name: CopyCoreTest_UnregisterListener_001 + * @tc.desc: Test function of CopyCore::UnregisterListener interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_UnregisterListener_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_UnregisterListener_001"; + + auto infos = make_shared(); + auto callback = CopyCore::RegisterListener(infos); + EXPECT_NE(callback, nullptr); + + CopyCore::UnregisterListener(infos); + + { + std::lock_guard lock(CopyCore::mutex_); + auto iter = CopyCore::callbackMap_.find(*infos); + EXPECT_EQ(iter, CopyCore::callbackMap_.end()); + } + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_UnregisterListener_001"; +} + +/** + * @tc.name: CopyCoreTest_DoCopy_001 + * @tc.desc: Test function of CopyCore::DoCopy interface for failure (invalid params). + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_DoCopy_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_DoCopy_001"; + + string src = "invalid:/" + srcFile; + string dest = "invalid:/" + destFile; + optional options; + + auto res = CopyCore::DoCopy(src, dest, options); + EXPECT_FALSE(res.IsSuccess()); + auto err = res.GetError(); + EXPECT_EQ(err.GetErrNo(), E_PARAMS); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_DoCopy_001"; +} } // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file -- Gitee From c736e09ea82fd523c8ee9a076622a434b3d8be30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=91=A8=E9=91=AB?= Date: Tue, 17 Jun 2025 11:18:35 +0000 Subject: [PATCH 06/19] !2 tdd * tdd --- interfaces/test/unittest/js/BUILD.gn | 3 + .../mod_fs/properties/trans_listener_test.cpp | 479 ++++++++++++++++++ 2 files changed, 482 insertions(+) create mode 100644 interfaces/test/unittest/js/mod_fs/properties/trans_listener_test.cpp diff --git a/interfaces/test/unittest/js/BUILD.gn b/interfaces/test/unittest/js/BUILD.gn index 799c10eb3..3b5e3f420 100644 --- a/interfaces/test/unittest/js/BUILD.gn +++ b/interfaces/test/unittest/js/BUILD.gn @@ -41,6 +41,7 @@ ohos_unittest("ani_file_fs_test") { "mod_fs/properties/fdopen_stream_core_test.cpp", "mod_fs/properties/listfile_core_test.cpp", "mod_fs/properties/read_text_core_test.cpp", + "mod_fs/properties/trans_listener_test.cpp", "mod_fs/class_stream/fs_stream_test.cpp", "mod_fs/class_tasksignal/fs_task_signal_test.cpp", ] @@ -58,6 +59,8 @@ ohos_unittest("ani_file_fs_test") { "ability_runtime:ability_manager", "app_file_service:fileuri_native", "c_utils:utils", + "dfs_service:distributed_file_daemon_kit_inner", + "dfs_service:libdistributedfileutils", "googletest:gtest_main", "hilog:libhilog", "ipc:ipc_core", diff --git a/interfaces/test/unittest/js/mod_fs/properties/trans_listener_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/trans_listener_test.cpp new file mode 100644 index 000000000..645ebfdb8 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/trans_listener_test.cpp @@ -0,0 +1,479 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "trans_listener_core.h" + +#include +#include + +#include "copy_core.h" + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +string g_path = "/data/test/TransListenerCoreTest.txt"; +const string FILE_MANAGER_AUTHORITY = "docs"; +const string MEDIA_AUTHORITY = "media"; + +class TransListenerCoreTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void TransListenerCoreTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + int32_t fd = open(g_path.c_str(), O_CREAT | O_RDWR, 0644); + close(fd); +} + +void TransListenerCoreTest::TearDownTestCase(void) +{ + rmdir(g_path.c_str()); + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void TransListenerCoreTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void TransListenerCoreTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +// /** +// * @tc.name: TransListenerCoreTest_RmDir_001 +// * @tc.desc: Test function of TransListenerCore::RmDir interface for FALSE. +// * @tc.size: MEDIUM +// * @tc.type: FUNC +// * @tc.level Level 1 +// */ +// HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_RmDir_001, testing::ext::TestSize.Level1) +// { +// GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_RmDir_001"; + +// string path = "/data/test/TransListenerCoreTest_RmDir_001.txt"; + +// TransListenerCore::RmDir(path); + +// GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_RmDir_001"; +// } + +// /** +// * @tc.name: TransListenerCoreTest_RmDir_002 +// * @tc.desc: Test function of TransListenerCore::RmDir interface for SUCC. +// * @tc.size: MEDIUM +// * @tc.type: FUNC +// * @tc.level Level 1 +// */ +// HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_RmDir_002, testing::ext::TestSize.Level1) +// { +// GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_RmDir_002"; + +// string path = "/data/test/TransListenerCoreTest_RmDir_002.txt"; +// int32_t fd = open(path, O_CREAT | O_RDWR, 0644); +// close(fd); + +// TransListenerCore::RmDir(path); + +// GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_RmDir_002"; +// } + +/** + * @tc.name: TransListenerCoreTest_CreateDfsCopyPath_001 + * @tc.desc: Test function of TransListenerCore::CreateDfsCopyPath interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_CreateDfsCopyPath_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_CreateDfsCopyPath_001"; + + string result = TransListenerCore::CreateDfsCopyPath(); + EXPECT_EQ(result, "/data/storage/el2/distributedfiles/"); + + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_CreateDfsCopyPath_001"; +} + +/** + * @tc.name: TransListenerCoreTest_HandleCopyFailure_001 + * @tc.desc: Test function of TransListenerCore::HandleCopyFailure interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_HandleCopyFailure_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_HandleCopyFailure_001"; + + string path = "/data/test/TransListenerCoreTest_HandleCopyFailure_001.txt"; + Storage::DistributedFile::HmdfsInfo info; + info.authority = "abc"; + CopyEvent event; + event.errorCode = 0; + int result = TransListenerCore::HandleCopyFailure(event, info, path, ""); + EXPECT_EQ(result, EIO); + + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_HandleCopyFailure_001"; +} + +/** + * @tc.name: TransListenerCoreTest_HandleCopyFailure_002 + * @tc.desc: Test function of TransListenerCore::HandleCopyFailure interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_HandleCopyFailure_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_HandleCopyFailure_002"; + + string path = "/data/test/TransListenerCoreTest_HandleCopyFailure_002.txt"; + int32_t fd = open(path.c_str(), O_CREAT | O_RDWR, 0644); + close(fd); + + Storage::DistributedFile::HmdfsInfo info; + info.authority = "abc"; + CopyEvent event; + event.errorCode = SOFTBUS_TRANS_FILE_EXISTED; + int result = TransListenerCore::HandleCopyFailure(event, info, path, ""); + EXPECT_EQ(result, EEXIST); + + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_HandleCopyFailure_002"; +} + +/** + * @tc.name: TransListenerCoreTest_HandleCopyFailure_003 + * @tc.desc: Test function of TransListenerCore::HandleCopyFailure interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_HandleCopyFailure_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_HandleCopyFailure_003"; + + Storage::DistributedFile::HmdfsInfo info; + info.authority = MEDIA_AUTHORITY; + CopyEvent event; + event.errorCode = DFS_CANCEL_SUCCESS; + int result = TransListenerCore::HandleCopyFailure(event, info, "", ""); + EXPECT_EQ(result, ECANCELED); + + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_HandleCopyFailure_003"; +} + +/** + * @tc.name: TransListenerCoreTest_WaitForCopyResult_001 + * @tc.desc: Test function of TransListenerCore::WaitForCopyResult interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_WaitForCopyResult_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_WaitForCopyResult_001"; + + shared_ptr transListener(new TransListenerCore); + transListener->copyEvent_.copyResult = FAILED; + int result = TransListenerCore::WaitForCopyResult(transListener.get()); + EXPECT_EQ(result, 2); + + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_WaitForCopyResult_001"; +} + +/** + * @tc.name: TransListenerCoreTest_WaitForCopyResult_002 + * @tc.desc: Test function of TransListenerCore::WaitForCopyResult interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_WaitForCopyResult_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_WaitForCopyResult_002"; + + int result = TransListenerCore::WaitForCopyResult(nullptr); + EXPECT_TRUE(result); + + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_WaitForCopyResult_002"; +} + +// /** +// * @tc.name: TransListenerCoreTest_PrepareCopySession_001 +// * @tc.desc: Test function of TransListenerCore::PrepareCopySession interface for FALSE. +// * @tc.size: MEDIUM +// * @tc.type: FUNC +// * @tc.level Level 1 +// */ +// HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_PrepareCopySession_001, testing::ext::TestSize.Level1) +// { +// GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_PrepareCopySession_001"; + +// Storage::DistributedFile::HmdfsInfo info; +// info.authority = "abc"; +// info.authority = MEDIA_AUTHORITY; +// string srcUri = "http://translistener.preparecopysession?networkid=AD125AD1CF"; + +// string disSandboxPath = "disSandboxPath"; + +// int result = TransListenerCore::PrepareCopySession(srcUri, "destUri", nullptr, info, disSandboxPath); +// EXPECT_EQ(result, EIO); + +// GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_PrepareCopySession_001"; +// } + +// /** +// * @tc.name: TransListenerCoreTest_PrepareCopySession_002 +// * @tc.desc: Test function of TransListenerCore::PrepareCopySession interface for FALSE. +// * @tc.size: MEDIUM +// * @tc.type: FUNC +// * @tc.level Level 1 +// */ +// HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_PrepareCopySession_002, testing::ext::TestSize.Level1) +// { +// GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_PrepareCopySession_002"; + +// Storage::DistributedFile::HmdfsInfo info; +// info.authority = FILE_MANAGER_AUTHORITY; +// info.authority = "abc"; + +// string disSandboxPath = "disSandboxPath"; +// string srcUri = "http://translistener.preparecopysession?networkid=AD125AD1CF"; + +// int result = TransListenerCore::PrepareCopySession(srcUri, "destUri", nullptr, info, disSandboxPath); +// EXPECT_EQ(result, EIO); + +// GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_PrepareCopySession_002"; +// } + +/** + * @tc.name: TransListenerCoreTest_PrepareCopySession_003 + * @tc.desc: Test function of TransListenerCore::PrepareCopySession interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_PrepareCopySession_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_PrepareCopySession_003"; + + Storage::DistributedFile::HmdfsInfo info; + info.authority = "abc"; + info.authority = "abc"; + info.sandboxPath = "abc"; + + string disSandboxPath = "disSandboxPath"; + string srcUri = "http://translistener.preparecopysession?networkid=AD125AD1CF"; + + int result = TransListenerCore::PrepareCopySession(srcUri, "destUri", nullptr, info, disSandboxPath); + EXPECT_EQ(result, ENOENT); + + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_PrepareCopySession_003"; +} + +// /** +// * @tc.name: TransListenerCoreTest_PrepareCopySession_004 +// * @tc.desc: Test function of TransListenerCore::PrepareCopySession interface for FALSE. +// * @tc.size: MEDIUM +// * @tc.type: FUNC +// * @tc.level Level 1 +// */ +// HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_PrepareCopySession_004, testing::ext::TestSize.Level1) +// { +// GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_PrepareCopySession_004"; + +// Storage::DistributedFile::HmdfsInfo info; +// info.authority = "abc"; +// info.authority = "abc"; +// info.sandboxPath = "/data/test/PrepareCopySession_004.txt"; + +// string disSandboxPath = "disSandboxPath"; +// string srcUri = "http://translistener.preparecopysession?networkid=AD125AD1CF"; + +// int result = TransListenerCore::PrepareCopySession(srcUri, "destUri", nullptr, info, disSandboxPath); +// EXPECT_EQ(result, ERRNO_NOERR); + +// GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_PrepareCopySession_004"; +// } + +// /** +// * @tc.name: TransListenerCoreTest_PrepareCopySession_005 +// * @tc.desc: Test function of TransListenerCore::PrepareCopySession interface for FALSE. +// * @tc.size: MEDIUM +// * @tc.type: FUNC +// * @tc.level Level 1 +// */ +// HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_PrepareCopySession_005, testing::ext::TestSize.Level1) +// { +// GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_PrepareCopySession_005"; + +// Storage::DistributedFile::HmdfsInfo info; +// info.authority = "abc"; +// info.authority = "abc"; +// info.sandboxPath = "/data/test/PrepareCopySession_004.txt"; +// int32_t fd = open(info.sandboxPath.c_str(), O_CREAT | O_RDWR, 0644); +// close(fd); + +// string disSandboxPath = "disSandboxPath"; +// string srcUri = "http://translistener.preparecopysession?networkid=AD125AD1CF"; + +// int result = TransListenerCore::PrepareCopySession(srcUri, "destUri", nullptr, info, disSandboxPath); +// EXPECT_EQ(result, ERRNO_NOERR); + +// GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_PrepareCopySession_005"; +// } + +/** + * @tc.name: TransListenerCoreTest_CopyToSandBox_001 + * @tc.desc: Test function of TransListenerCore::CopyToSandBox interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_CopyToSandBox_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_CopyToSandBox_001"; + + string disSandboxPath = "disSandboxPath"; + string sandboxPath = "sandboxPath"; + string currentId = "currentId"; + + int result = TransListenerCore::CopyToSandBox("srcUri", disSandboxPath, sandboxPath, currentId); + EXPECT_EQ(result, EIO); + + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_CopyToSandBox_001"; +} + +/** + * @tc.name: TransListenerCoreTest_CopyToSandBox_002 + * @tc.desc: Test function of TransListenerCore::CopyToSandBox interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_CopyToSandBox_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_CopyToSandBox_002"; + + string disSandboxPath = g_path; + string sandboxPath = "/data/test"; + string currentId = "currentId"; + + int result = TransListenerCore::CopyToSandBox("srcUri", disSandboxPath, sandboxPath, currentId); + EXPECT_EQ(result, EIO); + + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_CopyToSandBox_002"; +} + +/** + * @tc.name: TransListenerCoreTest_GetFileName_001 + * @tc.desc: Test function of TransListenerCore::GetFileName interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_GetFileName_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_GetFileName_001"; + + string path = "abc"; + + auto result = TransListenerCore::GetFileName(path); + EXPECT_EQ(result, ""); + + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_GetFileName_001"; +} + +/** + * @tc.name: TransListenerCoreTest_GetFileName_002 + * @tc.desc: Test function of TransListenerCore::GetFileName interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_GetFileName_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_GetFileName_002"; + + auto result = TransListenerCore::GetFileName(g_path); + EXPECT_EQ(result, "/TransListenerCoreTest.txt"); + + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_GetFileName_002"; +} + +// /** +// * @tc.name: TransListenerCoreTest_GetNetworkIdFromUri_001 +// * @tc.desc: Test function of TransListenerCore::GetNetworkIdFromUri interface for FALSE. +// * @tc.size: MEDIUM +// * @tc.type: FUNC +// * @tc.level Level 1 +// */ +// HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_GetNetworkIdFromUri_001, testing::ext::TestSize.Level1) +// { +// GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_GetNetworkIdFromUri_001"; + +// string path = "abc"; + +// auto result = TransListenerCore::GetNetworkIdFromUri(path); +// EXPECT_EQ(result, ""); + +// GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_GetNetworkIdFromUri_001"; +// } + +/** + * @tc.name: TransListenerCoreTest_CallbackComplete_001 + * @tc.desc: Test function of TransListenerCore::CallbackComplete interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_CallbackComplete_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_CallbackComplete_001"; + + TransListenerCore::CallbackComplete(nullptr); + + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_CallbackComplete_001"; +} + +// /** +// * @tc.name: TransListenerCoreTest_CallbackComplete_002 +// * @tc.desc: Test function of TransListenerCore::CallbackComplete interface for FALSE. +// * @tc.size: MEDIUM +// * @tc.type: FUNC +// * @tc.level Level 1 +// */ +// HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_CallbackComplete_002, testing::ext::TestSize.Level1) +// { +// GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_CallbackComplete_002"; + +// std::shared_ptr infos(new FsFileInfos); +// std::shared_ptr entry(CopyCore::GetUVEntry(infos)); +// entry->callback = nullptr; +// TransListenerCore::CallbackComplete(entry); + +// GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_CallbackComplete_002"; +// } + +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file -- Gitee From 6514f5ec38b49ba408f404f01b311c58f772c475 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=91=A8=E9=91=AB?= Date: Wed, 18 Jun 2025 08:55:34 +0000 Subject: [PATCH 07/19] =?UTF-8?q?!3=20tdd=20Merge=20pull=20request=20!3=20?= =?UTF-8?q?from=20=E5=91=A8=E9=91=AB/0616=5Fcopy?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../js/mod_fs/properties/copy_core_test.cpp | 4 +- .../mod_fs/properties/trans_listener_test.cpp | 287 ++++++++++++------ 2 files changed, 194 insertions(+), 97 deletions(-) diff --git a/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp index 088817b9c..b2565730c 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp @@ -418,8 +418,8 @@ HWTEST_F(CopyCoreTest, CopyCoreTest_CreateFileInfos_001, testing::ext::TestSize. auto [errCode, infos] = CopyCore::CreateFileInfos(srcFile, destFile, options); EXPECT_EQ(errCode, ERRNO_NOERR); - GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_CreateFileInfos_001"; -} +// GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_CreateFileInfos_001"; +// } /** * @tc.name: CopyCoreTest_CopySubDir_001 diff --git a/interfaces/test/unittest/js/mod_fs/properties/trans_listener_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/trans_listener_test.cpp index 645ebfdb8..bd7e97009 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/trans_listener_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/trans_listener_test.cpp @@ -219,53 +219,53 @@ HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_WaitForCopyResult_002, tes GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_WaitForCopyResult_002"; } -// /** -// * @tc.name: TransListenerCoreTest_PrepareCopySession_001 -// * @tc.desc: Test function of TransListenerCore::PrepareCopySession interface for FALSE. -// * @tc.size: MEDIUM -// * @tc.type: FUNC -// * @tc.level Level 1 -// */ -// HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_PrepareCopySession_001, testing::ext::TestSize.Level1) -// { -// GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_PrepareCopySession_001"; +/** + * @tc.name: TransListenerCoreTest_PrepareCopySession_001 + * @tc.desc: Test function of TransListenerCore::PrepareCopySession interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_PrepareCopySession_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_PrepareCopySession_001"; -// Storage::DistributedFile::HmdfsInfo info; -// info.authority = "abc"; -// info.authority = MEDIA_AUTHORITY; -// string srcUri = "http://translistener.preparecopysession?networkid=AD125AD1CF"; + Storage::DistributedFile::HmdfsInfo info; + info.authority = "abc"; + info.authority = MEDIA_AUTHORITY; + string srcUri = "http://translistener.preparecopysession?networkid=AD125AD1CF"; -// string disSandboxPath = "disSandboxPath"; + string disSandboxPath = "disSandboxPath"; -// int result = TransListenerCore::PrepareCopySession(srcUri, "destUri", nullptr, info, disSandboxPath); -// EXPECT_EQ(result, EIO); + int result = TransListenerCore::PrepareCopySession(srcUri, "destUri", nullptr, info, disSandboxPath); + EXPECT_EQ(result, EIO); -// GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_PrepareCopySession_001"; -// } + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_PrepareCopySession_001"; +} -// /** -// * @tc.name: TransListenerCoreTest_PrepareCopySession_002 -// * @tc.desc: Test function of TransListenerCore::PrepareCopySession interface for FALSE. -// * @tc.size: MEDIUM -// * @tc.type: FUNC -// * @tc.level Level 1 -// */ -// HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_PrepareCopySession_002, testing::ext::TestSize.Level1) -// { -// GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_PrepareCopySession_002"; +/** + * @tc.name: TransListenerCoreTest_PrepareCopySession_002 + * @tc.desc: Test function of TransListenerCore::PrepareCopySession interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_PrepareCopySession_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_PrepareCopySession_002"; -// Storage::DistributedFile::HmdfsInfo info; -// info.authority = FILE_MANAGER_AUTHORITY; -// info.authority = "abc"; + Storage::DistributedFile::HmdfsInfo info; + info.authority = FILE_MANAGER_AUTHORITY; + info.authority = "abc"; -// string disSandboxPath = "disSandboxPath"; -// string srcUri = "http://translistener.preparecopysession?networkid=AD125AD1CF"; + string disSandboxPath = "disSandboxPath"; + string srcUri = "http://translistener.preparecopysession?networkid=AD125AD1CF"; -// int result = TransListenerCore::PrepareCopySession(srcUri, "destUri", nullptr, info, disSandboxPath); -// EXPECT_EQ(result, EIO); + int result = TransListenerCore::PrepareCopySession(srcUri, "destUri", nullptr, info, disSandboxPath); + EXPECT_EQ(result, ENOENT); -// GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_PrepareCopySession_002"; -// } + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_PrepareCopySession_002"; +} /** * @tc.name: TransListenerCoreTest_PrepareCopySession_003 @@ -292,57 +292,57 @@ HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_PrepareCopySession_003, te GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_PrepareCopySession_003"; } -// /** -// * @tc.name: TransListenerCoreTest_PrepareCopySession_004 -// * @tc.desc: Test function of TransListenerCore::PrepareCopySession interface for FALSE. -// * @tc.size: MEDIUM -// * @tc.type: FUNC -// * @tc.level Level 1 -// */ -// HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_PrepareCopySession_004, testing::ext::TestSize.Level1) -// { -// GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_PrepareCopySession_004"; +/** + * @tc.name: TransListenerCoreTest_PrepareCopySession_004 + * @tc.desc: Test function of TransListenerCore::PrepareCopySession interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_PrepareCopySession_004, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_PrepareCopySession_004"; -// Storage::DistributedFile::HmdfsInfo info; -// info.authority = "abc"; -// info.authority = "abc"; -// info.sandboxPath = "/data/test/PrepareCopySession_004.txt"; + Storage::DistributedFile::HmdfsInfo info; + info.authority = "abc"; + info.authority = "abc"; + info.sandboxPath = "/data/test/PrepareCopySession_004.txt"; -// string disSandboxPath = "disSandboxPath"; -// string srcUri = "http://translistener.preparecopysession?networkid=AD125AD1CF"; + string disSandboxPath = "disSandboxPath"; + string srcUri = "http://translistener.preparecopysession?networkid=AD125AD1CF"; -// int result = TransListenerCore::PrepareCopySession(srcUri, "destUri", nullptr, info, disSandboxPath); -// EXPECT_EQ(result, ERRNO_NOERR); + int result = TransListenerCore::PrepareCopySession(srcUri, "destUri", nullptr, info, disSandboxPath); + EXPECT_EQ(result, ENOENT); -// GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_PrepareCopySession_004"; -// } + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_PrepareCopySession_004"; +} -// /** -// * @tc.name: TransListenerCoreTest_PrepareCopySession_005 -// * @tc.desc: Test function of TransListenerCore::PrepareCopySession interface for FALSE. -// * @tc.size: MEDIUM -// * @tc.type: FUNC -// * @tc.level Level 1 -// */ -// HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_PrepareCopySession_005, testing::ext::TestSize.Level1) -// { -// GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_PrepareCopySession_005"; +/** + * @tc.name: TransListenerCoreTest_PrepareCopySession_005 + * @tc.desc: Test function of TransListenerCore::PrepareCopySession interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_PrepareCopySession_005, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_PrepareCopySession_005"; -// Storage::DistributedFile::HmdfsInfo info; -// info.authority = "abc"; -// info.authority = "abc"; -// info.sandboxPath = "/data/test/PrepareCopySession_004.txt"; -// int32_t fd = open(info.sandboxPath.c_str(), O_CREAT | O_RDWR, 0644); -// close(fd); + Storage::DistributedFile::HmdfsInfo info; + info.authority = "abc"; + info.authority = "abc"; + info.sandboxPath = "/data/test/PrepareCopySession_004.txt"; + int32_t fd = open(info.sandboxPath.c_str(), O_CREAT | O_RDWR, 0644); + close(fd); -// string disSandboxPath = "disSandboxPath"; -// string srcUri = "http://translistener.preparecopysession?networkid=AD125AD1CF"; + string disSandboxPath = "disSandboxPath"; + string srcUri = "http://translistener.preparecopysession?networkid=AD125AD1CF"; -// int result = TransListenerCore::PrepareCopySession(srcUri, "destUri", nullptr, info, disSandboxPath); -// EXPECT_EQ(result, ERRNO_NOERR); + int result = TransListenerCore::PrepareCopySession(srcUri, "destUri", nullptr, info, disSandboxPath); + EXPECT_EQ(result, ENOENT); -// GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_PrepareCopySession_005"; -// } + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_PrepareCopySession_005"; +} /** * @tc.name: TransListenerCoreTest_CopyToSandBox_001 @@ -422,24 +422,24 @@ HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_GetFileName_002, testing:: GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_GetFileName_002"; } -// /** -// * @tc.name: TransListenerCoreTest_GetNetworkIdFromUri_001 -// * @tc.desc: Test function of TransListenerCore::GetNetworkIdFromUri interface for FALSE. -// * @tc.size: MEDIUM -// * @tc.type: FUNC -// * @tc.level Level 1 -// */ -// HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_GetNetworkIdFromUri_001, testing::ext::TestSize.Level1) -// { -// GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_GetNetworkIdFromUri_001"; +/** + * @tc.name: TransListenerCoreTest_GetNetworkIdFromUri_001 + * @tc.desc: Test function of TransListenerCore::GetNetworkIdFromUri interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_GetNetworkIdFromUri_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_GetNetworkIdFromUri_001"; -// string path = "abc"; + string uri = "http://translistener.preparecopysession?networkid=AD125AD1CF"; -// auto result = TransListenerCore::GetNetworkIdFromUri(path); -// EXPECT_EQ(result, ""); + auto result = TransListenerCore::GetNetworkIdFromUri(uri); + EXPECT_EQ(result, "AD125AD1CF"); -// GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_GetNetworkIdFromUri_001"; -// } + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_GetNetworkIdFromUri_001"; +} /** * @tc.name: TransListenerCoreTest_CallbackComplete_001 @@ -476,4 +476,101 @@ HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_CallbackComplete_001, test // GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_CallbackComplete_002"; // } +/** + * @tc.name: TransListenerCoreTest_OnFileReceive_001 + * @tc.desc: Test function of TransListenerCore::OnFileReceive interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_OnFileReceive_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_OnFileReceive_001"; + + shared_ptr transListener(new TransListenerCore); + transListener->callback_ = nullptr; + auto res = transListener->OnFileReceive(0, 0); + EXPECT_EQ(res, ENOMEM); + + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_OnFileReceive_001"; +} + +// /** +// * @tc.name: TransListenerCoreTest_OnFileReceive_002 +// * @tc.desc: Test function of TransListenerCore::OnFileReceive interface for FALSE. +// * @tc.size: MEDIUM +// * @tc.type: FUNC +// * @tc.level Level 1 +// */ +// HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_OnFileReceive_002, testing::ext::TestSize.Level1) +// { +// GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_OnFileReceive_002"; + +// shared_ptr transListener(new TransListenerCore); +// transListener->callback_ = make_shared(reinterpret_cast(0x1000)); +// auto res = transListener->OnFileReceive(0, 0); +// EXPECT_EQ(res, ERRNO_NOERR); + +// GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_OnFileReceive_002"; +// } + +/** + * @tc.name: TransListenerCoreTest_OnFinished_001 + * @tc.desc: Test function of TransListenerCore::OnFinished interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_OnFinished_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_OnFinished_001"; + + shared_ptr transListener(new TransListenerCore); + auto res = transListener->OnFinished("sessionName"); + EXPECT_EQ(res, ERRNO_NOERR); + + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_OnFinished_001"; +} + +/** + * @tc.name: TransListenerCoreTest_OnFailed_001 + * @tc.desc: Test function of TransListenerCore::OnFailed interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_OnFailed_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_OnFailed_001"; + + shared_ptr transListener(new TransListenerCore); + auto res = transListener->OnFailed("sessionName", 0); + EXPECT_EQ(res, ERRNO_NOERR); + + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_OnFailed_001"; +} + +/** + * @tc.name: TransListenerCoreTest_CopyFileFromSoftBus_001 + * @tc.desc: Test function of TransListenerCore::CopyFileFromSoftBus interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_CopyFileFromSoftBus_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_CopyFileFromSoftBus_001"; + + string srcUri = "http://translistener.preparecopysession?networkid=AD125AD1CF"; + shared_ptr transListener(new TransListenerCore); + std::shared_ptr infos(new FsFileInfos); + transListener->copyEvent_.copyResult = FAILED; + + auto res = transListener->CopyFileFromSoftBus(srcUri, "destUri", infos, nullptr); + + EXPECT_EQ(res, EIO); + + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_CopyFileFromSoftBus_001"; +} + } // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file -- Gitee From 5dfe052d7f0e80d0e4b86adda7a78720700f52f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=91=A8=E9=91=AB?= Date: Thu, 19 Jun 2025 08:34:48 +0000 Subject: [PATCH 08/19] =?UTF-8?q?!4=200619=20*=20Merge=20branch=20'copy=5F?= =?UTF-8?q?bugfix'=20of=20gitee.com:tian-peng8881/OpenHarmony=5Ffile?= =?UTF-8?q?=E2=80=A6=20*=200619=20*=20tdd=20*=20bak=20*=20bak=20*=20tdd?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- interfaces/test/unittest/js/BUILD.gn | 50 ++++ .../js/mod_fs/properties/copy_core_test.cpp | 4 +- .../properties/trans_listener_mock_test.cpp | 229 ++++++++++++++++++ .../mod_fs/properties/trans_listener_test.cpp | 108 ++++++--- 4 files changed, 352 insertions(+), 39 deletions(-) create mode 100644 interfaces/test/unittest/js/mod_fs/properties/trans_listener_mock_test.cpp diff --git a/interfaces/test/unittest/js/BUILD.gn b/interfaces/test/unittest/js/BUILD.gn index 3b5e3f420..be174c36a 100644 --- a/interfaces/test/unittest/js/BUILD.gn +++ b/interfaces/test/unittest/js/BUILD.gn @@ -70,4 +70,54 @@ ohos_unittest("ani_file_fs_test") { defines = [ "private=public", ] +} + +ohos_unittest("ani_file_fs_mock_test") { + branch_protector_ret = "pac_ret" + testonly = true + + module_out_path = "file_api/file_api" + + include_dirs = [ + "${file_api_path}/interfaces/kits/js/src/mod_fs/class_atomicfile", + "${file_api_path}/interfaces/kits/js/src/mod_fs/class_file", + "${file_api_path}/interfaces/kits/js/src/mod_fs/class_randomaccessfile", + "${file_api_path}/interfaces/kits/js/src/mod_fs/class_readeriterator", + "${file_api_path}/interfaces/kits/js/src/mod_fs/class_stat", + "${file_api_path}/interfaces/kits/js/src/mod_fs/class_stream", + "${file_api_path}/interfaces/kits/js/src/mod_fs/class_tasksignal", + "${file_api_path}/interfaces/kits/js/src/mod_fs/properties", + "${file_api_path}/interfaces/kits/js/src/mod_fs/properties/copy_listener", + ] + + sources = [ + "mod_fs/properties/trans_listener_mock_test.cpp", + ] + + deps = [ + "${file_api_path}/interfaces/kits/native:remote_uri_native", + "${file_api_path}/interfaces/kits/native:task_signal_native", + "${file_api_path}/interfaces/kits/rust:rust_file", + "${utils_path}/filemgmt_libfs:filemgmt_libfs", + "${utils_path}/filemgmt_libhilog:filemgmt_libhilog", + "${file_api_path}/interfaces/kits/js:ani_file_fs", + ] + + external_deps = [ + "ability_runtime:ability_manager", + "app_file_service:fileuri_native", + "c_utils:utils", + "dfs_service:distributed_file_daemon_kit_inner", + "dfs_service:libdistributedfileutils", + "googletest:gmock_main", + "googletest:gtest_main", + "hilog:libhilog", + "ipc:ipc_core", + "libuv:uv", + ] + + defines = [ + "ENABLE_DISTRIBUTED_FILE_MOCK", + "private=public", + ] } \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp index b2565730c..088817b9c 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp @@ -418,8 +418,8 @@ HWTEST_F(CopyCoreTest, CopyCoreTest_CreateFileInfos_001, testing::ext::TestSize. auto [errCode, infos] = CopyCore::CreateFileInfos(srcFile, destFile, options); EXPECT_EQ(errCode, ERRNO_NOERR); -// GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_CreateFileInfos_001"; -// } + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_CreateFileInfos_001"; +} /** * @tc.name: CopyCoreTest_CopySubDir_001 diff --git a/interfaces/test/unittest/js/mod_fs/properties/trans_listener_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/trans_listener_mock_test.cpp new file mode 100644 index 000000000..56c11d8b5 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/trans_listener_mock_test.cpp @@ -0,0 +1,229 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "trans_listener_core.h" + +#include +#include +#include + +#include "copy_core.h" + +using namespace OHOS; +using namespace OHOS::Storage::DistributedFile; + +class MockDistributedFileDaemonManager : public DistributedFileDaemonManager { +public: + MOCK_METHOD(int32_t, CancelCopyTask, (const std::string &sessionName), (override)); + + int32_t OpenP2PConnection(const DistributedHardware::DmDeviceInfo &deviceInfo) override + { + return 0; + } + + int32_t CloseP2PConnection(const DistributedHardware::DmDeviceInfo &deviceInfo) override + { + return 0; + } + + int32_t OpenP2PConnectionEx(const std::string &networkId, sptr remoteReverseObj) override + { + return 0; + } + + int32_t CloseP2PConnectionEx(const std::string &networkId) override + { + return 0; + } + + // int32_t PrepareSession(const std::string &srcUri, const std::string &dstUri, const std::string &srcDeviceId, + // const sptr &listener, HmdfsInfo &info) override + // { + // return 0; + // } + MOCK_METHOD(int32_t, PrepareSession, (const std::string &srcUri, const std::string &dstUri, + const std::string &srcDeviceId, + const sptr &listener, HmdfsInfo &info), (override)); + + int32_t PushAsset( + int32_t userId, const sptr &assetObj, const sptr &sendCallback) override + { + return 0; + } + + int32_t RegisterAssetCallback(const sptr &recvCallback) override + { + return 0; + } + + int32_t UnRegisterAssetCallback(const sptr &recvCallback) override + { + return 0; + } + + int32_t GetSize(const std::string &uri, bool isSrcUri, uint64_t &size) override + { + return 0; + } + + int32_t IsDirectory(const std::string &uri, bool isSrcUri, bool &isDirectory) override + { + return 0; + } + + int32_t Copy(const std::string &srcUri, const std::string &destUri, ProcessCallback processCallback) override + { + return 0; + } + + int32_t Cancel(const std::string &srcUri, const std::string &destUri) override + { + return 0; + } + + int32_t Cancel() override + { + return 0; + } + + static MockDistributedFileDaemonManager &GetInstance() + { + static MockDistributedFileDaemonManager instance; + return instance; + } +}; + +static MockDistributedFileDaemonManager &g_mockDistributedFileDaemonManager = + MockDistributedFileDaemonManager::GetInstance(); + +#ifdef ENABLE_DISTRIBUTED_FILE_MOCK +DistributedFileDaemonManager &DistributedFileDaemonManager::GetInstance() +{ + return MockDistributedFileDaemonManager::GetInstance(); +} +#endif + +class MockTaskSignalListener : public OHOS::DistributedFS::ModuleTaskSignal::TaskSignalListener { +public: + MOCK_METHOD(void, OnCancel, (), (override)); +}; + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +string g_path = "/data/test/TransListenerCoreTest.txt"; +const string FILE_MANAGER_AUTHORITY = "docs"; +const string MEDIA_AUTHORITY = "media"; + +class IProgressListenerTest : public IProgressListener { +public: + void InvokeListener(uint64_t progressSize, uint64_t totalSize) const override {} +}; + +class TransListenerCoreTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + MockDistributedFileDaemonManager &GetMock() + { + return g_mockDistributedFileDaemonManager; + } +}; + +void TransListenerCoreTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + int32_t fd = open(g_path.c_str(), O_CREAT | O_RDWR, 0644); + close(fd); +} + +void TransListenerCoreTest::TearDownTestCase(void) +{ + rmdir(g_path.c_str()); + GTEST_LOG_(INFO) << "TearDownTestCase"; +} + +void TransListenerCoreTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void TransListenerCoreTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: TransListenerCoreTest_PrepareCopySession_001 + * @tc.desc: Test function of TransListenerCore::PrepareCopySession interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_PrepareCopySession_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_PrepareCopySession_001"; + + Storage::DistributedFile::HmdfsInfo info; + info.authority = FILE_MANAGER_AUTHORITY; + info.authority = MEDIA_AUTHORITY; + string srcUri = "http://translistener.preparecopysession?networkid=AD125AD1CF"; + + string disSandboxPath = "disSandboxPath"; + + EXPECT_CALL(GetMock(), PrepareSession(testing::_, testing::_, testing::_, testing::_, testing::_)) + .WillOnce(testing::Return(ERRNO_NOERR)); + auto result = TransListenerCore::PrepareCopySession(srcUri, "destUri", nullptr, info, disSandboxPath); + EXPECT_EQ(result, ERRNO_NOERR); + + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_PrepareCopySession_001"; +} + +/** + * @tc.name: TransListenerCoreTest_CopyFileFromSoftBus_001 + * @tc.desc: Test function of TransListenerCore::CopyFileFromSoftBus interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_CopyFileFromSoftBus_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_CopyFileFromSoftBus_001"; + + Storage::DistributedFile::HmdfsInfo info; + info.authority = FILE_MANAGER_AUTHORITY; + + string srcUri = "http://translistener.preparecopysession?networkid=AD125AD1CF"; + shared_ptr transListener(new TransListenerCore); + std::shared_ptr infos(new FsFileInfos); + // transListener->copyEvent_.copyResult = FAILED; + + // shared_ptr transListenerArg(new TransListenerCore); + // transListenerArg->copyEvent_.errorCode = DFS_CANCEL_SUCCESS; + + EXPECT_CALL(GetMock(), PrepareSession(testing::_, testing::_, testing::_, testing::_, testing::_)) + .WillOnce(testing::Return(ERRNO_NOERR)); + + auto res = transListener->CopyFileFromSoftBus(srcUri, "destUri", infos, nullptr); + EXPECT_EQ(res, EIO); + + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_CopyFileFromSoftBus_001"; +} + +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/trans_listener_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/trans_listener_test.cpp index bd7e97009..b1a727d4e 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/trans_listener_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/trans_listener_test.cpp @@ -29,6 +29,11 @@ string g_path = "/data/test/TransListenerCoreTest.txt"; const string FILE_MANAGER_AUTHORITY = "docs"; const string MEDIA_AUTHORITY = "media"; +class IProgressListenerTest : public IProgressListener { +public: + void InvokeListener(uint64_t progressSize, uint64_t totalSize) const override {} +}; + class TransListenerCoreTest : public testing::Test { public: static void SetUpTestCase(void); @@ -231,7 +236,6 @@ HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_PrepareCopySession_001, te GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_PrepareCopySession_001"; Storage::DistributedFile::HmdfsInfo info; - info.authority = "abc"; info.authority = MEDIA_AUTHORITY; string srcUri = "http://translistener.preparecopysession?networkid=AD125AD1CF"; @@ -255,7 +259,6 @@ HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_PrepareCopySession_002, te GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_PrepareCopySession_002"; Storage::DistributedFile::HmdfsInfo info; - info.authority = FILE_MANAGER_AUTHORITY; info.authority = "abc"; string disSandboxPath = "disSandboxPath"; @@ -280,7 +283,6 @@ HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_PrepareCopySession_003, te Storage::DistributedFile::HmdfsInfo info; info.authority = "abc"; - info.authority = "abc"; info.sandboxPath = "abc"; string disSandboxPath = "disSandboxPath"; @@ -305,7 +307,6 @@ HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_PrepareCopySession_004, te Storage::DistributedFile::HmdfsInfo info; info.authority = "abc"; - info.authority = "abc"; info.sandboxPath = "/data/test/PrepareCopySession_004.txt"; string disSandboxPath = "disSandboxPath"; @@ -330,7 +331,6 @@ HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_PrepareCopySession_005, te Storage::DistributedFile::HmdfsInfo info; info.authority = "abc"; - info.authority = "abc"; info.sandboxPath = "/data/test/PrepareCopySession_004.txt"; int32_t fd = open(info.sandboxPath.c_str(), O_CREAT | O_RDWR, 0644); close(fd); @@ -457,24 +457,58 @@ HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_CallbackComplete_001, test GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_CallbackComplete_001"; } -// /** -// * @tc.name: TransListenerCoreTest_CallbackComplete_002 -// * @tc.desc: Test function of TransListenerCore::CallbackComplete interface for FALSE. -// * @tc.size: MEDIUM -// * @tc.type: FUNC -// * @tc.level Level 1 -// */ -// HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_CallbackComplete_002, testing::ext::TestSize.Level1) -// { -// GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_CallbackComplete_002"; +/** + * @tc.name: TransListenerCoreTest_CallbackComplete_002 + * @tc.desc: Test function of TransListenerCore::CallbackComplete interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_CallbackComplete_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_CallbackComplete_002"; -// std::shared_ptr infos(new FsFileInfos); -// std::shared_ptr entry(CopyCore::GetUVEntry(infos)); -// entry->callback = nullptr; -// TransListenerCore::CallbackComplete(entry); + auto entry = make_shared(make_shared(std::make_shared())); + entry->callback = nullptr; + TransListenerCore::CallbackComplete(entry); -// GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_CallbackComplete_002"; -// } + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_CallbackComplete_002"; +} + +/** + * @tc.name: TransListenerCoreTest_CallbackComplete_003 + * @tc.desc: Test function of TransListenerCore::CallbackComplete interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_CallbackComplete_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_CallbackComplete_003"; + + auto entry = make_shared(make_shared(std::make_shared())); + entry->callback->listener = nullptr; + TransListenerCore::CallbackComplete(entry); + + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_CallbackComplete_003"; +} + +/** + * @tc.name: TransListenerCoreTest_CallbackComplete_004 + * @tc.desc: Test function of TransListenerCore::CallbackComplete interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_CallbackComplete_004, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_CallbackComplete_004"; + + auto entry = make_shared(make_shared(std::make_shared())); + TransListenerCore::CallbackComplete(entry); + + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_CallbackComplete_004"; +} /** * @tc.name: TransListenerCoreTest_OnFileReceive_001 @@ -495,24 +529,24 @@ HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_OnFileReceive_001, testing GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_OnFileReceive_001"; } -// /** -// * @tc.name: TransListenerCoreTest_OnFileReceive_002 -// * @tc.desc: Test function of TransListenerCore::OnFileReceive interface for FALSE. -// * @tc.size: MEDIUM -// * @tc.type: FUNC -// * @tc.level Level 1 -// */ -// HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_OnFileReceive_002, testing::ext::TestSize.Level1) -// { -// GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_OnFileReceive_002"; +/** + * @tc.name: TransListenerCoreTest_OnFileReceive_002 + * @tc.desc: Test function of TransListenerCore::OnFileReceive interface for SUCC. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_OnFileReceive_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "TransListenerCoreTest-begin TransListenerCoreTest_OnFileReceive_002"; -// shared_ptr transListener(new TransListenerCore); -// transListener->callback_ = make_shared(reinterpret_cast(0x1000)); -// auto res = transListener->OnFileReceive(0, 0); -// EXPECT_EQ(res, ERRNO_NOERR); + shared_ptr transListener(new TransListenerCore); + transListener->callback_ = make_shared(std::make_shared()); + auto res = transListener->OnFileReceive(0, 0); + EXPECT_EQ(res, ERRNO_NOERR); -// GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_OnFileReceive_002"; -// } + GTEST_LOG_(INFO) << "TransListenerCoreTest-end TransListenerCoreTest_OnFileReceive_002"; +} /** * @tc.name: TransListenerCoreTest_OnFinished_001 -- Gitee From 5a2c39ba3de471f81cd92676af861e10eac40be7 Mon Sep 17 00:00:00 2001 From: tianp Date: Thu, 19 Jun 2025 16:59:29 +0800 Subject: [PATCH 09/19] copy Signed-off-by: tianp Change-Id: Ia589d5c80946aac16fc0e8d9603758ac7af20cfd --- interfaces/test/unittest/BUILD.gn | 1 + interfaces/test/unittest/js/BUILD.gn | 5 +- .../mod_fs/properties/copy_core_mock_test.cpp | 134 ++++++++++ .../js/mod_fs/properties/copy_core_test.cpp | 243 +++++++++++++++++- .../js/mod_fs/properties/mock/uv_fs_mock.cpp | 5 + .../js/mod_fs/properties/mock/uv_fs_mock.h | 4 + 6 files changed, 390 insertions(+), 2 deletions(-) create mode 100644 interfaces/test/unittest/js/mod_fs/properties/copy_core_mock_test.cpp diff --git a/interfaces/test/unittest/BUILD.gn b/interfaces/test/unittest/BUILD.gn index 3a6c6eb26..e7ec1360f 100644 --- a/interfaces/test/unittest/BUILD.gn +++ b/interfaces/test/unittest/BUILD.gn @@ -17,6 +17,7 @@ group("file_api_unittest") { "class_file:class_file_test", "filemgmt_libn_test:filemgmt_libn_test", "js:ani_file_fs_test", + "js:ani_file_fs_mock_test", "remote_uri:remote_uri_test", "task_signal:task_signal_test", ] diff --git a/interfaces/test/unittest/js/BUILD.gn b/interfaces/test/unittest/js/BUILD.gn index be174c36a..c3afa2779 100644 --- a/interfaces/test/unittest/js/BUILD.gn +++ b/interfaces/test/unittest/js/BUILD.gn @@ -88,10 +88,13 @@ ohos_unittest("ani_file_fs_mock_test") { "${file_api_path}/interfaces/kits/js/src/mod_fs/class_tasksignal", "${file_api_path}/interfaces/kits/js/src/mod_fs/properties", "${file_api_path}/interfaces/kits/js/src/mod_fs/properties/copy_listener", + "${file_api_path}/interfaces/test/unittest/js/mod_fs/properties/mock", ] sources = [ + "mod_fs/properties/copy_core_mock_test.cpp", "mod_fs/properties/trans_listener_mock_test.cpp", + "mod_fs/properties/mock/uv_fs_mock.cpp", ] deps = [ @@ -115,7 +118,7 @@ ohos_unittest("ani_file_fs_mock_test") { "ipc:ipc_core", "libuv:uv", ] - + defines = [ "ENABLE_DISTRIBUTED_FILE_MOCK", "private=public", diff --git a/interfaces/test/unittest/js/mod_fs/properties/copy_core_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/copy_core_mock_test.cpp new file mode 100644 index 000000000..6c4e34455 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/copy_core_mock_test.cpp @@ -0,0 +1,134 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "copy_core.h" +#include "mock/uv_fs_mock.h" + +#include +#include +#include +#include +#include + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class CopyCoreMockTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr uvMock = nullptr; + + static const string testDir; + static const string srcDir; + static const string destDir; + static const string srcFile; + static const string destFile; +}; + +const string CopyCoreMockTest::testDir = "/data/test"; +const string CopyCoreMockTest::srcDir = testDir + "/src"; +const string CopyCoreMockTest::destDir = testDir + "/dest"; +const string CopyCoreMockTest::srcFile = srcDir + "/src.txt"; +const string CopyCoreMockTest::destFile = destDir + "/dest.txt"; + +void CopyCoreMockTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + mkdir(testDir.c_str(), 0755); + mkdir(srcDir.c_str(), 0755); + mkdir(destDir.c_str(), 0755); + int32_t fd = open(srcFile.c_str(), O_CREAT | O_RDWR, 0644); + if (fd >= 0) { + close(fd); + } + uvMock = std::make_shared(); + Uvfs::ins = uvMock; +} + +void CopyCoreMockTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; + remove(srcFile.c_str()); + rmdir(srcDir.c_str()); + rmdir(destDir.c_str()); + rmdir(testDir.c_str()); + Uvfs::ins = nullptr; + uvMock = nullptr; +} + +void CopyCoreMockTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void CopyCoreMockTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; + remove(destFile.c_str()); +} + +/** + * @tc.name: CopyCoreMockTest_CopyFile_001 + * @tc.desc: Test function of CopyCore::CopyFile interface for file copy FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreMockTest, CopyCoreMockTest_CopyFile_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreMockTest-begin CopyCoreMockTest_CopyFile_001"; + + auto infos = make_shared(); + infos->isFile = true; + infos->srcPath = CopyCoreMockTest::srcFile; + infos->destPath = CopyCoreMockTest::destFile; + + EXPECT_CALL(*uvMock, uv_fs_sendfile(_, _, _, _, _, _, _)).WillOnce(Return(-1)); + + auto res = CopyCore::CopyFile(srcFile, destFile, infos); + EXPECT_EQ(res, errno); + + GTEST_LOG_(INFO) << "CopyCoreMockTest-end CopyCoreMockTest_CopyFile_001"; +} + +/** + * @tc.name: CopyCoreMockTest_DoCopy_001 + * @tc.desc: Test function of CopyCore::DoCopy interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreMockTest, CopyCoreMockTest_DoCopy_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreMockTest-begin CopyCoreMockTest_DoCopy_001"; + + string srcFile = "/data/test/src/src.txt"; + string destFile = "/data/test/dest/dest.txt"; + optional options; + + EXPECT_CALL(*uvMock, uv_fs_sendfile(_, _, _, _, _, _, _)).WillOnce(Return(0)); + + auto res = CopyCore::DoCopy(srcFile, destFile, options); + EXPECT_EQ(res.IsSuccess(), false); + + GTEST_LOG_(INFO) << "CopyCoreMockTest-end CopyCoreMockTest_DoCopy_001"; +} + +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp index 088817b9c..29dea123a 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp @@ -455,6 +455,37 @@ HWTEST_F(CopyCoreTest, CopyCoreTest_CopySubDir_001, testing::ext::TestSize.Level GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_CopySubDir_001"; } +/** + * @tc.name: CopyCoreTest_CopySubDir_002 + * @tc.desc: Test function of CopyCore::CopySubDir interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_CopySubDir_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_CopySubDir_002"; + + string subDir = srcDir + "/sub_dir"; + mkdir(subDir.c_str(), 0755); + string subFile = subDir + "/sub_file.txt"; + int fd = open(subFile.c_str(), O_CREAT | O_RDWR, 0644); + if (fd >= 0) { + close(fd); + } + + string destSubDir = destDir + "/sub_dir"; + auto infos = make_shared(); + infos->notifyFd = 1; + auto res = CopyCore::CopySubDir(subDir, destSubDir, infos); + EXPECT_EQ(res, errno); + + remove(subFile.c_str()); + rmdir(subDir.c_str()); + rmdir(destSubDir.c_str()); + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_CopySubDir_002"; +} + /** * @tc.name: CopyCoreTest_RecurCopyDir_001 * @tc.desc: Test function of CopyCore::RecurCopyDir interface for success. @@ -540,8 +571,8 @@ HWTEST_F(CopyCoreTest, CopyCoreTest_ExecLocal_001, testing::ext::TestSize.Level1 infos->isFile = true; infos->srcPath = srcFile; infos->destPath = destFile; - auto callback = make_shared(nullptr); + auto res = CopyCore::ExecLocal(infos, callback); EXPECT_EQ(res, ERRNO_NOERR); EXPECT_TRUE(CopyCore::IsFile(destFile)); @@ -549,6 +580,29 @@ HWTEST_F(CopyCoreTest, CopyCoreTest_ExecLocal_001, testing::ext::TestSize.Level1 GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_ExecLocal_001"; } +/** + * @tc.name: CopyCoreTest_ExecLocal_002 + * @tc.desc: Test function of CopyCore::ExecLocal interface for file copy FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_ExecLocal_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_ExecLocal_002"; + + auto infos = make_shared(); + infos->isFile = true; + infos->srcPath = srcFile; + infos->destPath = srcFile; + auto callback = make_shared(nullptr); + + auto res = CopyCore::ExecLocal(infos, callback); + EXPECT_EQ(res, EINVAL); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_ExecLocal_002"; +} + /** * @tc.name: CopyCoreTest_RegisterListener_001 * @tc.desc: Test function of CopyCore::RegisterListener interface for success. @@ -623,4 +677,191 @@ HWTEST_F(CopyCoreTest, CopyCoreTest_DoCopy_001, testing::ext::TestSize.Level1) GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_DoCopy_001"; } +/** + * @tc.name: CopyCoreTest_GetDirSize_001 + * @tc.desc: Test function of CopyCore::GetDirSize interface for file copy success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_GetDirSize_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_GetDirSize_001"; + + auto infos = make_shared(); + infos->isFile = true; + infos->srcPath = srcFile; + infos->destPath = destFile; + + auto res = CopyCore::GetDirSize(infos, srcDir); + EXPECT_EQ(res, 0); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_GetDirSize_001"; +} + +/** + * @tc.name: CopyCoreTest_GetUVEntry_001 + * @tc.desc: Test function of CopyCore::GetUVEntry interface for file copy FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_GetUVEntry_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_GetUVEntry_001"; + + auto infos = make_shared(); + auto res = CopyCore::GetUVEntry(infos); + EXPECT_EQ(res, nullptr); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_GetUVEntry_001"; +} + +/** + * @tc.name: CopyCoreTest_CheckFileValid_001 + * @tc.desc: Test function of CopyCore::CheckFileValid interface for file copy FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_CheckFileValid_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_CheckFileValid_001"; + + auto infos = make_shared(); + infos->isFile = true; + infos->srcPath = srcFile; + infos->destPath = destFile; + + auto res = CopyCore::CheckFileValid(srcFile, infos); + EXPECT_EQ(res, false); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_CheckFileValid_001"; +} + +/** + * @tc.name: CopyCoreTest_UpdateProgressSize_001 + * @tc.desc: Test function of CopyCore::UpdateProgressSize interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_UpdateProgressSize_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_UpdateProgressSize_001"; + + auto receivedInfo = make_shared(); + auto callback = make_shared(nullptr); + + auto res = CopyCore::UpdateProgressSize(srcFile, receivedInfo, callback); + EXPECT_EQ(res, ERRNO_NOERR); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_UpdateProgressSize_001"; +} + +/** + * @tc.name: CopyCoreTest_GetRegisteredListener_001 + * @tc.desc: Test function of CopyCore::GetRegisteredListener interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_GetRegisteredListener_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_GetRegisteredListener_001"; + + auto infos = make_shared(); + infos->isFile = true; + infos->srcPath = srcFile; + infos->destPath = destFile; + + auto res = CopyCore::GetRegisteredListener(infos); + EXPECT_EQ(res, nullptr); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_GetRegisteredListener_001"; +} + +/** + * @tc.name: CopyCoreTest_SubscribeLocalListener_001 + * @tc.desc: Test function of CopyCore::SubscribeLocalListener interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_SubscribeLocalListener_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_SubscribeLocalListener_001"; + + auto infos = make_shared(); + infos->isFile = true; + infos->srcPath = srcFile; + infos->destPath = destFile; + auto callback = make_shared(nullptr); + + auto res = CopyCore::SubscribeLocalListener(infos, callback); + EXPECT_EQ(res, errno); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_SubscribeLocalListener_001"; +} + +/** + * @tc.name: CopyCoreTest_GetRealPath_001 + * @tc.desc: Test function of CopyCore::GetRealPath interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_GetRealPath_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_GetRealPath_001"; + + string path = "./data/test/src/src.txt"; + + auto res = CopyCore::GetRealPath(path); + EXPECT_EQ(res, "data/test/src/src.txt"); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_GetRealPath_001"; +} + +/** + * @tc.name: CopyCoreTest_GetRealPath_002 + * @tc.desc: Test function of CopyCore::GetRealPath interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_GetRealPath_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_GetRealPath_002"; + + string path = "../data/test/src/src.txt"; + + auto res = CopyCore::GetRealPath(path); + EXPECT_EQ(res, "data/test/src/src.txt"); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_GetRealPath_002"; +} + +/** + * @tc.name: CopyCoreTest_ExecCopy_001 + * @tc.desc: Test function of CopyCore::ExecCopy interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_ExecCopy_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_ExecCopy_001"; + + auto infos = make_shared(); + infos->isFile = false; + infos->srcPath = "/data/test/src"; + infos->destPath = "/data/test/dest"; + + auto res = CopyCore::ExecCopy(infos); + EXPECT_EQ(res, ERRNO_NOERR); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_ExecCopy_001"; +} + } // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/mock/uv_fs_mock.cpp b/interfaces/test/unittest/js/mod_fs/properties/mock/uv_fs_mock.cpp index 13ceb7b54..1174c92d6 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/mock/uv_fs_mock.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/mock/uv_fs_mock.cpp @@ -100,3 +100,8 @@ int uv_fs_unlink(uv_loop_t *loop, uv_fs_t *req, const char *path, uv_fs_cb cb) } void uv_fs_req_cleanup(uv_fs_t *req) {} + +int uv_fs_sendfile(uv_loop_t *loop, uv_fs_t *req, uv_file outFd, uv_file inFd, int64_t off, size_t len, uv_fs_cb cb) +{ + return Uvfs::ins->uv_fs_sendfile(loop, req, outFd, inFd, off, len, cb); +} \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/mock/uv_fs_mock.h b/interfaces/test/unittest/js/mod_fs/properties/mock/uv_fs_mock.h index 6b0f3c5fd..9216b6ce6 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/mock/uv_fs_mock.h +++ b/interfaces/test/unittest/js/mod_fs/properties/mock/uv_fs_mock.h @@ -48,6 +48,8 @@ public: virtual int uv_fs_access(uv_loop_t *loop, uv_fs_t *req, const char *path, int flags, uv_fs_cb cb) = 0; virtual int uv_fs_mkdtemp(uv_loop_t *loop, uv_fs_t *req, const char *tpl, uv_fs_cb cb) = 0; virtual int uv_fs_unlink(uv_loop_t *loop, uv_fs_t *req, const char *path, uv_fs_cb cb) = 0; + virtual int uv_fs_sendfile(uv_loop_t* loop, uv_fs_t* req, uv_file outFd, uv_file inFd, + int64_t off, size_t len, uv_fs_cb cb) = 0; }; class UvfsMock : public Uvfs { @@ -72,6 +74,8 @@ public: MOCK_METHOD5(uv_fs_access, int(uv_loop_t *loop, uv_fs_t *req, const char *path, int flags, uv_fs_cb cb)); MOCK_METHOD4(uv_fs_mkdtemp, int(uv_loop_t *loop, uv_fs_t *req, const char *tpl, uv_fs_cb cb)); MOCK_METHOD4(uv_fs_unlink, int(uv_loop_t *loop, uv_fs_t *req, const char *path, uv_fs_cb cb)); + MOCK_METHOD7(uv_fs_sendfile, int(uv_loop_t* loop, uv_fs_t* req, uv_file outFd, uv_file inFd, + int64_t off, size_t len, uv_fs_cb cb)); }; } // namespace OHOS::FileManagement::ModuleFileIO -- Gitee From d9022799b5545fa4e9dc9cf9ed48b47ab6c443a7 Mon Sep 17 00:00:00 2001 From: tianp Date: Sat, 21 Jun 2025 11:31:36 +0800 Subject: [PATCH 10/19] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: tianp Change-Id: Id892efdde77e4b8de5ff9fef48f0e4799e17ad47 --- .../mod_fs/properties/copy_core_mock_test.cpp | 9 +++---- .../js/mod_fs/properties/copy_core_test.cpp | 24 +++++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/interfaces/test/unittest/js/mod_fs/properties/copy_core_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/copy_core_mock_test.cpp index 6c4e34455..32e9f0e65 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/copy_core_mock_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/copy_core_mock_test.cpp @@ -119,14 +119,15 @@ HWTEST_F(CopyCoreMockTest, CopyCoreMockTest_DoCopy_001, testing::ext::TestSize.L { GTEST_LOG_(INFO) << "CopyCoreMockTest-begin CopyCoreMockTest_DoCopy_001"; - string srcFile = "/data/test/src/src.txt"; - string destFile = "/data/test/dest/dest.txt"; + string srcUri = "file://" + srcFile; + string destUri = "file://" + destFile; optional options; EXPECT_CALL(*uvMock, uv_fs_sendfile(_, _, _, _, _, _, _)).WillOnce(Return(0)); - auto res = CopyCore::DoCopy(srcFile, destFile, options); - EXPECT_EQ(res.IsSuccess(), false); + auto res = CopyCore::DoCopy(srcUri, destUri, options); + EXPECT_EQ(res.IsSuccess(), true); + EXPECT_TRUE(filesystem::exists(destFile)); GTEST_LOG_(INFO) << "CopyCoreMockTest-end CopyCoreMockTest_DoCopy_001"; } diff --git a/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp index 29dea123a..a8af87656 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp @@ -864,4 +864,28 @@ HWTEST_F(CopyCoreTest, CopyCoreTest_ExecCopy_001, testing::ext::TestSize.Level1) GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_ExecCopy_001"; } +/** + * @tc.name: CopyCoreTest_CopyFile_001 + * @tc.desc: Test function of CopyCore::CopyFile interface for file copy FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_CopyFile_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_CopyFile_001"; + + string src = "datashare:///media/src_test.jpg"; + string dest = "datashare:///media/dest_test.jpg"; + auto infos = make_shared(); + infos->isFile = true; + infos->srcPath = src; + infos->destPath = dest; + + auto res = CopyCore::CopyFile(src, dest, infos); + EXPECT_EQ(res, errno); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_CopyFile_001"; +} + } // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file -- Gitee From 24ea5ef9a1117271e5124173e8f4333360f14cca Mon Sep 17 00:00:00 2001 From: tianp Date: Sat, 21 Jun 2025 15:01:14 +0800 Subject: [PATCH 11/19] =?UTF-8?q?HandleProgress=E6=96=B0=E5=A2=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: tianp Change-Id: I5509c7826da2b02412f8cddc6ec1a94cdf65b8f9 --- .../js/mod_fs/properties/copy_core_test.cpp | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp index a8af87656..6b330deb2 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp @@ -888,4 +888,36 @@ HWTEST_F(CopyCoreTest, CopyCoreTest_CopyFile_001, testing::ext::TestSize.Level1) GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_CopyFile_001"; } +/** + * @tc.name: CopyCoreTest_HandleProgress_001 + * @tc.desc: Test function of CopyCore::HandleProgress interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_HandleProgress_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_HandleProgress_001"; + + auto infos = make_shared(); + infos->isFile = false; + infos->srcPath = "/data/test/src"; + infos->destPath = "/data/test/dest"; + + auto event = make_unique(); + const int testWd = 123; + event->wd = testWd; + event->mask = IN_MODIFY; + event->len = 0; + // 执行处理 + auto [continueProcess, errCode, needSend] = CopyCore::HandleProgress(event.get(), infos, nullptr); + + // 验证结果 + EXPECT_TRUE(continueProcess); + EXPECT_EQ(errCode, EINVAL); + EXPECT_FALSE(needSend); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_HandleProgress_001"; +} + } // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file -- Gitee From c2af647004648acac2f5fb727ed1d269caa33b2a Mon Sep 17 00:00:00 2001 From: tianp Date: Mon, 23 Jun 2025 19:05:16 +0800 Subject: [PATCH 12/19] =?UTF-8?q?=E6=96=B0=E5=A2=9EcopyTDD=E7=94=A8?= =?UTF-8?q?=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: tianp Change-Id: I395ab668862455962477caa3511489f717604935 --- interfaces/test/unittest/js/BUILD.gn | 1 + .../mod_fs/properties/copy_core_mock_test.cpp | 43 +++++++- .../js/mod_fs/properties/copy_core_test.cpp | 103 ++++++++++++++++++ .../mod_fs/properties/mock/inotify_mock.cpp | 41 +++++++ .../js/mod_fs/properties/mock/inotify_mock.h | 51 +++++++++ 5 files changed, 236 insertions(+), 3 deletions(-) create mode 100644 interfaces/test/unittest/js/mod_fs/properties/mock/inotify_mock.cpp create mode 100644 interfaces/test/unittest/js/mod_fs/properties/mock/inotify_mock.h diff --git a/interfaces/test/unittest/js/BUILD.gn b/interfaces/test/unittest/js/BUILD.gn index c3afa2779..ef5592d20 100644 --- a/interfaces/test/unittest/js/BUILD.gn +++ b/interfaces/test/unittest/js/BUILD.gn @@ -95,6 +95,7 @@ ohos_unittest("ani_file_fs_mock_test") { "mod_fs/properties/copy_core_mock_test.cpp", "mod_fs/properties/trans_listener_mock_test.cpp", "mod_fs/properties/mock/uv_fs_mock.cpp", + "mod_fs/properties/mock/inotify_mock.cpp", ] deps = [ diff --git a/interfaces/test/unittest/js/mod_fs/properties/copy_core_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/copy_core_mock_test.cpp index 32e9f0e65..2ad56f7f5 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/copy_core_mock_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/copy_core_mock_test.cpp @@ -13,15 +13,16 @@ * limitations under the License. */ -#include "copy_core.h" -#include "mock/uv_fs_mock.h" - #include #include #include #include #include +#include "copy_core.h" +#include "inotify_mock.h" +#include "mock/uv_fs_mock.h" + namespace OHOS::FileManagement::ModuleFileIO::Test { using namespace testing; using namespace testing::ext; @@ -132,4 +133,40 @@ HWTEST_F(CopyCoreMockTest, CopyCoreMockTest_DoCopy_001, testing::ext::TestSize.L GTEST_LOG_(INFO) << "CopyCoreMockTest-end CopyCoreMockTest_DoCopy_001"; } +/** + * @tc.name: CopyCoreMockTest_CopySubDir_001 + * @tc.desc: Test function of CopyCore::CopySubDir interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreMockTest, CopyCoreMockTest_CopySubDir_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreMockTest-begin CopyCoreMockTest_CopySubDir_001"; + + string subDir = srcDir + "/sub_dir"; + mkdir(subDir.c_str(), 0755); + string subFile = subDir + "/sub_file.txt"; + int fd = open(subFile.c_str(), O_CREAT | O_RDWR, 0644); + if (fd >= 0) { + close(fd); + } + + testing::StrictMock &inotifyMock = static_cast &>(GetInotifyMock()); + string destSubDir = destDir + "/sub_dir"; + auto infos = make_shared(); + infos->notifyFd = 1; + EXPECT_CALL(inotifyMock, inotify_add_watch(testing::_, testing::_, testing::_)) + .Times(1) + .WillOnce(testing::Return(100)); + auto res = CopyCore::CopySubDir(subDir, destSubDir, infos); + testing::Mock::VerifyAndClearExpectations(&inotifyMock); + EXPECT_EQ(res, UNKNOWN_ERR); + + remove(subFile.c_str()); + rmdir(subDir.c_str()); + rmdir(destSubDir.c_str()); + GTEST_LOG_(INFO) << "CopyCoreMockTest-end CopyCoreMockTest_CopySubDir_001"; +} + } // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp index 6b330deb2..71ec4a813 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp @@ -216,6 +216,23 @@ HWTEST_F(CopyCoreTest, CopyCoreTest_IsFile_002, testing::ext::TestSize.Level1) GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_IsFile_002"; } +/** + * @tc.name: CopyCoreTest_IsMediaUri_001 + * @tc.desc: Test function of CopyCore::IsMediaUri interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_IsMediaUri_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_IsMediaUri_001"; + + auto res = CopyCore::IsMediaUri(srcFile); + EXPECT_EQ(res, false); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_IsMediaUri_001"; +} + /** * @tc.name: CopyCoreTest_GetFileSize_001 * @tc.desc: Test function of CopyCore::GetFileSize interface for success. @@ -920,4 +937,90 @@ HWTEST_F(CopyCoreTest, CopyCoreTest_HandleProgress_001, testing::ext::TestSize.L GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_HandleProgress_001"; } +/** + * @tc.name: CopyCoreTest_HandleProgress_002 + * @tc.desc: Test function of CopyCore::HandleProgress interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_HandleProgress_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_HandleProgress_002"; + + auto infos = make_shared(); + infos->srcPath = srcDir; + infos->destPath = destDir; + infos->isFile = true; + + auto callback = make_shared(nullptr); + + // 添加接收信息(使用不同的wd) + const int testWd = 123; + const int differentWd = 456; + auto receiveInfo = make_shared(); + receiveInfo->path = testDir; + callback->wds.push_back({differentWd, receiveInfo}); + + // 初始化事件结构 + auto event = make_unique(); + event->wd = testWd; + event->mask = IN_MODIFY; + event->len = 0; + + // 执行处理 + auto [continueProcess, errCode, needSend] = + CopyCore::HandleProgress(event.get(), infos, callback); + + // 验证结果 + EXPECT_TRUE(continueProcess); + EXPECT_EQ(errCode, EINVAL); + EXPECT_FALSE(needSend); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_HandleProgress_002"; +} + +/** + * @tc.name: CopyCoreTest_HandleProgress_003 + * @tc.desc: Test function of CopyCore::HandleProgress interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_HandleProgress_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_HandleProgress_003"; + + // 创建测试用的文件信息对象 + auto infos = make_shared(); + infos->srcPath = srcDir; + infos->destPath = destDir; + infos->isFile = true; + + // 创建测试用的回调对象 + auto callback = make_shared(nullptr); + + // 添加匹配的接收信息 + const int testWd = 123; + auto receiveInfo = make_shared(); + receiveInfo->path = srcFile; + callback->wds.push_back({testWd, receiveInfo}); + + // 初始化事件结构 + auto event = make_unique(); + event->wd = testWd; + event->mask = IN_MODIFY; + event->len = 0; + + // 执行处理 + auto [continueProcess, errCode, needSend] = CopyCore::HandleProgress(event.get(), infos, callback); + + // 验证结果 + EXPECT_TRUE(continueProcess); + EXPECT_EQ(errCode, ERRNO_NOERR); + EXPECT_TRUE(needSend); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_HandleProgress_003"; +} + } // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/mock/inotify_mock.cpp b/interfaces/test/unittest/js/mod_fs/properties/mock/inotify_mock.cpp new file mode 100644 index 000000000..67c5c1a26 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/mock/inotify_mock.cpp @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "inotify_mock.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace Test { + +InotifyMock &GetInotifyMock() +{ + return InotifyMock::GetMock(); +} + +} // namespace Test +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS + +extern "C" { +using namespace OHOS::FileManagement::ModuleFileIO::Test; + +int inotify_add_watch(int fd, const char *pathname, uint32_t mask) +{ + return GetInotifyMock().inotify_add_watch(fd, pathname, mask); +} + +} // extern "C" \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_fs/properties/mock/inotify_mock.h b/interfaces/test/unittest/js/mod_fs/properties/mock/inotify_mock.h new file mode 100644 index 000000000..803b20944 --- /dev/null +++ b/interfaces/test/unittest/js/mod_fs/properties/mock/inotify_mock.h @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_TEST_UNITTEST_JS_MOD_FS_MOCK_INOTIFY_MOCK_H +#define INTERFACES_TEST_UNITTEST_JS_MOD_FS_MOCK_INOTIFY_MOCK_H + +#include +#include + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace Test { + +class IInotifyMock { +public: + virtual ~IInotifyMock() = default; + virtual int inotify_add_watch(int, const char *, uint32_t) = 0; +}; + +class InotifyMock : public IInotifyMock { +public: + MOCK_METHOD(int, inotify_add_watch, (int, const char *, uint32_t), (override)); + + static InotifyMock &GetMock() + { + static InotifyMock mock; + return mock; + } +}; + +InotifyMock &GetInotifyMock(); + +} // namespace Test +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS + +#endif // INTERFACES_TEST_UNITTEST_JS_MOD_FS_MOCK_INOTIFY_MOCK_H \ No newline at end of file -- Gitee From 2fbd5cd96c46c1271016170641374faac39fe175 Mon Sep 17 00:00:00 2001 From: tianp Date: Tue, 24 Jun 2025 10:36:08 +0800 Subject: [PATCH 13/19] =?UTF-8?q?copyTDD=E6=96=B0=E5=A2=9E=E7=94=A8?= =?UTF-8?q?=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: tianp Change-Id: Id3a2d9ee0d398cc9cb1f7355df16302cc3624745 --- .../js/mod_fs/properties/copy_core_test.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp index 71ec4a813..34ed69f4c 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/copy_core_test.cpp @@ -694,6 +694,27 @@ HWTEST_F(CopyCoreTest, CopyCoreTest_DoCopy_001, testing::ext::TestSize.Level1) GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_DoCopy_001"; } +/** + * @tc.name: CopyCoreTest_DoCopy_002 + * @tc.desc: Test function of CopyCore::DoCopy interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(CopyCoreTest, CopyCoreTest_DoCopy_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "CopyCoreTest-begin CopyCoreTest_DoCopy_002"; + + string src = "file:///data/test/src/src.txt"; + string dest = "file:///data/test/dest/dest.txt"; + optional options; + + auto res = CopyCore::DoCopy(src, dest, options); + EXPECT_TRUE(res.IsSuccess()); + + GTEST_LOG_(INFO) << "CopyCoreTest-end CopyCoreTest_DoCopy_002"; +} + /** * @tc.name: CopyCoreTest_GetDirSize_001 * @tc.desc: Test function of CopyCore::GetDirSize interface for file copy success. -- Gitee From 328dfb79f86ad62a0030346885d50ef7ce6df70b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9C=E5=B0=8F=E6=9E=97?= Date: Fri, 16 May 2025 17:32:12 +0800 Subject: [PATCH 14/19] =?UTF-8?q?copy=E6=8E=A5=E5=8F=A3bug=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Change-Id: I4958b6b4ea03d236d089391c2c755b5391f0d485 Signed-off-by: 姜小林 --- interfaces/kits/js/BUILD.gn | 6 +- .../js/src/mod_fs/ani/ets/@ohos.file.fs.ets | 15 +- .../class_tasksignal/ani/task_signal_ani.cpp | 81 ++----- .../class_tasksignal/ani/task_signal_ani.h | 8 +- .../ani/task_signal_listener_ani.cpp | 63 +++++ .../task_signal_listener_ani.h} | 41 ++-- .../ani/task_signal_wrapper.cpp | 71 ++++++ .../ani/task_signal_wrapper.h | 37 +++ .../class_tasksignal/fs_task_signal.cpp | 79 +++++++ .../mod_fs/class_tasksignal/fs_task_signal.h | 50 ++++ .../js/src/mod_fs/properties/ani/copy_ani.cpp | 159 ++++++------- .../js/src/mod_fs/properties/copy_core.cpp | 222 ++++++++---------- .../kits/js/src/mod_fs/properties/copy_core.h | 126 +++++----- .../ani/progress_listener_ani.cpp | 93 ++++++++ .../copy_listener/ani/progress_listener_ani.h | 39 +++ .../copy_listener/i_progress_listener.h} | 27 ++- .../copy_listener/trans_listener_core.cpp | 56 +++-- .../copy_listener/trans_listener_core.h | 28 +-- 18 files changed, 782 insertions(+), 419 deletions(-) create mode 100644 interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_listener_ani.cpp rename interfaces/kits/js/src/mod_fs/class_tasksignal/{task_signal_entity_core.h => ani/task_signal_listener_ani.h} (47%) create mode 100644 interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_wrapper.cpp create mode 100644 interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_wrapper.h create mode 100644 interfaces/kits/js/src/mod_fs/class_tasksignal/fs_task_signal.cpp create mode 100644 interfaces/kits/js/src/mod_fs/class_tasksignal/fs_task_signal.h create mode 100644 interfaces/kits/js/src/mod_fs/properties/copy_listener/ani/progress_listener_ani.cpp create mode 100644 interfaces/kits/js/src/mod_fs/properties/copy_listener/ani/progress_listener_ani.h rename interfaces/kits/js/src/mod_fs/{class_tasksignal/task_signal_entity_core.cpp => properties/copy_listener/i_progress_listener.h} (50%) diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index 3c4ddabd9..125de4eed 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -681,6 +681,7 @@ ohos_shared_library("ani_file_fs") { "src/mod_fs/properties", "src/mod_fs/properties/ani", "src/mod_fs/properties/copy_listener", + "src/mod_fs/properties/copy_listener/ani", ] sources = [ "src/common/ani_helper/ani_signature.cpp", @@ -709,7 +710,9 @@ ohos_shared_library("ani_file_fs") { "src/mod_fs/class_stream/fs_stream.cpp", "src/mod_fs/class_stream/stream_instantiator.cpp", "src/mod_fs/class_tasksignal/ani/task_signal_ani.cpp", - "src/mod_fs/class_tasksignal/task_signal_entity_core.cpp", + "src/mod_fs/class_tasksignal/ani/task_signal_listener_ani.cpp", + "src/mod_fs/class_tasksignal/ani/task_signal_wrapper.cpp", + "src/mod_fs/class_tasksignal/fs_task_signal.cpp", "src/mod_fs/class_watcher/ani/fs_watcher_ani.cpp", "src/mod_fs/class_watcher/ani/fs_watcher_wrapper.cpp", "src/mod_fs/class_watcher/ani/watch_event_listener.cpp", @@ -755,6 +758,7 @@ ohos_shared_library("ani_file_fs") { "src/mod_fs/properties/copy_core.cpp", "src/mod_fs/properties/copy_dir_core.cpp", "src/mod_fs/properties/copy_file_core.cpp", + "src/mod_fs/properties/copy_listener/ani/progress_listener_ani.cpp", "src/mod_fs/properties/copy_listener/trans_listener_core.cpp", "src/mod_fs/properties/create_randomaccessfile_core.cpp", "src/mod_fs/properties/create_stream_core.cpp", diff --git a/interfaces/kits/js/src/mod_fs/ani/ets/@ohos.file.fs.ets b/interfaces/kits/js/src/mod_fs/ani/ets/@ohos.file.fs.ets index 03f56f6b0..1ebce3e37 100644 --- a/interfaces/kits/js/src/mod_fs/ani/ets/@ohos.file.fs.ets +++ b/interfaces/kits/js/src/mod_fs/ani/ets/@ohos.file.fs.ets @@ -1263,20 +1263,29 @@ export type ProgressListener = (progress: Progress) => void; export class TaskSignal { private nativeTaskSignal: long = 0; + private native onCancelNative(): void; - private onCancelResolve: (path: string) => void = (path: string): void => {}; + + private onCancelResolve: (path: string) => void; private onCancelCallback(path: string): void { if (this.onCancelResolve) { this.onCancelResolve(path); } } + native cancel(): void; + onCancel(): Promise { - return new Promise((resolve: (path: string) => void, reject: (e: BusinessError) => void): void => { + return new Promise((resolve: (result: string) => void, reject: (e: BusinessError) => void): void => { this.onCancelResolve = resolve; - this.onCancelNative(); + try { + this.onCancelNative(); + } catch (e: BusinessError) { + reject(e); + } }); } + } export interface CopyOptions { diff --git a/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_ani.cpp b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_ani.cpp index f22a814f9..2b1229a69 100644 --- a/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_ani.cpp @@ -19,7 +19,8 @@ #include "copy_core.h" #include "error_handler.h" #include "filemgmt_libhilog.h" -#include "task_signal_entity_core.h" +#include "fs_task_signal.h" +#include "task_signal_wrapper.h" #include "type_converter.h" namespace OHOS { @@ -29,84 +30,40 @@ namespace ANI { using namespace std; using namespace OHOS::FileManagement::ModuleFileIO; -static TaskSignalEntityCore *Unwrap(ani_env *env, ani_object object) -{ - ani_long entity; - auto ret = env->Object_GetFieldByName_Long(object, "nativeTaskSignal", &entity); - if (ret != ANI_OK) { - HILOGE("Unwrap taskSignalEntityCore err: %{private}d", ret); - return nullptr; - } - return reinterpret_cast(entity); -} - void TaskSignalAni::Cancel(ani_env *env, [[maybe_unused]] ani_object object) { - auto entity = Unwrap(env, object); - if (entity == nullptr) { + FsTaskSignal *copySignal = TaskSignalWrapper::Unwrap(env, object); + if (copySignal == nullptr) { + HILOGE("Cannot unwrap copySignal!"); ErrorHandler::Throw(env, EINVAL); return; } - if (entity->taskSignal_ == nullptr) { - HILOGE("Failed to get watcherEntity when stop."); - ErrorHandler::Throw(env, EINVAL); - return; - } - - auto ret = entity->taskSignal_->Cancel(); - if (ret != NO_ERROR) { - HILOGE("Failed to cancel the task."); - ErrorHandler::Throw(env, CANCEL_ERR); + auto ret = copySignal->Cancel(); + if (!ret.IsSuccess()) { + HILOGE("Cannot Cancel!"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); return; } } void TaskSignalAni::OnCancel(ani_env *env, [[maybe_unused]] ani_object object) { - auto entity = Unwrap(env, object); - if (entity == nullptr) { + FsTaskSignal *copySignal = TaskSignalWrapper::Unwrap(env, object); + if (copySignal == nullptr) { + HILOGE("Cannot unwrap copySignal!"); ErrorHandler::Throw(env, EINVAL); return; } - if (entity->taskSignal_ == nullptr) { - HILOGE("Failed to get watcherEntity when stop."); - ErrorHandler::Throw(env, EINVAL); - return; - } - - ani_ref globalObj; - auto status = env->GlobalReference_Create(object, &globalObj); - if (status != ANI_OK) { - HILOGE("GlobalReference_Create, err: %{private}d", status); + auto ret = copySignal->OnCancel(); + if (!ret.IsSuccess()) { + HILOGE("Cannot Cancel!"); + const auto &err = ret.GetError(); + ErrorHandler::Throw(env, err); return; } - ani_vm *vm = nullptr; - env->GetVM(&vm); - auto cb = [vm, &globalObj](string filePath) -> void { - auto env = AniHelper::GetThreadEnv(vm); - if (env == nullptr) { - HILOGE("failed to GetThreadEnv"); - return; - } - - // std::vector vec; - auto [succPath, path] = TypeConverter::ToAniString(env, filePath); - if (!succPath) { - HILOGE("ToAniString failed"); - return; - } - - auto ret = env->Object_CallMethodByName_Void(static_cast(globalObj), - "onCancelCallback", nullptr, path); - if (ret != ANI_OK) { - HILOGE("Call onCancelCallback failed, err: %{private}d", ret); - return; - } - }; - auto callbackContext = std::make_shared(cb); - entity->callbackContextCore_ = callbackContext; - entity->taskSignal_->SetTaskSignalListener(entity); } + } // namespace ANI } // namespace ModuleFileIO } // namespace FileManagement diff --git a/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_ani.h b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_ani.h index 6db3301ce..d27e52538 100644 --- a/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_ani.h +++ b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_ani.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef FILEMANAGEMENT_FILE_API_TASK_SIGNAL_ANI_H -#define FILEMANAGEMENT_FILE_API_TASK_SIGNAL_ANI_H +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_TASKSIGNAL_ANI_TASK_SIGNAL_ANI_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_TASKSIGNAL_ANI_TASK_SIGNAL_ANI_H #include @@ -22,13 +22,15 @@ namespace OHOS { namespace FileManagement { namespace ModuleFileIO { namespace ANI { + class TaskSignalAni final { public: static void Cancel(ani_env *env, [[maybe_unused]] ani_object object); static void OnCancel(ani_env *env, [[maybe_unused]] ani_object object); }; + } // namespace ANI } // namespace ModuleFileIO } // namespace FileManagement } // namespace OHOS -#endif // FILEMANAGEMENT_FILE_API_TASK_SIGNAL_ANI_H \ No newline at end of file +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_TASKSIGNAL_ANI_TASK_SIGNAL_ANI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_listener_ani.cpp b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_listener_ani.cpp new file mode 100644 index 000000000..a80010e95 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_listener_ani.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "task_signal_listener_ani.h" + +#include +#include "ani_helper.h" +#include "ani_signature.h" +#include "file_utils.h" +#include "filemgmt_libhilog.h" +#include "type_converter.h" + +namespace OHOS::FileManagement::ModuleFileIO::ANI { +using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; + +void TaskSignalListenerAni::OnCancel() +{ + auto filepath = taskSignal->filePath_; + auto task = [this, filepath]() { SendCancelEvent(filepath); }; + AniHelper::SendEventToMainThread(task); +} + +void TaskSignalListenerAni::SendCancelEvent(const string &filepath) const +{ + if (vm == nullptr) { + HILOGE("Cannot send cancel event because the vm is null."); + return; + } + if (signalObj == nullptr) { + HILOGE("Cannot send cancel event because the signalObj is null."); + return; + } + ani_env *env = AniHelper::GetThreadEnv(vm); + if (env == nullptr) { + HILOGE("Cannot send cancel event because the env is null."); + return; + } + auto [succ, aniPath] = TypeConverter::ToAniString(env, filepath); + if (!succ) { + HILOGE("Cannot convert filepath to ani string!"); + return; + } + auto ret = env->Object_CallMethodByName_Void(signalObj, "onCancelCallback", nullptr, aniPath); + if (ret != ANI_OK) { + HILOGE("Call onCancelCallback failed, err: %{private}d", ret); + return; + } +} + +} // namespace OHOS::FileManagement::ModuleFileIO::ANI diff --git a/interfaces/kits/js/src/mod_fs/class_tasksignal/task_signal_entity_core.h b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_listener_ani.h similarity index 47% rename from interfaces/kits/js/src/mod_fs/class_tasksignal/task_signal_entity_core.h rename to interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_listener_ani.h index c301442c7..a11be571b 100644 --- a/interfaces/kits/js/src/mod_fs/class_tasksignal/task_signal_entity_core.h +++ b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_listener_ani.h @@ -13,34 +13,35 @@ * limitations under the License. */ -#ifndef FILEMANAGEMENT_FILE_API_TASK_SIGNAL_ENTITY_CORE_H -#define FILEMANAGEMENT_FILE_API_TASK_SIGNAL_ENTITY_CORE_H +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_TASKSIGNAL_ANI_TASK_SIGNAL_LISTENER_ANI_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_TASKSIGNAL_ANI_TASK_SIGNAL_LISTENER_ANI_H -#include "task_signal.h" +#include #include "task_signal_listener.h" +#include "task_signal.h" -namespace OHOS::FileManagement::ModuleFileIO { +namespace OHOS::FileManagement::ModuleFileIO::ANI { using namespace DistributedFS::ModuleTaskSignal; -typedef std::function TaskSignalCb; -class CallbackContextCore { +class TaskSignalListenerAni : public TaskSignalListener { public: - explicit CallbackContextCore(TaskSignalCb cb) : cb(cb) {} - ~CallbackContextCore() = default; - - TaskSignalCb cb; - std::string filePath_; -}; + TaskSignalListenerAni(ani_vm *vm, const ani_object &signalObj, std::shared_ptr taskSignal) + : vm(vm), signalObj(signalObj), taskSignal(taskSignal) {} + void OnCancel() override; -class TaskSignalEntityCore : public TaskSignalListener { public: - TaskSignalEntityCore() = default; - ~TaskSignalEntityCore() override; - void OnCancel() override; + TaskSignalListenerAni() = default; + ~TaskSignalListenerAni() = default; - std::shared_ptr taskSignal_ = nullptr; - std::shared_ptr callbackContextCore_ = nullptr; +private: + void SendCancelEvent(const std::string &filepath) const; + +private: + ani_vm *vm; + ani_object signalObj; + std::shared_ptr taskSignal; }; -} // namespace OHOS::FileManagement::ModuleFileIO -#endif // FILEMANAGEMENT_FILE_API_TASK_SIGNAL_ENTITY_CORE_H \ No newline at end of file +} // namespace OHOS::FileManagement::ModuleFileIO::ANI + +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_TASKSIGNAL_ANI_TASK_SIGNAL_LISTENER_ANI_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_wrapper.cpp b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_wrapper.cpp new file mode 100644 index 000000000..79be64231 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_wrapper.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "task_signal_wrapper.h" + +#include "ani_signature.h" +#include "error_handler.h" +#include "filemgmt_libhilog.h" +#include "fs_task_signal.h" +#include "type_converter.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { +using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; + +FsTaskSignal *TaskSignalWrapper::Unwrap(ani_env *env, ani_object object) +{ + ani_long nativePtr; + auto status = env->Object_GetFieldByName_Long(object, "nativeTaskSignal", &nativePtr); + if (status != ANI_OK) { + HILOGE("Unwrap taskSignal obj failed! status: %{public}d", status); + return nullptr; + } + uintptr_t ptrValue = static_cast(nativePtr); + FsTaskSignal *copySignal = reinterpret_cast(ptrValue); + return copySignal; +} + +bool TaskSignalWrapper::Wrap(ani_env *env, ani_object object, const FsTaskSignal *signal) +{ + if (object == nullptr) { + HILOGE("TaskSignal obj is null!"); + return false; + } + + if (signal == nullptr) { + HILOGE("FsTaskSignal pointer is null!"); + return false; + } + + ani_long ptr = static_cast(reinterpret_cast(signal)); + + auto status = env->Object_SetFieldByName_Long(object, "nativeTaskSignal", ptr); + if (status != ANI_OK) { + HILOGE("Wrap taskSignal obj failed! status: %{public}d", status); + return false; + } + + return true; +} + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_wrapper.h b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_wrapper.h new file mode 100644 index 000000000..2cfd04e4d --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_wrapper.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_TASKSIGNAL_ANI_TASK_SIGNAL_WRAPPER_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_TASKSIGNAL_ANI_TASK_SIGNAL_WRAPPER_H + +#include +#include "fs_task_signal.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +namespace ANI { + +class TaskSignalWrapper final { +public: + static FsTaskSignal *Unwrap(ani_env *env, ani_object object); + static bool Wrap(ani_env *env, ani_object object, const FsTaskSignal *signal); +}; + +} // namespace ANI +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_TASKSIGNAL_ANI_TASK_SIGNAL_WRAPPER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_tasksignal/fs_task_signal.cpp b/interfaces/kits/js/src/mod_fs/class_tasksignal/fs_task_signal.cpp new file mode 100644 index 000000000..d9b4b6ffe --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_tasksignal/fs_task_signal.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "fs_task_signal.h" + +#include "file_utils.h" +#include "filemgmt_libhilog.h" +#include "fs_utils.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; + +FsResult> FsTaskSignal::Constructor( + shared_ptr taskSignal, shared_ptr signalListener) +{ + if (!taskSignal) { + HILOGE("Invalid taskSignal"); + return FsResult>::Error(EINVAL); + } + if (!signalListener) { + HILOGE("Invalid signalListener"); + return FsResult>::Error(EINVAL); + } + auto copySignal = CreateSharedPtr(); + if (copySignal == nullptr) { + HILOGE("Failed to request heap memory."); + return FsResult>::Error(ENOMEM); + } + copySignal->taskSignal_ = move(taskSignal); + copySignal->signalListener_ = move(signalListener); + return FsResult>::Success(copySignal); +} + +FsResult FsTaskSignal::Cancel() +{ + if (taskSignal_ == nullptr) { + HILOGE("Failed to get taskSignal"); + return FsResult::Error(EINVAL); + } + auto ret = taskSignal_->Cancel(); + if (ret != ERRNO_NOERR) { + HILOGE("Failed to cancel the task."); + return FsResult::Error(CANCEL_ERR); + } + return FsResult::Success(); +} + +FsResult FsTaskSignal::OnCancel() +{ + if (taskSignal_ == nullptr) { + HILOGE("Failed to get taskSignal"); + return FsResult::Error(EINVAL); + } + taskSignal_->SetTaskSignalListener(signalListener_.get()); + return FsResult::Success(); +} + +shared_ptr FsTaskSignal::GetTaskSignal() const +{ + return taskSignal_; +} + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_tasksignal/fs_task_signal.h b/interfaces/kits/js/src/mod_fs/class_tasksignal/fs_task_signal.h new file mode 100644 index 000000000..33161108c --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/class_tasksignal/fs_task_signal.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_TASKSIGNAL_FS_TASK_SIGNAL_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_TASKSIGNAL_FS_TASK_SIGNAL_H + +#include "filemgmt_libfs.h" +#include "task_signal.h" + +namespace OHOS { +namespace FileManagement { +namespace ModuleFileIO { +using namespace std; +using namespace DistributedFS::ModuleTaskSignal; + +class FsTaskSignal { +public: + static FsResult> Constructor( + shared_ptr taskSignal, shared_ptr signalListener); + FsResult Cancel(); + FsResult OnCancel(); + shared_ptr GetTaskSignal() const; + +public: + FsTaskSignal() = default; + ~FsTaskSignal() = default; + FsTaskSignal(const FsTaskSignal &other) = delete; + FsTaskSignal &operator=(const FsTaskSignal &other) = delete; + +private: + shared_ptr taskSignal_ = nullptr; + shared_ptr signalListener_ = nullptr; +}; + +} // namespace ModuleFileIO +} // namespace FileManagement +} // namespace OHOS +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_CLASS_TASKSIGNAL_FS_TASK_SIGNAL_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/copy_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/copy_ani.cpp index e086c5ee1..7e84bce8f 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/copy_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/ani/copy_ani.cpp @@ -21,6 +21,10 @@ #include "error_handler.h" #include "file_utils.h" #include "filemgmt_libhilog.h" +#include "fs_task_signal.h" +#include "progress_listener_ani.h" +#include "task_signal_listener_ani.h" +#include "task_signal_wrapper.h" #include "type_converter.h" namespace OHOS { @@ -31,112 +35,100 @@ using namespace std; using namespace OHOS::FileManagement::ModuleFileIO; using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; -static void SetProgressListenerCb(ani_env *env, ani_ref &callback, CopyOptions &opts) +static bool ParseListenerFromOptionArg(ani_env *env, const ani_object &options, CopyOptions &opts) { + ani_ref prog; + if (ANI_OK != env->Object_GetPropertyByName_Ref(options, "progressListener", &prog)) { + HILOGE("Illegal options.progressListener type"); + return false; + } + + ani_boolean isUndefined = true; + env->Reference_IsUndefined(prog, &isUndefined); + if (isUndefined) { + return true; + } + + ani_ref cbRef; + if (ANI_OK != env->GlobalReference_Create(prog, &cbRef)) { + HILOGE("Illegal options.progressListener type"); + return false; + } + ani_vm *vm = nullptr; env->GetVM(&vm); + auto listener = CreateSharedPtr(vm, cbRef); + if (listener == nullptr) { + HILOGE("Failed to request heap memory."); + return false; + } - opts.listenerCb = [vm, &callback](uint64_t progressSize, uint64_t totalSize) -> void { - ani_status ret; - ani_object progress = {}; - auto classDesc = FS::ProgressInner::classDesc.c_str(); - ani_class cls; - - auto env = AniHelper::GetThreadEnv(vm); - if (env == nullptr) { - HILOGE("failed to GetThreadEnv"); - return; - } - - if (progressSize > MAX_VALUE || totalSize > MAX_VALUE) { - HILOGE("progressSize or totalSize exceed MAX_VALUE: %{private}" PRIu64 " %{private}" PRIu64, progressSize, - totalSize); - } - - if ((ret = env->FindClass(classDesc, &cls)) != ANI_OK) { - HILOGE("Not found %{private}s, err: %{private}d", classDesc, ret); - return; - } - - auto ctorDesc = FS::ProgressInner::ctorDesc.c_str(); - auto ctorSig = FS::ProgressInner::ctorSig.c_str(); - ani_method ctor; - if ((ret = env->Class_FindMethod(cls, ctorDesc, ctorSig, &ctor)) != ANI_OK) { - HILOGE("Not found ctor, err: %{private}d", ret); - return; - } - - if ((ret = env->Object_New(cls, ctor, &progress, ani_double(static_cast(progressSize)), - ani_double(static_cast(totalSize)))) != ANI_OK) { - HILOGE("New ProgressInner Fail, err: %{private}d", ret); - return; - } - - std::vector vec; - vec.push_back(progress); - ani_ref result; - ret = env->FunctionalObject_Call(static_cast(callback), vec.size(), vec.data(), &result); - if (ret != ANI_OK) { - HILOGE("FunctionalObject_Call, err: %{private}d", ret); - return; - } - }; + opts.progressListener = move(listener); + return true; } -static bool SetTaskSignal(ani_env *env, ani_ref ©Signal, CopyOptions &opts) +static bool ParseCopySignalFromOptionArg(ani_env *env, const ani_object &options, CopyOptions &opts) { - ani_status ret; - auto taskSignalEntityCore = CreateSharedPtr(); - if (taskSignalEntityCore == nullptr) { + ani_ref prog; + if (ANI_OK != env->Object_GetPropertyByName_Ref(options, "copySignal", &prog)) { + HILOGE("Illegal options.CopySignal type"); + return false; + } + + ani_boolean isUndefined = true; + env->Reference_IsUndefined(prog, &isUndefined); + if (isUndefined) { + return true; + } + + auto taskSignal = CreateSharedPtr(); + if (taskSignal == nullptr) { HILOGE("Failed to request heap memory."); return false; } - ret = env->Object_SetFieldByName_Long(static_cast(copySignal), "nativeTaskSignal", - reinterpret_cast(taskSignalEntityCore.get())); - if (ret != ANI_OK) { - HILOGE("Object set nativeTaskSignal err: %{private}d", ret); + auto signalObj = static_cast(prog); + ani_vm *vm = nullptr; + env->GetVM(&vm); + auto listener = CreateSharedPtr(vm, signalObj, taskSignal); + if (listener == nullptr) { + HILOGE("Failed to request heap memory."); return false; } - taskSignalEntityCore->taskSignal_ = std::make_shared(); - opts.taskSignalEntityCore = move(taskSignalEntityCore); + auto result = FsTaskSignal::Constructor(taskSignal, listener); + if (!result.IsSuccess()) { + return false; + } + auto copySignal = result.GetData().value(); + auto succ = TaskSignalWrapper::Wrap(env, signalObj, copySignal.get()); + if (!succ) { + return false; + } + + opts.copySignal = move(copySignal); return true; } -static tuple> ParseOptions(ani_env *env, ani_ref &cb, ani_object &options) +static tuple> ParseOptions(ani_env *env, ani_object &options) { ani_boolean isUndefined; - ani_status ret; env->Reference_IsUndefined(options, &isUndefined); if (isUndefined) { return { true, nullopt }; } CopyOptions opts; - ani_ref prog; - if ((ret = env->Object_GetPropertyByName_Ref(options, "progressListener", &prog)) != ANI_OK) { - HILOGE("Object_GetPropertyByName_Ref progressListener, err: %{private}d", ret); + auto succ = ParseListenerFromOptionArg(env, options, opts); + if (!succ) { return { false, nullopt }; } - env->Reference_IsUndefined(prog, &isUndefined); - if (!isUndefined) { - env->GlobalReference_Create(prog, &cb); - SetProgressListenerCb(env, cb, opts); - } - ani_ref signal; - if ((ret = env->Object_GetPropertyByName_Ref(options, "copySignal", &signal)) != ANI_OK) { - HILOGE("Object_GetPropertyByName_Ref copySignal, err: %{private}d", ret); + succ = ParseCopySignalFromOptionArg(env, options, opts); + if (!succ) { return { false, nullopt }; } - env->Reference_IsUndefined(signal, &isUndefined); - if (!isUndefined) { - if (!SetTaskSignal(env, signal, opts)) { - return { false, nullopt }; - } - } return { true, make_optional(move(opts)) }; } @@ -146,24 +138,15 @@ void CopyAni::CopySync( { auto [succSrc, src] = TypeConverter::ToUTF8String(env, srcUri); auto [succDest, dest] = TypeConverter::ToUTF8String(env, destUri); - if (!succSrc || !succDest) { - HILOGE("The first/second argument requires filepath"); - ErrorHandler::Throw(env, EINVAL); - return; - } + auto [succOpts, opts] = ParseOptions(env, options); - ani_ref cb; - auto [succOpts, opts] = ParseOptions(env, cb, options); - if (!succOpts) { - HILOGE("Failed to parse opts"); - ErrorHandler::Throw(env, EINVAL); + if (!succSrc || !succDest || !succOpts) { + HILOGE("The first/second/third argument requires uri/uri/napi_function"); + ErrorHandler::Throw(env, E_PARAMS); return; } auto ret = CopyCore::DoCopy(src, dest, opts); - if (opts.has_value() && opts->listenerCb != nullptr) { - env->GlobalReference_Delete(cb); - } if (!ret.IsSuccess()) { HILOGE("DoCopy failed!"); const FsError &err = ret.GetError(); diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_core.cpp b/interfaces/kits/js/src/mod_fs/properties/copy_core.cpp index f3d4613d7..45403ca6d 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy_core.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copy_core.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2024 Huawei Device Co., Ltd. + * Copyright (c) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -60,25 +60,9 @@ constexpr int BUF_SIZE = 1024; constexpr size_t MAX_SIZE = 1024 * 1024 * 4; constexpr std::chrono::milliseconds NOTIFY_PROGRESS_DELAY(300); std::recursive_mutex CopyCore::mutex_; -std::map> CopyCore::jsCbMap_; +std::map> CopyCore::callbackMap_; -static string GetModeFromFlags(unsigned int flags) -{ - const string readMode = "r"; - const string writeMode = "w"; - const string appendMode = "a"; - const string truncMode = "t"; - string mode = readMode; - mode += (((flags & O_RDWR) == O_RDWR) ? writeMode : ""); - mode = (((flags & O_WRONLY) == O_WRONLY) ? writeMode : mode); - if (mode != readMode) { - mode += ((flags & O_TRUNC) ? truncMode : ""); - mode += ((flags & O_APPEND) ? appendMode : ""); - } - return mode; -} - -static int OpenSrcFile(const string &srcPth, std::shared_ptr infos, int32_t &srcFd) +static int OpenSrcFile(const string &srcPth, std::shared_ptr infos, int32_t &srcFd) { Uri uri(infos->srcUri); if (uri.GetAuthority() == MEDIA) { @@ -93,7 +77,7 @@ static int OpenSrcFile(const string &srcPth, std::shared_ptr info HILOGE("Failed to connect to datashare"); return E_PERMISSION; } - srcFd = dataShareHelper->OpenFile(uri, GetModeFromFlags(O_RDONLY)); + srcFd = dataShareHelper->OpenFile(uri, FsUtils::GetModeFromFlags(O_RDONLY)); if (srcFd < 0) { HILOGE("Open media uri by data share fail. ret = %{public}d", srcFd); return EPERM; @@ -108,18 +92,17 @@ static int OpenSrcFile(const string &srcPth, std::shared_ptr info return ERRNO_NOERR; } -static int SendFileCore(std::unique_ptr srcFdg, - std::unique_ptr destFdg, - std::shared_ptr infos) +static int SendFileCore(std::unique_ptr srcFdg, std::unique_ptr destFdg, + std::shared_ptr infos) { - std::unique_ptr sendFileReq = { - new (nothrow) uv_fs_t, FsUtils::FsReqCleanup }; + std::unique_ptr sendFileReq = { new (nothrow) uv_fs_t, + FsUtils::FsReqCleanup }; if (sendFileReq == nullptr) { HILOGE("Failed to request heap memory."); return ENOMEM; } int64_t offset = 0; - struct stat srcStat{}; + struct stat srcStat {}; if (fstat(srcFdg->GetFD(), &srcStat) < 0) { HILOGE("Failed to get stat of file by fd: %{public}d ,errno = %{public}d", srcFdg->GetFD(), errno); return errno; @@ -127,15 +110,13 @@ static int SendFileCore(std::unique_ptr srcFdg, int32_t ret = 0; int64_t size = static_cast(srcStat.st_size); while (size >= 0) { - ret = uv_fs_sendfile(nullptr, sendFileReq.get(), destFdg->GetFD(), srcFdg->GetFD(), - offset, MAX_SIZE, nullptr); + ret = uv_fs_sendfile(nullptr, sendFileReq.get(), destFdg->GetFD(), srcFdg->GetFD(), offset, MAX_SIZE, nullptr); if (ret < 0) { HILOGE("Failed to sendfile by errno : %{public}d", errno); return errno; } if (infos != nullptr && infos->taskSignal != nullptr) { if (infos->taskSignal->CheckCancelIfNeed(infos->srcPath)) { - HILOGE("===Copy Task Canceled Success"); return ECANCELED; } } @@ -159,10 +140,7 @@ bool CopyCore::IsValidUri(const std::string &uri) bool CopyCore::ValidOperand(std::string uriStr) { - if (IsValidUri(uriStr)) { - return true; - } - return false; + return IsValidUri(uriStr); } bool CopyCore::IsRemoteUri(const std::string &uri) @@ -228,7 +206,7 @@ int CopyCore::CheckOrCreatePath(const std::string &destPath) return ERRNO_NOERR; } -int CopyCore::CopyFile(const string &src, const string &dest, std::shared_ptr infos) +int CopyCore::CopyFile(const string &src, const string &dest, std::shared_ptr infos) { HILOGD("src = %{public}s, dest = %{public}s", GetAnonyString(src).c_str(), GetAnonyString(dest).c_str()); int32_t srcFd = -1; @@ -264,7 +242,7 @@ int CopyCore::MakeDir(const string &path) return ERRNO_NOERR; } -int CopyCore::CopySubDir(const string &srcPath, const string &destPath, std::shared_ptr infos) +int CopyCore::CopySubDir(const string &srcPath, const string &destPath, std::shared_ptr infos) { std::error_code errCode; if (!filesystem::exists(destPath, errCode) && errCode.value() == ERRNO_NOERR) { @@ -286,14 +264,14 @@ int CopyCore::CopySubDir(const string &srcPath, const string &destPath, std::sha } { std::lock_guard lock(CopyCore::mutex_); - auto iter = CopyCore::jsCbMap_.find(*infos); + auto iter = CopyCore::callbackMap_.find(*infos); auto receiveInfo = CreateSharedPtr(); if (receiveInfo == nullptr) { HILOGE("Failed to request heap memory."); return ENOMEM; } receiveInfo->path = destPath; - if (iter == CopyCore::jsCbMap_.end() || iter->second == nullptr) { + if (iter == CopyCore::callbackMap_.end() || iter->second == nullptr) { HILOGE("Failed to find infos, srcPath = %{public}s, destPath = %{public}s", GetAnonyString(infos->srcPath).c_str(), GetAnonyString(infos->destPath).c_str()); return UNKNOWN_ERR; @@ -329,11 +307,11 @@ static void Deleter(struct NameList *arg) arg = nullptr; } -std::string CopyCore::GetRealPath(const std::string& path) +std::string CopyCore::GetRealPath(const std::string &path) { fs::path tempPath(path); - fs::path realPath{}; - for (const auto& component : tempPath) { + fs::path realPath {}; + for (const auto &component : tempPath) { if (component == ".") { continue; } else if (component == "..") { @@ -345,7 +323,7 @@ std::string CopyCore::GetRealPath(const std::string& path) return realPath.string(); } -uint64_t CopyCore::GetDirSize(std::shared_ptr infos, std::string path) +uint64_t CopyCore::GetDirSize(std::shared_ptr infos, std::string path) { unique_ptr pNameList = { new (nothrow) struct NameList, Deleter }; if (pNameList == nullptr) { @@ -374,7 +352,7 @@ uint64_t CopyCore::GetDirSize(std::shared_ptr infos, std::string return size; } -int CopyCore::RecurCopyDir(const string &srcPath, const string &destPath, std::shared_ptr infos) +int CopyCore::RecurCopyDir(const string &srcPath, const string &destPath, std::shared_ptr infos) { unique_ptr pNameList = { new (nothrow) struct NameList, Deleter }; if (pNameList == nullptr) { @@ -404,7 +382,7 @@ int CopyCore::RecurCopyDir(const string &srcPath, const string &destPath, std::s return ERRNO_NOERR; } -int CopyCore::CopyDirFunc(const string &src, const string &dest, std::shared_ptr infos) +int CopyCore::CopyDirFunc(const string &src, const string &dest, std::shared_ptr infos) { HILOGD("CopyDirFunc in, src = %{public}s, dest = %{public}s", GetAnonyString(src).c_str(), GetAnonyString(dest).c_str()); @@ -421,7 +399,7 @@ int CopyCore::CopyDirFunc(const string &src, const string &dest, std::shared_ptr return CopySubDir(src, destStr, infos); } -int CopyCore::ExecLocal(std::shared_ptr infos, std::shared_ptr callback) +int CopyCore::ExecLocal(std::shared_ptr infos, std::shared_ptr callback) { if (infos->isFile) { if (infos->srcPath == infos->destPath) { @@ -446,8 +424,7 @@ int CopyCore::ExecLocal(std::shared_ptr infos, std::shared_ptr infos, - std::shared_ptr callback) +int CopyCore::SubscribeLocalListener(std::shared_ptr infos, std::shared_ptr callback) { infos->notifyFd = inotify_init(); if (infos->notifyFd < 0) { @@ -465,7 +442,7 @@ int CopyCore::SubscribeLocalListener(std::shared_ptr infos, if (newWd < 0) { auto errCode = errno; HILOGE("Failed to add watch, errno = %{public}d, notifyFd: %{public}d, destPath: %{public}s", errno, - infos->notifyFd, infos->destPath.c_str()); + infos->notifyFd, infos->destPath.c_str()); CloseNotifyFdLocked(infos, callback); return errCode; } @@ -489,66 +466,73 @@ int CopyCore::SubscribeLocalListener(std::shared_ptr infos, return err; } -std::shared_ptr CopyCore::RegisterListener(const std::shared_ptr &infos) +std::shared_ptr CopyCore::RegisterListener(const std::shared_ptr &infos) { - auto callback = CreateSharedPtr(infos->listenerCb); + auto callback = CreateSharedPtr(infos->listener); if (callback == nullptr) { HILOGE("Failed to request heap memory."); return nullptr; } std::lock_guard lock(mutex_); - auto iter = jsCbMap_.find(*infos); - if (iter != jsCbMap_.end()) { + auto iter = callbackMap_.find(*infos); + if (iter != callbackMap_.end()) { HILOGE("CopyCore::RegisterListener, already registered."); return nullptr; } - jsCbMap_.insert({ *infos, callback }); + callbackMap_.insert({ *infos, callback }); return callback; } -void CopyCore::UnregisterListener(std::shared_ptr fileInfos) +void CopyCore::UnregisterListener(std::shared_ptr fileInfos) { if (fileInfos == nullptr) { HILOGE("fileInfos is nullptr"); return; } std::lock_guard lock(mutex_); - auto iter = jsCbMap_.find(*fileInfos); - if (iter == jsCbMap_.end()) { + auto iter = callbackMap_.find(*fileInfos); + if (iter == callbackMap_.end()) { HILOGI("It is not be registered."); return; } - jsCbMap_.erase(*fileInfos); + callbackMap_.erase(*fileInfos); } -void CopyCore::ReceiveComplete(std::shared_ptr entry) +void CopyCore::ReceiveComplete(std::shared_ptr entry) { if (entry == nullptr) { HILOGE("entry pointer is nullptr."); return; } + if (entry->callback == nullptr) { + HILOGE("entry callback pointer is nullptr."); + return; + } auto processedSize = entry->progressSize; if (processedSize < entry->callback->maxProgressSize) { - HILOGE("enter ReceiveComplete2"); return; } entry->callback->maxProgressSize = processedSize; - - entry->callback->listenerCb(processedSize, entry->totalSize); + auto listener = entry->callback->listener; + if (listener == nullptr) { + HILOGE("listener pointer is nullptr."); + return; + } + listener->InvokeListener(processedSize, entry->totalSize); } -UvEntryCore *CopyCore::GetUVEntry(std::shared_ptr infos) +FsUvEntry *CopyCore::GetUVEntry(std::shared_ptr infos) { - UvEntryCore *entry = nullptr; + FsUvEntry *entry = nullptr; { std::lock_guard lock(mutex_); - auto iter = jsCbMap_.find(*infos); - if (iter == jsCbMap_.end()) { + auto iter = callbackMap_.find(*infos); + if (iter == callbackMap_.end()) { HILOGE("Failed to find callback"); return nullptr; } auto callback = iter->second; - entry = new (std::nothrow) UvEntryCore(iter->second, infos); + entry = new (std::nothrow) FsUvEntry(iter->second, infos); if (entry == nullptr) { HILOGE("entry ptr is nullptr."); return nullptr; @@ -559,9 +543,9 @@ UvEntryCore *CopyCore::GetUVEntry(std::shared_ptr infos) return entry; } -void CopyCore::OnFileReceive(std::shared_ptr infos) +void CopyCore::OnFileReceive(std::shared_ptr infos) { - std::shared_ptr entry(GetUVEntry(infos)); + std::shared_ptr entry(GetUVEntry(infos)); if (entry == nullptr) { HILOGE("failed to get uv entry"); return; @@ -569,25 +553,22 @@ void CopyCore::OnFileReceive(std::shared_ptr infos) ReceiveComplete(entry); } -std::shared_ptr CopyCore::GetReceivedInfo(int wd, std::shared_ptr callback) +std::shared_ptr CopyCore::GetReceivedInfo(int wd, std::shared_ptr callback) { - auto it = find_if(callback->wds.begin(), callback->wds.end(), [wd](const auto& item) { - return item.first == wd; - }); + auto it = find_if(callback->wds.begin(), callback->wds.end(), [wd](const auto &item) { return item.first == wd; }); if (it != callback->wds.end()) { return it->second; } return nullptr; } -bool CopyCore::CheckFileValid(const std::string &filePath, std::shared_ptr infos) +bool CopyCore::CheckFileValid(const std::string &filePath, std::shared_ptr infos) { return infos->filePaths.count(filePath) != 0; } -int CopyCore::UpdateProgressSize(const std::string &filePath, - std::shared_ptr receivedInfo, - std::shared_ptr callback) +int CopyCore::UpdateProgressSize( + const std::string &filePath, std::shared_ptr receivedInfo, std::shared_ptr callback) { auto [err, fileSize] = GetFileSize(filePath); if (err != ERRNO_NOERR) { @@ -608,18 +589,18 @@ int CopyCore::UpdateProgressSize(const std::string &filePath, return ERRNO_NOERR; } -std::shared_ptr CopyCore::GetRegisteredListener(std::shared_ptr infos) +std::shared_ptr CopyCore::GetRegisteredListener(std::shared_ptr infos) { std::lock_guard lock(mutex_); - auto iter = jsCbMap_.find(*infos); - if (iter == jsCbMap_.end()) { + auto iter = callbackMap_.find(*infos); + if (iter == callbackMap_.end()) { HILOGE("It is not registered."); return nullptr; } return iter->second; } -void CopyCore::CloseNotifyFd(std::shared_ptr infos, std::shared_ptr callback) +void CopyCore::CloseNotifyFd(std::shared_ptr infos, std::shared_ptr callback) { callback->closed = false; infos->eventFd = -1; @@ -631,7 +612,7 @@ void CopyCore::CloseNotifyFd(std::shared_ptr infos, std::shared_p } } -void CopyCore::CloseNotifyFdLocked(std::shared_ptr infos, std::shared_ptr callback) +void CopyCore::CloseNotifyFdLocked(std::shared_ptr infos, std::shared_ptr callback) { { lock_guard lock(callback->readMutex); @@ -645,7 +626,7 @@ void CopyCore::CloseNotifyFdLocked(std::shared_ptr infos, std::sh } tuple CopyCore::HandleProgress( - inotify_event *event, std::shared_ptr infos, std::shared_ptr callback) + inotify_event *event, std::shared_ptr infos, std::shared_ptr callback) { if (callback == nullptr) { return { true, EINVAL, false }; @@ -674,14 +655,15 @@ tuple CopyCore::HandleProgress( return { true, callback->errorCode, true }; } -void CopyCore::ReadNotifyEvent(std::shared_ptr infos) +void CopyCore::ReadNotifyEvent(std::shared_ptr infos) { char buf[BUF_SIZE] = { 0 }; struct inotify_event *event = nullptr; int len = 0; int64_t index = 0; auto callback = GetRegisteredListener(infos); - while (infos->run && ((len = read(infos->notifyFd, &buf, sizeof(buf))) < 0) && (errno == EINTR)) {} + while (infos->run && ((len = read(infos->notifyFd, &buf, sizeof(buf))) < 0) && (errno == EINTR)) { + } while (infos->run && index < len) { event = reinterpret_cast(buf + index); auto [needContinue, errCode, needSend] = HandleProgress(event, infos, callback); @@ -706,7 +688,7 @@ void CopyCore::ReadNotifyEvent(std::shared_ptr infos) } } -void CopyCore::ReadNotifyEventLocked(std::shared_ptr infos, std::shared_ptr callback) +void CopyCore::ReadNotifyEventLocked(std::shared_ptr infos, std::shared_ptr callback) { { std::lock_guard lock(callback->readMutex); @@ -728,7 +710,7 @@ void CopyCore::ReadNotifyEventLocked(std::shared_ptr infos, std:: } } -void CopyCore::GetNotifyEvent(std::shared_ptr infos) +void CopyCore::GetNotifyEvent(std::shared_ptr infos) { auto callback = GetRegisteredListener(infos); if (callback == nullptr) { @@ -760,17 +742,16 @@ void CopyCore::GetNotifyEvent(std::shared_ptr infos) } { std::unique_lock lock(callback->cvLock); - callback->cv.wait_for(lock, std::chrono::microseconds(SLEEP_TIME), [callback]() -> bool { - return callback->notifyFd == -1; - }); + callback->cv.wait_for( + lock, std::chrono::microseconds(SLEEP_TIME), [callback]() -> bool { return callback->notifyFd == -1; }); } } } -tuple> CopyCore::CreateFileInfos( - const std::string &srcUri, const std::string &destUri, std::optional options) +tuple> CopyCore::CreateFileInfos( + const std::string &srcUri, const std::string &destUri, const std::optional &options) { - auto infos = CreateSharedPtr(); + auto infos = CreateSharedPtr(); if (infos == nullptr) { HILOGE("Failed to request heap memory."); return { ENOMEM, nullptr }; @@ -785,29 +766,29 @@ tuple> CopyCore::CreateFileInfos( infos->destPath = GetRealPath(infos->destPath); infos->isFile = IsMediaUri(infos->srcUri) || IsFile(infos->srcPath); infos->notifyTime = std::chrono::steady_clock::now() + NOTIFY_PROGRESS_DELAY; - if (options != std::nullopt) { - if (options.value().listenerCb) { + if (options.has_value()) { + auto listener = options.value().progressListener; + if (listener) { infos->hasListener = true; - infos->listenerCb = options.value().listenerCb; + infos->listener = listener; } - if (options.value().taskSignalEntityCore != nullptr) { - infos->taskSignal = options.value().taskSignalEntityCore->taskSignal_; + auto copySignal = options.value().copySignal; + if (copySignal) { + infos->taskSignal = copySignal->GetTaskSignal(); } } return { ERRNO_NOERR, infos }; } -void CopyCore::StartNotify(std::shared_ptr infos, std::shared_ptr callback) +void CopyCore::StartNotify(std::shared_ptr infos, std::shared_ptr callback) { if (infos->hasListener && callback != nullptr) { - callback->notifyHandler = std::thread([infos] { - GetNotifyEvent(infos); - }); + callback->notifyHandler = std::thread([infos] { GetNotifyEvent(infos); }); } } -int CopyCore::ExecCopy(std::shared_ptr infos) +int CopyCore::ExecCopy(std::shared_ptr infos) { if (infos->isFile && IsFile(infos->destPath)) { // copyFile @@ -826,25 +807,18 @@ int CopyCore::ExecCopy(std::shared_ptr infos) return EINVAL; } -int CopyCore::ValidParam(const string& src, const string& dest, - std::optional options, - std::shared_ptr &fileInfos) +bool CopyCore::ValidParams(const string &src, const string &dest) { auto succSrc = ValidOperand(src); auto succDest = ValidOperand(dest); if (!succSrc || !succDest) { HILOGE("The first/second argument requires uri/uri"); - return E_PARAMS; - } - auto [errCode, infos] = CreateFileInfos(src, dest, options); - if (errCode != ERRNO_NOERR) { - return errCode; + return false; } - fileInfos = infos; - return ERRNO_NOERR; + return true; } -void CopyCore::WaitNotifyFinished(std::shared_ptr callback) +void CopyCore::WaitNotifyFinished(std::shared_ptr callback) { if (callback != nullptr) { if (callback->notifyHandler.joinable()) { @@ -853,7 +827,7 @@ void CopyCore::WaitNotifyFinished(std::shared_ptr callback) } } -void CopyCore::CopyComplete(std::shared_ptr infos, std::shared_ptr callback) +void CopyCore::CopyComplete(std::shared_ptr infos, std::shared_ptr callback) { if (callback != nullptr && infos->hasListener) { callback->progressSize = callback->totalSize; @@ -861,12 +835,16 @@ void CopyCore::CopyComplete(std::shared_ptr infos, std::shared_pt } } -FsResult CopyCore::DoCopy(const string& src, const string& dest, std::optional &options) +FsResult CopyCore::DoCopy(const string &src, const string &dest, std::optional &options) { - std::shared_ptr infos = nullptr; - auto result = ValidParam(src, dest, options, infos); - if (result != ERRNO_NOERR) { - return FsResult::Error(result); + auto isValid = ValidParams(src, dest); + if (!isValid) { + return FsResult::Error(E_PARAMS); + } + + auto [errCode, infos] = CreateFileInfos(src, dest, options); + if (errCode != ERRNO_NOERR) { + return FsResult::Error(errCode); } auto callback = RegisterListener(infos); @@ -878,23 +856,25 @@ FsResult CopyCore::DoCopy(const string& src, const string& dest, std::opti if (infos->taskSignal != nullptr) { infos->taskSignal->MarkRemoteTask(); } - auto ret = TransListenerCore::CopyFileFromSoftBus(infos->srcUri, infos->destUri, - infos, std::move(callback)); + auto ret = TransListenerCore::CopyFileFromSoftBus(infos->srcUri, infos->destUri, infos, std::move(callback)); + UnregisterListener(infos); if (ret != ERRNO_NOERR) { return FsResult::Error(ret); } else { return FsResult::Success(); } } - result = CopyCore::ExecLocal(infos, callback); + auto result = CopyCore::ExecLocal(infos, callback); CloseNotifyFdLocked(infos, callback); infos->run = false; WaitNotifyFinished(callback); if (result != ERRNO_NOERR) { infos->exceptionCode = result; + UnregisterListener(infos); return FsResult::Error(infos->exceptionCode); } CopyComplete(infos, callback); + UnregisterListener(infos); if (infos->exceptionCode != ERRNO_NOERR) { return FsResult::Error(infos->exceptionCode); } else { diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_core.h b/interfaces/kits/js/src/mod_fs/properties/copy_core.h index 58aa4f999..387792260 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy_core.h +++ b/interfaces/kits/js/src/mod_fs/properties/copy_core.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,20 +13,20 @@ * limitations under the License. */ -#ifndef FILEMANAGEMENT_FILE_API_COPY_CORE_H -#define FILEMANAGEMENT_FILE_API_COPY_CORE_H +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_CORE_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_CORE_H #include #include #include -#include #include +#include #include "bundle_mgr_client_impl.h" #include "filemgmt_libfs.h" #include "filemgmt_libhilog.h" -#include "task_signal.h" -#include "task_signal_entity_core.h" +#include "fs_task_signal.h" +#include "i_progress_listener.h" namespace OHOS { namespace FileManagement { @@ -34,12 +34,10 @@ namespace ModuleFileIO { using namespace std; using namespace OHOS::AppExecFwk; using namespace DistributedFS::ModuleTaskSignal; -const uint64_t MAX_VALUE = 0x7FFFFFFFFFFFFFFF; -typedef std::function ProgressListenerCb; struct CopyOptions { - ProgressListenerCb listenerCb; - std::shared_ptr taskSignalEntityCore; + std::shared_ptr progressListener; + std::shared_ptr copySignal; }; struct ReceiveInfo { @@ -47,8 +45,8 @@ struct ReceiveInfo { std::map fileList; // filename, proceededSize }; -struct CallbackObjectCore { - ProgressListenerCb listenerCb; +struct FsCallbackObject { + std::shared_ptr listener = nullptr; int32_t notifyFd = -1; int32_t eventFd = -1; std::vector>> wds; @@ -62,7 +60,7 @@ struct CallbackObjectCore { std::mutex cvLock; bool reading = false; bool closed = false; - explicit CallbackObjectCore(ProgressListenerCb cb) : listenerCb(cb) {} + explicit FsCallbackObject(std::shared_ptr listener) : listener(listener) {} void CloseFd() { @@ -80,13 +78,13 @@ struct CallbackObjectCore { notifyFd = -1; } - ~CallbackObjectCore() + ~FsCallbackObject() { CloseFd(); } }; -struct FileInfosCore { +struct FsFileInfos { std::string srcUri; std::string destUri; std::string srcPath; @@ -97,15 +95,15 @@ struct FileInfosCore { int32_t eventFd = -1; bool run = true; bool hasListener = false; - ProgressListenerCb listenerCb; + std::shared_ptr listener = nullptr; std::shared_ptr taskSignal = nullptr; std::set filePaths; - int exceptionCode = ERRNO_NOERR; // notify copy thread or listener thread has exceptions. - bool operator==(const FileInfosCore &infos) const + int exceptionCode = ERRNO_NOERR; // notify copy thread or listener thread has exceptions. + bool operator==(const FsFileInfos &infos) const { return (srcUri == infos.srcUri && destUri == infos.destUri); } - bool operator<(const FileInfosCore &infos) const + bool operator<(const FsFileInfos &infos) const { if (srcUri == infos.srcUri) { return destUri < infos.destUri; @@ -114,73 +112,65 @@ struct FileInfosCore { } }; -struct UvEntryCore { - std::shared_ptr callback; - std::shared_ptr fileInfos; +struct FsUvEntry { + std::shared_ptr callback; + std::shared_ptr fileInfos; uint64_t progressSize = 0; uint64_t totalSize = 0; - UvEntryCore(const std::shared_ptr &cb, std::shared_ptr fileInfos) + FsUvEntry(const std::shared_ptr &cb, std::shared_ptr fileInfos) : callback(cb), fileInfos(fileInfos) { } - explicit UvEntryCore(const std::shared_ptr &cb) : callback(cb) {} + explicit FsUvEntry(const std::shared_ptr &cb) : callback(cb) {} }; class CopyCore final { public: - static std::map> jsCbMap_; - static void UnregisterListener(std::shared_ptr fileInfos); - static std::recursive_mutex mutex_; - static FsResult DoCopy(const string& src, const string& dest, std::optional &options); + static FsResult DoCopy(const string &src, const string &dest, std::optional &options); private: - // operator of napi + // operator of params static bool ValidOperand(std::string uriStr); static int CheckOrCreatePath(const std::string &destPath); - static int ValidParam(const string& src, const string& dest, std::optional options, - std::shared_ptr &fileInfos); + static bool ValidParams(const string &src, const string &dest); // operator of local listener - static int ExecLocal(std::shared_ptr infos, std::shared_ptr callback); - static void CopyComplete(std::shared_ptr infos, std::shared_ptr callback); - static void WaitNotifyFinished(std::shared_ptr callback); - static void ReadNotifyEvent(std::shared_ptr infos); - static void ReadNotifyEventLocked(std::shared_ptr infos, - std::shared_ptr callback); - static int SubscribeLocalListener(std::shared_ptr infos, - std::shared_ptr callback); - static std::shared_ptr RegisterListener( - const std::shared_ptr &infos); - static void OnFileReceive(std::shared_ptr infos); - static void GetNotifyEvent(std::shared_ptr infos); - static void StartNotify(std::shared_ptr infos, std::shared_ptr callback); - static UvEntryCore *GetUVEntry(std::shared_ptr infos); - static void ReceiveComplete(std::shared_ptr entry); - static std::shared_ptr GetRegisteredListener(std::shared_ptr infos); - static void CloseNotifyFd(std::shared_ptr infos, std::shared_ptr callback); - static void CloseNotifyFdLocked(std::shared_ptr infos, - std::shared_ptr callback); + static std::shared_ptr RegisterListener(const std::shared_ptr &infos); + static std::shared_ptr GetRegisteredListener(std::shared_ptr infos); + static void UnregisterListener(std::shared_ptr fileInfos); + static int ExecLocal(std::shared_ptr infos, std::shared_ptr callback); + static void CopyComplete(std::shared_ptr infos, std::shared_ptr callback); + static void WaitNotifyFinished(std::shared_ptr callback); + static void ReadNotifyEvent(std::shared_ptr infos); + static void ReadNotifyEventLocked(std::shared_ptr infos, std::shared_ptr callback); + static int SubscribeLocalListener(std::shared_ptr infos, std::shared_ptr callback); + static void OnFileReceive(std::shared_ptr infos); + static void GetNotifyEvent(std::shared_ptr infos); + static void StartNotify(std::shared_ptr infos, std::shared_ptr callback); + static FsUvEntry *GetUVEntry(std::shared_ptr infos); + static void ReceiveComplete(std::shared_ptr entry); + static void CloseNotifyFd(std::shared_ptr infos, std::shared_ptr callback); + static void CloseNotifyFdLocked(std::shared_ptr infos, std::shared_ptr callback); // operator of file - static int RecurCopyDir(const string &srcPath, const string &destPath, std::shared_ptr infos); + static int RecurCopyDir(const string &srcPath, const string &destPath, std::shared_ptr infos); static tuple GetFileSize(const std::string &path); - static uint64_t GetDirSize(std::shared_ptr infos, std::string path); - static int CopyFile(const string &src, const string &dest, std::shared_ptr infos); + static uint64_t GetDirSize(std::shared_ptr infos, std::string path); + static int CopyFile(const string &src, const string &dest, std::shared_ptr infos); static int MakeDir(const string &path); - static int CopySubDir(const string &srcPath, const string &destPath, std::shared_ptr infos); - static int CopyDirFunc(const string &src, const string &dest, std::shared_ptr infos); - static tuple> CreateFileInfos( - const std::string &srcUri, const std::string &destUri, std::optional options); - static int ExecCopy(std::shared_ptr infos); + static int CopySubDir(const string &srcPath, const string &destPath, std::shared_ptr infos); + static int CopyDirFunc(const string &src, const string &dest, std::shared_ptr infos); + static tuple> CreateFileInfos( + const std::string &srcUri, const std::string &destUri, const std::optional &options); + static int ExecCopy(std::shared_ptr infos); // operator of file size - static int UpdateProgressSize(const std::string &filePath, - std::shared_ptr receivedInfo, - std::shared_ptr callback); + static int UpdateProgressSize(const std::string &filePath, std::shared_ptr receivedInfo, + std::shared_ptr callback); static tuple HandleProgress( - inotify_event *event, std::shared_ptr infos, std::shared_ptr callback); - static std::shared_ptr GetReceivedInfo(int wd, std::shared_ptr callback); - static bool CheckFileValid(const std::string &filePath, std::shared_ptr infos); + inotify_event *event, std::shared_ptr infos, std::shared_ptr callback); + static std::shared_ptr GetReceivedInfo(int wd, std::shared_ptr callback); + static bool CheckFileValid(const std::string &filePath, std::shared_ptr infos); // operator of uri or path static bool IsValidUri(const std::string &uri); @@ -189,10 +179,14 @@ private: static bool IsFile(const std::string &path); static bool IsMediaUri(const std::string &uriPath); static std::string ConvertUriToPath(const std::string &uri); - static std::string GetRealPath(const std::string& path); + static std::string GetRealPath(const std::string &path); + +private: + static std::recursive_mutex mutex_; + static std::map> callbackMap_; }; } // namespace ModuleFileIO } // namespace FileManagement } // namespace OHOS -#endif // FILEMANAGEMENT_FILE_API_COPY_CORE_H \ No newline at end of file +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_CORE_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_listener/ani/progress_listener_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/copy_listener/ani/progress_listener_ani.cpp new file mode 100644 index 000000000..58be19337 --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/copy_listener/ani/progress_listener_ani.cpp @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "progress_listener_ani.h" + +#include +#include "ani_helper.h" +#include "ani_signature.h" +#include "file_utils.h" +#include "filemgmt_libhilog.h" +#include "type_converter.h" + +namespace OHOS::FileManagement::ModuleFileIO::ANI { +using namespace std; +using namespace OHOS::FileManagement::ModuleFileIO::ANI::AniSignature; + +void ProgressListenerAni::InvokeListener(uint64_t progressSize, uint64_t totalSize) const +{ + auto task = [this, progressSize, totalSize]() { SendCopyProgress(progressSize, totalSize); }; + AniHelper::SendEventToMainThread(task); +} + +static ani_object WrapCopyProgress(ani_env *env, uint64_t progressSize, uint64_t totalSize) +{ + auto classDesc = FS::ProgressInner::classDesc.c_str(); + ani_class cls; + if (ANI_OK != env->FindClass(classDesc, &cls)) { + HILOGE("Cannot find class %{private}s", classDesc); + return nullptr; + } + auto ctorDesc = FS::ProgressInner::ctorDesc.c_str(); + auto ctorSig = FS::ProgressInner::ctorSig.c_str(); + ani_method ctor; + if (ANI_OK != env->Class_FindMethod(cls, ctorDesc, ctorSig, &ctor)) { + HILOGE("Cannot find constructor method for class %{private}s", classDesc); + return nullptr; + } + + const ani_double aniProgressSize = static_cast(progressSize <= MAX_VALUE ? progressSize : 0); + const ani_double aniTotalSize = static_cast(totalSize <= MAX_VALUE ? totalSize : 0); + + ani_object obj; + if (ANI_OK != env->Object_New(cls, ctor, &obj, aniProgressSize, aniTotalSize)) { + HILOGE("Create %{private}s object failed!", classDesc); + return nullptr; + } + return obj; +} + +void ProgressListenerAni::SendCopyProgress(uint64_t progressSize, uint64_t totalSize) const +{ + if (vm == nullptr) { + HILOGE("Cannot send copy progress because the vm is null."); + return; + } + if (listener == nullptr) { + HILOGE("Cannot send copy progress because the listener is null."); + return; + } + ani_env *env = AniHelper::GetThreadEnv(vm); + if (env == nullptr) { + HILOGE("Cannot send copy progress because the env is null."); + return; + } + auto evtObj = WrapCopyProgress(env, progressSize, totalSize); + if (evtObj == nullptr) { + HILOGE("Create copy progress obj failed!"); + return; + } + vector args = { static_cast(evtObj) }; + auto argc = args.size(); + ani_ref result; + auto cbObj = static_cast(listener); + auto status = env->FunctionalObject_Call(cbObj, argc, args.data(), &result); + if (status != ANI_OK) { + HILOGE("Failed to call FunctionalObject_Call, status: %{public}d", static_cast(status)); + return; + } +} + +} // namespace OHOS::FileManagement::ModuleFileIO::ANI diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_listener/ani/progress_listener_ani.h b/interfaces/kits/js/src/mod_fs/properties/copy_listener/ani/progress_listener_ani.h new file mode 100644 index 000000000..07894982a --- /dev/null +++ b/interfaces/kits/js/src/mod_fs/properties/copy_listener/ani/progress_listener_ani.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_LISTENER_ANI_PROGRESS_LISTENER_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_LISTENER_ANI_PROGRESS_LISTENER_H + +#include +#include +#include "i_progress_listener.h" + +namespace OHOS::FileManagement::ModuleFileIO::ANI { + +class ProgressListenerAni final : public IProgressListener { +public: + ProgressListenerAni(ani_vm *vm, const ani_ref &listener) : vm(vm), listener(listener) {} + void InvokeListener(uint64_t progressSize, uint64_t totalSize) const override; + +private: + void SendCopyProgress(uint64_t progressSize, uint64_t totalSize) const; + +private: + ani_vm *vm; + ani_ref listener; +}; + +} // namespace OHOS::FileManagement::ModuleFileIO::ANI +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_LISTENER_ANI_PROGRESS_LISTENER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/class_tasksignal/task_signal_entity_core.cpp b/interfaces/kits/js/src/mod_fs/properties/copy_listener/i_progress_listener.h similarity index 50% rename from interfaces/kits/js/src/mod_fs/class_tasksignal/task_signal_entity_core.cpp rename to interfaces/kits/js/src/mod_fs/properties/copy_listener/i_progress_listener.h index 85dd60f91..f51f4f421 100644 --- a/interfaces/kits/js/src/mod_fs/class_tasksignal/task_signal_entity_core.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copy_listener/i_progress_listener.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,18 +13,19 @@ * limitations under the License. */ -#include "task_signal_entity_core.h" -#include "filemgmt_libhilog.h" +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_LISTENER_I_PROGRESS_LISTENER_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_LISTENER_I_PROGRESS_LISTENER_H + +#include namespace OHOS::FileManagement::ModuleFileIO { -TaskSignalEntityCore::~TaskSignalEntityCore() {} +const uint64_t MAX_VALUE = 0x7FFFFFFFFFFFFFFF; + +class IProgressListener { +public: + virtual ~IProgressListener() = default; + virtual void InvokeListener(uint64_t progressSize, uint64_t totalSize) const = 0; +}; -void TaskSignalEntityCore::OnCancel() -{ - if (!callbackContextCore_) { - return; - } - - callbackContextCore_->cb(taskSignal_->filePath_); -} -} // namespace OHOS::FileManagement::ModuleFileIO \ No newline at end of file +} // namespace OHOS::FileManagement::ModuleFileIO +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_LISTENER_I_PROGRESS_LISTENER_H \ No newline at end of file diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener_core.cpp b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener_core.cpp index 431a4f9e1..0b8d32b78 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener_core.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener_core.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,10 +19,10 @@ #include #include +#include "dfs_event_dfx.h" #include "ipc_skeleton.h" #include "sandbox_helper.h" #include "uri.h" -#include "dfs_event_dfx.h" #include "utils_log.h" namespace OHOS { @@ -70,22 +70,20 @@ int TransListenerCore::HandleCopyFailure(CopyEvent ©Event, const Storage::Di auto it = softbusErr2ErrCodeTable.find(copyEvent.errorCode); if (it == softbusErr2ErrCodeTable.end()) { RADAR_REPORT(RadarReporter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, - RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, - RadarReporter::SEND_FILE_ERROR, RadarReporter::CONCURRENT_ID, currentId, - RadarReporter::PACKAGE_NAME, to_string(copyEvent.errorCode)); + RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, RadarReporter::SEND_FILE_ERROR, + RadarReporter::CONCURRENT_ID, currentId, RadarReporter::PACKAGE_NAME, to_string(copyEvent.errorCode)); return EIO; } if (copyEvent.errorCode != DFS_CANCEL_SUCCESS) { HILOGE("HandleCopyFailure failed, copyEvent.errorCode = %{public}d.", copyEvent.errorCode); RADAR_REPORT(RadarReporter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, - RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, - RadarReporter::SEND_FILE_ERROR, RadarReporter::CONCURRENT_ID, currentId, - RadarReporter::PACKAGE_NAME, to_string(copyEvent.errorCode)); + RadarReporter::BIZ_STATE, RadarReporter::DFX_END, RadarReporter::ERROR_CODE, RadarReporter::SEND_FILE_ERROR, + RadarReporter::CONCURRENT_ID, currentId, RadarReporter::PACKAGE_NAME, to_string(copyEvent.errorCode)); } return it->second; } -int TransListenerCore::WaitForCopyResult(TransListenerCore* transListener) +int TransListenerCore::WaitForCopyResult(TransListenerCore *transListener) { if (transListener == nullptr) { HILOGE("transListener is nullptr"); @@ -93,14 +91,13 @@ int TransListenerCore::WaitForCopyResult(TransListenerCore* transListener) } std::unique_lock lock(transListener->cvMutex_); transListener->cv_.wait(lock, [&transListener]() { - return transListener->copyEvent_.copyResult == SUCCESS || - transListener->copyEvent_.copyResult == FAILED; + return transListener->copyEvent_.copyResult == SUCCESS || transListener->copyEvent_.copyResult == FAILED; }); return transListener->copyEvent_.copyResult; } int TransListenerCore::CopyFileFromSoftBus(const std::string &srcUri, const std::string &destUri, - std::shared_ptr fileInfos, std::shared_ptr callback) + std::shared_ptr fileInfos, std::shared_ptr callback) { HILOGI("CopyFileFromSoftBus begin."); std::string currentId = "CopyFile_" + std::to_string(getpid()) + "_" + std::to_string(getSequenceId_); @@ -115,7 +112,7 @@ int TransListenerCore::CopyFileFromSoftBus(const std::string &srcUri, const std: } transListener->callback_ = std::move(callback); - Storage::DistributedFile::HmdfsInfo info{}; + Storage::DistributedFile::HmdfsInfo info {}; Uri uri(destUri); info.authority = uri.GetAuthority(); info.sandboxPath = SandboxHelper::Decode(uri.GetPath()); @@ -151,14 +148,11 @@ int TransListenerCore::CopyFileFromSoftBus(const std::string &srcUri, const std: return ERRNO_NOERR; } -int32_t TransListenerCore::PrepareCopySession(const std::string &srcUri, - const std::string &destUri, - TransListenerCore* transListener, - Storage::DistributedFile::HmdfsInfo &info, - std::string &disSandboxPath) +int32_t TransListenerCore::PrepareCopySession(const std::string &srcUri, const std::string &destUri, + TransListenerCore *transListener, Storage::DistributedFile::HmdfsInfo &info, std::string &disSandboxPath) { std::string tmpDir; - if (info.authority != FILE_MANAGER_AUTHORITY && info.authority != MEDIA_AUTHORITY) { + if (info.authority != FILE_MANAGER_AUTHORITY && info.authority != MEDIA_AUTHORITY) { tmpDir = CreateDfsCopyPath(); disSandboxPath = DISTRIBUTED_PATH + tmpDir; std::error_code errCode; @@ -181,8 +175,8 @@ int32_t TransListenerCore::PrepareCopySession(const std::string &srcUri, info.copyPath = tmpDir; auto networkId = GetNetworkIdFromUri(srcUri); HILOGI("dfs PrepareSession begin."); - auto ret = Storage::DistributedFile::DistributedFileDaemonManager::GetInstance().PrepareSession(srcUri, destUri, - networkId, transListener, info); + auto ret = Storage::DistributedFile::DistributedFileDaemonManager::GetInstance().PrepareSession( + srcUri, destUri, networkId, transListener, info); if (ret != ERRNO_NOERR) { HILOGE("PrepareSession failed, ret = %{public}d.", ret); if (info.authority != FILE_MANAGER_AUTHORITY && info.authority != MEDIA_AUTHORITY) { @@ -218,8 +212,8 @@ int32_t TransListenerCore::CopyToSandBox(const std::string &srcUri, const std::s RmDir(disSandboxPath); return EIO; } - std::filesystem::copy(disSandboxPath + fileName, sandboxPath, std::filesystem::copy_options::update_existing, - errCode); + std::filesystem::copy( + disSandboxPath + fileName, sandboxPath, std::filesystem::copy_options::update_existing, errCode); if (errCode.value() != 0) { HILOGE("Copy file failed: errCode: %{public}d", errCode.value()); RADAR_REPORT(RadarReporter::DFX_SET_DFS, RadarReporter::DFX_SET_BIZ_SCENE, RadarReporter::DFX_FAILED, @@ -250,14 +244,24 @@ std::string TransListenerCore::GetNetworkIdFromUri(const std::string &uri) return uri.substr(uri.find(NETWORK_PARA) + NETWORK_PARA.size(), uri.size()); } -void TransListenerCore::CallbackComplete(std::shared_ptr entry) +void TransListenerCore::CallbackComplete(std::shared_ptr entry) { if (entry == nullptr) { HILOGE("entry pointer is nullptr."); return; } - entry->callback->listenerCb(entry->progressSize, entry->totalSize); + if (entry->callback == nullptr) { + HILOGE("entry callback pointer is nullptr."); + return; + } + + auto listener = entry->callback->listener; + if (listener == nullptr) { + HILOGE("listener pointer is nullptr."); + return; + } + listener->InvokeListener(entry->progressSize, entry->totalSize); } int32_t TransListenerCore::OnFileReceive(uint64_t totalBytes, uint64_t processedBytes) @@ -268,7 +272,7 @@ int32_t TransListenerCore::OnFileReceive(uint64_t totalBytes, uint64_t processed return ENOMEM; } - std::shared_ptr entry = std::make_shared(callback_); + std::shared_ptr entry = std::make_shared(callback_); if (entry == nullptr) { HILOGE("entry ptr is nullptr"); return ENOMEM; diff --git a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener_core.h b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener_core.h index d5b8f9585..c797454de 100644 --- a/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener_core.h +++ b/interfaces/kits/js/src/mod_fs/properties/copy_listener/trans_listener_core.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef FILEMANAGEMENT_FILE_API_TRANS_LISTENER_CORE_H -#define FILEMANAGEMENT_FILE_API_TRANS_LISTENER_CORE_H +#ifndef INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_LISTENER_TRANS_LISTENER_CORE_H +#define INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_LISTENER_TRANS_LISTENER_CORE_H #include @@ -40,35 +40,31 @@ public: int32_t OnFileReceive(uint64_t totalBytes, uint64_t processedBytes) override; int32_t OnFinished(const std::string &sessionName) override; int32_t OnFailed(const std::string &sessionName, int32_t errorCode) override; - static int CopyFileFromSoftBus(const std::string &srcUri, - const std::string &destUri, - std::shared_ptr fileInfos, - std::shared_ptr callback); + static int CopyFileFromSoftBus(const std::string &srcUri, const std::string &destUri, + std::shared_ptr fileInfos, std::shared_ptr callback); + private: static std::string GetNetworkIdFromUri(const std::string &uri); - static void CallbackComplete(std::shared_ptr entry); + static void CallbackComplete(std::shared_ptr entry); static void RmDir(const std::string &path); static std::string CreateDfsCopyPath(); static std::string GetFileName(const std::string &path); static int32_t CopyToSandBox(const std::string &srcUri, const std::string &disSandboxPath, const std::string &sandboxPath, const std::string ¤tId); - static int32_t PrepareCopySession(const std::string &srcUri, - const std::string &destUri, - TransListenerCore* transListener, - Storage::DistributedFile::HmdfsInfo &info, - std::string &disSandboxPath); + static int32_t PrepareCopySession(const std::string &srcUri, const std::string &destUri, + TransListenerCore *transListener, Storage::DistributedFile::HmdfsInfo &info, std::string &disSandboxPath); static int HandleCopyFailure(CopyEvent ©Event, const Storage::DistributedFile::HmdfsInfo &info, const std::string &disSandboxPath, const std::string ¤tId); - static int WaitForCopyResult(TransListenerCore* transListener); + static int WaitForCopyResult(TransListenerCore *transListener); static std::atomic getSequenceId_; std::mutex cvMutex_; std::condition_variable cv_; CopyEvent copyEvent_; std::mutex callbackMutex_; - std::shared_ptr callback_; + std::shared_ptr callback_; }; } // namespace ModuleFileIO } // namespace FileManagement } // namespace OHOS -#endif // FILEMANAGEMENT_FILE_API_TRANS_LISTENER_CORE_H \ No newline at end of file +#endif // INTERFACES_KITS_JS_SRC_MOD_FS_PROPERTIES_COPY_LISTENER_TRANS_LISTENER_CORE_H \ No newline at end of file -- Gitee From d82e4d49707da4990ea0bc397c794718a4b55e09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9C=E5=B0=8F=E6=9E=97?= Date: Fri, 13 Jun 2025 09:49:18 +0800 Subject: [PATCH 15/19] =?UTF-8?q?=E6=A0=B9=E6=8D=AE=E6=A3=80=E8=A7=86?= =?UTF-8?q?=E6=84=8F=E8=A7=81=E8=BF=9B=E8=A1=8C=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Change-Id: I1727413a28b67a39be892c644136f960df59590f Signed-off-by: 姜小林 --- .../kits/js/src/mod_fs/ani/ets/@ohos.file.fs.ets | 4 +++- .../ani/task_signal_listener_ani.cpp | 2 +- .../kits/js/src/mod_fs/properties/ani/copy_ani.cpp | 14 ++++++++++++-- 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/interfaces/kits/js/src/mod_fs/ani/ets/@ohos.file.fs.ets b/interfaces/kits/js/src/mod_fs/ani/ets/@ohos.file.fs.ets index 1ebce3e37..610c1094f 100644 --- a/interfaces/kits/js/src/mod_fs/ani/ets/@ohos.file.fs.ets +++ b/interfaces/kits/js/src/mod_fs/ani/ets/@ohos.file.fs.ets @@ -1266,7 +1266,7 @@ export class TaskSignal { private native onCancelNative(): void; - private onCancelResolve: (path: string) => void; + private onCancelResolve: (path: string) => void = (path: string): void => {}; private onCancelCallback(path: string): void { if (this.onCancelResolve) { this.onCancelResolve(path); @@ -1282,6 +1282,8 @@ export class TaskSignal { this.onCancelNative(); } catch (e: BusinessError) { reject(e); + } catch (e: Error) { + reject(e as BusinessError); } }); } diff --git a/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_listener_ani.cpp b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_listener_ani.cpp index a80010e95..8f533889c 100644 --- a/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_listener_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/class_tasksignal/ani/task_signal_listener_ani.cpp @@ -55,7 +55,7 @@ void TaskSignalListenerAni::SendCancelEvent(const string &filepath) const } auto ret = env->Object_CallMethodByName_Void(signalObj, "onCancelCallback", nullptr, aniPath); if (ret != ANI_OK) { - HILOGE("Call onCancelCallback failed, err: %{private}d", ret); + HILOGE("Call onCancelCallback failed, err: %{public}d", ret); return; } } diff --git a/interfaces/kits/js/src/mod_fs/properties/ani/copy_ani.cpp b/interfaces/kits/js/src/mod_fs/properties/ani/copy_ani.cpp index 7e84bce8f..541cd7f6c 100644 --- a/interfaces/kits/js/src/mod_fs/properties/ani/copy_ani.cpp +++ b/interfaces/kits/js/src/mod_fs/properties/ani/copy_ani.cpp @@ -140,8 +140,18 @@ void CopyAni::CopySync( auto [succDest, dest] = TypeConverter::ToUTF8String(env, destUri); auto [succOpts, opts] = ParseOptions(env, options); - if (!succSrc || !succDest || !succOpts) { - HILOGE("The first/second/third argument requires uri/uri/napi_function"); + if (!succSrc) { + HILOGE("The first argument requires uri"); + ErrorHandler::Throw(env, E_PARAMS); + return; + } + if (!succDest) { + HILOGE("The second argument requires uri"); + ErrorHandler::Throw(env, E_PARAMS); + return; + } + if (!succOpts) { + HILOGE("The third argument requires listener function"); ErrorHandler::Throw(env, E_PARAMS); return; } -- Gitee From cc4e944744e92c49e35c7eb7588037c143d8fa78 Mon Sep 17 00:00:00 2001 From: liyuke Date: Fri, 13 Jun 2025 15:41:15 +0800 Subject: [PATCH 16/19] =?UTF-8?q?environment=20TDD=E6=B7=BB=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: liyuke --- .../src/mod_environment/environment_core.cpp | 4 +- .../environment_core_mock_test.cpp | 521 ++++++++++++++++++ .../mock/accesstoken_kit_mock.cpp | 29 + .../mock/accesstoken_kit_mock.h | 44 ++ .../mock/ipc_skeleton_mock.cpp | 33 ++ .../mod_environment/mock/ipc_skeleton_mock.h | 46 ++ .../mod_environment/mock/parameter_mock.cpp | 27 + .../js/mod_environment/mock/parameter_mock.h | 41 ++ 8 files changed, 743 insertions(+), 2 deletions(-) create mode 100644 interfaces/test/unittest/js/mod_environment/environment_core_mock_test.cpp create mode 100644 interfaces/test/unittest/js/mod_environment/mock/accesstoken_kit_mock.cpp create mode 100644 interfaces/test/unittest/js/mod_environment/mock/accesstoken_kit_mock.h create mode 100644 interfaces/test/unittest/js/mod_environment/mock/ipc_skeleton_mock.cpp create mode 100644 interfaces/test/unittest/js/mod_environment/mock/ipc_skeleton_mock.h create mode 100644 interfaces/test/unittest/js/mod_environment/mock/parameter_mock.cpp create mode 100644 interfaces/test/unittest/js/mod_environment/mock/parameter_mock.h diff --git a/interfaces/kits/js/src/mod_environment/environment_core.cpp b/interfaces/kits/js/src/mod_environment/environment_core.cpp index f13e9b942..5be54fe32 100644 --- a/interfaces/kits/js/src/mod_environment/environment_core.cpp +++ b/interfaces/kits/js/src/mod_environment/environment_core.cpp @@ -42,7 +42,7 @@ const std::string DOWNLOAD_PATH = "/Download"; const std::string DESKTOP_PATH = "/Desktop"; const std::string DOCUMENTS_PATH = "/Documents"; const std::string DEFAULT_USERNAME = "currentUser"; -const char *FILE_MANAMER_FULL_MOUNT_ENABLE_PARAMETER = "const.filemanager.full_mount.enable"; +const char *FILE_MANAGER_FULL_MOUNT_ENABLE_PARAMETER = "const.filemanager.full_mount.enable"; static bool IsSystemApp() { uint64_t fullTokenId = OHOS::IPCSkeleton::GetCallingFullTokenID(); @@ -79,7 +79,7 @@ static std::string GetPublicPath(const std::string &directoryName) static bool CheckFileManagerFullMountEnable() { char value[] = "false"; - int retSystem = GetParameter(FILE_MANAMER_FULL_MOUNT_ENABLE_PARAMETER, "false", value, sizeof(value)); + int retSystem = GetParameter(FILE_MANAGER_FULL_MOUNT_ENABLE_PARAMETER, "false", value, sizeof(value)); if (retSystem > 0 && !std::strcmp(value, "true")) { return true; } diff --git a/interfaces/test/unittest/js/mod_environment/environment_core_mock_test.cpp b/interfaces/test/unittest/js/mod_environment/environment_core_mock_test.cpp new file mode 100644 index 000000000..b3f619103 --- /dev/null +++ b/interfaces/test/unittest/js/mod_environment/environment_core_mock_test.cpp @@ -0,0 +1,521 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "accesstoken_kit_mock.h" +#include "environment_core.h" +#include "ipc_skeleton_mock.h" +#include "parameter_mock.h" +#include "securec.h" + +namespace OHOS::FileManagement::ModuleFileIO::Test { +using namespace testing; +using namespace testing::ext; +using namespace std; + +class EnvironmentCoreTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); + static inline shared_ptr accessToken = nullptr; + static inline std::shared_ptr paramMoc = nullptr; + static inline shared_ptr skeleton = nullptr; +}; + +void EnvironmentCoreTest::SetUpTestCase(void) +{ + GTEST_LOG_(INFO) << "SetUpTestCase"; + accessToken = std::make_shared(); + Backup::BAccessTokenKit::token = accessToken; + paramMoc = std::make_shared(); + AppFileService::ParamMoc::paramMoc = paramMoc; + skeleton = make_shared(); + Backup::IPCSkeletonMock::skeleton = skeleton; +} + +void EnvironmentCoreTest::TearDownTestCase(void) +{ + GTEST_LOG_(INFO) << "TearDownTestCase"; + Backup::BAccessTokenKit::token = nullptr; + accessToken = nullptr; + AppFileService::IParamMoc::paramMoc = nullptr; + paramMoc = nullptr; + Backup::IPCSkeletonMock::skeleton = nullptr; + skeleton = nullptr; +} + +void EnvironmentCoreTest::SetUp(void) +{ + GTEST_LOG_(INFO) << "SetUp"; +} + +void EnvironmentCoreTest::TearDown(void) +{ + GTEST_LOG_(INFO) << "TearDown"; +} + +/** + * @tc.name: EnvironmentCoreTest_DoGetStorageDataDir_001 + * @tc.desc: Test function of DoGetStorageDataDir interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetStorageDataDir_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "EnvironmentCoreTest-begin EnvironmentCoreTest_DoGetStorageDataDir_001"; + + EXPECT_CALL(*accessToken, IsSystemAppByFullTokenID(_)).WillOnce(Return(false)); + + auto res = ModuleEnvironment::DoGetStorageDataDir(); + + EXPECT_FALSE(res.IsSuccess()); + + GTEST_LOG_(INFO) << "EnvironmentCoreTest-end EnvironmentCoreTest_DoGetStorageDataDir_001"; +} + +/** + * @tc.name: EnvironmentCoreTest_DoGetStorageDataDir_002 + * @tc.desc: Test function of DoGetStorageDataDir interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetStorageDataDir_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "EnvironmentCoreTest-begin EnvironmentCoreTest_DoGetStorageDataDir_002"; + + EXPECT_CALL(*accessToken, IsSystemAppByFullTokenID(_)).WillOnce(Return(true)); + + auto res = ModuleEnvironment::DoGetStorageDataDir(); + + EXPECT_TRUE(res.IsSuccess()); + + GTEST_LOG_(INFO) << "EnvironmentCoreTest-end EnvironmentCoreTest_DoGetStorageDataDir_002"; +} + +/** + * @tc.name: EnvironmentCoreTest_DoGetUserDataDir_001 + * @tc.desc: Test function of DoGetUserDataDir interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetUserDataDir_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "EnvironmentCoreTest-begin EnvironmentCoreTest_DoGetUserDataDir_001"; + + EXPECT_CALL(*accessToken, IsSystemAppByFullTokenID(_)).WillOnce(Return(false)); + + auto res = ModuleEnvironment::DoGetUserDataDir(); + + EXPECT_FALSE(res.IsSuccess()); + + GTEST_LOG_(INFO) << "EnvironmentCoreTest-end EnvironmentCoreTest_DoGetUserDataDir_001"; +} + +/** + * @tc.name: EnvironmentCoreTest_DoGetUserDataDir_002 + * @tc.desc: Test function of DoGetUserDataDir interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetUserDataDir_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "EnvironmentCoreTest-begin EnvironmentCoreTest_DoGetUserDataDir_002"; + + EXPECT_CALL(*accessToken, IsSystemAppByFullTokenID(_)).WillOnce(Return(true)); + + auto res = ModuleEnvironment::DoGetUserDataDir(); + + EXPECT_TRUE(res.IsSuccess()); + + GTEST_LOG_(INFO) << "EnvironmentCoreTest-end EnvironmentCoreTest_DoGetUserDataDir_002"; +} + +/** + * @tc.name: EnvironmentCoreTest_DoGetUserDownloadDir_001 + * @tc.desc: Test function of DoGetUserDownloadDir interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetUserDownloadDir_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "EnvironmentCoreTest-begin EnvironmentCoreTest_DoGetUserDownloadDir_001"; + + EXPECT_CALL(*paramMoc, GetParameter(_, _, _, _)) + .WillRepeatedly(Invoke([&](const char *, const char *, char *value, uint32_t) { + strcpy_s(value, 5, "true"); + return 1; + })); + EXPECT_CALL(*skeleton, GetOsAccountShortName(_)).WillRepeatedly(Return(ERR_OK)); + + auto res = ModuleEnvironment::DoGetUserDownloadDir(); + + EXPECT_TRUE(res.IsSuccess()); + + GTEST_LOG_(INFO) << "EnvironmentCoreTest-end EnvironmentCoreTest_DoGetUserDownloadDir_001"; +} + +/** + * @tc.name: EnvironmentCoreTest_DoGetUserDownloadDir_002 + * @tc.desc: Test function of DoGetUserDownloadDir interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetUserDownloadDir_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "EnvironmentCoreTest-begin EnvironmentCoreTest_DoGetUserDownloadDir_002"; + + EXPECT_CALL(*paramMoc, GetParameter(_, _, _, _)).WillOnce(Return(-1)); + + auto res = ModuleEnvironment::DoGetUserDownloadDir(); + + EXPECT_FALSE(res.IsSuccess()); + + GTEST_LOG_(INFO) << "EnvironmentCoreTest-end EnvironmentCoreTest_DoGetUserDownloadDir_002"; +} + +/** + * @tc.name: EnvironmentCoreTest_DoGetUserDownloadDir_003 + * @tc.desc: Test function of DoGetUserDownloadDir interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetUserDownloadDir_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "EnvironmentCoreTest-begin EnvironmentCoreTest_DoGetUserDownloadDir_003"; + + EXPECT_CALL(*paramMoc, GetParameter(_, _, _, _)) + .WillRepeatedly(Invoke([&](const char *, const char *, char *value, uint32_t) { + strcpy_s(value, 5, "true"); + return 1; + })); + EXPECT_CALL(*skeleton, GetOsAccountShortName(_)).WillRepeatedly(Return(1)); + + auto res = ModuleEnvironment::DoGetUserDownloadDir(); + + EXPECT_FALSE(res.IsSuccess()); + + GTEST_LOG_(INFO) << "EnvironmentCoreTest-end EnvironmentCoreTest_DoGetUserDownloadDir_003"; +} + +/** + * @tc.name: EnvironmentCoreTest_DoGetUserDesktopDir_001 + * @tc.desc: Test function of DoGetUserDesktopDir interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetUserDesktopDir_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "EnvironmentCoreTest-begin EnvironmentCoreTest_DoGetUserDesktopDir_001"; + + EXPECT_CALL(*paramMoc, GetParameter(_, _, _, _)) + .WillOnce(Invoke([&](const char *key, const char *def, char *value, uint32_t len) { + strcpy_s(value, 5, "true"); + return 1; + })); + + auto res = ModuleEnvironment::DoGetUserDesktopDir(); + + EXPECT_TRUE(res.IsSuccess()); + + GTEST_LOG_(INFO) << "EnvironmentCoreTest-end EnvironmentCoreTest_DoGetUserDesktopDir_001"; +} + +/** + * @tc.name: EnvironmentCoreTest_DoGetUserDesktopDir_002 + * @tc.desc: Test function of DoGetUserDesktopDir interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetUserDesktopDir_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "EnvironmentCoreTest-begin EnvironmentCoreTest_DoGetUserDesktopDir_002"; + + EXPECT_CALL(*paramMoc, GetParameter(_, _, _, _)) + .WillOnce(Invoke([&](const char *key, const char *def, char *value, uint32_t len) { + strcpy_s(value, 5, "true"); + return -1; + })); + + auto res = ModuleEnvironment::DoGetUserDesktopDir(); + + EXPECT_FALSE(res.IsSuccess()); + + GTEST_LOG_(INFO) << "EnvironmentCoreTest-end EnvironmentCoreTest_DoGetUserDesktopDir_002"; +} + +/** + * @tc.name: EnvironmentCoreTest_DoGetUserDesktopDir_003 + * @tc.desc: Test function of DoGetUserDesktopDir interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetUserDesktopDir_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "EnvironmentCoreTest-begin EnvironmentCoreTest_DoGetUserDesktopDir_003"; + + EXPECT_CALL(*paramMoc, GetParameter(_, _, _, _)) + .WillOnce(Invoke([&](const char *, const char *, char *value, uint32_t) { + strcpy_s(value, 5, "true"); + return 1; + })); + EXPECT_CALL(*skeleton, GetOsAccountShortName(_)).WillRepeatedly(Return(ERR_OK)); + + auto res = ModuleEnvironment::DoGetUserDesktopDir(); + + EXPECT_FALSE(res.IsSuccess()); + + GTEST_LOG_(INFO) << "EnvironmentCoreTest-end EnvironmentCoreTest_DoGetUserDesktopDir_003"; +} + +/** + * @tc.name: EnvironmentCoreTest_DoGetUserDocumentDir_001 + * @tc.desc: Test function of DoGetUserDocumentDir interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetUserDocumentDir_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "EnvironmentCoreTest-begin EnvironmentCoreTest_DoGetUserDocumentDir_001"; + + EXPECT_CALL(*paramMoc, GetParameter(_, _, _, _)) + .WillOnce(Invoke([&](const char *key, const char *def, char *value, uint32_t len) { + strcpy_s(value, 5, "true"); + return 1; + })); + + auto res = ModuleEnvironment::DoGetUserDocumentDir(); + + EXPECT_TRUE(res.IsSuccess()); + + GTEST_LOG_(INFO) << "EnvironmentCoreTest-end EnvironmentCoreTest_DoGetUserDocumentDir_001"; +} + +/** + * @tc.name: EnvironmentCoreTest_DoGetUserDocumentDir_002 + * @tc.desc: Test function of DoGetUserDocumentDir interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetUserDocumentDir_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "EnvironmentCoreTest-begin EnvironmentCoreTest_DoGetUserDocumentDir_002"; + + EXPECT_CALL(*paramMoc, GetParameter(_, _, _, _)) + .WillOnce(Invoke([&](const char *key, const char *def, char *value, uint32_t len) { + strcpy_s(value, 5, "true"); + return -1; + })); + + auto res = ModuleEnvironment::DoGetUserDocumentDir(); + + EXPECT_FALSE(res.IsSuccess()); + + GTEST_LOG_(INFO) << "EnvironmentCoreTest-end EnvironmentCoreTest_DoGetUserDocumentDir_002"; +} + +/** + * @tc.name: EnvironmentCoreTest_DoGetUserDocumentDir_003 + * @tc.desc: Test function of DoGetUserDocumentDir interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetUserDocumentDir_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "EnvironmentCoreTest-begin EnvironmentCoreTest_DoGetUserDocumentDir_003"; + + EXPECT_CALL(*paramMoc, GetParameter(_, _, _, _)) + .WillOnce(Invoke([&](const char *, const char *, char *value, uint32_t) { + strcpy_s(value, 5, "true"); + return 1; + })); + + auto res = ModuleEnvironment::DoGetUserDocumentDir(); + + EXPECT_FALSE(res.IsSuccess()); + + GTEST_LOG_(INFO) << "EnvironmentCoreTest-end EnvironmentCoreTest_DoGetUserDocumentDir_003"; +} + +/** + * @tc.name: EnvironmentCoreTest_DoGetExternalStorageDir_001 + * @tc.desc: Test function of DoGetExternalStorageDir interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetExternalStorageDir_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "EnvironmentCoreTest-begin EnvironmentCoreTest_DoGetExternalStorageDir_001"; + + EXPECT_CALL(*paramMoc, GetParameter(_, _, _, _)) + .WillOnce(Invoke([&](const char *key, const char *def, char *value, uint32_t len) { + strcpy_s(value, 5, "true"); + return 1; + })); + EXPECT_CALL(*accessToken, IsSystemAppByFullTokenID(_)).WillOnce(Return(false)); + + auto res = ModuleEnvironment::DoGetExternalStorageDir(); + + EXPECT_FALSE(res.IsSuccess()); + + GTEST_LOG_(INFO) << "EnvironmentCoreTest-end EnvironmentCoreTest_DoGetExternalStorageDir_001"; +} + +/** + * @tc.name: EnvironmentCoreTest_DoGetExternalStorageDir_002 + * @tc.desc: Test function of DoGetExternalStorageDir interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetExternalStorageDir_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "EnvironmentCoreTest-begin EnvironmentCoreTest_DoGetExternalStorageDir_002"; + + EXPECT_CALL(*paramMoc, GetParameter(_, _, _, _)) + .WillOnce(Invoke([&](const char *key, const char *def, char *value, uint32_t len) { + strcpy_s(value, 5, "true"); + return 1; + })); + EXPECT_CALL(*accessToken, IsSystemAppByFullTokenID(_)).WillOnce(Return(true)); + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); + EXPECT_CALL(*accessToken, VerifyAccessToken(_, _)).WillOnce(Return(1)); + + auto res = ModuleEnvironment::DoGetExternalStorageDir(); + + EXPECT_FALSE(res.IsSuccess()); + + GTEST_LOG_(INFO) << "EnvironmentCoreTest-end EnvironmentCoreTest_DoGetExternalStorageDir_002"; +} + +/** + * @tc.name: EnvironmentCoreTest_DoGetExternalStorageDir_003 + * @tc.desc: Test function of DoGetExternalStorageDir interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetExternalStorageDir_003, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "EnvironmentCoreTest-begin EnvironmentCoreTest_DoGetExternalStorageDir_003"; + + EXPECT_CALL(*paramMoc, GetParameter(_, _, _, _)) + .WillOnce(Invoke([&](const char *key, const char *def, char *value, uint32_t len) { + strcpy_s(value, 5, "true"); + return 1; + })); + EXPECT_CALL(*accessToken, IsSystemAppByFullTokenID(_)).WillOnce(Return(true)); + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); + EXPECT_CALL(*accessToken, VerifyAccessToken(_, _)) + .WillOnce(Return(Security::AccessToken::PermissionState::PERMISSION_GRANTED)); + + auto res = ModuleEnvironment::DoGetExternalStorageDir(); + + EXPECT_TRUE(res.IsSuccess()); + + GTEST_LOG_(INFO) << "EnvironmentCoreTest-end EnvironmentCoreTest_DoGetExternalStorageDir_003"; +} + +/** + * @tc.name: EnvironmentCoreTest_DoGetExternalStorageDir_004 + * @tc.desc: Test function of DoGetExternalStorageDir interface for success. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetExternalStorageDir_004, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "EnvironmentCoreTest-begin EnvironmentCoreTest_DoGetExternalStorageDir_004"; + + EXPECT_CALL(*paramMoc, GetParameter(_, _, _, _)) + .WillOnce(Invoke([&](const char *key, const char *def, char *value, uint32_t len) { + strcpy_s(value, 5, "true"); + return 1; + })); + EXPECT_CALL(*accessToken, IsSystemAppByFullTokenID(_)).WillOnce(Return(false)); + + auto res = ModuleEnvironment::DoGetExternalStorageDir(); + + EXPECT_FALSE(res.IsSuccess()); + + GTEST_LOG_(INFO) << "EnvironmentCoreTest-end EnvironmentCoreTest_DoGetExternalStorageDir_004"; +} + +/** + * @tc.name: EnvironmentCoreTest_DoGetUserHomeDir_001 + * @tc.desc: Test function of DoGetUserHomeDir interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetUserHomeDir_001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "EnvironmentCoreTest-begin EnvironmentCoreTest_DoGetUserHomeDir_001"; + + EXPECT_CALL(*paramMoc, GetParameter(_, _, _, _)).WillOnce(Return(1)); + + auto res = ModuleEnvironment::DoGetUserHomeDir(); + + EXPECT_FALSE(res.IsSuccess()); + + GTEST_LOG_(INFO) << "EnvironmentCoreTest-end EnvironmentCoreTest_DoGetUserHomeDir_001"; +} + +/** + * @tc.name: EnvironmentCoreTest_DoGetUserHomeDir_002 + * @tc.desc: Test function of DoGetUserHomeDir interface for FALSE. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetUserHomeDir_002, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "EnvironmentCoreTest-begin EnvironmentCoreTest_DoGetUserHomeDir_002"; + + EXPECT_CALL(*paramMoc, GetParameter(_, _, _, _)) + .WillOnce(Invoke([&](const char *key, const char *def, char *value, uint32_t len) { + strcpy_s(value, 5, "true"); + return 1; + })); + EXPECT_CALL(*accessToken, IsSystemAppByFullTokenID(_)).WillOnce(Return(true)); + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); + EXPECT_CALL(*accessToken, VerifyAccessToken(_, _)) + .WillOnce(Return(Security::AccessToken::PermissionState::PERMISSION_GRANTED)); + + auto res = ModuleEnvironment::DoGetUserHomeDir(); + + EXPECT_TRUE(res.IsSuccess()); + + GTEST_LOG_(INFO) << "EnvironmentCoreTest-end EnvironmentCoreTest_DoGetUserHomeDir_002"; +} + +} // namespace OHOS::FileManagement::ModuleFileIO::Test \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_environment/mock/accesstoken_kit_mock.cpp b/interfaces/test/unittest/js/mod_environment/mock/accesstoken_kit_mock.cpp new file mode 100644 index 000000000..021e591fe --- /dev/null +++ b/interfaces/test/unittest/js/mod_environment/mock/accesstoken_kit_mock.cpp @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "accesstoken_kit_mock.h" + +namespace OHOS::Security::AccessToken { + +bool TokenIdKit::IsSystemAppByFullTokenID(uint64_t tokenId) +{ + return OHOS::FileManagement::Backup::BAccessTokenKit::token->IsSystemAppByFullTokenID(tokenId); +} + +int AccessTokenKit::VerifyAccessToken(AccessTokenID tokenID, const std::string &permissionName) +{ + return OHOS::FileManagement::Backup::BAccessTokenKit::token->VerifyAccessToken(tokenID, permissionName); +} +} // namespace OHOS::Security::AccessToken diff --git a/interfaces/test/unittest/js/mod_environment/mock/accesstoken_kit_mock.h b/interfaces/test/unittest/js/mod_environment/mock/accesstoken_kit_mock.h new file mode 100644 index 000000000..5f5c0b18b --- /dev/null +++ b/interfaces/test/unittest/js/mod_environment/mock/accesstoken_kit_mock.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License") = 0; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_TEST_UNITTEST_JS_MOD_ENVIRONMENT_MOCK_ACCESSTOKEN_KIT_MOCK_H +#define INTERFACES_TEST_UNITTEST_JS_MOD_ENVIRONMENT_MOCK_ACCESSTOKEN_KIT_MOCK_H + +#include + +#include "accesstoken_kit.h" +#include "tokenid_kit.h" + +namespace OHOS::FileManagement::Backup { +class BAccessTokenKit { +public: + virtual bool IsSystemAppByFullTokenID(uint64_t) = 0; + virtual int VerifyAccessToken(Security::AccessToken::AccessTokenID, const std::string &) = 0; + +public: + BAccessTokenKit() = default; + virtual ~BAccessTokenKit() = default; + +public: + static inline std::shared_ptr token = nullptr; +}; + +class AccessTokenKitMock : public BAccessTokenKit { +public: + MOCK_METHOD(bool, IsSystemAppByFullTokenID, (uint64_t)); + MOCK_METHOD(int, VerifyAccessToken, (Security::AccessToken::AccessTokenID, const std::string &)); +}; +} // namespace OHOS::FileManagement::Backup +#endif // INTERFACES_TEST_UNITTEST_JS_MOD_ENVIRONMENT_MOCK_ACCESSTOKEN_KIT_MOCK_H \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_environment/mock/ipc_skeleton_mock.cpp b/interfaces/test/unittest/js/mod_environment/mock/ipc_skeleton_mock.cpp new file mode 100644 index 000000000..a231dfdee --- /dev/null +++ b/interfaces/test/unittest/js/mod_environment/mock/ipc_skeleton_mock.cpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ipc_skeleton_mock.h" + +namespace OHOS { +#ifdef CONFIG_IPC_SINGLE +using namespace IPC_SINGLE; +#endif + +uint32_t IPCSkeleton::GetCallingTokenID() +{ + return OHOS::FileManagement::Backup::BIPCSkeleton::skeleton->GetCallingTokenID(); +} + +ErrCode OHOS::AccountSA::OsAccountManager::GetOsAccountShortName(std::string &shortName) +{ + return OHOS::FileManagement::Backup::BIPCSkeleton::skeleton->GetOsAccountShortName(shortName); +} + +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_environment/mock/ipc_skeleton_mock.h b/interfaces/test/unittest/js/mod_environment/mock/ipc_skeleton_mock.h new file mode 100644 index 000000000..89c5e9fc8 --- /dev/null +++ b/interfaces/test/unittest/js/mod_environment/mock/ipc_skeleton_mock.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License") = 0; + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_TEST_UNITTEST_JS_MOD_ENVIRONMENT_IPC_SKELETON_MOCK_H +#define INTERFACES_TEST_UNITTEST_JS_MOD_ENVIRONMENT_IPC_SKELETON_MOCK_H + +#include + +#include "ipc_skeleton.h" +#include "os_account_manager.h" + +using ErrCode = int; + +namespace OHOS::FileManagement::Backup { +class BIPCSkeleton : public RefBase { +public: + virtual uint32_t GetCallingTokenID() = 0; + virtual ErrCode GetOsAccountShortName(std::string &shortName) = 0; + +public: + BIPCSkeleton() = default; + virtual ~BIPCSkeleton() = default; + +public: + static inline std::shared_ptr skeleton = nullptr; +}; + +class IPCSkeletonMock : public BIPCSkeleton { +public: + MOCK_METHOD(uint32_t, GetCallingTokenID, ()); + MOCK_METHOD(ErrCode, GetOsAccountShortName, (std::string & shortName)); +}; +} // namespace OHOS::FileManagement::Backup +#endif // INTERFACES_TEST_UNITTEST_JS_MOD_ENVIRONMENT_IPC_SKELETON_MOCK_H \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_environment/mock/parameter_mock.cpp b/interfaces/test/unittest/js/mod_environment/mock/parameter_mock.cpp new file mode 100644 index 000000000..106ce53d8 --- /dev/null +++ b/interfaces/test/unittest/js/mod_environment/mock/parameter_mock.cpp @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "parameter_mock.h" + +#include "parameter.h" + +using namespace OHOS::AppFileService; +int GetParameter(const char *key, const char *def, char *value, uint32_t len) +{ + if (IParamMoc::paramMoc == nullptr) { + return -1; + } + return IParamMoc::paramMoc->GetParameter(key, def, value, len); +} \ No newline at end of file diff --git a/interfaces/test/unittest/js/mod_environment/mock/parameter_mock.h b/interfaces/test/unittest/js/mod_environment/mock/parameter_mock.h new file mode 100644 index 000000000..41fc24fba --- /dev/null +++ b/interfaces/test/unittest/js/mod_environment/mock/parameter_mock.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INTERFACES_TEST_UNITTEST_JS_MOD_ENVIRONMENT_PARAMETER_MOCK_H +#define INTERFACES_TEST_UNITTEST_JS_MOD_ENVIRONMENT_PARAMETER_MOCK_H + +#include +#include + +namespace OHOS { +namespace AppFileService { +class IParamMoc { +public: + virtual ~IParamMoc() = default; + +public: + virtual int GetParameter(const char *key, const char *def, char *value, uint32_t len) = 0; + +public: + static inline std::shared_ptr paramMoc = nullptr; +}; + +class ParamMoc : public IParamMoc { +public: + MOCK_METHOD4(GetParameter, int(const char *key, const char *def, char *value, uint32_t len)); +}; +} // namespace AppFileService +} // namespace OHOS +#endif // INTERFACES_TEST_UNITTEST_JS_MOD_ENVIRONMENT_PARAMETER_MOCK_H \ No newline at end of file -- Gitee From e9dd7040ad6bc2632677ca61f86c227e5550b4be Mon Sep 17 00:00:00 2001 From: liyuke Date: Mon, 23 Jun 2025 11:32:45 +0800 Subject: [PATCH 17/19] =?UTF-8?q?=E6=B7=BB=E5=8A=A0build.gn?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: liyuke Change-Id: I39fc5f4bf8854a0a5009d5d376eb3ccc8d97326b --- interfaces/test/unittest/js/BUILD.gn | 44 ++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/interfaces/test/unittest/js/BUILD.gn b/interfaces/test/unittest/js/BUILD.gn index 45b4cf16f..8d56266c1 100644 --- a/interfaces/test/unittest/js/BUILD.gn +++ b/interfaces/test/unittest/js/BUILD.gn @@ -14,6 +14,50 @@ import("//build/test.gni") import("//foundation/filemanagement/file_api/file_api.gni") +ohos_unittest("ani_file_environment_test") { + branch_protector_ret = "pac_ret" + testonly = true + + module_out_path = "file_api/file_api" + include_dirs = [ + "${src_path}/mod_environment", + "${src_path}/mod_environment/ani", + "${file_api_path}/interfaces/test/unittest/js/mod_environment/mock", + ] + + sources = [ + "mod_environment/environment_core_mock_test.cpp", + "mod_environment/mock/accesstoken_kit_mock.cpp", + "mod_environment/mock/ipc_skeleton_mock.cpp", + "mod_environment/mock/parameter_mock.cpp", + ] + + deps = [ + "${file_api_path}/interfaces/kits/js:ani_file_environment", + "${utils_path}/filemgmt_libfs:filemgmt_libfs", + "${utils_path}/filemgmt_libhilog:filemgmt_libhilog", + ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "googletest:gmock_main", + "googletest:gtest_main", + "hilog:libhilog", + "libuv:uv", + "ipc:ipc_core", + "init:libbegetutil", + "openssl:libcrypto_shared", + "os_account:os_account_innerkits", + "runtime_core:ani", + "runtime_core:libarkruntime", + ] + + defines = [ + "private=public", + ] +} + ohos_unittest("ani_file_fs_test") { branch_protector_ret = "pac_ret" testonly = true -- Gitee From 49c8d2eb8543297e8e32bf33c00b34937815a9fa Mon Sep 17 00:00:00 2001 From: liyuke Date: Mon, 23 Jun 2025 14:32:01 +0800 Subject: [PATCH 18/19] =?UTF-8?q?=E6=84=8F=E8=A7=81=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: liyuke Change-Id: If4cb0220fa2e6219fc237e0bf51504fd55a3f8de --- interfaces/test/unittest/BUILD.gn | 1 + .../environment_core_mock_test.cpp | 22 +++++++++---------- .../mod_environment/mock/parameter_mock.cpp | 2 +- 3 files changed, 13 insertions(+), 12 deletions(-) diff --git a/interfaces/test/unittest/BUILD.gn b/interfaces/test/unittest/BUILD.gn index 5578deae0..527a36cb5 100644 --- a/interfaces/test/unittest/BUILD.gn +++ b/interfaces/test/unittest/BUILD.gn @@ -16,6 +16,7 @@ group("file_api_unittest") { deps = [ "class_file:class_file_test", "filemgmt_libn_test:filemgmt_libn_test", + "js:ani_file_environment_test", "js:ani_file_fs_mock_test", "js:ani_file_fs_test", "js:ani_file_hash_test", diff --git a/interfaces/test/unittest/js/mod_environment/environment_core_mock_test.cpp b/interfaces/test/unittest/js/mod_environment/environment_core_mock_test.cpp index b3f619103..6b680cc5b 100644 --- a/interfaces/test/unittest/js/mod_environment/environment_core_mock_test.cpp +++ b/interfaces/test/unittest/js/mod_environment/environment_core_mock_test.cpp @@ -92,7 +92,7 @@ HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetStorageDataDir_001, testi /** * @tc.name: EnvironmentCoreTest_DoGetStorageDataDir_002 - * @tc.desc: Test function of DoGetStorageDataDir interface for FALSE. + * @tc.desc: Test function of DoGetStorageDataDir interface for success. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 @@ -112,7 +112,7 @@ HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetStorageDataDir_002, testi /** * @tc.name: EnvironmentCoreTest_DoGetUserDataDir_001 - * @tc.desc: Test function of DoGetUserDataDir interface for success. + * @tc.desc: Test function of DoGetUserDataDir interface for FALSE. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 @@ -177,7 +177,7 @@ HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetUserDownloadDir_001, test /** * @tc.name: EnvironmentCoreTest_DoGetUserDownloadDir_002 - * @tc.desc: Test function of DoGetUserDownloadDir interface for success. + * @tc.desc: Test function of DoGetUserDownloadDir interface for FALSE. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 @@ -197,7 +197,7 @@ HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetUserDownloadDir_002, test /** * @tc.name: EnvironmentCoreTest_DoGetUserDownloadDir_003 - * @tc.desc: Test function of DoGetUserDownloadDir interface for success. + * @tc.desc: Test function of DoGetUserDownloadDir interface for FALSE. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 @@ -246,7 +246,7 @@ HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetUserDesktopDir_001, testi /** * @tc.name: EnvironmentCoreTest_DoGetUserDesktopDir_002 - * @tc.desc: Test function of DoGetUserDesktopDir interface for success. + * @tc.desc: Test function of DoGetUserDesktopDir interface for FALSE. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 @@ -319,7 +319,7 @@ HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetUserDocumentDir_001, test /** * @tc.name: EnvironmentCoreTest_DoGetUserDocumentDir_002 - * @tc.desc: Test function of DoGetUserDocumentDir interface for success. + * @tc.desc: Test function of DoGetUserDocumentDir interface for FALSE. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 @@ -343,7 +343,7 @@ HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetUserDocumentDir_002, test /** * @tc.name: EnvironmentCoreTest_DoGetUserDocumentDir_003 - * @tc.desc: Test function of DoGetUserDocumentDir interface for success. + * @tc.desc: Test function of DoGetUserDocumentDir interface for FALSE. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 @@ -367,7 +367,7 @@ HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetUserDocumentDir_003, test /** * @tc.name: EnvironmentCoreTest_DoGetExternalStorageDir_001 - * @tc.desc: Test function of DoGetExternalStorageDir interface for success. + * @tc.desc: Test function of DoGetExternalStorageDir interface for FALSE. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 @@ -392,7 +392,7 @@ HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetExternalStorageDir_001, t /** * @tc.name: EnvironmentCoreTest_DoGetExternalStorageDir_002 - * @tc.desc: Test function of DoGetExternalStorageDir interface for success. + * @tc.desc: Test function of DoGetExternalStorageDir interface for FALSE. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 @@ -447,7 +447,7 @@ HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetExternalStorageDir_003, t /** * @tc.name: EnvironmentCoreTest_DoGetExternalStorageDir_004 - * @tc.desc: Test function of DoGetExternalStorageDir interface for success. + * @tc.desc: Test function of DoGetExternalStorageDir interface for FALSE. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 @@ -492,7 +492,7 @@ HWTEST_F(EnvironmentCoreTest, EnvironmentCoreTest_DoGetUserHomeDir_001, testing: /** * @tc.name: EnvironmentCoreTest_DoGetUserHomeDir_002 - * @tc.desc: Test function of DoGetUserHomeDir interface for FALSE. + * @tc.desc: Test function of DoGetUserHomeDir interface for success. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 diff --git a/interfaces/test/unittest/js/mod_environment/mock/parameter_mock.cpp b/interfaces/test/unittest/js/mod_environment/mock/parameter_mock.cpp index 106ce53d8..2905890c1 100644 --- a/interfaces/test/unittest/js/mod_environment/mock/parameter_mock.cpp +++ b/interfaces/test/unittest/js/mod_environment/mock/parameter_mock.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at -- Gitee From ccc00073e4027ea2c7bb125379fb59e8f0df2e55 Mon Sep 17 00:00:00 2001 From: tianp Date: Tue, 24 Jun 2025 21:54:59 +0800 Subject: [PATCH 19/19] =?UTF-8?q?=E9=97=AE=E9=A2=98=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: tianp Change-Id: I25af54cd2c3f1601c9b8eb53ffdb23282371a476 --- .../js/mod_fs/properties/trans_listener_mock_test.cpp | 9 --------- 1 file changed, 9 deletions(-) diff --git a/interfaces/test/unittest/js/mod_fs/properties/trans_listener_mock_test.cpp b/interfaces/test/unittest/js/mod_fs/properties/trans_listener_mock_test.cpp index 56c11d8b5..d5fa384e1 100644 --- a/interfaces/test/unittest/js/mod_fs/properties/trans_listener_mock_test.cpp +++ b/interfaces/test/unittest/js/mod_fs/properties/trans_listener_mock_test.cpp @@ -48,11 +48,6 @@ public: return 0; } - // int32_t PrepareSession(const std::string &srcUri, const std::string &dstUri, const std::string &srcDeviceId, - // const sptr &listener, HmdfsInfo &info) override - // { - // return 0; - // } MOCK_METHOD(int32_t, PrepareSession, (const std::string &srcUri, const std::string &dstUri, const std::string &srcDeviceId, const sptr &listener, HmdfsInfo &info), (override)); @@ -212,10 +207,6 @@ HWTEST_F(TransListenerCoreTest, TransListenerCoreTest_CopyFileFromSoftBus_001, t string srcUri = "http://translistener.preparecopysession?networkid=AD125AD1CF"; shared_ptr transListener(new TransListenerCore); std::shared_ptr infos(new FsFileInfos); - // transListener->copyEvent_.copyResult = FAILED; - - // shared_ptr transListenerArg(new TransListenerCore); - // transListenerArg->copyEvent_.errorCode = DFS_CANCEL_SUCCESS; EXPECT_CALL(GetMock(), PrepareSession(testing::_, testing::_, testing::_, testing::_, testing::_)) .WillOnce(testing::Return(ERRNO_NOERR)); -- Gitee